sql_parse.cc 327 KB
Newer Older
1
/* Copyright (c) 2000, 2017, Oracle and/or its affiliates.
2
   Copyright (c) 2008, 2024, MariaDB
3

unknown's avatar
unknown committed
4 5
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
6
   the Free Software Foundation; version 2 of the License.
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
12

unknown's avatar
unknown committed
13 14
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
Vicențiu Ciorbaru's avatar
Vicențiu Ciorbaru committed
15
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1335  USA */
unknown's avatar
unknown committed
16

17
#define MYSQL_LEX 1
18
#include "mariadb.h"
19 20
#include "sql_priv.h"
#include "sql_parse.h"        // sql_kill, *_precheck, *_prepare
21
#include "lock.h"             // try_transactional_lock,
22 23 24 25
                              // check_transactional_lock,
                              // set_handler_table_locks,
                              // lock_global_read_lock,
                              // make_global_read_lock_block_commit
26 27 28 29
#include "sql_base.h"         // open_tables, open_and_lock_tables,
                              // lock_tables, unique_table,
                              // close_thread_tables, is_temporary_table
                              // table_cache.h
30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include "sql_cache.h"        // QUERY_CACHE_FLAGS_SIZE, query_cache_*
#include "sql_show.h"         // mysqld_list_*, mysqld_show_*,
                              // calc_sum_of_all_status
#include "mysqld.h"
#include "sql_locale.h"                         // my_locale_en_US
#include "log.h"                                // flush_error_log
#include "sql_view.h"         // mysql_create_view, mysql_drop_view
#include "sql_insert.h"       // mysql_insert
#include "sql_partition.h"    // struct partition_info
#include "sql_db.h"           // mysql_change_db, mysql_create_db,
                              // mysql_rm_db, mysql_upgrade_db,
                              // mysql_alter_db,
                              // check_db_dir_existence,
                              // my_dbopt_cleanup
44
#include "sql_table.h"        // mysql_alter_table,
45 46
                              // mysql_backup_table,
                              // mysql_restore_table
47
#include "sql_reload.h"       // reload_acl_and_cache
48
#include "sql_admin.h"        // mysql_assign_to_keycache
Sergei Golubchik's avatar
Sergei Golubchik committed
49 50
#include "sql_connect.h"      // decrease_user_connections,
                              // check_mqh,
51
                              // reset_mqh
52
#include "sql_rename.h"       // mysql_rename_tables
53 54 55 56 57 58 59 60 61 62 63 64 65 66
#include "hostname.h"         // hostname_cache_refresh
#include "sql_test.h"         // mysql_print_status
#include "sql_select.h"       // handle_select, mysql_select,
                              // mysql_explain_union
#include "sql_load.h"         // mysql_load
#include "sql_servers.h"      // create_servers, alter_servers,
                              // drop_servers, servers_reload
#include "sql_handler.h"      // mysql_ha_open, mysql_ha_close,
                              // mysql_ha_read
#include "sql_binlog.h"       // mysql_client_binlog_statement
#include "sql_do.h"           // mysql_do
#include "sql_help.h"         // mysqld_help
#include "rpl_constants.h"    // Incident, INCIDENT_LOST_EVENTS
#include "log_event.h"
67
#include "sql_repl.h"
unknown's avatar
unknown committed
68
#include "rpl_filter.h"
69
#include "repl_failsafe.h"
unknown's avatar
unknown committed
70 71 72
#include <m_ctype.h>
#include <myisam.h>
#include <my_dir.h>
73
#include "rpl_mi.h"
unknown's avatar
unknown committed
74

Sergei Golubchik's avatar
Sergei Golubchik committed
75 76
#include "sql_digest.h"

77
#include "sp_head.h"
78
#include "sp.h"
79
#include "sp_cache.h"
80
#include "events.h"
81
#include "sql_trigger.h"
Konstantin Osipov's avatar
Konstantin Osipov committed
82
#include "transaction.h"
83
#include "sql_alter.h"
84
#include "sql_audit.h"
85
#include "sql_prepare.h"
86
#include "sql_cte.h"
87
#include "debug_sync.h"
88
#include "probes_mysql.h"
89
#include "set_var.h"
90
#include "sql_bootstrap.h"
91
#include "sql_sequence.h"
Varun Gupta's avatar
Varun Gupta committed
92
#include "opt_trace.h"
93
#include "mysql/psi/mysql_sp.h"
94

Sergei Petrunia's avatar
Sergei Petrunia committed
95 96
#include "my_json_writer.h" 

97 98
#define FLAGSTR(V,F) ((V)&(F)?#F" ":"")

Sergei Golubchik's avatar
Sergei Golubchik committed
99
#ifdef WITH_ARIA_STORAGE_ENGINE
unknown's avatar
unknown committed
100 101 102
#include "../storage/maria/ha_maria.h"
#endif

Marko Mäkelä's avatar
Marko Mäkelä committed
103
#include "wsrep.h"
104
#include "wsrep_mysqld.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
105
#ifdef WITH_WSREP
106
#include "wsrep_thd.h"
Brave Galera Crew's avatar
Brave Galera Crew committed
107
#include "wsrep_trans_observer.h" /* wsrep transaction hooks */
108

Brave Galera Crew's avatar
Brave Galera Crew committed
109
static bool wsrep_mysql_parse(THD *thd, char *rawbuf, uint length,
110
                              Parser_state *parser_state);
111

Brave Galera Crew's avatar
Brave Galera Crew committed
112
#endif /* WITH_WSREP */
113 114 115 116 117
/**
  @defgroup Runtime_Environment Runtime Environment
  @{
*/

118
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables);
119
static void sql_kill(THD *thd, my_thread_id id, killed_state state, killed_type type);
Sergei Golubchik's avatar
Sergei Golubchik committed
120
static void sql_kill_user(THD *thd, LEX_USER *user, killed_state state);
121
static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables);
Sergei Golubchik's avatar
Sergei Golubchik committed
122
static bool execute_show_status(THD *, TABLE_LIST *);
123
static bool check_rename_table(THD *, TABLE_LIST *, TABLE_LIST *);
124 125 126 127
static bool generate_incident_event(THD *thd);
static int  show_create_db(THD *thd, LEX *lex);
static bool alter_routine(THD *thd, LEX *lex);
static bool drop_routine(THD *thd, LEX *lex);
unknown's avatar
unknown committed
128

129
const Lex_ident_db_normalized any_db(STRING_WITH_LEN("*any*"));
unknown's avatar
unknown committed
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
const LEX_CSTRING command_name[257]={
  { STRING_WITH_LEN("Sleep") },           //0
  { STRING_WITH_LEN("Quit") },            //1
  { STRING_WITH_LEN("Init DB") },         //2
  { STRING_WITH_LEN("Query") },           //3
  { STRING_WITH_LEN("Field List") },      //4
  { STRING_WITH_LEN("Create DB") },       //5
  { STRING_WITH_LEN("Drop DB") },         //6
  { STRING_WITH_LEN("Refresh") },         //7
  { STRING_WITH_LEN("Shutdown") },        //8
  { STRING_WITH_LEN("Statistics") },      //9
  { STRING_WITH_LEN("Processlist") },     //10
  { STRING_WITH_LEN("Connect") },         //11
  { STRING_WITH_LEN("Kill") },            //12
  { STRING_WITH_LEN("Debug") },           //13
  { STRING_WITH_LEN("Ping") },            //14
  { STRING_WITH_LEN("Time") },            //15
  { STRING_WITH_LEN("Delayed insert") },  //16
  { STRING_WITH_LEN("Change user") },     //17
  { STRING_WITH_LEN("Binlog Dump") },     //18
  { STRING_WITH_LEN("Table Dump") },      //19
  { STRING_WITH_LEN("Connect Out") },     //20
  { STRING_WITH_LEN("Register Slave") },  //21
  { STRING_WITH_LEN("Prepare") },         //22
  { STRING_WITH_LEN("Execute") },         //23
  { STRING_WITH_LEN("Long Data") },       //24
  { STRING_WITH_LEN("Close stmt") },      //25
  { STRING_WITH_LEN("Reset stmt") },      //26
  { STRING_WITH_LEN("Set option") },      //27
  { STRING_WITH_LEN("Fetch") },           //28
  { STRING_WITH_LEN("Daemon") },          //29
  { STRING_WITH_LEN("Unimpl get tid") },  //30
  { STRING_WITH_LEN("Reset connection") },//31
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  { 0, 0 }, //32
  { 0, 0 }, //33
  { 0, 0 }, //34
  { 0, 0 }, //35
  { 0, 0 }, //36
  { 0, 0 }, //37
  { 0, 0 }, //38
  { 0, 0 }, //39
  { 0, 0 }, //40
  { 0, 0 }, //41
  { 0, 0 }, //42
  { 0, 0 }, //43
  { 0, 0 }, //44
  { 0, 0 }, //45
  { 0, 0 }, //46
  { 0, 0 }, //47
  { 0, 0 }, //48
  { 0, 0 }, //49
  { 0, 0 }, //50
  { 0, 0 }, //51
  { 0, 0 }, //52
  { 0, 0 }, //53
  { 0, 0 }, //54
  { 0, 0 }, //55
  { 0, 0 }, //56
  { 0, 0 }, //57
  { 0, 0 }, //58
  { 0, 0 }, //59
  { 0, 0 }, //60
  { 0, 0 }, //61
  { 0, 0 }, //62
  { 0, 0 }, //63
  { 0, 0 }, //64
  { 0, 0 }, //65
  { 0, 0 }, //66
  { 0, 0 }, //67
  { 0, 0 }, //68
  { 0, 0 }, //69
  { 0, 0 }, //70
  { 0, 0 }, //71
  { 0, 0 }, //72
  { 0, 0 }, //73
  { 0, 0 }, //74
  { 0, 0 }, //75
  { 0, 0 }, //76
  { 0, 0 }, //77
  { 0, 0 }, //78
  { 0, 0 }, //79
  { 0, 0 }, //80
  { 0, 0 }, //81
  { 0, 0 }, //82
  { 0, 0 }, //83
  { 0, 0 }, //84
  { 0, 0 }, //85
  { 0, 0 }, //86
  { 0, 0 }, //87
  { 0, 0 }, //88
  { 0, 0 }, //89
  { 0, 0 }, //90
  { 0, 0 }, //91
  { 0, 0 }, //92
  { 0, 0 }, //93
  { 0, 0 }, //94
  { 0, 0 }, //95
  { 0, 0 }, //96
  { 0, 0 }, //97
  { 0, 0 }, //98
  { 0, 0 }, //99
  { 0, 0 }, //100
  { 0, 0 }, //101
  { 0, 0 }, //102
  { 0, 0 }, //103
  { 0, 0 }, //104
  { 0, 0 }, //105
  { 0, 0 }, //106
  { 0, 0 }, //107
  { 0, 0 }, //108
  { 0, 0 }, //109
  { 0, 0 }, //110
  { 0, 0 }, //111
  { 0, 0 }, //112
  { 0, 0 }, //113
  { 0, 0 }, //114
  { 0, 0 }, //115
  { 0, 0 }, //116
  { 0, 0 }, //117
  { 0, 0 }, //118
  { 0, 0 }, //119
  { 0, 0 }, //120
  { 0, 0 }, //121
  { 0, 0 }, //122
  { 0, 0 }, //123
  { 0, 0 }, //124
  { 0, 0 }, //125
  { 0, 0 }, //126
  { 0, 0 }, //127
  { 0, 0 }, //128
  { 0, 0 }, //129
  { 0, 0 }, //130
  { 0, 0 }, //131
  { 0, 0 }, //132
  { 0, 0 }, //133
  { 0, 0 }, //134
  { 0, 0 }, //135
  { 0, 0 }, //136
  { 0, 0 }, //137
  { 0, 0 }, //138
  { 0, 0 }, //139
  { 0, 0 }, //140
  { 0, 0 }, //141
  { 0, 0 }, //142
  { 0, 0 }, //143
  { 0, 0 }, //144
  { 0, 0 }, //145
  { 0, 0 }, //146
  { 0, 0 }, //147
  { 0, 0 }, //148
  { 0, 0 }, //149
  { 0, 0 }, //150
  { 0, 0 }, //151
  { 0, 0 }, //152
  { 0, 0 }, //153
  { 0, 0 }, //154
  { 0, 0 }, //155
  { 0, 0 }, //156
  { 0, 0 }, //157
  { 0, 0 }, //158
  { 0, 0 }, //159
  { 0, 0 }, //160
  { 0, 0 }, //161
  { 0, 0 }, //162
  { 0, 0 }, //163
  { 0, 0 }, //164
  { 0, 0 }, //165
  { 0, 0 }, //166
  { 0, 0 }, //167
  { 0, 0 }, //168
  { 0, 0 }, //169
  { 0, 0 }, //170
  { 0, 0 }, //171
  { 0, 0 }, //172
  { 0, 0 }, //173
  { 0, 0 }, //174
  { 0, 0 }, //175
  { 0, 0 }, //176
  { 0, 0 }, //177
  { 0, 0 }, //178
  { 0, 0 }, //179
  { 0, 0 }, //180
  { 0, 0 }, //181
  { 0, 0 }, //182
  { 0, 0 }, //183
  { 0, 0 }, //184
  { 0, 0 }, //185
  { 0, 0 }, //186
  { 0, 0 }, //187
  { 0, 0 }, //188
  { 0, 0 }, //189
  { 0, 0 }, //190
  { 0, 0 }, //191
  { 0, 0 }, //192
  { 0, 0 }, //193
  { 0, 0 }, //194
  { 0, 0 }, //195
  { 0, 0 }, //196
  { 0, 0 }, //197
  { 0, 0 }, //198
  { 0, 0 }, //199
  { 0, 0 }, //200
  { 0, 0 }, //201
  { 0, 0 }, //202
  { 0, 0 }, //203
  { 0, 0 }, //204
  { 0, 0 }, //205
  { 0, 0 }, //206
  { 0, 0 }, //207
  { 0, 0 }, //208
  { 0, 0 }, //209
  { 0, 0 }, //210
  { 0, 0 }, //211
  { 0, 0 }, //212
  { 0, 0 }, //213
  { 0, 0 }, //214
  { 0, 0 }, //215
  { 0, 0 }, //216
  { 0, 0 }, //217
  { 0, 0 }, //218
  { 0, 0 }, //219
  { 0, 0 }, //220
  { 0, 0 }, //221
  { 0, 0 }, //222
  { 0, 0 }, //223
  { 0, 0 }, //224
  { 0, 0 }, //225
  { 0, 0 }, //226
  { 0, 0 }, //227
  { 0, 0 }, //228
  { 0, 0 }, //229
  { 0, 0 }, //230
  { 0, 0 }, //231
  { 0, 0 }, //232
  { 0, 0 }, //233
  { 0, 0 }, //234
  { 0, 0 }, //235
  { 0, 0 }, //236
  { 0, 0 }, //237
  { 0, 0 }, //238
  { 0, 0 }, //239
  { 0, 0 }, //240
  { 0, 0 }, //241
  { 0, 0 }, //242
  { 0, 0 }, //243
  { 0, 0 }, //244
  { 0, 0 }, //245
  { 0, 0 }, //246
  { 0, 0 }, //247
  { 0, 0 }, //248
  { 0, 0 }, //249
382 383 384 385
  { STRING_WITH_LEN("Bulk_execute") }, //250
  { STRING_WITH_LEN("Slave_worker") }, //251
  { STRING_WITH_LEN("Slave_IO") }, //252
  { STRING_WITH_LEN("Slave_SQL") }, //253
386
  { 0, 0},
387
  { STRING_WITH_LEN("Error") }  // Last command number 255
unknown's avatar
unknown committed
388 389
};

unknown's avatar
unknown committed
390
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
391 392
/**
  Returns true if all tables should be ignored.
393
*/
394 395
inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables)
{
396 397
  Rpl_filter *rpl_filter= thd->system_thread_info.rpl_sql_info->rpl_filter;
  return rpl_filter->is_on() && tables && !thd->spcont &&
398
         !rpl_filter->tables_ok(thd->db.str, tables);
399
}
unknown's avatar
unknown committed
400
#endif
401 402


403 404 405 406
static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
{
  for (TABLE_LIST *table= tables; table; table= table->next_global)
  {
407
    DBUG_ASSERT(table->db.str && table->table_name.str);
408
    if (table->updating && !thd->find_tmp_table_share(table))
409 410 411 412 413
      return 1;
  }
  return 0;
}

414

Konstantin Osipov's avatar
Konstantin Osipov committed
415
/*
416
  Check whether the statement implicitly commits an active transaction.
Konstantin Osipov's avatar
Konstantin Osipov committed
417 418 419 420

  @param thd    Thread handle.
  @param mask   Bitmask used for the SQL command match.

421 422
  @return 0     No implicit commit
  @return 1     Do a commit
Konstantin Osipov's avatar
Konstantin Osipov committed
423
*/
424
bool stmt_causes_implicit_commit(THD *thd, uint mask)
Konstantin Osipov's avatar
Konstantin Osipov committed
425 426
{
  LEX *lex= thd->lex;
427 428
  bool skip= FALSE;
  DBUG_ENTER("stmt_causes_implicit_commit");
Konstantin Osipov's avatar
Konstantin Osipov committed
429 430 431 432 433 434

  if (!(sql_command_flags[lex->sql_command] & mask))
    DBUG_RETURN(FALSE);

  switch (lex->sql_command) {
  case SQLCOM_ALTER_TABLE:
435
  case SQLCOM_ALTER_SEQUENCE:
436
    /* If ALTER TABLE of non-temporary table, do implicit commit */
437
    skip= (lex->tmp_table());
438
    break;
439 440
  case SQLCOM_DROP_TABLE:
  case SQLCOM_DROP_SEQUENCE:
Konstantin Osipov's avatar
Konstantin Osipov committed
441
  case SQLCOM_CREATE_TABLE:
442
  case SQLCOM_CREATE_SEQUENCE:
443 444 445 446 447 448
    /*
      If CREATE TABLE of non-temporary table and the table is not part
      if a BEGIN GTID ... COMMIT group, do a implicit commit.
      This ensures that CREATE ... SELECT will in the same GTID group on the
      master and slave.
    */
449
    skip= (lex->tmp_table() ||
450
           (thd->variables.option_bits & OPTION_GTID_BEGIN));
Konstantin Osipov's avatar
Konstantin Osipov committed
451 452 453 454 455 456 457 458
    break;
  case SQLCOM_SET_OPTION:
    skip= lex->autocommit ? FALSE : TRUE;
    break;
  default:
    break;
  }

459
  DBUG_RETURN(!skip);
Konstantin Osipov's avatar
Konstantin Osipov committed
460 461 462
}


unknown's avatar
unknown committed
463 464 465 466
/**
  Mark all commands that somehow changes a table.

  This is used to check number of updates / hour.
unknown's avatar
unknown committed
467 468 469

  sql_command is actually set to SQLCOM_END sometimes
  so we need the +1 to include it in the array.
unknown's avatar
unknown committed
470

471
  See COMMAND_FLAG_xxx for different type of commands
unknown's avatar
unknown committed
472 473
     2  - query that returns meaningful ROW_COUNT() -
          a number of modified rows
474 475
*/

476
uint sql_command_flags[SQLCOM_END+1];
Konstantin Osipov's avatar
Konstantin Osipov committed
477
uint server_command_flags[COM_END+1];
478 479 480

void init_update_queries(void)
{
Konstantin Osipov's avatar
Konstantin Osipov committed
481 482 483
  /* Initialize the server command flags array. */
  memset(server_command_flags, 0, sizeof(server_command_flags));

484
  server_command_flags[COM_STATISTICS]= CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
485
  server_command_flags[COM_PING]=       CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
486 487 488 489 490 491 492

  server_command_flags[COM_QUIT]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_PROCESS_INFO]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_PROCESS_KILL]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SHUTDOWN]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SLEEP]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_TIME]= CF_SKIP_WSREP_CHECK;
493
  server_command_flags[COM_INIT_DB]= CF_SKIP_WSREP_CHECK;
494
  server_command_flags[COM_END]= CF_SKIP_WSREP_CHECK;
495 496 497 498
  for (uint i= COM_MDB_GAP_BEG; i <= COM_MDB_GAP_END; i++)
  {
    server_command_flags[i]= CF_SKIP_WSREP_CHECK;
  }
499 500

  /*
501 502
    COM_QUERY, COM_SET_OPTION and COM_STMT_XXX are allowed to pass the early
    COM_xxx filter, they're checked later in mysql_execute_command().
503 504 505
  */
  server_command_flags[COM_QUERY]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_SET_OPTION]= CF_SKIP_WSREP_CHECK;
506
  server_command_flags[COM_STMT_PREPARE]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
507 508
  server_command_flags[COM_STMT_EXECUTE]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_FETCH]=   CF_SKIP_WSREP_CHECK;
509 510 511 512
  server_command_flags[COM_STMT_CLOSE]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_RESET]= CF_SKIP_QUESTIONS | CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_EXECUTE]= CF_SKIP_WSREP_CHECK;
  server_command_flags[COM_STMT_SEND_LONG_DATA]= CF_SKIP_WSREP_CHECK;
513
  server_command_flags[COM_REGISTER_SLAVE]= CF_SKIP_WSREP_CHECK;
Konstantin Osipov's avatar
Konstantin Osipov committed
514 515 516 517

  /* Initialize the sql command flags array. */
  memset(sql_command_flags, 0, sizeof(sql_command_flags));

518 519 520 521 522 523 524 525 526 527
  /*
    In general, DDL statements do not generate row events and do not go
    through a cache before being written to the binary log. However, the
    CREATE TABLE...SELECT is an exception because it may generate row
    events. For that reason,  the SQLCOM_CREATE_TABLE  which represents
    a CREATE TABLE, including the CREATE TABLE...SELECT, has the
    CF_CAN_GENERATE_ROW_EVENTS flag. The distinction between a regular
    CREATE TABLE and the CREATE TABLE...SELECT is made in other parts of
    the code, in particular in the Query_log_event's constructor.
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
528
  sql_command_flags[SQLCOM_CREATE_TABLE]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
Sergei Golubchik's avatar
Sergei Golubchik committed
529
                                            CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS |
530 531 532 533 534 535
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_SCHEMA_CHANGE;
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]=  (CF_CHANGES_DATA |
                                            CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS |
                                            CF_SCHEMA_CHANGE);
536
  sql_command_flags[SQLCOM_CREATE_INDEX]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS |
537
                                            CF_ADMIN_COMMAND | CF_REPORT_PROGRESS;
Konstantin Osipov's avatar
Konstantin Osipov committed
538
  sql_command_flags[SQLCOM_ALTER_TABLE]=    CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
539
                                            CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS |
540
                                            CF_INSERTS_DATA | CF_ADMIN_COMMAND;
541
  sql_command_flags[SQLCOM_ALTER_SEQUENCE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
542 543
                                            CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE |
                                            CF_ADMIN_COMMAND;
Konstantin Osipov's avatar
Konstantin Osipov committed
544
  sql_command_flags[SQLCOM_TRUNCATE]=       CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
545
                                            CF_AUTO_COMMIT_TRANS;
546 547
  sql_command_flags[SQLCOM_DROP_TABLE]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE;
  sql_command_flags[SQLCOM_DROP_SEQUENCE]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_SCHEMA_CHANGE;
Jon Olav Hauglid's avatar
Jon Olav Hauglid committed
548
  sql_command_flags[SQLCOM_LOAD]=           CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
549 550
                                            CF_CAN_GENERATE_ROW_EVENTS | CF_REPORT_PROGRESS |
                                            CF_INSERTS_DATA;
551 552
  sql_command_flags[SQLCOM_CREATE_DB]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
  sql_command_flags[SQLCOM_DROP_DB]=        CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
553 554 555 556
  sql_command_flags[SQLCOM_CREATE_PACKAGE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_PACKAGE_BODY]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE_BODY]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
557
  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS;
558
  sql_command_flags[SQLCOM_ALTER_DB]=       CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_DB_CHANGE;
559
  sql_command_flags[SQLCOM_RENAME_TABLE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_ADMIN_COMMAND;
560 561
  sql_command_flags[SQLCOM_DROP_INDEX]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS |
                                            CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
Konstantin Osipov's avatar
Konstantin Osipov committed
562 563 564
  sql_command_flags[SQLCOM_CREATE_VIEW]=    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_VIEW]=      CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
565 566
  sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
Konstantin Osipov's avatar
Konstantin Osipov committed
567 568 569
  sql_command_flags[SQLCOM_CREATE_EVENT]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_EVENT]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_EVENT]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
570

571
  sql_command_flags[SQLCOM_UPDATE]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
572 573
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
574
                                            CF_CAN_BE_EXPLAINED |
575 576
                                            CF_UPDATES_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE;
577
  sql_command_flags[SQLCOM_UPDATE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
578 579
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
580
                                            CF_CAN_BE_EXPLAINED |
581 582
                                            CF_UPDATES_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE;
583
  sql_command_flags[SQLCOM_INSERT]=	    CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
584 585
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
586
                                            CF_CAN_BE_EXPLAINED |
587
                                            CF_INSERTS_DATA |
588 589
                                            CF_PS_ARRAY_BINDING_SAFE |
                                            CF_PS_ARRAY_BINDING_OPTIMIZED;
590
  sql_command_flags[SQLCOM_INSERT_SELECT]=  CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
591 592
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
593 594
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA;
595
  sql_command_flags[SQLCOM_DELETE]=         CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
596 597
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
598
                                            CF_CAN_BE_EXPLAINED |
Marko Mäkelä's avatar
Marko Mäkelä committed
599
                                            CF_DELETES_DATA |
600
                                            CF_PS_ARRAY_BINDING_SAFE;
601
  sql_command_flags[SQLCOM_DELETE_MULTI]=   CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
602 603
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
604 605
                                            CF_CAN_BE_EXPLAINED |
                                            CF_DELETES_DATA;
606
  sql_command_flags[SQLCOM_REPLACE]=        CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
607 608
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
609
                                            CF_CAN_BE_EXPLAINED |
610 611 612
                                            CF_INSERTS_DATA |
                                            CF_PS_ARRAY_BINDING_SAFE |
                                            CF_PS_ARRAY_BINDING_OPTIMIZED;
613
  sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
614 615
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
616 617
                                            CF_CAN_BE_EXPLAINED |
                                            CF_INSERTS_DATA;
618
  sql_command_flags[SQLCOM_SELECT]=         CF_REEXECUTION_FRAGILE |
619 620 621 622 623 624 625 626 627 628 629
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE |
                                            CF_CAN_BE_EXPLAINED;
  // (1) so that subquery is traced when doing "SET @var = (subquery)"
  /*
    @todo SQLCOM_SET_OPTION should have CF_CAN_GENERATE_ROW_EVENTS
    set, because it may invoke a stored function that generates row
    events. /Sven
  */
  sql_command_flags[SQLCOM_SET_OPTION]=     CF_REEXECUTION_FRAGILE |
                                            CF_AUTO_COMMIT_TRANS |
630
                                            CF_CAN_GENERATE_ROW_EVENTS |
631 632
                                            CF_OPTIMIZER_TRACE; // (1)
  // (1) so that subquery is traced when doing "DO @var := (subquery)"
633
  sql_command_flags[SQLCOM_DO]=             CF_REEXECUTION_FRAGILE |
634 635
                                            CF_CAN_GENERATE_ROW_EVENTS |
                                            CF_OPTIMIZER_TRACE; // (1)
636 637

  sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
638 639
  sql_command_flags[SQLCOM_SHOW_STATUS_PACKAGE]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_STATUS_PACKAGE_BODY]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
640 641 642 643 644
  sql_command_flags[SQLCOM_SHOW_STATUS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_DATABASES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_TRIGGERS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_EVENTS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
645
  sql_command_flags[SQLCOM_SHOW_PLUGINS]=     CF_STATUS_COMMAND;
646
  sql_command_flags[SQLCOM_SHOW_GENERIC]=     CF_STATUS_COMMAND;
647 648 649 650 651
  sql_command_flags[SQLCOM_SHOW_FIELDS]=      CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_KEYS]=        CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_VARIABLES]=   CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_CHARSETS]=    CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_COLLATIONS]=  CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
652
  sql_command_flags[SQLCOM_SHOW_BINLOGS]=     CF_STATUS_COMMAND;
653 654 655
  sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND;
656
  sql_command_flags[SQLCOM_SHOW_AUTHORS]=     CF_STATUS_COMMAND;
657
  sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND;
658 659 660
  sql_command_flags[SQLCOM_SHOW_PRIVILEGES]=  CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_WARNS]=       CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
  sql_command_flags[SQLCOM_SHOW_ERRORS]=      CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT;
661 662 663
  sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND;
664
  sql_command_flags[SQLCOM_SHOW_EXPLAIN]= CF_STATUS_COMMAND;
665
  sql_command_flags[SQLCOM_SHOW_ANALYZE]= CF_STATUS_COMMAND;
666
  sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND;
667
  sql_command_flags[SQLCOM_SHOW_GRANTS]=      CF_STATUS_COMMAND;
668
  sql_command_flags[SQLCOM_SHOW_CREATE_USER]= CF_STATUS_COMMAND;
669
  sql_command_flags[SQLCOM_SHOW_CREATE_DB]=   CF_STATUS_COMMAND;
670
  sql_command_flags[SQLCOM_SHOW_CREATE]=  CF_STATUS_COMMAND;
671
  sql_command_flags[SQLCOM_SHOW_BINLOG_STAT]= CF_STATUS_COMMAND;
672
  sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]=  CF_STATUS_COMMAND;
673 674
  sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND;
675 676
  sql_command_flags[SQLCOM_SHOW_CREATE_PACKAGE]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_CREATE_PACKAGE_BODY]= CF_STATUS_COMMAND;
677
  sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]=  CF_STATUS_COMMAND;
678 679 680
  sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
  sql_command_flags[SQLCOM_SHOW_PROC_CODE]=   CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_FUNC_CODE]=   CF_STATUS_COMMAND;
681
  sql_command_flags[SQLCOM_SHOW_PACKAGE_BODY_CODE]= CF_STATUS_COMMAND;
682 683 684
  sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILES]=    CF_STATUS_COMMAND;
  sql_command_flags[SQLCOM_SHOW_PROFILE]=     CF_STATUS_COMMAND;
685
  sql_command_flags[SQLCOM_BINLOG_BASE64_EVENT]= CF_STATUS_COMMAND | CF_CAN_GENERATE_ROW_EVENTS;
Sergei Golubchik's avatar
Sergei Golubchik committed
686 687
  sql_command_flags[SQLCOM_SHOW_TABLES]=       (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE);
  sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE);
688

689

690 691 692
  sql_command_flags[SQLCOM_CREATE_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_RENAME_USER]=       CF_CHANGES_DATA;
  sql_command_flags[SQLCOM_DROP_USER]=         CF_CHANGES_DATA;
693
  sql_command_flags[SQLCOM_ALTER_USER]=        CF_CHANGES_DATA;
694
  sql_command_flags[SQLCOM_CREATE_ROLE]=       CF_CHANGES_DATA;
695
  sql_command_flags[SQLCOM_GRANT]=             CF_CHANGES_DATA;
696
  sql_command_flags[SQLCOM_GRANT_ROLE]=        CF_CHANGES_DATA;
697
  sql_command_flags[SQLCOM_REVOKE]=            CF_CHANGES_DATA;
698
  sql_command_flags[SQLCOM_REVOKE_ROLE]=       CF_CHANGES_DATA;
699
  sql_command_flags[SQLCOM_OPTIMIZE]=          CF_CHANGES_DATA;
700
  sql_command_flags[SQLCOM_CREATE_FUNCTION]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
701 702 703 704 705 706
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]=     CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]=   CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
707 708
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]=    CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]=  CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
709

710 711 712 713 714 715
  /*
    The following is used to preserver CF_ROW_COUNT during the
    a CALL or EXECUTE statement, so the value generated by the
    last called (or executed) statement is preserved.
    See mysql_execute_command() for how CF_ROW_COUNT is used.
  */
716 717 718 719
  /*
    (1): without it, in "CALL some_proc((subq))", subquery would not be
    traced.
  */
720
  sql_command_flags[SQLCOM_CALL]=      CF_REEXECUTION_FRAGILE |
721 722
                                       CF_CAN_GENERATE_ROW_EVENTS |
                                       CF_OPTIMIZER_TRACE; // (1)
723
  sql_command_flags[SQLCOM_EXECUTE]=   CF_CAN_GENERATE_ROW_EVENTS;
724
  sql_command_flags[SQLCOM_EXECUTE_IMMEDIATE]= CF_CAN_GENERATE_ROW_EVENTS;
725
  sql_command_flags[SQLCOM_COMPOUND]=  CF_CAN_GENERATE_ROW_EVENTS;
726

727 728 729 730 731 732 733 734 735 736
  /*
    We don't want to change to statement based replication for these commands
  */
  sql_command_flags[SQLCOM_ROLLBACK]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate ALTER TABLE for temp tables in row format */
  sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate TRUNCATE for temp tables in row format */
  sql_command_flags[SQLCOM_TRUNCATE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  /* We don't want to replicate DROP for temp tables in row format */
  sql_command_flags[SQLCOM_DROP_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
737
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
738 739 740
  /* We don't want to replicate CREATE/DROP INDEX for temp tables in row format */
  sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
  sql_command_flags[SQLCOM_DROP_INDEX]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;
741 742 743
  /* One can change replication mode with SET */
  sql_command_flags[SQLCOM_SET_OPTION]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT;

744 745 746 747
  /*
    The following admin table operations are allowed
    on log tables.
  */
748 749 750 751 752 753 754 755
  sql_command_flags[SQLCOM_REPAIR]=    CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_ANALYZE]=   CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
  sql_command_flags[SQLCOM_CHECK]=     CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS |
                                       CF_REPORT_PROGRESS | CF_ADMIN_COMMAND;
Sergei Golubchik's avatar
Sergei Golubchik committed
756
  sql_command_flags[SQLCOM_CHECKSUM]=  CF_REPORT_PROGRESS;
757 758

  sql_command_flags[SQLCOM_CREATE_USER]|=       CF_AUTO_COMMIT_TRANS;
759
  sql_command_flags[SQLCOM_ALTER_USER]|=        CF_AUTO_COMMIT_TRANS;
760 761
  sql_command_flags[SQLCOM_DROP_USER]|=         CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_RENAME_USER]|=       CF_AUTO_COMMIT_TRANS;
762
  sql_command_flags[SQLCOM_CREATE_ROLE]|=       CF_AUTO_COMMIT_TRANS;
Sergei Golubchik's avatar
Sergei Golubchik committed
763
  sql_command_flags[SQLCOM_DROP_ROLE]|=         CF_AUTO_COMMIT_TRANS;
764
  sql_command_flags[SQLCOM_REVOKE]|=            CF_AUTO_COMMIT_TRANS;
765
  sql_command_flags[SQLCOM_REVOKE_ALL]=         CF_AUTO_COMMIT_TRANS;
766
  sql_command_flags[SQLCOM_REVOKE_ROLE]|=       CF_AUTO_COMMIT_TRANS;
767
  sql_command_flags[SQLCOM_GRANT]|=             CF_AUTO_COMMIT_TRANS;
768
  sql_command_flags[SQLCOM_GRANT_ROLE]|=        CF_AUTO_COMMIT_TRANS;
769

Konstantin Osipov's avatar
Konstantin Osipov committed
770
  sql_command_flags[SQLCOM_FLUSH]=              CF_AUTO_COMMIT_TRANS;
771
  sql_command_flags[SQLCOM_RESET]=              CF_AUTO_COMMIT_TRANS;
772 773 774
  sql_command_flags[SQLCOM_CREATE_SERVER]=      CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_ALTER_SERVER]=       CF_AUTO_COMMIT_TRANS;
  sql_command_flags[SQLCOM_DROP_SERVER]=        CF_AUTO_COMMIT_TRANS;
775
  sql_command_flags[SQLCOM_BACKUP]=             CF_AUTO_COMMIT_TRANS;
776
  sql_command_flags[SQLCOM_BACKUP_LOCK]=        CF_AUTO_COMMIT_TRANS;
777 778 779 780 781 782 783 784 785

  /*
    The following statements can deal with temporary tables,
    so temporary tables should be pre-opened for those statements to
    simplify privilege checking.

    There are other statements that deal with temporary tables and open
    them, but which are not listed here. The thing is that the order of
    pre-opening temporary tables for those statements is somewhat custom.
786 787

    Note that SQLCOM_RENAME_TABLE should not be in this list!
788 789
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=    CF_PREOPEN_TMP_TABLES;
790
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]|= CF_PREOPEN_TMP_TABLES;
791 792 793 794 795 796 797 798 799 800 801 802 803 804
  sql_command_flags[SQLCOM_CREATE_INDEX]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=     CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_TRUNCATE]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_LOAD]|=            CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DROP_INDEX]|=      CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_UPDATE]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_UPDATE_MULTI]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_INSERT_SELECT]|=   CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DELETE]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DELETE_MULTI]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_REPLACE_SELECT]|=  CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_SELECT]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_SET_OPTION]|=      CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_DO]|=              CF_PREOPEN_TMP_TABLES;
unknown's avatar
unknown committed
805
  sql_command_flags[SQLCOM_HA_OPEN]|=         CF_PREOPEN_TMP_TABLES;
806 807 808 809 810 811 812 813 814 815 816 817 818
  sql_command_flags[SQLCOM_CALL]|=            CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CHECKSUM]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ANALYZE]|=         CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_CHECK]|=           CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_OPTIMIZE]|=        CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_REPAIR]|=          CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_PRELOAD_KEYS]|=    CF_PREOPEN_TMP_TABLES;
  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_PREOPEN_TMP_TABLES;

  /*
    DDL statements that should start with closing opened handlers.

    We use this flag only for statements for which open HANDLERs
Michael Widenius's avatar
Michael Widenius committed
819
    have to be closed before temporary tables are pre-opened.
820 821
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=    CF_HA_CLOSE;
822
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]|= CF_HA_CLOSE;
823
  sql_command_flags[SQLCOM_DROP_TABLE]|=      CF_HA_CLOSE;
824
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|=   CF_HA_CLOSE;
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
  sql_command_flags[SQLCOM_ALTER_TABLE]|=     CF_HA_CLOSE;
  sql_command_flags[SQLCOM_TRUNCATE]|=        CF_HA_CLOSE;
  sql_command_flags[SQLCOM_REPAIR]|=          CF_HA_CLOSE;
  sql_command_flags[SQLCOM_OPTIMIZE]|=        CF_HA_CLOSE;
  sql_command_flags[SQLCOM_ANALYZE]|=         CF_HA_CLOSE;
  sql_command_flags[SQLCOM_CHECK]|=           CF_HA_CLOSE;
  sql_command_flags[SQLCOM_CREATE_INDEX]|=    CF_HA_CLOSE;
  sql_command_flags[SQLCOM_DROP_INDEX]|=      CF_HA_CLOSE;
  sql_command_flags[SQLCOM_PRELOAD_KEYS]|=    CF_HA_CLOSE;
  sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|=  CF_HA_CLOSE;

  /*
    Mark statements that always are disallowed in read-only
    transactions. Note that according to the SQL standard,
    even temporary table DDL should be disallowed.
  */
  sql_command_flags[SQLCOM_CREATE_TABLE]|=     CF_DISALLOW_IN_RO_TRANS;
842
  sql_command_flags[SQLCOM_CREATE_SEQUENCE]|=  CF_DISALLOW_IN_RO_TRANS;
843 844
  sql_command_flags[SQLCOM_ALTER_TABLE]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_TABLE]|=       CF_DISALLOW_IN_RO_TRANS;
845
  sql_command_flags[SQLCOM_DROP_SEQUENCE]|=    CF_DISALLOW_IN_RO_TRANS;
846 847 848 849 850
  sql_command_flags[SQLCOM_RENAME_TABLE]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_INDEX]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_INDEX]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_DB]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_DB]|=          CF_DISALLOW_IN_RO_TRANS;
851 852 853 854
  sql_command_flags[SQLCOM_CREATE_PACKAGE]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_PACKAGE_BODY]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PACKAGE_BODY]|= CF_DISALLOW_IN_RO_TRANS;
855 856 857 858 859 860 861 862 863 864
  sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_DB]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_VIEW]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_VIEW]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_TRIGGER]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_TRIGGER]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_EVENT]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_EVENT]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_EVENT]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_USER]|=      CF_DISALLOW_IN_RO_TRANS;
865
  sql_command_flags[SQLCOM_ALTER_USER]|=       CF_DISALLOW_IN_RO_TRANS;
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
  sql_command_flags[SQLCOM_RENAME_USER]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_USER]|=        CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_SERVER]|=    CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_SERVER]|=     CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_SERVER]|=      CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_FUNCTION]|=  CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_CREATE_SPFUNCTION]|=CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_PROCEDURE]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_DROP_FUNCTION]|=    CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_PROCEDURE]|=  CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_ALTER_FUNCTION]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_TRUNCATE]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REPAIR]|=           CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_OPTIMIZE]|=         CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_GRANT]|=            CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REVOKE]|=           CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_REVOKE_ALL]|=       CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_INSTALL_PLUGIN]|=   CF_DISALLOW_IN_RO_TRANS;
  sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS;
Brave Galera Crew's avatar
Brave Galera Crew committed
886 887 888 889 890 891 892 893 894 895
#ifdef WITH_WSREP
  /*
    Statements for which some errors are ignored when
    wsrep_ignore_apply_errors = WSREP_IGNORE_ERRORS_ON_RECONCILING_DDL
  */
  sql_command_flags[SQLCOM_DROP_DB]|=          CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_DROP_TABLE]|=       CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_DROP_INDEX]|=       CF_WSREP_MAY_IGNORE_ERRORS;
  sql_command_flags[SQLCOM_ALTER_TABLE]|=      CF_WSREP_MAY_IGNORE_ERRORS;
#endif /* WITH_WSREP */
896 897
}

898 899 900 901 902 903
bool sqlcom_can_generate_row_events(const THD *thd)
{
  return (sql_command_flags[thd->lex->sql_command] &
          CF_CAN_GENERATE_ROW_EVENTS);
}
 
unknown's avatar
unknown committed
904 905
bool is_update_query(enum enum_sql_command command)
{
906
  DBUG_ASSERT(command <= SQLCOM_END);
907
  return (sql_command_flags[command] & CF_CHANGES_DATA) != 0;
unknown's avatar
unknown committed
908
}
909

910 911 912 913 914 915 916
/**
  Check if a sql command is allowed to write to log tables.
  @param command The SQL command
  @return true if writing is allowed
*/
bool is_log_table_write_query(enum enum_sql_command command)
{
917
  DBUG_ASSERT(command <= SQLCOM_END);
918 919
  return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0;
}
920

921
void execute_init_command(THD *thd, LEX_STRING *init_command,
Marc Alff's avatar
Marc Alff committed
922
                          mysql_rwlock_t *var_lock)
unknown's avatar
unknown committed
923 924
{
  Vio* save_vio;
925
  ulonglong save_client_capabilities;
unknown's avatar
unknown committed
926

Marc Alff's avatar
Marc Alff committed
927
  mysql_rwlock_rdlock(var_lock);
928 929
  if (!init_command->length)
  {
Marc Alff's avatar
Marc Alff committed
930
    mysql_rwlock_unlock(var_lock);
931 932 933 934 935 936 937 938 939 940
    return;
  }

  /*
    copy the value under a lock, and release the lock.
    init_command has to be executed without a lock held,
    as it may try to change itself
  */
  size_t len= init_command->length;
  char *buf= thd->strmake(init_command->str, len);
Marc Alff's avatar
Marc Alff committed
941
  mysql_rwlock_unlock(var_lock);
942

Sergei Golubchik's avatar
Sergei Golubchik committed
943
  THD_STAGE_INFO(thd, stage_execution_of_init_command);
unknown's avatar
unknown committed
944 945
  save_client_capabilities= thd->client_capabilities;
  thd->client_capabilities|= CLIENT_MULTI_QUERIES;
946 947 948 949
  /*
    We don't need return result of execution to client side.
    To forbid this we should set thd->net.vio to 0.
  */
unknown's avatar
unknown committed
950 951
  save_vio= thd->net.vio;
  thd->net.vio= 0;
952
  thd->clear_error(1);
953
  dispatch_command(COM_QUERY, thd, buf, (uint)len);
unknown's avatar
unknown committed
954 955
  thd->client_capabilities= save_client_capabilities;
  thd->net.vio= save_vio;
956

unknown's avatar
unknown committed
957 958 959
}


960
static char *fgets_fn(char *buffer, size_t size, fgets_input_t input, int *error)
961 962
{
  MYSQL_FILE *in= static_cast<MYSQL_FILE*> (input);
963
  char *line= mysql_file_fgets(buffer, (int)size, in);
964
  if (unlikely(error))
965 966
    *error= (line == NULL) ? ferror(in->m_file) : 0;
  return line;
967 968 969
}


Sergey Vojtovich's avatar
Sergey Vojtovich committed
970
int bootstrap(MYSQL_FILE *file)
unknown's avatar
unknown committed
971
{
Sergey Vojtovich's avatar
Sergey Vojtovich committed
972
  int bootstrap_error= 0;
973 974 975
  DBUG_ENTER("handle_bootstrap");

  THD *thd= new THD(next_thread_id());
976
  char *buffer= new char[MAX_BOOTSTRAP_QUERY_SIZE];
977 978 979 980 981 982
#ifdef WITH_WSREP
  thd->variables.wsrep_on= 0;
#endif
  thd->bootstrap=1;
  my_net_init(&thd->net,(st_vio*) 0, thd, MYF(0));
  thd->max_client_packet_length= thd->net.max_packet;
983
  thd->security_ctx->master_access= ALL_KNOWN_ACL;
984

unknown's avatar
unknown committed
985
#ifndef EMBEDDED_LIBRARY
986 987 988 989 990 991
  mysql_thread_set_psi_id(thd->thread_id);
#else
  thd->mysql= 0;
#endif

  /* The following must be called before DBUG_ENTER */
992
  thd->thread_stack= (char*) &thd;
993
  thd->store_globals();
unknown's avatar
unknown committed
994

995 996
  thd->security_ctx->user= (char*) my_strdup(key_memory_MPVIO_EXT_auth_info,
                                             "boot", MYF(MY_WME));
Sergei Golubchik's avatar
Sergei Golubchik committed
997 998
  thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]=
    thd->security_ctx->priv_role[0]= 0;
999 1000 1001 1002 1003 1004
  /*
    Make the "client" handle multiple results. This is necessary
    to enable stored procedures with SELECTs and Dynamic SQL
    in init-file.
  */
  thd->client_capabilities|= CLIENT_MULTI_RESULTS;
unknown's avatar
unknown committed
1005

1006
  thd->init_for_queries();
1007 1008

  for ( ; ; )
unknown's avatar
unknown committed
1009
  {
1010
    buffer[0]= 0;
1011
    int rc, length;
Marc Alff's avatar
Marc Alff committed
1012
    char *query;
1013
    int error= 0;
1014

1015
    rc= read_bootstrap_query(buffer, &length, file, fgets_fn, 0, &error);
1016

1017 1018 1019 1020 1021 1022 1023
    if (rc == READ_BOOTSTRAP_EOF)
      break;
    /*
      Check for bootstrap file errors. SQL syntax errors will be
      caught below.
    */
    if (rc != READ_BOOTSTRAP_SUCCESS)
1024
    {
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
      /*
        mysql_parse() may have set a successful error status for the previous
        query. We must clear the error status to report the bootstrap error.
      */
      thd->get_stmt_da()->reset_diagnostics_area();

      /* Get the nearest query text for reference. */
      char *err_ptr= buffer + (length <= MAX_BOOTSTRAP_ERROR_LEN ?
                                        0 : (length - MAX_BOOTSTRAP_ERROR_LEN));
      switch (rc)
      {
      case READ_BOOTSTRAP_ERROR:
        my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error, return code (%d). "
                        "Nearest query: '%s'", MYF(0), error, err_ptr);
        break;

      case READ_BOOTSTRAP_QUERY_SIZE:
1042
        my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error. Query size "
1043
                        "exceeded %d bytes near '%s'.", MYF(0),
1044
                        MAX_BOOTSTRAP_QUERY_SIZE, err_ptr);
1045 1046 1047 1048 1049 1050 1051
        break;

      default:
        DBUG_ASSERT(false);
        break;
      }

1052 1053 1054
      thd->protocol->end_statement();
      bootstrap_error= 1;
      break;
1055
    }
unknown's avatar
unknown committed
1056

1057
    query= (char *) thd->memdup_w_gap(buffer, length + 1,
1058
                                      thd->db.length + 1 +
1059
                                      QUERY_CACHE_DB_LENGTH_SIZE +
Gleb Shchepa's avatar
Gleb Shchepa committed
1060
                                      QUERY_CACHE_FLAGS_SIZE);
1061 1062
    size_t db_len= 0;
    memcpy(query + length + 1, (char *) &db_len, sizeof(size_t));
1063
    thd->set_query_and_id(query, length, thd->charset(), next_query_id());
1064
    int2store(query + length + 1, 0);           // No db in bootstrap
1065
    DBUG_PRINT("query",("%-.4096s",thd->query()));
1066
#if defined(ENABLED_PROFILING)
1067
    thd->profiling.start_new_query();
1068
    thd->profiling.set_query_source(thd->query(), length);
1069 1070
#endif

1071
    thd->set_time();
1072 1073 1074 1075 1076 1077 1078 1079
    Parser_state parser_state;
    if (parser_state.init(thd, thd->query(), length))
    {
      thd->protocol->end_statement();
      bootstrap_error= 1;
      break;
    }

1080
    mysql_parse(thd, thd->query(), length, &parser_state);
1081

1082
    bootstrap_error= thd->is_error();
1083
    thd->protocol->end_statement();
1084

1085
#if defined(ENABLED_PROFILING)
1086 1087
    thd->profiling.finish_current_query();
#endif
1088
    delete_explain_query(thd->lex);
1089

1090
    if (unlikely(bootstrap_error))
1091 1092
      break;

1093
    thd->reset_kill_query();  /* Ensure that killed_errmsg is released */
unknown's avatar
unknown committed
1094
    free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
1095
    thd->lex->restore_set_statement_var();
unknown's avatar
unknown committed
1096
  }
1097
  delete thd;
1098
  delete[] buffer;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1099
  DBUG_RETURN(bootstrap_error);
unknown's avatar
unknown committed
1100 1101
}

1102

1103
/* This works because items are allocated on THD::mem_root */
unknown's avatar
unknown committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

void free_items(Item *item)
{
  Item *next;
  DBUG_ENTER("free_items");
  for (; item ; item=next)
  {
    next=item->next;
    item->delete_self();
  }
  DBUG_VOID_RETURN;
}

1117
/**
1118
   This works because items are allocated on THD::mem_root.
1119 1120
   @note The function also handles null pointers (empty list).
*/
1121 1122
void cleanup_items(Item *item)
{
unknown's avatar
unknown committed
1123
  DBUG_ENTER("cleanup_items");  
1124 1125
  for (; item ; item=item->next)
    item->cleanup();
unknown's avatar
unknown committed
1126
  DBUG_VOID_RETURN;
1127 1128
}

1129 1130 1131
#ifdef WITH_WSREP
static bool wsrep_tables_accessible_when_detached(const TABLE_LIST *tables)
{
1132
  for (const TABLE_LIST *t= tables; t; t= t->next_global)
1133
  {
1134
    if (get_table_category(t->db, t->table_name) < TABLE_CATEGORY_INFORMATION)
1135 1136
      return false;
  }
Jan Lindström's avatar
Jan Lindström committed
1137
  return tables != NULL;
1138
}
1139 1140 1141

static bool wsrep_command_no_result(char command)
{
1142
  return (command == COM_STMT_FETCH            ||
1143 1144 1145
          command == COM_STMT_SEND_LONG_DATA   ||
          command == COM_STMT_CLOSE);
}
1146 1147
#endif /* WITH_WSREP */
#ifndef EMBEDDED_LIBRARY
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
static enum enum_server_command fetch_command(THD *thd, char *packet)
{
  enum enum_server_command
    command= (enum enum_server_command) (uchar) packet[0];
  DBUG_ENTER("fetch_command");

  if (command >= COM_END ||
      (command >= COM_MDB_GAP_BEG && command <= COM_MDB_GAP_END))
    command= COM_END;				// Wrong command

  DBUG_PRINT("info",("Command on %s = %d (%s)",
Michael Widenius's avatar
Michael Widenius committed
1159
                     vio_description(thd->net.vio), command,
1160 1161 1162 1163
                     command_name[command].str));
  DBUG_RETURN(command);
}

unknown's avatar
unknown committed
1164
/**
unknown's avatar
unknown committed
1165
  Read one command from connection and execute it (query or simple command).
1166 1167
  This function is to be used by different schedulers (one-thread-per-connection,
  pool-of-threads)
1168 1169 1170

  For profiling to work, it must never be called recursively.

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
  @param thd - client connection context

  @param blocking - wait for command to finish.
                    if false (nonblocking), then the function might
                    return when command is "half-finished", with
                    DISPATCH_COMMAND_WOULDBLOCK.
                    Currenly, this can *only* happen when using
                    threadpool. The command will resume, after all outstanding
                    async operations (i.e group commit) finish.
                    Threadpool scheduler takes care of "resume".

  @retval
    DISPATCH_COMMAND_SUCCESS - success
unknown's avatar
unknown committed
1184
  @retval
1185 1186
    DISPATCH_COMMAND_CLOSE_CONNECTION  request of THD shutdown
          (s. dispatch_command() description)
unknown's avatar
unknown committed
1187
  @retval
1188
    DISPATCH_COMMAND_WOULDBLOCK - need to wait for asynchronous operations
1189 1190
                                  to finish. Only returned if parameter
                                  'blocking' is false.
1191 1192
*/

1193
dispatch_command_return do_command(THD *thd, bool blocking)
unknown's avatar
unknown committed
1194
{
1195
  dispatch_command_return return_value;
unknown's avatar
unknown committed
1196
  char *packet= 0;
unknown's avatar
unknown committed
1197
  ulong packet_length;
unknown's avatar
unknown committed
1198
  NET *net= &thd->net;
unknown's avatar
unknown committed
1199 1200 1201
  enum enum_server_command command;
  DBUG_ENTER("do_command");

1202
#ifdef WITH_WSREP
1203
  DBUG_ASSERT(!thd->async_state.pending_ops() ||
1204 1205 1206 1207 1208 1209
              (WSREP(thd) &&
               thd->wsrep_trx().state() == wsrep::transaction::s_aborted));
#else
  DBUG_ASSERT(!thd->async_state.pending_ops());
#endif

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
  if (thd->async_state.m_state == thd_async_state::enum_async_state::RESUMED)
  {
    /*
     Resuming previously suspended command.
     Restore the state
    */
    command = thd->async_state.m_command;
    packet = thd->async_state.m_packet.str;
    packet_length = (ulong)thd->async_state.m_packet.length;
    goto resume;
  }

unknown's avatar
unknown committed
1222 1223 1224 1225
  /*
    indicator of uninitialized lex => normal flow of errors handling
    (see my_message_sql)
  */
1226
  thd->lex->current_select= 0;
unknown's avatar
unknown committed
1227

unknown's avatar
unknown committed
1228 1229 1230 1231
  /*
    This thread will do a blocking read from the client which
    will be interrupted when the next command is received from
    the client, the connection is closed or "net_wait_timeout"
1232
    number of seconds has passed.
unknown's avatar
unknown committed
1233
  */
1234 1235
  if (!thd->skip_wait_timeout)
    my_net_set_read_timeout(net, thd->get_net_wait_timeout());
1236

1237 1238
  /* Errors and diagnostics are cleared once here before query */
  thd->clear_error(1);
unknown's avatar
unknown committed
1239 1240

  net_new_transaction(net);
1241

1242 1243
  /* Save for user statistics */
  thd->start_bytes_received= thd->status_var.bytes_received;
Sergei Golubchik's avatar
Sergei Golubchik committed
1244

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
  /*
    Synchronization point for testing of KILL_CONNECTION.
    This sync point can wait here, to simulate slow code execution
    between the last test of thd->killed and blocking in read().

    The goal of this test is to verify that a connection does not
    hang, if it is killed at this point of execution.
    (Bug#37780 - main.kill fails randomly)

    Note that the sync point wait itself will be terminated by a
    kill. In this case it consumes a condition broadcast, but does
    not change anything else. The consumed broadcast should not
    matter here, because the read/recv() below doesn't use it.
  */
  DEBUG_SYNC(thd, "before_do_command_net_read");

1261
  packet_length= my_net_read_packet(net, 1);
1262

1263
  if (unlikely(packet_length == packet_error))
unknown's avatar
unknown committed
1264
  {
1265 1266 1267
    DBUG_PRINT("info",("Got error %d reading command from socket %s",
		       net->error,
		       vio_description(net->vio)));
1268

1269 1270 1271 1272 1273 1274
    /* Instrument this broken statement as "statement/com/error" */
    thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                                 com_statement_info[COM_END].
                                                 m_key);


1275
    /* Check if we can continue without closing the connection */
1276

1277 1278
    /* The error must be set. */
    DBUG_ASSERT(thd->is_error());
1279
    thd->protocol->end_statement();
1280

1281 1282 1283
    /* Mark the statement completed. */
    MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
    thd->m_statement_psi= NULL;
Sergei Golubchik's avatar
Sergei Golubchik committed
1284
    thd->m_digest= NULL;
1285

1286
    if (net->error != 3)
1287
    {
1288
      return_value= DISPATCH_COMMAND_CLOSE_CONNECTION;     // We have to close it.
1289 1290
      goto out;
    }
1291

1292
    net->error= 0;
1293
    return_value= DISPATCH_COMMAND_SUCCESS;
1294
    goto out;
unknown's avatar
unknown committed
1295
  }
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

  packet= (char*) net->read_pos;
  /*
    'packet_length' contains length of data, as it was stored in packet
    header. In case of malformed header, my_net_read returns zero.
    If packet_length is not zero, my_net_read ensures that the returned
    number of bytes was actually read from network.
    There is also an extra safety measure in my_net_read:
    it sets packet[packet_length]= 0, but only for non-zero packets.
  */
  if (packet_length == 0)                       /* safety */
unknown's avatar
unknown committed
1307
  {
1308 1309 1310
    /* Initialize with COM_SLEEP packet */
    packet[0]= (uchar) COM_SLEEP;
    packet_length= 1;
unknown's avatar
unknown committed
1311
  }
1312 1313 1314 1315
  /* Do not rely on my_net_read, extra safety against programming errors. */
  packet[packet_length]= '\0';                  /* safety */


1316
  command= fetch_command(thd, packet);
unknown's avatar
unknown committed
1317

1318
#ifdef WITH_WSREP
1319
  DEBUG_SYNC(thd, "wsrep_before_before_command");
Brave Galera Crew's avatar
Brave Galera Crew committed
1320
  /*
1321 1322 1323 1324 1325
    If this command does not return a result, then we
    instruct wsrep_before_command() to skip result handling.
    This causes BF aborted transaction to roll back but keep
    the error state until next command which is able to return
    a result to the client.
Brave Galera Crew's avatar
Brave Galera Crew committed
1326
  */
Marko Mäkelä's avatar
Marko Mäkelä committed
1327 1328
  if (unlikely(wsrep_service_started) &&
      wsrep_before_command(thd, wsrep_command_no_result(command)))
Brave Galera Crew's avatar
Brave Galera Crew committed
1329
  {
1330 1331 1332 1333 1334 1335
    /*
      Aborted by background rollbacker thread.
      Handle error here and jump straight to out.
      Notice that thd->store_globals() is called
      in wsrep_before_command().
    */
Brave Galera Crew's avatar
Brave Galera Crew committed
1336
    WSREP_LOG_THD(thd, "enter found BF aborted");
1337
    DBUG_ASSERT(!thd->mdl_context.has_transactional_locks());
Brave Galera Crew's avatar
Brave Galera Crew committed
1338 1339
    DBUG_ASSERT(!thd->get_stmt_da()->is_set());
    /* We let COM_QUIT and COM_STMT_CLOSE to execute even if wsrep aborted. */
1340 1341 1342 1343 1344 1345 1346
    if (command == COM_STMT_EXECUTE)
    {
      WSREP_DEBUG("PS BF aborted at do_command");
      thd->wsrep_delayed_BF_abort= true;
    }
    if (command != COM_STMT_CLOSE   &&
	command != COM_STMT_EXECUTE &&
Brave Galera Crew's avatar
Brave Galera Crew committed
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        command != COM_QUIT)
    {
      my_error(ER_LOCK_DEADLOCK, MYF(0));
      WSREP_DEBUG("Deadlock error for: %s", thd->query());
      thd->reset_killed();
      thd->mysys_var->abort     = 0;
      thd->wsrep_retry_counter  = 0;

      /* Instrument this broken statement as "statement/com/error" */
      thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                                 com_statement_info[COM_END].
                                                 m_key);

      thd->protocol->end_statement();

      /* Mark the statement completed. */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
      thd->m_digest= NULL;
1366
      return_value= DISPATCH_COMMAND_SUCCESS;
Brave Galera Crew's avatar
Brave Galera Crew committed
1367 1368 1369 1370 1371 1372

      wsrep_after_command_before_result(thd);
      goto out;
    }
  }

1373
  if (WSREP(thd))
1374
  {
1375
    /*
Brave Galera Crew's avatar
Brave Galera Crew committed
1376 1377 1378 1379 1380
     * bail out if DB snapshot has not been installed. We however,
     * allow queries "SET" and "SHOW", they are trapped later in execute_command
     */
    if (!(thd->wsrep_applier) &&
        (!wsrep_ready_get() || wsrep_reject_queries != WSREP_REJECT_NONE) &&
1381
        (server_command_flags[command] & CF_SKIP_WSREP_CHECK) == 0)
1382
    {
1383 1384
      my_message(ER_UNKNOWN_COM_ERROR,
                 "WSREP has not yet prepared node for application use", MYF(0));
1385
      thd->protocol->end_statement();
1386

1387 1388 1389 1390
      /* Performance Schema Interface instrumentation end. */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
      thd->m_digest= NULL;
1391

1392
      return_value= DISPATCH_COMMAND_SUCCESS;
Brave Galera Crew's avatar
Brave Galera Crew committed
1393
      wsrep_after_command_before_result(thd);
1394 1395
      goto out;
    }
1396
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1397
#endif /* WITH_WSREP */
unknown's avatar
unknown committed
1398
  /* Restore read timeout value */
1399
  my_net_set_read_timeout(net, thd->variables.net_read_timeout);
unknown's avatar
unknown committed
1400

1401
  DBUG_ASSERT(packet_length);
1402
  DBUG_ASSERT(!thd->apc_target.is_enabled());
1403 1404

resume:
1405
  return_value= dispatch_command(command, thd, packet+1,
1406 1407 1408 1409 1410 1411 1412 1413 1414
                                 (uint) (packet_length-1), blocking);
  if (return_value == DISPATCH_COMMAND_WOULDBLOCK)
  {
    /* Save current state, and resume later.*/
    thd->async_state.m_command= command;
    thd->async_state.m_packet={packet,packet_length};
    DBUG_RETURN(return_value);
  }

1415
  DBUG_ASSERT(!thd->apc_target.is_enabled());
1416 1417

out:
1418
  thd->lex->restore_set_statement_var();
1419
  /* The statement instrumentation must be closed in all cases. */
Sergei Golubchik's avatar
Sergei Golubchik committed
1420
  DBUG_ASSERT(thd->m_digest == NULL);
1421
  DBUG_ASSERT(thd->m_statement_psi == NULL);
Brave Galera Crew's avatar
Brave Galera Crew committed
1422 1423 1424 1425
#ifdef WITH_WSREP
  if (packet_length != packet_error)
  {
    /* there was a command to process, and before_command() has been called */
1426 1427
    if (unlikely(wsrep_service_started))
      wsrep_after_command_after_result(thd);
Brave Galera Crew's avatar
Brave Galera Crew committed
1428
  }
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

  if (thd->wsrep_delayed_BF_abort)
  {
      my_error(ER_LOCK_DEADLOCK, MYF(0));
      WSREP_DEBUG("Deadlock error for PS query: %s", thd->query());
      thd->reset_killed();
      thd->mysys_var->abort     = 0;
      thd->wsrep_retry_counter  = 0;

      thd->wsrep_delayed_BF_abort= false;
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1440
#endif /* WITH_WSREP */
1441
  DBUG_RETURN(return_value);
1442
}
1443
#endif  /* EMBEDDED_LIBRARY */
1444

1445 1446 1447 1448 1449 1450
/**
  @brief Determine if an attempt to update a non-temporary table while the
    read-only option was enabled has been made.

  This is a helper function to mysql_execute_command.

1451
  @note SQLCOM_MULTI_UPDATE is an exception and dealt with elsewhere.
1452 1453 1454 1455 1456 1457 1458

  @see mysql_execute_command
  @returns Status code
    @retval TRUE The statement should be denied.
    @retval FALSE The statement isn't updating any relevant tables.
*/

1459
static bool deny_updates_if_read_only_option(THD *thd, TABLE_LIST *all_tables)
1460 1461 1462 1463 1464 1465 1466 1467
{
  DBUG_ENTER("deny_updates_if_read_only_option");

  if (!opt_readonly)
    DBUG_RETURN(FALSE);

  LEX *lex= thd->lex;

1468
  /* Super user is allowed to do changes */
1469
  if ((thd->security_ctx->master_access & PRIV_IGNORE_READ_ONLY) != NO_ACL)
1470 1471
    DBUG_RETURN(FALSE);

1472
  /* Check if command doesn't update anything */
1473
  if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA))
1474 1475 1476 1477 1478 1479
    DBUG_RETURN(FALSE);

  /* Multi update is an exception and is dealt with later. */
  if (lex->sql_command == SQLCOM_UPDATE_MULTI)
    DBUG_RETURN(FALSE);

1480 1481 1482 1483
  /*
    a table-to-be-created is not in the temp table list yet,
    so CREATE TABLE needs a special treatment
  */
1484 1485
  if (lex->sql_command == SQLCOM_CREATE_TABLE)
    DBUG_RETURN(!lex->tmp_table());
1486

1487 1488 1489 1490
  /*
    a table-to-be-dropped might not exist (DROP TEMPORARY TABLE IF EXISTS),
    cannot use the temp table list either.
  */
1491
  if (lex->sql_command == SQLCOM_DROP_TABLE && lex->tmp_table())
1492
    DBUG_RETURN(FALSE);
1493

1494
  /* Check if we created, dropped, or renamed a database */
1495 1496
  if ((sql_command_flags[lex->sql_command] & CF_DB_CHANGE))
    DBUG_RETURN(TRUE);
1497

1498 1499
  if (some_non_temp_table_to_be_updated(thd, all_tables))
    DBUG_RETURN(TRUE);
1500 1501 1502 1503

  /* Assuming that only temporary tables are modified. */
  DBUG_RETURN(FALSE);
}
1504

Brave Galera Crew's avatar
Brave Galera Crew committed
1505 1506 1507 1508 1509 1510 1511 1512
#ifdef WITH_WSREP
static void wsrep_copy_query(THD *thd)
{
  thd->wsrep_retry_command   = thd->get_command();
  thd->wsrep_retry_query_len = thd->query_length();
  if (thd->wsrep_retry_query) {
      my_free(thd->wsrep_retry_query);
  }
1513
  thd->wsrep_retry_query = (char *)my_malloc(PSI_INSTRUMENT_ME,
Brave Galera Crew's avatar
Brave Galera Crew committed
1514 1515 1516 1517 1518
                                 thd->wsrep_retry_query_len + 1, MYF(0));
  strncpy(thd->wsrep_retry_query, thd->query(), thd->wsrep_retry_query_len);
  thd->wsrep_retry_query[thd->wsrep_retry_query_len] = '\0';
}
#endif /* WITH_WSREP */
1519

1520 1521


1522 1523 1524 1525 1526 1527 1528
#if defined(WITH_ARIA_STORAGE_ENGINE)
class Silence_all_errors : public Internal_error_handler
{
  char m_message[MYSQL_ERRMSG_SIZE];
  int error;
public:
  Silence_all_errors():error(0) {}
1529
  ~Silence_all_errors() override {}
1530

1531
  bool handle_condition(THD *thd,
1532 1533 1534 1535
                                uint sql_errno,
                                const char* sql_state,
                                Sql_condition::enum_warning_level *level,
                                const char* msg,
1536
                                Sql_condition ** cond_hdl) override
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
  {
    error= sql_errno;
    *cond_hdl= NULL;
    strmake_buf(m_message, msg);
    return true;                              // Error handled
  }
};
#endif


unknown's avatar
unknown committed
1547 1548
/**
  Perform one connection-level (COM_XXXX) command.
1549

unknown's avatar
unknown committed
1550 1551 1552 1553 1554 1555
  @param command         type of command to perform
  @param thd             connection handle
  @param packet          data for the command, packet is always null-terminated
  @param packet_length   length of packet + 1 (to show that data is
                         null-terminated) except for COM_SLEEP, where it
                         can be zero.
1556 1557 1558 1559 1560 1561 1562
  @param blocking        if false (nonblocking), then the function might
                         return when command is "half-finished", with
                         DISPATCH_COMMAND_WOULDBLOCK.
                         Currenly, this can *only* happen when using threadpool.
                         The current command will resume, after all outstanding
                         async operations (i.e group commit) finish.
                         Threadpool scheduler takes care of "resume".
unknown's avatar
unknown committed
1563 1564

  @todo
1565 1566 1567
    set thd->lex->sql_command to SQLCOM_END here.
  @todo
    The following has to be changed to an 8 byte integer
unknown's avatar
unknown committed
1568 1569

  @retval
1570
    0   ok
unknown's avatar
unknown committed
1571
  @retval
1572 1573 1574
    1   request of thread shutdown, i. e. if command is
        COM_QUIT/COM_SHUTDOWN
*/
1575 1576
dispatch_command_return dispatch_command(enum enum_server_command command, THD *thd,
		      char* packet, uint packet_length, bool blocking)
1577 1578
{
  NET *net= &thd->net;
1579
  bool error= 0;
1580
  bool do_end_of_statement= true;
1581
  DBUG_ENTER("dispatch_command");
1582 1583 1584 1585 1586 1587
  DBUG_PRINT("info", ("command: %d %s", command,
                      (command_name[command].str != 0 ?
                       command_name[command].str :
                       "<?>")));
  bool drop_more_results= 0;

1588 1589 1590 1591 1592 1593
  if (thd->async_state.m_state == thd_async_state::enum_async_state::RESUMED)
  {
    thd->async_state.m_state = thd_async_state::enum_async_state::NONE;
    goto resume;
  }

1594 1595
  /* keep it withing 1 byte */
  compile_time_assert(COM_END == 255);
1596

Konstantin Osipov's avatar
Konstantin Osipov committed
1597 1598 1599
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query();
#endif
1600
  MYSQL_COMMAND_START(thd->thread_id, command,
1601
                      &thd->security_ctx->priv_user[0],
1602 1603
                      (char *) thd->security_ctx->host_or_ip);
  
1604 1605
  DBUG_EXECUTE_IF("crash_dispatch_command_before",
                  { DBUG_PRINT("crash_dispatch_command_before", ("now"));
1606
                    DBUG_SUICIDE(); });
1607

1608 1609 1610 1611
  /* Performance Schema Interface instrumentation, begin */
  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                               com_statement_info[command].
                                               m_key);
1612 1613 1614 1615 1616 1617 1618
  /*
    We should always call reset_for_next_command() before a query.
    mysql_parse() will do this for queries. Ensure it's also done
    for other commands.
  */
  if (command != COM_QUERY)
    thd->reset_for_next_command();
1619 1620
  thd->set_command(command);

1621
  thd->enable_slow_log= true;
1622
  thd->query_plan_flags= QPLAN_INIT;
1623
  thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */
1624
  thd->reset_kill_query();
1625 1626 1627

  DEBUG_SYNC(thd,"dispatch_command_before_set_time");

unknown's avatar
unknown committed
1628
  thd->set_time();
Konstantin Osipov's avatar
Konstantin Osipov committed
1629
  if (!(server_command_flags[command] & CF_SKIP_QUERY_ID))
Michael Widenius's avatar
Michael Widenius committed
1630 1631 1632 1633 1634 1635 1636 1637 1638
    thd->set_query_id(next_query_id());
  else
  {
    /*
      ping, get statistics or similar stateless command.
      No reason to increase query id here.
    */
    thd->set_query_id(get_query_id());
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
1639 1640 1641 1642
#ifdef WITH_WSREP
  if (WSREP(thd) && thd->wsrep_next_trx_id() == WSREP_UNDEFINED_TRX_ID)
  {
    thd->set_wsrep_next_trx_id(thd->query_id);
Marko Mäkelä's avatar
Marko Mäkelä committed
1643
    WSREP_DEBUG("assigned new next trx id: %" PRIu64, thd->wsrep_next_trx_id());
Brave Galera Crew's avatar
Brave Galera Crew committed
1644 1645
  }
#endif /* WITH_WSREP */
unknown's avatar
unknown committed
1646

Konstantin Osipov's avatar
Konstantin Osipov committed
1647 1648 1649
  if (!(server_command_flags[command] & CF_SKIP_QUESTIONS))
    statistic_increment(thd->status_var.questions, &LOCK_status);

1650 1651 1652 1653 1654 1655 1656 1657
  /* Copy data for user stats */
  if ((thd->userstat_running= opt_userstat_running))
  {
    thd->start_cpu_time= my_getcputime();
    memcpy(&thd->org_status_var, &thd->status_var, sizeof(thd->status_var));
    thd->select_commands= thd->update_commands= thd->other_commands= 0;
  }

1658 1659 1660 1661 1662
  /**
    Clear the set of flags that are expected to be cleared at the
    beginning of each command.
  */
  thd->server_status&= ~SERVER_STATUS_CLEAR_SET;
1663

1664 1665 1666
  if (unlikely(thd->security_ctx->password_expired &&
               command != COM_QUERY &&
               command != COM_PING &&
1667 1668
               command != COM_QUIT &&
               command != COM_STMT_PREPARE &&
1669 1670
               command != COM_STMT_EXECUTE &&
               command != COM_STMT_CLOSE))
1671 1672 1673 1674 1675
  {
    my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
    goto dispatch_end;
  }

1676
  switch (command) {
unknown's avatar
unknown committed
1677
  case COM_INIT_DB:
unknown's avatar
unknown committed
1678
  {
1679
    LEX_CSTRING tmp;
1680
    status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]);
1681 1682
    if (unlikely(thd->copy_with_error(system_charset_info, (LEX_STRING*) &tmp,
                                      thd->charset(), packet, packet_length)))
1683
      break;
unknown's avatar
unknown committed
1684
    if (!mysql_change_db(thd, &tmp, FALSE))
1685
    {
1686
      general_log_write(thd, command, thd->db.str, thd->db.length);
1687
      my_ok(thd);
1688
    }
unknown's avatar
unknown committed
1689 1690
    break;
  }
unknown's avatar
unknown committed
1691
#ifdef HAVE_REPLICATION
1692 1693
  case COM_REGISTER_SLAVE:
  {
Monty's avatar
Monty committed
1694
    status_var_increment(thd->status_var.com_register_slave);
Sergey Vojtovich's avatar
Sergey Vojtovich committed
1695
    if (!thd->register_slave((uchar*) packet, packet_length))
1696
      my_ok(thd);
1697 1698
    break;
  }
1699
#endif
1700 1701 1702
  case COM_RESET_CONNECTION:
  {
    thd->status_var.com_other++;
1703
#ifdef WITH_WSREP
1704 1705 1706 1707 1708
    if (unlikely(wsrep_service_started))
    {
      wsrep_after_command_ignore_result(thd);
      wsrep_close(thd);
    }
1709
#endif /* WITH_WSREP */
1710 1711
    thd->change_user();
    thd->clear_error();                         // if errors from rollback
1712
#ifdef WITH_WSREP
1713 1714 1715 1716 1717
    if (unlikely(wsrep_service_started))
    {
      wsrep_open(thd);
      wsrep_before_command(thd);
    }
1718
#endif /* WITH_WSREP */
1719 1720 1721
    /* Restore original charset from client authentication packet.*/
    if(thd->org_charset)
      thd->update_charset(thd->org_charset,thd->org_charset,thd->org_charset);
1722 1723 1724
    my_ok(thd, 0, 0, 0);
    break;
  }
unknown's avatar
unknown committed
1725 1726
  case COM_CHANGE_USER:
  {
unknown's avatar
unknown committed
1727
    int auth_rc;
1728
    status_var_increment(thd->status_var.com_other);
1729

1730
#ifdef WITH_WSREP
1731 1732 1733 1734 1735
    if (unlikely(wsrep_service_started))
    {
      wsrep_after_command_ignore_result(thd);
      wsrep_close(thd);
    }
1736
#endif /* WITH_WSREP */
unknown's avatar
unknown committed
1737
    thd->change_user();
1738
#ifdef WITH_WSREP
1739 1740 1741 1742 1743
    if (unlikely(wsrep_service_started))
    {
      wsrep_open(thd);
      wsrep_before_command(thd);
    }
1744
#endif /* WITH_WSREP */
1745
    thd->clear_error();                         // if errors from rollback
unknown's avatar
unknown committed
1746

1747 1748
    /* acl_authenticate() takes the data from net->read_pos */
    net->read_pos= (uchar*)packet;
1749

1750
    LEX_CSTRING save_db= thd->db;
1751
    USER_CONN *save_user_connect= thd->user_connect;
1752
    Security_context save_security_ctx= *thd->security_ctx;
1753 1754 1755 1756 1757 1758
    CHARSET_INFO *save_character_set_client=
      thd->variables.character_set_client;
    CHARSET_INFO *save_collation_connection=
      thd->variables.collation_connection;
    CHARSET_INFO *save_character_set_results=
      thd->variables.character_set_results;
1759

Michael Widenius's avatar
Michael Widenius committed
1760 1761
    /* Ensure we don't free security_ctx->user in case we have to revert */
    thd->security_ctx->user= 0;
1762
    thd->user_connect= 0;
1763

1764 1765 1766 1767 1768 1769
    /*
      to limit COM_CHANGE_USER ability to brute-force passwords,
      we only allow three unsuccessful COM_CHANGE_USER per connection.
    */
    if (thd->failed_com_change_user >= 3)
    {
1770 1771
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd,ER_UNKNOWN_COM_ERROR),
                 MYF(0));
unknown's avatar
unknown committed
1772
      auth_rc= 1;
1773 1774
    }
    else
1775
      auth_rc= acl_authenticate(thd, packet_length);
1776

1777
    mysql_audit_notify_connection_change_user(thd, &save_security_ctx);
unknown's avatar
unknown committed
1778
    if (auth_rc)
1779
    {
Michael Widenius's avatar
Michael Widenius committed
1780
      /* Free user if allocated by acl_authenticate */
1781
      my_free(const_cast<char*>(thd->security_ctx->user));
1782
      *thd->security_ctx= save_security_ctx;
1783 1784
      if (thd->user_connect)
	decrease_user_connections(thd->user_connect);
unknown's avatar
unknown committed
1785
      thd->user_connect= save_user_connect;
1786
      thd->reset_db(&save_db);
1787 1788
      thd->update_charset(save_character_set_client, save_collation_connection,
                          save_character_set_results);
1789 1790
      thd->failed_com_change_user++;
      my_sleep(1000000);
1791 1792 1793
    }
    else
    {
1794
#ifndef NO_EMBEDDED_ACCESS_CHECKS
1795
      /* we've authenticated new user */
unknown's avatar
unknown committed
1796 1797
      if (save_user_connect)
	decrease_user_connections(save_user_connect);
1798
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
1799
      my_free((char*) save_db.str);
1800
      my_free(const_cast<char*>(save_security_ctx.user));
1801
    }
unknown's avatar
unknown committed
1802 1803
    break;
  }
1804 1805 1806
  case COM_STMT_BULK_EXECUTE:
  {
    mysqld_stmt_bulk_execute(thd, packet, packet_length);
1807
#ifdef WITH_WSREP
1808
    if (WSREP(thd))
1809 1810 1811 1812
    {
        (void)wsrep_after_statement(thd);
    }
#endif /* WITH_WSREP */
1813 1814
    break;
  }
1815
  case COM_STMT_EXECUTE:
unknown's avatar
unknown committed
1816
  {
1817
    mysqld_stmt_execute(thd, packet, packet_length);
1818
#ifdef WITH_WSREP
1819
    if (WSREP(thd))
1820 1821 1822 1823
    {
        (void)wsrep_after_statement(thd);
    }
#endif /* WITH_WSREP */
unknown's avatar
unknown committed
1824 1825
    break;
  }
1826
  case COM_STMT_FETCH:
1827
  {
1828
    mysqld_stmt_fetch(thd, packet, packet_length);
1829 1830
    break;
  }
1831
  case COM_STMT_SEND_LONG_DATA:
unknown's avatar
unknown committed
1832
  {
1833
    mysql_stmt_get_longdata(thd, packet, packet_length);
unknown's avatar
unknown committed
1834 1835
    break;
  }
1836
  case COM_STMT_PREPARE:
unknown's avatar
unknown committed
1837
  {
1838
    mysqld_stmt_prepare(thd, packet, packet_length);
unknown's avatar
unknown committed
1839 1840
    break;
  }
1841
  case COM_STMT_CLOSE:
unknown's avatar
unknown committed
1842
  {
1843
    mysqld_stmt_close(thd, packet);
unknown's avatar
unknown committed
1844 1845
    break;
  }
1846
  case COM_STMT_RESET:
1847
  {
1848
    mysqld_stmt_reset(thd, packet);
1849 1850
    break;
  }
unknown's avatar
unknown committed
1851 1852
  case COM_QUERY:
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
1853 1854 1855 1856
    DBUG_ASSERT(thd->m_digest == NULL);
    thd->m_digest= & thd->m_digest_state;
    thd->m_digest->reset(thd->m_token_array, max_digest_length);

1857
    if (unlikely(alloc_query(thd, packet, packet_length)))
1858
      break;					// fatal error is set
1859
    MYSQL_QUERY_START(thd->query(), thd->thread_id,
1860
                      thd->get_db(),
1861
                      &thd->security_ctx->priv_user[0],
1862
                      (char *) thd->security_ctx->host_or_ip);
1863 1864 1865
    char *packet_end= thd->query() + thd->query_length();
    general_log_write(thd, command, thd->query(), thd->query_length());
    DBUG_PRINT("query",("%-.4096s",thd->query()));
1866
#if defined(ENABLED_PROFILING)
1867
    thd->profiling.set_query_source(thd->query(), thd->query_length());
1868
#endif
1869 1870 1871
    MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(),
                             thd->query_length());

1872
    Parser_state parser_state;
1873
    if (unlikely(parser_state.init(thd, thd->query(), thd->query_length())))
1874
      break;
1875

Brave Galera Crew's avatar
Brave Galera Crew committed
1876
#ifdef WITH_WSREP
1877
    if (WSREP(thd))
Brave Galera Crew's avatar
Brave Galera Crew committed
1878 1879
    {
      if (wsrep_mysql_parse(thd, thd->query(), thd->query_length(),
1880
                            &parser_state))
Brave Galera Crew's avatar
Brave Galera Crew committed
1881 1882 1883
      {
        WSREP_DEBUG("Deadlock error for: %s", thd->query());
        mysql_mutex_lock(&thd->LOCK_thd_data);
1884
        thd->reset_kill_query();
Brave Galera Crew's avatar
Brave Galera Crew committed
1885 1886 1887 1888 1889
        thd->wsrep_retry_counter  = 0;
        mysql_mutex_unlock(&thd->LOCK_thd_data);
        goto dispatch_end;
      }
    }
1890
    else
Brave Galera Crew's avatar
Brave Galera Crew committed
1891
#endif /* WITH_WSREP */
1892
      mysql_parse(thd, thd->query(), thd->query_length(), &parser_state);
1893

1894 1895
    while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) &&
           ! thd->is_error())
1896
    {
1897
      /*
1898
        Multiple queries exist, execute them individually
1899
      */
1900
      char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon;
1901

1902 1903
      /* Finalize server status flags after executing a statement. */
      thd->update_server_status();
1904 1905
      thd->protocol->end_statement();
      query_cache_end_of_result(thd);
1906 1907

      mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
Sergei Golubchik's avatar
Sergei Golubchik committed
1908 1909 1910 1911
                          thd->get_stmt_da()->is_error()
                            ? thd->get_stmt_da()->sql_errno()
                            : 0,
                          command_name[command].str);
1912

1913
      ulong length= (ulong)(packet_end - beginning_of_next_stmt);
1914

1915
      log_slow_statement(thd);
1916
      DBUG_ASSERT(!thd->apc_target.is_enabled());
1917

1918
      /* Remove garbage at start of query */
1919
      while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt))
1920
      {
1921
        beginning_of_next_stmt++;
1922 1923
        length--;
      }
1924

1925 1926 1927
      /* PSI end */
      MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
      thd->m_statement_psi= NULL;
Sergei Golubchik's avatar
Sergei Golubchik committed
1928
      thd->m_digest= NULL;
1929 1930

      /* DTRACE end */
1931 1932 1933 1934 1935
      if (MYSQL_QUERY_DONE_ENABLED())
      {
        MYSQL_QUERY_DONE(thd->is_error());
      }

1936 1937
      thd->lex->restore_set_statement_var();

1938
#if defined(ENABLED_PROFILING)
1939 1940 1941 1942 1943
      thd->profiling.finish_current_query();
      thd->profiling.start_new_query("continuing");
      thd->profiling.set_query_source(beginning_of_next_stmt, length);
#endif

1944
      /* DTRACE begin */
1945
      MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
1946
                        thd->get_db(),
1947
                        &thd->security_ctx->priv_user[0],
1948 1949
                        (char *) thd->security_ctx->host_or_ip);

1950
      /* PSI begin */
Sergei Golubchik's avatar
Sergei Golubchik committed
1951 1952
      thd->m_digest= & thd->m_digest_state;

1953 1954
      thd->m_statement_psi= MYSQL_START_STATEMENT(&thd->m_statement_state,
                                                  com_statement_info[command].m_key,
1955
                                                  thd->db.str, thd->db.length,
1956
                                                  thd->charset(), NULL);
1957
      THD_STAGE_INFO(thd, stage_starting);
1958 1959 1960
      MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, beginning_of_next_stmt,
                               length);

1961 1962
      thd->set_query_and_id(beginning_of_next_stmt, length,
                            thd->charset(), next_query_id());
1963

1964 1965 1966 1967
      /*
        Count each statement from the client.
      */
      statistic_increment(thd->status_var.questions, &LOCK_status);
1968

Brave Galera Crew's avatar
Brave Galera Crew committed
1969 1970
      if (!WSREP(thd))
        thd->set_time(); /* Reset the query start time. */
1971

1972
      parser_state.reset(beginning_of_next_stmt, length);
1973

Brave Galera Crew's avatar
Brave Galera Crew committed
1974
#ifdef WITH_WSREP
1975
      if (WSREP(thd))
Brave Galera Crew's avatar
Brave Galera Crew committed
1976 1977
      {
        if (wsrep_mysql_parse(thd, beginning_of_next_stmt,
1978
                              length, &parser_state))
Brave Galera Crew's avatar
Brave Galera Crew committed
1979 1980 1981
        {
          WSREP_DEBUG("Deadlock error for: %s", thd->query());
          mysql_mutex_lock(&thd->LOCK_thd_data);
1982
          thd->reset_kill_query();
Brave Galera Crew's avatar
Brave Galera Crew committed
1983 1984 1985 1986 1987 1988
          thd->wsrep_retry_counter  = 0;
          mysql_mutex_unlock(&thd->LOCK_thd_data);

          goto dispatch_end;
        }
      }
1989
      else
Brave Galera Crew's avatar
Brave Galera Crew committed
1990
#endif /* WITH_WSREP */
1991
      mysql_parse(thd, beginning_of_next_stmt, length, &parser_state);
1992

1993 1994
    }

unknown's avatar
unknown committed
1995 1996 1997
    DBUG_PRINT("info",("query ready"));
    break;
  }
1998
  case COM_FIELD_LIST:				// This isn't actually needed
unknown's avatar
unknown committed
1999
#ifdef DONT_ALLOW_SHOW_COMMANDS
2000
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
unknown's avatar
unknown committed
2001
               MYF(0));	/* purecov: inspected */
unknown's avatar
unknown committed
2002 2003 2004
    break;
#else
  {
2005
    char *fields, *packet_end= packet + packet_length, *arg_end;
2006
    /* Locked closure of all tables */
unknown's avatar
unknown committed
2007
    TABLE_LIST table_list;
2008
    LEX_STRING table_name;
2009
    LEX_CSTRING db;
2010 2011 2012 2013
    /*
      SHOW statements should not add the used tables to the list of tables
      used in a transaction.
    */
2014
    MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
2015

2016
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
2017
    if (thd->copy_db_to(&db))
unknown's avatar
unknown committed
2018
      break;
2019 2020
    /*
      We have name + wildcard in packet, separated by endzero
Michael Widenius's avatar
Michael Widenius committed
2021
      (The packet is guaranteed to end with an end zero)
2022 2023
    */
    arg_end= strend(packet);
2024
    uint arg_length= (uint)(arg_end - packet);
2025

2026
    /* Check given table name length. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2027
    if (packet_length - arg_length > NAME_LEN + 1 || arg_length > SAFE_NAME_LEN)
2028
    {
2029 2030
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
                 MYF(0));
2031 2032
      break;
    }
2033
    thd->convert_string(&table_name, system_charset_info,
2034
			packet, arg_length, thd->charset());
2035
    if (Lex_ident_table::check_name(table_name, false))
2036 2037
    {
      /* this is OK due to convert_string() null-terminating the string */
2038
      my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
2039 2040
      break;
    }
2041
    packet= arg_end + 1;
2042

2043 2044 2045
    lex_start(thd);
    /* Must be before we init the table list. */
    if (lower_case_table_names)
2046
    {
2047 2048
      table_name= thd->make_ident_casedn(table_name);
      db= thd->make_ident_casedn(db);
2049
    }
2050
    table_list.init_one_table(&db, (LEX_CSTRING*) &table_name, 0, TL_READ);
2051 2052 2053 2054
    /*
      Init TABLE_LIST members necessary when the undelrying
      table is view.
    */
2055
    table_list.select_lex= thd->lex->first_select_lex();
2056
    thd->lex->
2057 2058
      first_select_lex()->table_list.link_in_list(&table_list,
                                                  &table_list.next_local);
2059
    thd->lex->add_to_query_tables(&table_list);
2060

2061
    if (is_infoschema_db(&table_list.db))
2062
    {
2063
      ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, &table_list.alias);
2064 2065 2066 2067
      if (schema_table)
        table_list.schema_table= schema_table;
    }

Gleb Shchepa's avatar
Gleb Shchepa committed
2068 2069
    uint query_length= (uint) (packet_end - packet); // Don't count end \0
    if (!(fields= (char *) thd->memdup(packet, query_length + 1)))
unknown's avatar
unknown committed
2070
      break;
2071
    thd->set_query(fields, query_length);
2072 2073
    general_log_print(thd, command, "%s %s", table_list.table_name.str,
                      fields);
unknown's avatar
unknown committed
2074

2075
    if (thd->open_temporary_tables(&table_list))
Michael Widenius's avatar
Michael Widenius committed
2076 2077
      break;

2078 2079
    if (check_table_access(thd, SELECT_ACL, &table_list,
                           TRUE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
2080
      break;
2081 2082 2083 2084
    /*
      Turn on an optimization relevant if the underlying table
      is a view: do not fill derived tables.
    */
2085
    thd->lex->sql_command= SQLCOM_SHOW_FIELDS;
2086

unknown's avatar
unknown committed
2087
    mysqld_list_fields(thd,&table_list,fields);
2088
    thd->lex->unit.cleanup();
2089
    /* No need to rollback statement transaction, it's not started. */
2090
    DBUG_ASSERT(thd->transaction->stmt.is_empty());
2091 2092 2093
    close_thread_tables(thd);
    thd->mdl_context.rollback_to_savepoint(mdl_savepoint);

2094 2095 2096 2097 2098 2099 2100 2101 2102
    if (thd->transaction_rollback_request)
    {
      /*
        Transaction rollback was requested since MDL deadlock was
        discovered while trying to open tables. Rollback transaction
        in all storage engines including binary log and release all
        locks.
      */
      trans_rollback_implicit(thd);
2103
      thd->release_transactional_locks();
2104 2105
    }

2106
    thd->cleanup_after_query();
unknown's avatar
unknown committed
2107 2108 2109 2110
    break;
  }
#endif
  case COM_QUIT:
2111 2112 2113 2114
    /* Note: We don't calculate statistics for this command */

    /* Ensure that quit works even if max_mem_used is set */
    thd->variables.max_mem_used= LONGLONG_MAX;
unknown's avatar
unknown committed
2115
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
2116
    net->error=0;				// Don't give 'abort' message
2117
    thd->get_stmt_da()->disable_status();       // Don't send anything back
unknown's avatar
unknown committed
2118 2119
    error=TRUE;					// End server
    break;
2120
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2121 2122
  case COM_BINLOG_DUMP:
    {
unknown's avatar
unknown committed
2123 2124 2125
      ulong pos;
      ushort flags;

2126
      status_var_increment(thd->status_var.com_other);
2127

2128
      thd->query_plan_flags|= QPLAN_ADMIN;
2129
      if (check_global_access(thd, PRIV_COM_BINLOG_DUMP))
unknown's avatar
unknown committed
2130
	break;
unknown's avatar
unknown committed
2131

2132
      /* TODO: The following has to be changed to an 8 byte integer */
2133 2134
      pos = uint4korr(packet);
      flags = uint2korr(packet + 4);
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
      if ((thd->variables.server_id= uint4korr(packet+6)))
      {
        bool got_error;

        got_error= kill_zombie_dump_threads(thd,
                                            thd->variables.server_id);
        if (got_error || thd->killed)
        {
          if (!thd->killed)
            my_printf_error(ER_MASTER_FATAL_ERROR_READING_BINLOG,
                            "Could not start dump thread for slave: %u as "
                            "it has already a running dump thread",
                            MYF(0), (uint) thd->variables.server_id);
          else if (! thd->get_stmt_da()->is_set())
            thd->send_kill_message();
          error= TRUE;
          thd->unregister_slave(); // todo: can be extraneous
          break;
        }
      }
unknown's avatar
unknown committed
2155

2156 2157 2158 2159 2160 2161
      const char *name= packet + 10;
      size_t nlen= strlen(name);

      general_log_print(thd, command, "Log: '%s'  Pos: %lu", name, pos);
      if (nlen < FN_REFLEN)
        mysql_binlog_send(thd, thd->strmake(name, nlen), (my_off_t)pos, flags);
2162 2163
      if (thd->killed && ! thd->get_stmt_da()->is_set())
        thd->send_kill_message();
Marko Mäkelä's avatar
Marko Mäkelä committed
2164
      thd->unregister_slave(); // todo: can be extraneous
unknown's avatar
unknown committed
2165
      /*  fake COM_QUIT -- if we get here, the thread needs to terminate */
2166
      error = TRUE;
unknown's avatar
unknown committed
2167 2168
      break;
    }
2169
#endif
unknown's avatar
unknown committed
2170
  case COM_REFRESH:
unknown's avatar
unknown committed
2171
  {
2172
    int not_used;
2173 2174 2175 2176 2177 2178 2179 2180

    /*
      Initialize thd->lex since it's used in many base functions, such as
      open_tables(). Otherwise, it remains unitialized and may cause crash
      during execution of COM_REFRESH.
    */
    lex_start(thd);
    
2181
    status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
2182
    ulonglong options= (ulonglong) (uchar) packet[0];
Konstantin Osipov's avatar
Konstantin Osipov committed
2183
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
2184
      break;
2185
    thd->release_transactional_locks();
2186 2187 2188
    if (options & REFRESH_STATUS &&
        !(thd->variables.old_behavior & OLD_MODE_OLD_FLUSH_STATUS))
      options= (options & ~REFRESH_STATUS) | REFRESH_SESSION_STATUS;
Monty's avatar
Monty committed
2189 2190
    if ((options & ~REFRESH_SESSION_STATUS) &&
        check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
2191
      break;
unknown's avatar
unknown committed
2192
    general_log_print(thd, command, NullS);
2193
#ifndef DBUG_OFF
2194 2195 2196 2197
    bool debug_simulate= FALSE;
    DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
    if (debug_simulate)
    {
2198 2199
      /* This code doesn't work under FTWRL */
      DBUG_ASSERT(! (options & REFRESH_READ_LOCK));
2200 2201 2202 2203 2204 2205 2206
      /*
        Simulate a reload without a attached thread session.
        Provides a environment similar to that of when the
        server receives a SIGHUP signal and reloads caches
        and flushes tables.
      */
      bool res;
2207
      set_current_thd(0);
2208 2209
      res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
                                NULL, &not_used);
2210
      set_current_thd(thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
2211 2212
      if (res)
        break;
2213
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
2214
    else
2215
#endif
2216
    {
2217
      thd->lex->relay_log_connection_name= empty_clex_str;
2218 2219 2220
      if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
        break;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
2221
    if (trans_commit_implicit(thd))
Konstantin Osipov's avatar
Konstantin Osipov committed
2222
      break;
2223
    close_thread_tables(thd);
2224
    thd->release_transactional_locks();
Konstantin Osipov's avatar
Konstantin Osipov committed
2225
    my_ok(thd);
unknown's avatar
unknown committed
2226 2227
    break;
  }
2228
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2229
  case COM_SHUTDOWN:
2230
  {
2231
    status_var_increment(thd->status_var.com_other);
unknown's avatar
unknown committed
2232
    if (check_global_access(thd,SHUTDOWN_ACL))
unknown's avatar
unknown committed
2233
      break; /* purecov: inspected */
2234
    /*
2235
      If the client is < 4.1.3, it is going to send us no argument; then
2236
      packet_length is 0, packet[0] is the end 0 of the packet. Note that
2237 2238
      SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in
      packet[0].
2239
    */
2240
    enum mysql_enum_shutdown_level level;
2241
    level= (enum mysql_enum_shutdown_level) (uchar) packet[0];
2242
    thd->lex->is_shutdown_wait_for_slaves= false;  // "deferred" cleanup
2243 2244 2245 2246 2247 2248 2249
    if (level == SHUTDOWN_DEFAULT)
      level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable
    else if (level != SHUTDOWN_WAIT_ALL_BUFFERS)
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level");
      break;
    }
2250
    DBUG_PRINT("quit",("Got shutdown command for level %u", level));
unknown's avatar
unknown committed
2251
    general_log_print(thd, command, NullS);
2252
    my_eof(thd);
2253
    kill_mysql(thd);
unknown's avatar
unknown committed
2254
    error=TRUE;
2255
    DBUG_EXECUTE_IF("simulate_slow_client_at_shutdown", my_sleep(2000000););
unknown's avatar
unknown committed
2256
    break;
2257
  }
2258
#endif
unknown's avatar
unknown committed
2259 2260
  case COM_STATISTICS:
  {
2261
    STATUS_VAR *current_global_status_var;      // Big; Don't allocate on stack
2262
    ulong uptime;
2263
    ulonglong queries_per_second1000;
2264 2265
    char buff[250];
    uint buff_len= sizeof(buff);
2266

2267 2268 2269
    if (!(current_global_status_var= (STATUS_VAR*)
          thd->alloc(sizeof(STATUS_VAR))))
      break;
2270
    general_log_print(thd, command, NullS);
2271
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]);
2272
    *current_global_status_var= global_status_var;
2273
    calc_sum_of_all_status(current_global_status_var);
2274 2275 2276
    if (!(uptime= (ulong) (thd->start_time - server_start_time)))
      queries_per_second1000= 0;
    else
2277
      queries_per_second1000= thd->query_id * 1000 / uptime;
2278 2279 2280 2281
#ifndef EMBEDDED_LIBRARY
    size_t length=
#endif
    my_snprintf(buff, buff_len - 1,
2282
                        "Uptime: %lu  Threads: %u  Questions: %lu  "
2283
                        "Slow queries: %lu  Opens: %lu  "
2284
                        "Open tables: %u  Queries per second avg: %u.%03u",
2285
                        uptime, THD_count::value(), (ulong) thd->query_id,
Sergei Golubchik's avatar
Sergei Golubchik committed
2286 2287
                        current_global_status_var->long_query_count,
                        current_global_status_var->opened_tables,
2288
                        tc_records(),
2289 2290
                        (uint) (queries_per_second1000 / 1000),
                        (uint) (queries_per_second1000 % 1000));
2291 2292
#ifdef EMBEDDED_LIBRARY
    /* Store the buffer in permanent memory */
2293
    my_ok(thd, 0, 0, buff);
2294
#else
Konstantin Osipov's avatar
Konstantin Osipov committed
2295 2296
    (void) my_net_write(net, (uchar*) buff, length);
    (void) net_flush(net);
2297
    thd->get_stmt_da()->disable_status();
unknown's avatar
unknown committed
2298
#endif
unknown's avatar
unknown committed
2299 2300 2301
    break;
  }
  case COM_PING:
2302
    status_var_increment(thd->status_var.com_other);
2303
    my_ok(thd);				// Tell client we are alive
unknown's avatar
unknown committed
2304 2305
    break;
  case COM_PROCESS_INFO:
2306
    status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]);
2307
    if (!thd->security_ctx->priv_user[0] &&
2308
        check_global_access(thd, PRIV_COM_PROCESS_INFO))
unknown's avatar
unknown committed
2309
      break;
unknown's avatar
unknown committed
2310
    general_log_print(thd, command, NullS);
unknown's avatar
unknown committed
2311
    mysqld_list_processes(thd,
2312 2313
                     thd->security_ctx->master_access & PRIV_COM_PROCESS_INFO ?
                     NullS : thd->security_ctx->priv_user, 0);
unknown's avatar
unknown committed
2314 2315 2316
    break;
  case COM_PROCESS_KILL:
  {
2317
    status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]);
2318
    ulong id=(ulong) uint4korr(packet);
2319
    sql_kill(thd, id, KILL_CONNECTION_HARD, KILL_TYPE_ID);
unknown's avatar
unknown committed
2320 2321
    break;
  }
2322 2323
  case COM_SET_OPTION:
  {
2324
    status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]);
unknown's avatar
unknown committed
2325 2326 2327 2328
    uint opt_command= uint2korr(packet);

    switch (opt_command) {
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON:
2329
      thd->client_capabilities|= CLIENT_MULTI_STATEMENTS;
2330
      my_eof(thd);
2331
      break;
unknown's avatar
unknown committed
2332
    case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF:
2333
      thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS;
2334
      my_eof(thd);
2335 2336
      break;
    default:
2337 2338
      my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
                 MYF(0));
2339 2340 2341 2342
      break;
    }
    break;
  }
unknown's avatar
unknown committed
2343
  case COM_DEBUG:
2344
    status_var_increment(thd->status_var.com_other);
2345
    if (check_global_access(thd, PRIV_DEBUG))
unknown's avatar
unknown committed
2346
      break;					/* purecov: inspected */
2347
    mysql_print_status();
unknown's avatar
unknown committed
2348
    general_log_print(thd, command, NullS);
2349
    my_eof(thd);
unknown's avatar
unknown committed
2350
    break;
2351

unknown's avatar
unknown committed
2352 2353 2354 2355
  case COM_SLEEP:
  case COM_CONNECT:				// Impossible here
  case COM_TIME:				// Impossible from client
  case COM_DELAYED_INSERT:
2356
  case COM_END:
2357
  case COM_UNIMPLEMENTED:
unknown's avatar
unknown committed
2358
  default:
2359 2360
    my_message(ER_UNKNOWN_COM_ERROR, ER_THD(thd, ER_UNKNOWN_COM_ERROR),
               MYF(0));
unknown's avatar
unknown committed
2361 2362
    break;
  }
2363

2364
dispatch_end:
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
  /*
   For the threadpool i.e if non-blocking call, if not all async operations
   are finished, return without cleanup. The cleanup will be done on
   later, when command execution is resumed.
  */
  if (!blocking && !error && thd->async_state.pending_ops())
  {
    DBUG_RETURN(DISPATCH_COMMAND_WOULDBLOCK);
  }

resume:

2377
#ifdef WITH_WSREP
Brave Galera Crew's avatar
Brave Galera Crew committed
2378
  /*
2379 2380
    Next test should really be WSREP(thd), but that causes a failure when doing
    'set WSREP_ON=0'
Brave Galera Crew's avatar
Brave Galera Crew committed
2381
  */
2382
  if (unlikely(wsrep_service_started))
2383
  {
2384 2385 2386 2387 2388
    if (thd->killed == KILL_QUERY)
    {
      WSREP_DEBUG("THD is killed at dispatch_end");
    }
    wsrep_after_command_before_result(thd);
Marko Mäkelä's avatar
Marko Mäkelä committed
2389
    if (wsrep_current_error(thd) && !wsrep_command_no_result(command))
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
    {
      /* todo: Pass wsrep client state current error to override */
      wsrep_override_error(thd, wsrep_current_error(thd),
                           wsrep_current_error_status(thd));
      WSREP_LOG_THD(thd, "leave");
    }
    if (WSREP(thd))
    {
      /*
        MDEV-10812
        In the case of COM_QUIT/COM_STMT_CLOSE thread status should be disabled.
      */
      DBUG_ASSERT((command != COM_QUIT && command != COM_STMT_CLOSE)
2403
                  || thd->get_stmt_da()->is_disabled());
2404 2405 2406 2407 2408 2409
      DBUG_ASSERT(thd->wsrep_trx().state() != wsrep::transaction::s_replaying);
      /* wsrep BF abort in query exec phase */
      mysql_mutex_lock(&thd->LOCK_thd_kill);
      do_end_of_statement= thd_is_connection_alive(thd);
      mysql_mutex_unlock(&thd->LOCK_thd_kill);
    }
2410 2411
  }
#endif /* WITH_WSREP */
2412

2413 2414 2415 2416 2417
  if (thd->reset_sp_cache)
  {
    thd->sp_caches_empty();
    thd->reset_sp_cache= false;
  }
2418

2419
  if (do_end_of_statement)
2420 2421 2422
  {
    DBUG_ASSERT(thd->derived_tables == NULL &&
               (thd->open_tables == NULL ||
2423
               (thd->locked_tables_mode == LTM_LOCK_TABLES)));
2424

2425
    thd_proc_info(thd, "Updating status");
2426 2427
    /* Finalize server status flags after executing a command. */
    thd->update_server_status();
2428 2429
    thd->protocol->end_statement();
    query_cache_end_of_result(thd);
2430
  }
2431 2432
  if (drop_more_results)
    thd->server_status&= ~SERVER_MORE_RESULTS_EXISTS;
unknown's avatar
unknown committed
2433

2434
  if (likely(!thd->is_error() && !thd->killed_errno()))
2435
    mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);
2436

2437
  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
2438 2439
                      thd->get_stmt_da()->is_error() ?
                      thd->get_stmt_da()->sql_errno() : 0,
2440 2441
                      command_name[command].str);

2442 2443
  thd->update_all_stats();

2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
  /*
    Write to slow query log only those statements that received via the text
    protocol except the EXECUTE statement. The reason we do that way is
    that for statements received via binary protocol and for the EXECUTE
    statement, the slow statements have been already written to slow query log
    inside the method Prepared_statement::execute().
  */
  if(command == COM_QUERY &&
     thd->lex->sql_command != SQLCOM_EXECUTE)
    log_slow_statement(thd);
  else
    delete_explain_query(thd->lex);
2456

Sergei Golubchik's avatar
Sergei Golubchik committed
2457
  THD_STAGE_INFO(thd, stage_cleaning_up);
2458
  thd->reset_query();
2459 2460 2461

  /* Performance Schema Interface instrumentation, end */
  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
2462 2463
  /* Reset values shown in processlist */
  thd->examined_row_count_for_statement= thd->sent_row_count_for_statement= 0;
2464
  thd->mark_connection_idle();
2465

2466
  thd->m_statement_psi= NULL;
Sergei Golubchik's avatar
Sergei Golubchik committed
2467
  thd->m_digest= NULL;
2468

2469
  thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory
2470

2471
  thd->reset_kill_query();  /* Ensure that killed_errmsg is released */
2472 2473 2474 2475 2476
  /*
    LEX::m_sql_cmd can point to Sql_cmd allocated on thd->mem_root.
    Unlink it now, before freeing the root.
  */
  thd->lex->m_sql_cmd= NULL;
2477
  free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC));
2478 2479
  DBUG_EXECUTE_IF("print_allocated_thread_memory",
                  SAFEMALLOC_REPORT_MEMORY(sf_malloc_dbug_id()););
2480

Konstantin Osipov's avatar
Konstantin Osipov committed
2481 2482 2483
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif
2484 2485
  if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED())
  {
2486
    int res __attribute__((unused));
2487 2488 2489 2490 2491 2492 2493
    res= (int) thd->is_error();
    if (command == COM_QUERY)
    {
      MYSQL_QUERY_DONE(res);
    }
    MYSQL_COMMAND_DONE(res);
  }
2494
  DEBUG_SYNC(thd,"dispatch_command_end");
2495
  DEBUG_SYNC(thd,"dispatch_command_end2");
Sergei Golubchik's avatar
Sergei Golubchik committed
2496

2497 2498
  /* Check that some variables are reset properly */
  DBUG_ASSERT(thd->abort_on_warning == 0);
2499
  thd->lex->restore_set_statement_var();
2500
  DBUG_RETURN(error?DISPATCH_COMMAND_CLOSE_CONNECTION: DISPATCH_COMMAND_SUCCESS);
2501 2502
}

2503
static bool slow_filter_masked(THD *thd, ulonglong mask)
2504
{
2505
  return thd->variables.log_slow_filter && !(thd->variables.log_slow_filter & mask);
2506 2507
}

2508
/*
2509 2510
  Log query to slow queries, if it passes filtering

2511
  @note
2512
    This function must call delete_explain_query().
2513
*/
2514

2515
void log_slow_statement(THD *thd)
2516
{
unknown's avatar
unknown committed
2517
  DBUG_ENTER("log_slow_statement");
2518 2519 2520 2521 2522 2523 2524

  /*
    The following should never be true with our current code base,
    but better to keep this here so we don't accidently try to log a
    statement in a trigger or stored function
  */
  if (unlikely(thd->in_sub_stmt))
2525
    goto end;                           // Don't set time for sub stmt
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
  /*
    Skip both long_query_count increment and logging if the current
    statement forces slow log suppression (e.g. an SP statement).

    Note, we don't check for global_system_variables.sql_log_slow here.
    According to the manual, the "Slow_queries" status variable does not require
    sql_log_slow to be ON. So even if sql_log_slow is OFF, we still need to
    continue and increment long_query_count (and skip only logging, see below):
  */
  if (!thd->enable_slow_log)
    goto end; // E.g. SP statement
2537

2538 2539 2540 2541 2542
  DBUG_EXECUTE_IF("simulate_slow_query", {
                  if (thd->get_command() == COM_QUERY ||
                      thd->get_command() == COM_STMT_EXECUTE)
                    thd->server_status|= SERVER_QUERY_WAS_SLOW;
                  });
2543

2544 2545
  if ((thd->server_status &
       (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
2546
      !(thd->query_plan_flags & QPLAN_STATUS) &&
2547
      (thd->variables.log_slow_filter & QPLAN_NOT_USING_INDEX))
2548 2549 2550 2551 2552
  {
    thd->query_plan_flags|= QPLAN_NOT_USING_INDEX;
    /* We are always logging no index queries if enabled in filter */
    thd->server_status|= SERVER_QUERY_WAS_SLOW;
  }
2553

2554
  if ((thd->server_status & SERVER_QUERY_WAS_SLOW) &&
Sergei Golubchik's avatar
Sergei Golubchik committed
2555
      thd->get_examined_row_count() >= thd->variables.min_examined_row_limit)
unknown's avatar
unknown committed
2556
  {
2557
    thd->status_var.long_query_count++;
2558

2559
    /*
2560
      until log_slow_disabled_statements=admin is removed, it
2561 2562 2563
      duplicates slow_log_filter=admin
    */
    if ((thd->query_plan_flags & QPLAN_ADMIN) &&
2564
        (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_ADMIN))
2565 2566 2567
      goto end;

    if (!global_system_variables.sql_log_slow || !thd->variables.sql_log_slow)
2568 2569
      goto end;

2570 2571 2572 2573 2574 2575
    /*
      If rate limiting of slow log writes is enabled, decide whether to log
      this query to the log or not.
    */ 
    if (thd->variables.log_slow_rate_limit > 1 &&
        (global_query_id % thd->variables.log_slow_rate_limit) != 0)
2576
      goto end;
2577

2578 2579 2580 2581
    /*
      Follow the slow log filter configuration:
      skip logging if the current statement matches the filter.
    */
2582
    if (slow_filter_masked(thd, thd->query_plan_flags))
2583 2584
      goto end;

Sergei Golubchik's avatar
Sergei Golubchik committed
2585
    THD_STAGE_INFO(thd, stage_logging_slow_query);
2586 2587
    slow_log_print(thd, thd->query(), thd->query_length(), 
                   thd->utime_after_query);
unknown's avatar
unknown committed
2588
  }
2589

2590
end:
2591
  delete_explain_query(thd->lex);
unknown's avatar
unknown committed
2592
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2593 2594
}

2595

unknown's avatar
unknown committed
2596
/**
unknown's avatar
unknown committed
2597 2598 2599 2600 2601 2602 2603
  Create a TABLE_LIST object for an INFORMATION_SCHEMA table.

    This function is used in the parser to convert a SHOW or DESCRIBE
    table_name command to a SELECT from INFORMATION_SCHEMA.
    It prepares a SELECT_LEX and a TABLE_LIST object to represent the
    given command as a SELECT parse tree.

unknown's avatar
unknown committed
2604 2605 2606 2607 2608 2609 2610
  @param thd              thread handle
  @param lex              current lex
  @param table_ident      table alias if it's used
  @param schema_table_idx the type of the INFORMATION_SCHEMA table to be
                          created

  @note
unknown's avatar
unknown committed
2611 2612 2613 2614
    Due to the way this function works with memory and LEX it cannot
    be used outside the parser (parse tree transformations outside
    the parser break PS and SP).

unknown's avatar
unknown committed
2615
  @retval
unknown's avatar
unknown committed
2616
    0                 success
unknown's avatar
unknown committed
2617
  @retval
unknown's avatar
unknown committed
2618 2619 2620 2621
    1                 out of memory or SHOW commands are not allowed
                      in this version of the server.
*/

2622 2623 2624
int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident,
                         enum enum_schema_tables schema_table_idx)
{
2625
  SELECT_LEX *schema_select_lex= NULL;
2626
  DBUG_ENTER("prepare_schema_table");
2627

2628
  switch (schema_table_idx) {
2629 2630
  case SCH_SCHEMATA:
#if defined(DONT_ALLOW_SHOW_COMMANDS)
unknown's avatar
unknown committed
2631
    my_message(ER_NOT_ALLOWED_COMMAND,
2632
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
2633 2634 2635 2636
    DBUG_RETURN(1);
#else
    break;
#endif
2637

2638 2639
  case SCH_TABLE_NAMES:
  case SCH_TABLES:
2640
  case SCH_CHECK_CONSTRAINTS:
2641
  case SCH_VIEWS:
2642
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
2643
  case SCH_EVENTS:
2644
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2645
    my_message(ER_NOT_ALLOWED_COMMAND,
2646
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
2647 2648 2649
    DBUG_RETURN(1);
#else
    {
2650 2651
      if (lex->first_select_lex()->db.str == NULL &&
          lex->copy_db_to(&lex->first_select_lex()->db))
2652
      {
unknown's avatar
unknown committed
2653
        DBUG_RETURN(1);
2654
      }
2655
      schema_select_lex= new (thd->mem_root) SELECT_LEX();
2656
      schema_select_lex->table_list.first= NULL;
2657
      if (lower_case_table_names == 1)
2658 2659
        lex->first_select_lex()->db=
          thd->make_ident_casedn(lex->first_select_lex()->db);
2660
      schema_select_lex->db= lex->first_select_lex()->db;
2661
      if (Lex_ident_db::check_name_with_error(lex->first_select_lex()->db))
2662 2663 2664 2665 2666 2667 2668
        DBUG_RETURN(1);
      break;
    }
#endif
  case SCH_COLUMNS:
  case SCH_STATISTICS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
unknown's avatar
unknown committed
2669
    my_message(ER_NOT_ALLOWED_COMMAND,
2670
               ER_THD(thd, ER_NOT_ALLOWED_COMMAND), MYF(0));
2671 2672
    DBUG_RETURN(1);
#else
Sergei Golubchik's avatar
Sergei Golubchik committed
2673
  {
unknown's avatar
unknown committed
2674 2675
    DBUG_ASSERT(table_ident);
    TABLE_LIST **query_tables_last= lex->query_tables_last;
2676
    schema_select_lex= new (thd->mem_root) SELECT_LEX();
unknown's avatar
unknown committed
2677 2678 2679
    /* 'parent_lex' is used in init_query() so it must be before it. */
    schema_select_lex->parent_lex= lex;
    schema_select_lex->init_query();
Monty's avatar
Monty committed
2680
    schema_select_lex->select_number= 0;
2681 2682
    if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ,
                                              MDL_SHARED_READ))
unknown's avatar
unknown committed
2683 2684 2685
      DBUG_RETURN(1);
    lex->query_tables_last= query_tables_last;
    break;
2686
  }
2687
#endif
2688 2689 2690 2691 2692
  case SCH_PROFILES:
    /* 
      Mark this current profiling record to be discarded.  We don't
      wish to have SHOW commands show up in profiling.
    */
2693
#if defined(ENABLED_PROFILING)
2694
    thd->profiling.discard_current_query();
2695 2696
#endif
    break;
2697 2698 2699
  default:
    break;
  }
2700 2701
  if (schema_select_lex)
    schema_select_lex->set_master_unit(&lex->unit);
2702
  SELECT_LEX *select_lex= lex->current_select;
2703
  if (make_schema_select(thd, select_lex, get_schema_table(schema_table_idx)))
2704
    DBUG_RETURN(1);
2705 2706

  select_lex->table_list.first->schema_select_lex= schema_select_lex;
2707 2708 2709 2710
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
2711 2712 2713
/**
  Read query from packet and store in thd->query.
  Used in COM_QUERY and COM_STMT_PREPARE.
2714 2715

    Sets the following THD variables:
unknown's avatar
unknown committed
2716 2717
  - query
  - query_length
2718

unknown's avatar
unknown committed
2719
  @retval
unknown's avatar
unknown committed
2720
    FALSE ok
unknown's avatar
unknown committed
2721
  @retval
unknown's avatar
unknown committed
2722
    TRUE  error;  In this case thd->fatal_error is set
2723 2724
*/

2725
bool alloc_query(THD *thd, const char *packet, size_t packet_length)
2726
{
2727
  char *query;
2728
  /* Remove garbage at start and end of query */
2729
  while (packet_length > 0 && my_isspace(thd->charset(), packet[0]))
2730 2731 2732 2733
  {
    packet++;
    packet_length--;
  }
2734
  const char *pos= packet + packet_length;     // Point at end null
unknown's avatar
unknown committed
2735
  while (packet_length > 0 &&
unknown's avatar
unknown committed
2736
	 (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1])))
2737 2738 2739 2740
  {
    pos--;
    packet_length--;
  }
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
  /* We must allocate some extra memory for query cache 

    The query buffer layout is:
       buffer :==
            <statement>   The input statement(s)
            '\0'          Terminating null char  (1 byte)
            <length>      Length of following current database name (size_t)
            <db_name>     Name of current database
            <flags>       Flags struct
  */
2751 2752
  if (! (query= (char*) thd->memdup_w_gap(packet,
                                          packet_length,
2753
                                          1 + thd->db.length +
2754
                                          QUERY_CACHE_DB_LENGTH_SIZE +
2755 2756 2757
                                          QUERY_CACHE_FLAGS_SIZE)))
      return TRUE;
  query[packet_length]= '\0';
2758 2759 2760 2761 2762
  /*
    Space to hold the name of the current database is allocated.  We
    also store this length, in case current database is changed during
    execution.  We might need to reallocate the 'query' buffer
  */
2763
  int2store(query + packet_length + 1, thd->db.length);
2764
    
2765
  thd->set_query(query, packet_length);
2766 2767 2768 2769

  /* Reclaim some memory */
  thd->packet.shrink(thd->variables.net_buffer_length);
  thd->convert_buffer.shrink(thd->variables.net_buffer_length);
2770

unknown's avatar
unknown committed
2771
  return FALSE;
2772 2773
}

2774

2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
bool sp_process_definer(THD *thd)
{
  DBUG_ENTER("sp_process_definer");

  LEX *lex= thd->lex;

  /*
    If the definer is not specified, this means that CREATE-statement missed
    DEFINER-clause. DEFINER-clause can be missed in two cases:

      - The user submitted a statement w/o the clause. This is a normal
        case, we should assign CURRENT_USER as definer.

      - Our slave received an updated from the master, that does not
        replicate definer for stored rountines. We should also assign
        CURRENT_USER as definer here, but also we should mark this routine
        as NON-SUID. This is essential for the sake of backward
        compatibility.

        The problem is the slave thread is running under "special" user (@),
        that actually does not exist. In the older versions we do not fail
        execution of a stored routine if its definer does not exist and
        continue the execution under the authorization of the invoker
        (BUG#13198). And now if we try to switch to slave-current-user (@),
        we will fail.

        Actually, this leads to the inconsistent state of master and
        slave (different definers, different SUID behaviour), but it seems,
        this is the best we can do.
  */

  if (!lex->definer)
  {
    Query_arena original_arena;
    Query_arena *ps_arena= thd->activate_stmt_arena_if_needed(&original_arena);

2811
    lex->definer= create_default_definer(thd, false);
2812 2813 2814 2815 2816 2817 2818 2819

    if (ps_arena)
      thd->restore_active_arena(ps_arena, &original_arena);

    /* Error has been already reported. */
    if (lex->definer == NULL)
      DBUG_RETURN(TRUE);

2820
    if (thd->slave_thread && lex->sphead)
2821
      lex->sphead->set_suid(SP_IS_NOT_SUID);
2822 2823 2824
  }
  else
  {
2825
    LEX_USER *d= get_current_user(thd, lex->definer);
2826 2827
    if (!d)
      DBUG_RETURN(TRUE);
2828
    if (d->user.str == public_name.str)
2829 2830 2831 2832
    {
      my_error(ER_INVALID_ROLE, MYF(0), lex->definer->user.str);
      DBUG_RETURN(TRUE);
    }
2833
    thd->change_item_tree((Item**)&lex->definer, (Item*)d);
2834

2835
    /*
2836
      If the specified definer differs from the current user or role, we
2837 2838 2839 2840
      should check that the current user has SUPER privilege (in order
      to create a stored routine under another user one must have
      SUPER privilege).
    */
2841 2842 2843
    bool curuser= !strcmp(d->user.str, thd->security_ctx->priv_user);
    bool currole= !curuser && !strcmp(d->user.str, thd->security_ctx->priv_role);
    bool curuserhost= curuser && d->host.str &&
2844 2845
                      Lex_ident_host(d->host).
                        streq(Lex_cstring_strlen(thd->security_ctx->priv_host));
2846
    if (!curuserhost && !currole &&
2847
        check_global_access(thd, PRIV_DEFINER_CLAUSE, false))
2848 2849 2850 2851 2852 2853
      DBUG_RETURN(TRUE);
  }

  /* Check that the specified definer exists. Emit a warning if not. */

#ifndef NO_EMBEDDED_ACCESS_CHECKS
2854
  if (!is_acl_user(lex->definer->host, lex->definer->user))
2855
  {
2856 2857 2858
    push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                        ER_NO_SUCH_USER, ER_THD(thd, ER_NO_SUCH_USER),
                        lex->definer->user.str, lex->definer->host.str);
2859 2860 2861 2862 2863 2864 2865
  }
#endif /* NO_EMBEDDED_ACCESS_CHECKS */

  DBUG_RETURN(FALSE);
}


unknown's avatar
unknown committed
2866
/**
2867 2868 2869 2870 2871 2872 2873 2874 2875
  Auxiliary call that opens and locks tables for LOCK TABLES statement
  and initializes the list of locked tables.

  @param thd     Thread context.
  @param tables  List of tables to be locked.

  @return FALSE in case of success, TRUE in case of error.
*/

2876 2877
static bool __attribute__ ((noinline))
lock_tables_open_and_lock_tables(THD *thd, TABLE_LIST *tables)
2878 2879
{
  Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
2880 2881
  MDL_deadlock_and_lock_abort_error_handler deadlock_handler;
  MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
2882 2883 2884 2885 2886
  uint counter;
  TABLE_LIST *table;

  thd->in_lock_tables= 1;

2887 2888
retry:

2889 2890 2891 2892
  if (open_tables(thd, &tables, &counter, 0, &lock_tables_prelocking_strategy))
    goto err;

  for (table= tables; table; table= table->next_global)
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
  {
    if (!table->placeholder())
    {
      if (table->table->s->tmp_table)
      {
        /*
          We allow to change temporary tables even if they were locked for read
          by LOCK TABLES. To avoid a discrepancy between lock acquired at LOCK
          TABLES time and by the statement which is later executed under LOCK
          TABLES we ensure that for temporary tables we always request a write
          lock (such discrepancy can cause problems for the storage engine).
          We don't set TABLE_LIST::lock_type in this case as this might result
          in extra warnings from THD::decide_logging_format() even though
          binary logging is totally irrelevant for LOCK TABLES.
        */
        table->table->reginfo.lock_type= TL_WRITE;
      }
      else if (table->mdl_request.type == MDL_SHARED_READ &&
               ! table->prelocking_placeholder &&
               table->table->file->lock_count() == 0)
      {
2914
        enum enum_mdl_type lock_type;
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
        /*
          In case when LOCK TABLE ... READ LOCAL was issued for table with
          storage engine which doesn't support READ LOCAL option and doesn't
          use THR_LOCK locks we need to upgrade weak SR metadata lock acquired
          in open_tables() to stronger SRO metadata lock.
          This is not needed for tables used through stored routines or
          triggers as we always acquire SRO (or even stronger SNRW) metadata
          lock for them.
        */
        deadlock_handler.init();
        thd->push_internal_handler(&deadlock_handler);

2927 2928 2929
        lock_type= table->table->mdl_ticket->get_type() == MDL_SHARED_WRITE ?
                   MDL_SHARED_NO_READ_WRITE : MDL_SHARED_READ_ONLY;

2930 2931
        bool result= thd->mdl_context.upgrade_shared_lock(
                                        table->table->mdl_ticket,
2932
                                        lock_type,
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
                                        thd->variables.lock_wait_timeout);

        thd->pop_internal_handler();

        if (deadlock_handler.need_reopen())
        {
          /*
            Deadlock occurred during upgrade of metadata lock.
            Let us restart acquring and opening tables for LOCK TABLES.
          */
2943
          close_tables_for_reopen(thd, &tables, mdl_savepoint, true);
2944 2945 2946 2947 2948 2949 2950 2951
          if (thd->open_temporary_tables(tables))
            goto err;
          goto retry;
        }

        if (result)
          goto err;
      }
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961

#ifdef WITH_WSREP
      if (WSREP(thd) && table->table->s->table_type == TABLE_TYPE_SEQUENCE)
      {
        my_error(ER_NOT_SUPPORTED_YET, MYF(0),
                 "LOCK TABLE on SEQUENCES in Galera cluster");
        goto err;
      }
#endif

2962
    }
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
    /*
       Check privileges of view tables here, after views were opened.
       Either definer or invoker has to have PRIV_LOCK_TABLES to be able
       to lock view and its tables. For mysqldump (that locks views
       before dumping their structures) compatibility we allow locking
       views that select from I_S or P_S tables, but downrade the lock
       to TL_READ
     */
    if (table->belong_to_view &&
        check_single_table_access(thd, PRIV_LOCK_TABLES, table, 1))
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
    {
      if (table->grant.m_internal.m_schema_access)
        table->lock_type= TL_READ;
      else
      {
        bool error= true;
        if (Security_context *sctx= table->security_ctx)
        {
          table->security_ctx= 0;
          error= check_single_table_access(thd, PRIV_LOCK_TABLES, table, 1);
          table->security_ctx= sctx;
        }
        if (error)
        {
          my_error(ER_VIEW_INVALID, MYF(0), table->belong_to_view->view_db.str,
                   table->belong_to_view->view_name.str);
          goto err;
        }
      }
    }
2993
  }
2994

2995 2996 2997 2998 2999
  if (lock_tables(thd, tables, counter, 0) ||
      thd->locked_tables_list.init_locked_tables(thd))
    goto err;

  thd->in_lock_tables= 0;
3000

3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
  return FALSE;

err:
  thd->in_lock_tables= 0;

  trans_rollback_stmt(thd);
  /*
    Need to end the current transaction, so the storage engine (InnoDB)
    can free its locks if LOCK TABLES locked some tables before finding
    that it can't lock a table in its list
  */
3012
  trans_rollback(thd);
3013 3014 3015
  /* Close tables and release metadata locks. */
  close_thread_tables(thd);
  DBUG_ASSERT(!thd->locked_tables_mode);
3016
  thd->release_transactional_locks();
3017 3018 3019 3020
  return TRUE;
}


Sergei Golubchik's avatar
Sergei Golubchik committed
3021 3022 3023 3024
static bool do_execute_sp(THD *thd, sp_head *sp)
{
  /* bits that should be cleared in thd->server_status */
  uint bits_to_be_cleared= 0;
3025
  ulonglong affected_rows;
Sergei Golubchik's avatar
Sergei Golubchik committed
3026 3027 3028 3029 3030
  if (sp->m_flags & sp_head::MULTI_RESULTS)
  {
    if (!(thd->client_capabilities & CLIENT_MULTI_RESULTS))
    {
      /* The client does not support multiple result sets being sent back */
3031
      my_error(ER_SP_BADSELECT, MYF(0), ErrConvDQName(sp).ptr());
Sergei Golubchik's avatar
Sergei Golubchik committed
3032 3033 3034
      return 1;
    }
  }
3035 3036 3037 3038 3039 3040 3041
  /*
    If SERVER_MORE_RESULTS_EXISTS is not set,
    then remember that it should be cleared
  */
  bits_to_be_cleared= (~thd->server_status &
                       SERVER_MORE_RESULTS_EXISTS);
  thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
Sergei Golubchik's avatar
Sergei Golubchik committed
3042 3043 3044
  ha_rows select_limit= thd->variables.select_limit;
  thd->variables.select_limit= HA_POS_ERROR;

3045 3046 3047 3048 3049
  /*
    Reset current_select as it may point to random data as a
    result of previous parsing.
  */
  thd->lex->current_select= NULL;
3050
  thd->lex->in_sum_func= 0;                     // For Item_field::fix_fields()
3051

Sergei Golubchik's avatar
Sergei Golubchik committed
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
  /*
    We never write CALL statements into binlog:
     - If the mode is non-prelocked, each statement will be logged
       separately.
     - If the mode is prelocked, the invoking statement will care
       about writing into binlog.
    So just execute the statement.
  */
  int res= sp->execute_procedure(thd, &thd->lex->value_list);

  thd->variables.select_limit= select_limit;
  thd->server_status&= ~bits_to_be_cleared;

  if (res)
  {
    DBUG_ASSERT(thd->is_error() || thd->killed);
    return 1;  		// Substatement should already have sent error
  }

3071 3072
  affected_rows= thd->affected_rows; // Affected rows for all sub statements
  thd->affected_rows= 0;             // Reset total, as my_ok() adds to it
3073
  my_ok(thd, affected_rows);
Sergei Golubchik's avatar
Sergei Golubchik committed
3074 3075 3076 3077
  return 0;
}


3078 3079
static int __attribute__ ((noinline))
mysql_create_routine(THD *thd, LEX *lex)
3080 3081 3082
{
  DBUG_ASSERT(lex->sphead != 0);
  DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */
3083 3084 3085
  DBUG_ASSERT(lower_case_table_names != 1 ||
              Lex_ident_fs(lex->sphead->m_db).is_in_lower_case());

3086
  if (Lex_ident_db::check_name_with_error(lex->sphead->m_db))
3087 3088 3089 3090 3091 3092 3093 3094 3095
    return true;

  if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str,
                   NULL, NULL, 0, 0))
    return true;

  /* Checking the drop permissions if CREATE OR REPLACE is used */
  if (lex->create_info.or_replace())
  {
3096 3097
    if (check_routine_access(thd, ALTER_PROC_ACL, &lex->sphead->m_db,
                             &lex->sphead->m_name,
3098
                             Sp_handler::handler(lex->sql_command), 0))
3099 3100 3101
      return true;
  }

3102
  const Lex_ident_routine name= Lex_ident_routine(*lex->sphead->name());
3103
#ifdef HAVE_DLOPEN
3104
  if (lex->sphead->m_handler->type() == SP_TYPE_FUNCTION)
3105
  {
3106
    udf_func *udf= find_udf(name.str, name.length);
3107 3108 3109

    if (udf)
    {
3110
      my_error(ER_UDF_EXISTS, MYF(0), name.str);
3111 3112 3113 3114 3115 3116 3117 3118
      return true;
    }
  }
#endif

  if (sp_process_definer(thd))
    return true;

3119
  WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
3120

3121
  if (!lex->sphead->m_handler->sp_create_routine(thd, lex->sphead))
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
  {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
    /* only add privileges if really neccessary */

    Security_context security_context;
    bool restore_backup_context= false;
    Security_context *backup= NULL;
    LEX_USER *definer= thd->lex->definer;
    /*
      We're going to issue an implicit GRANT statement so we close all
      open tables. We have to keep metadata locks as this ensures that
      this statement is atomic against concurent FLUSH TABLES WITH READ
      LOCK. Deadlocks which can arise due to fact that this implicit
      statement takes metadata locks should be detected by a deadlock
      detector in MDL subsystem and reported as errors.

      TODO: Long-term we should either ensure that implicit GRANT statement
            is written into binary log as a separate statement or make both
            creation of routine and implicit GRANT parts of one fully atomic
            statement.
      */
3143 3144
    if (trans_commit_stmt(thd))
      goto wsrep_error_label;
3145 3146 3147 3148 3149 3150 3151 3152 3153
    close_thread_tables(thd);
    /*
      Check if the definer exists on slave,
      then use definer privilege to insert routine privileges to mysql.procs_priv.

      For current user of SQL thread has GLOBAL_ACL privilege,
      which doesn't any check routine privileges,
      so no routine privilege record  will insert into mysql.procs_priv.
    */
3154
    if (thd->slave_thread && is_acl_user(definer->host, definer->user))
3155
    {
3156
      security_context.change_security_context(thd, &thd->lex->definer->user,
3157 3158 3159 3160 3161 3162 3163 3164
                                               &thd->lex->definer->host,
                                               &thd->lex->sphead->m_db,
                                               &backup);
      restore_backup_context= true;
    }

    if (sp_automatic_privileges && !opt_noacl &&
        check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS,
3165
                             &lex->sphead->m_db, &name,
3166
                             Sp_handler::handler(lex->sql_command), 1))
3167
    {
3168
      if (sp_grant_privileges(thd, lex->sphead->m_db, name,
3169
                              Sp_handler::handler(lex->sql_command)))
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
        push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
                     ER_PROC_AUTO_GRANT_FAIL, ER_THD(thd, ER_PROC_AUTO_GRANT_FAIL));
      thd->clear_error();
    }

    /*
      Restore current user with GLOBAL_ACL privilege of SQL thread
    */
    if (restore_backup_context)
    {
      DBUG_ASSERT(thd->slave_thread == 1);
      thd->security_ctx->restore_security_context(thd, backup);
    }

#endif
    return false;
  }
3187 3188 3189
  (void) trans_commit_stmt(thd);

#if !defined(NO_EMBEDDED_ACCESS_CHECKS) || defined(WITH_WSREP)
Marko Mäkelä's avatar
Marko Mäkelä committed
3190
wsrep_error_label:
3191 3192 3193 3194 3195
#endif
  return true;
}


3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
/**
  Prepare for CREATE DATABASE, ALTER DATABASE, DROP DATABASE.

  @param thd         - current THD
  @param want_access - access needed
  @param dbname      - the database name

  @retval false      - Ok to proceed with CREATE/ALTER/DROP
  @retval true       - not OK to proceed (error, or filtered)

  Note, on slave this function returns true if the database
  is in the ignore filter. The caller must distinguish this case
  from other cases: bad database error, no access error.
  This can be done by testing thd->is_error().
*/
3211
static bool prepare_db_action(THD *thd, privilege_t want_access,
3212
                              const Lex_ident_db &dbname)
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
{
  /*
    If in a slave thread :
    - CREATE DATABASE DB was certainly not preceded by USE DB.
    - ALTER DATABASE DB may not be preceded by USE DB.
    - DROP DATABASE DB may not be preceded by USE DB.
    For that reason, db_ok() in sql/slave.cc did not check the
    do_db/ignore_db. And as this query involves no tables, tables_ok()
    was not called. So we have to check rules again here.
  */
3223 3224
  return thd->check_slave_ignored_db_with_error(dbname) ||
         check_access(thd, want_access, dbname.str, NULL, NULL, 1, 0);
3225 3226
}

3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244

bool Sql_cmd_call::execute(THD *thd)
{
  TABLE_LIST *all_tables= thd->lex->query_tables;
  sp_head *sp;
  /*
    This will cache all SP and SF and open and lock all tables
    required for execution.
  */
  if (check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                         UINT_MAX, FALSE) ||
      open_and_lock_tables(thd, all_tables, TRUE, 0))
   return true;

  /*
    By this moment all needed SPs should be in cache so no need to look
    into DB.
  */
3245
  if (!(sp= m_handler->sp_find_routine(thd, m_name, true)))
3246 3247 3248 3249 3250
  {
    /*
      If the routine is not found, let's still check EXECUTE_ACL to decide
      whether to return "Access denied" or "Routine does not exist".
    */
3251 3252
    if (check_routine_access(thd, EXECUTE_ACL, &m_name->m_db,
                             &m_name->m_name,
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
                             &sp_handler_procedure,
                             false))
      return true;
    /*
      sp_find_routine can have issued an ER_SP_RECURSION_LIMIT error.
      Send message ER_SP_DOES_NOT_EXIST only if procedure is not found in
      cache.
    */
    if (!sp_cache_lookup(&thd->sp_proc_cache, m_name))
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE",
               ErrConvDQName(m_name).ptr());
    return true;
  }
  else
  {
    if (sp->check_execute_access(thd))
      return true;
    /*
      Check that the stored procedure doesn't contain Dynamic SQL
      and doesn't return result sets: such stored procedures can't
      be called from a function or trigger.
    */
    if (thd->in_sub_stmt)
    {
      const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ?
                          "trigger" : "function");
      if (sp->is_not_allowed_in_function(where))
        return true;
    }

    if (do_execute_sp(thd, sp))
      return true;
3285 3286 3287 3288 3289 3290 3291

    /*
      Disable slow log for the above call(), if calls are disabled.
      Instead we will log the executed statements to the slow log.
    */
    if (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_CALL)
      thd->enable_slow_log= 0;
3292 3293 3294 3295 3296
  }
  return false;
}


3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
/**
  Check whether the SQL statement being processed is prepended by
  SET STATEMENT clause and handle variables assignment if it is.

  @param thd  thread handle
  @param lex  current lex

  @return false in case of success, true in case of error.
*/

bool run_set_statement_if_requested(THD *thd, LEX *lex)
{
  if (!lex->stmt_var_list.is_empty() && !thd->slave_thread)
  {
    Query_arena backup;
    DBUG_PRINT("info", ("SET STATEMENT %d vars", lex->stmt_var_list.elements));

    lex->old_var_list.empty();
    List_iterator_fast<set_var_base> it(lex->stmt_var_list);
    set_var_base *var;

    if (lex->set_arena_for_set_stmt(&backup))
      return true;

    MEM_ROOT *mem_root= thd->mem_root;
    while ((var= it++))
    {
      DBUG_ASSERT(var->is_system());
      set_var *o= NULL, *v= (set_var*)var;
      if (!v->var->is_set_stmt_ok())
      {
        my_error(ER_SET_STATEMENT_NOT_SUPPORTED, MYF(0), v->var->name.str);
        lex->reset_arena_for_set_stmt(&backup);
        lex->old_var_list.empty();
        lex->free_arena_for_set_stmt();
        return true;
      }
      if (v->var->session_is_default(thd))
        o= new set_var(thd,v->type, v->var, &v->base, NULL);
      else
      {
        switch (v->var->option.var_type & GET_TYPE_MASK)
        {
3340
          case GET_BIT:
3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
          case GET_BOOL:
          case GET_INT:
          case GET_LONG:
          case GET_LL:
          {
            bool null_value;
            longlong val= v->var->val_int(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_int(thd, val)));
          }
          break;
          case GET_UINT:
          case GET_ULONG:
          case GET_ULL:
          {
            bool null_value;
            ulonglong val= v->var->val_int(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_uint(thd, val)));
          }
          break;
          case GET_DOUBLE:
          {
            bool null_value;
            double val= v->var->val_real(&null_value, thd, v->type, &v->base);
            o= new set_var(thd, v->type, v->var, &v->base,
                           (null_value ?
                            (Item *) new (mem_root) Item_null(thd) :
                            (Item *) new (mem_root) Item_float(thd, val, 1)));
          }
          break;
          default:
          case GET_NO_ARG:
          case GET_DISABLED:
            DBUG_ASSERT(0);
            /* fall through */
          case 0:
          case GET_FLAGSET:
          case GET_ENUM:
          case GET_SET:
          case GET_STR:
          case GET_STR_ALLOC:
          {
            char buff[STRING_BUFFER_USUAL_SIZE];
            String tmp(buff, sizeof(buff), v->var->charset(thd)),*val;
            val= v->var->val_str(&tmp, thd, v->type, &v->base);
            if (val)
            {
              Item_string *str=
		new (mem_root) Item_string(thd, v->var->charset(thd),
                                           val->ptr(), val->length());
              o= new set_var(thd, v->type, v->var, &v->base, str);
            }
            else
              o= new set_var(thd, v->type, v->var, &v->base,
                             new (mem_root) Item_null(thd));
          }
          break;
        }
      }
      DBUG_ASSERT(o);
      lex->old_var_list.push_back(o, thd->mem_root);
    }
    lex->reset_arena_for_set_stmt(&backup);

    if (lex->old_var_list.is_empty())
      lex->free_arena_for_set_stmt();

    if (thd->is_error() ||
        sql_set_variables(thd, &lex->stmt_var_list, false))
    {
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS, MYF(0), "SET");
      lex->restore_set_statement_var();
      return true;
    }
    /*
      The value of last_insert_id is remembered in THD to be written to binlog
      when it's used *the first time* in the statement. But SET STATEMENT
      must read the old value of last_insert_id to be able to restore it at
      the end. This should not count at "reading of last_insert_id" and
      should not remember last_insert_id for binlog. That is, it should clear
      stmt_depends_on_first_successful_insert_id_in_prev_stmt flag.
    */
    if (!thd->in_sub_stmt)
    {
      thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
    }
  }
  return false;
}


unknown's avatar
unknown committed
3438 3439
/**
  Execute command saved in thd and lex->sql_command.
3440

unknown's avatar
unknown committed
3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
  @param thd                       Thread handle

  @todo
    - Invalidate the table in the query cache if something changed
    after unlocking when changes become visible.
    TODO: this is workaround. right way will be move invalidating in
    the unlock procedure.
    - TODO: use check_change_password()

  @retval
3451
    FALSE       OK
unknown's avatar
unknown committed
3452
  @retval
3453 3454
    TRUE        Error
*/
unknown's avatar
unknown committed
3455

3456
int
3457
mysql_execute_command(THD *thd, bool is_called_from_prepared_stmt)
unknown's avatar
unknown committed
3458
{
3459
  int res= 0;
3460
  LEX  *lex= thd->lex;
unknown's avatar
unknown committed
3461
  /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */
3462
  SELECT_LEX *select_lex= lex->first_select_lex();
unknown's avatar
VIEW  
unknown committed
3463
  /* first table of first SELECT_LEX */
3464
  TABLE_LIST *first_table= select_lex->table_list.first;
unknown's avatar
VIEW  
unknown committed
3465 3466 3467
  /* list of all tables in query */
  TABLE_LIST *all_tables;
  /* most outer SELECT_LEX_UNIT of query */
3468
  SELECT_LEX_UNIT *unit= &lex->unit;
unknown's avatar
unknown committed
3469
  DBUG_ENTER("mysql_execute_command");
3470

3471 3472 3473 3474
  // check that we correctly marked first table for data insertion
  DBUG_ASSERT(!(sql_command_flags[lex->sql_command] & CF_INSERTS_DATA) ||
              first_table->for_insert_data);

3475
  if (thd->security_ctx->password_expired &&
3476 3477 3478 3479
      lex->sql_command != SQLCOM_SET_OPTION &&
      lex->sql_command != SQLCOM_PREPARE &&
      lex->sql_command != SQLCOM_EXECUTE &&
      lex->sql_command != SQLCOM_DEALLOCATE_PREPARE)
3480 3481 3482 3483 3484
  {
    my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
    DBUG_RETURN(1);
  }

3485
  DBUG_ASSERT(thd->transaction->stmt.is_empty() || thd->in_sub_stmt);
3486 3487 3488 3489 3490 3491 3492
  /*
    Each statement or replication event which might produce deadlock
    should handle transaction rollback on its own. So by the start of
    the next statement transaction rollback request should be fulfilled
    already.
  */
  DBUG_ASSERT(! thd->transaction_rollback_request || thd->in_sub_stmt);
unknown's avatar
VIEW  
unknown committed
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
  /*
    In many cases first table of main SELECT_LEX have special meaning =>
    check that it is first table in global list and relink it first in 
    queries_tables list if it is necessary (we need such relinking only
    for queries with subqueries in select list, in this case tables of
    subqueries will go to global list first)

    all_tables will differ from first_table only if most upper SELECT_LEX
    do not contain tables.

    Because of above in place where should be at least one table in most
    outer SELECT_LEX we have following check:
    DBUG_ASSERT(first_table == all_tables);
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
  */
  lex->first_lists_tables_same();
3509
  lex->fix_first_select_number();
3510
  /* should be assigned after making first tables same */
unknown's avatar
VIEW  
unknown committed
3511
  all_tables= lex->query_tables;
3512 3513
  /* set context for commands which do not use setup_tables */
  select_lex->
3514
    context.resolve_in_table_list_only(select_lex->
3515
                                       table_list.first);
unknown's avatar
VIEW  
unknown committed
3516

3517
  /*
3518 3519
    Remember last commmand executed, so that we can use it in places
    like mysql_audit_plugin.
3520 3521 3522
  */
  thd->last_sql_command= lex->sql_command;

3523 3524 3525 3526 3527 3528
  /*
    Reset warning count for each query that uses tables
    A better approach would be to reset this for any commands
    that is not a SHOW command or a select that only access local
    variables, but for now this is probably good enough.
  */
Marc Alff's avatar
Marc Alff committed
3529
  if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0)
3530
    thd->get_stmt_da()->set_warning_info_read_only(TRUE);
Marc Alff's avatar
Marc Alff committed
3531 3532
  else
  {
3533
    thd->get_stmt_da()->set_warning_info_read_only(FALSE);
Marc Alff's avatar
Marc Alff committed
3534
    if (all_tables)
3535
      thd->get_stmt_da()->opt_clear_warning_info(thd->query_id);
Marc Alff's avatar
Marc Alff committed
3536
  }
3537

unknown's avatar
SCRUM  
unknown committed
3538
#ifdef HAVE_REPLICATION
3539
  if (unlikely(thd->slave_thread))
3540
  {
3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557
    if (lex->sql_command == SQLCOM_DROP_TRIGGER)
    {
      /*
        When dropping a trigger, we need to load its table name
        before checking slave filter rules.
      */
      add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables);
      
      if (!all_tables)
      {
        /*
          If table name cannot be loaded,
          it means the trigger does not exists possibly because
          CREATE TRIGGER was previously skipped for this trigger
          according to slave filtering rules.
          Returning success without producing any errors in this case.
        */
3558 3559
        if (!thd->lex->create_info.if_exists() &&
            !(thd->variables.option_bits & OPTION_IF_EXISTS))
3560 3561 3562 3563 3564
          DBUG_RETURN(0);
        /*
          DROP TRIGGER IF NOT EXISTS will return without an error later
          after possibly writing the query to a binlog
        */
3565
      }
3566 3567
      else // force searching in slave.cc:tables_ok()
        all_tables->updating= 1;
3568
    }
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600

    /*
      For fix of BUG#37051, the master stores the table map for update
      in the Query_log_event, and the value is assigned to
      thd->variables.table_map_for_update before executing the update
      query.

      If thd->variables.table_map_for_update is set, then we are
      replicating from a new master, we can use this value to apply
      filter rules without opening all the tables. However If
      thd->variables.table_map_for_update is not set, then we are
      replicating from an old master, so we just skip this and
      continue with the old method. And of course, the bug would still
      exist for old masters.
    */
    if (lex->sql_command == SQLCOM_UPDATE_MULTI &&
        thd->table_map_for_update)
    {
      table_map table_map_for_update= thd->table_map_for_update;
      uint nr= 0;
      TABLE_LIST *table;
      for (table=all_tables; table; table=table->next_global, nr++)
      {
        if (table_map_for_update & ((table_map)1 << nr))
          table->updating= TRUE;
        else
          table->updating= FALSE;
      }

      if (all_tables_not_ok(thd, all_tables))
      {
        /* we warn the slave SQL thread */
3601 3602
        my_message(ER_SLAVE_IGNORED_TABLE, ER_THD(thd, ER_SLAVE_IGNORED_TABLE),
                   MYF(0));
3603 3604
      }
    }
3605
    
unknown's avatar
unknown committed
3606
    /*
unknown's avatar
unknown committed
3607 3608
      Check if statment should be skipped because of slave filtering
      rules
3609 3610

      Exceptions are:
unknown's avatar
unknown committed
3611 3612
      - UPDATE MULTI: For this statement, we want to check the filtering
        rules later in the code
3613
      - SET: we always execute it (Not that many SET commands exists in
unknown's avatar
unknown committed
3614 3615
        the binary log anyway -- only 4.1 masters write SET statements,
	in 5.0 there are no SET statements in the binary log)
3616 3617
      - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we
        have stale files on slave caused by exclusion of one tmp table).
unknown's avatar
merge  
unknown committed
3618
    */
unknown's avatar
unknown committed
3619 3620
    if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) &&
	!(lex->sql_command == SQLCOM_SET_OPTION) &&
3621 3622
	!((lex->sql_command == SQLCOM_DROP_TABLE ||
           lex->sql_command == SQLCOM_DROP_SEQUENCE) &&
3623
          lex->tmp_table() && lex->if_exists()) &&
unknown's avatar
Merge  
unknown committed
3624
        all_tables_not_ok(thd, all_tables))
unknown's avatar
unknown committed
3625 3626
    {
      /* we warn the slave SQL thread */
3627 3628
      my_message(ER_SLAVE_IGNORED_TABLE, ER_THD(thd, ER_SLAVE_IGNORED_TABLE),
                 MYF(0));
3629
      DBUG_RETURN(0);
unknown's avatar
unknown committed
3630
    }
3631 3632 3633 3634 3635
    /* 
       Execute deferred events first
    */
    if (slave_execute_deferred_events(thd))
      DBUG_RETURN(-1);
3636
  }
3637
  else
3638
  {
3639
#endif /* HAVE_REPLICATION */
3640 3641 3642 3643
    /*
      When option readonly is set deny operations which change non-temporary
      tables. Except for the replication thread and the 'super' users.
    */
3644
    if (deny_updates_if_read_only_option(thd, all_tables))
3645 3646 3647 3648 3649 3650 3651
    {
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only");
      DBUG_RETURN(-1);
    }
#ifdef HAVE_REPLICATION
  } /* endif unlikely slave */
#endif
3652
  Opt_trace_start ots(thd);
Varun Gupta's avatar
Varun Gupta committed
3653

3654 3655 3656 3657 3658
  /* store old value of binlog format */
  enum_binlog_format orig_binlog_format,orig_current_stmt_binlog_format;

  thd->get_binlog_format(&orig_binlog_format,
                         &orig_current_stmt_binlog_format);
3659
#ifdef WITH_WSREP
Brave Galera Crew's avatar
Brave Galera Crew committed
3660
  if (WSREP(thd))
3661 3662 3663 3664 3665 3666 3667 3668
  {
    /*
      change LOCK TABLE WRITE to transaction
    */
    if (lex->sql_command== SQLCOM_LOCK_TABLES && wsrep_convert_LOCK_to_trx)
    {
      for (TABLE_LIST *table= all_tables; table; table= table->next_global)
      {
3669
	if (table->lock_type >= TL_FIRST_WRITE)
3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
        {
	  lex->sql_command= SQLCOM_BEGIN;
	  thd->wsrep_converted_lock_session= true;
	  break;
	}
      }
    }
    if (lex->sql_command== SQLCOM_UNLOCK_TABLES &&
	thd->wsrep_converted_lock_session)
    {
      thd->wsrep_converted_lock_session= false;
      lex->sql_command= SQLCOM_COMMIT;
      lex->tx_release= TVL_NO;
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
3684

3685
    /*
3686 3687 3688 3689
     * Bail out if DB snapshot has not been installed. We however,
     * allow SET and SHOW queries and reads from information schema
     * and dirty reads (if configured)
     */
Brave Galera Crew's avatar
Brave Galera Crew committed
3690
    if (!(thd->wsrep_applier) &&
3691
        !(wsrep_ready_get() && wsrep_reject_queries == WSREP_REJECT_NONE)  &&
3692 3693
        !(thd->variables.wsrep_dirty_reads &&
          (sql_command_flags[lex->sql_command] & CF_CHANGES_DATA) == 0)    &&
3694
        !wsrep_tables_accessible_when_detached(all_tables)                 &&
3695
        lex->sql_command != SQLCOM_SET_OPTION                              &&
Jan Lindström's avatar
Jan Lindström committed
3696 3697
        lex->sql_command != SQLCOM_CHANGE_DB                               &&
        !(lex->sql_command == SQLCOM_SELECT && !all_tables)                &&
3698
        !wsrep_is_show_query(lex->sql_command))
3699 3700 3701
    {
      my_message(ER_UNKNOWN_COM_ERROR,
                 "WSREP has not yet prepared node for application use", MYF(0));
3702
      goto error;
3703
    }
3704 3705
  }
#endif /* WITH_WSREP */
3706
  status_var_increment(thd->status_var.com_stat[lex->sql_command]);
3707 3708
  thd->progress.report_to_client= MY_TEST(sql_command_flags[lex->sql_command] &
                                          CF_REPORT_PROGRESS);
3709

3710
  DBUG_ASSERT(thd->transaction->stmt.modified_non_trans_table == FALSE);
Konstantin Osipov's avatar
Konstantin Osipov committed
3711

3712 3713 3714 3715 3716 3717 3718
  /*
    Assign system variables with values specified by the clause
    SET STATEMENT var1=value1 [, var2=value2, ...] FOR <statement>
    if they are any.
  */
  if (run_set_statement_if_requested(thd, lex))
    goto error;
3719

3720 3721 3722 3723
  /* After SET STATEMENT is done, we can initialize the Optimizer Trace: */
  ots.init(thd, all_tables, lex->sql_command, &lex->var_list, thd->query(),
           thd->query_length(), thd->variables.character_set_client);

3724 3725 3726
  if (thd->lex->mi.connection_name.str == NULL)
      thd->lex->mi.connection_name= thd->variables.default_master_connection;

3727 3728 3729 3730 3731 3732 3733 3734 3735 3736
  /*
    Force statement logging for DDL commands to allow us to update
    privilege, system or statistic tables directly without the updates
    getting logged.
  */
  if (!(sql_command_flags[lex->sql_command] &
        (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT |
         CF_STATUS_COMMAND)))
    thd->set_binlog_format_stmt();

Konstantin Osipov's avatar
Konstantin Osipov committed
3737 3738 3739 3740 3741 3742
  /*
    End a active transaction so that this command will have it's
    own transaction and will also sync the binary log. If a DDL is
    not run in it's own transaction it may simply never appear on
    the slave in case the outside transaction rolls back.
  */
Brave Galera Crew's avatar
Brave Galera Crew committed
3743
  if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_BEGIN))
3744
  {
3745 3746 3747 3748 3749
    /*
      Note that this should never happen inside of stored functions
      or triggers as all such statements prohibited there.
    */
    DBUG_ASSERT(! thd->in_sub_stmt);
3750
    /* Statement transaction still should not be started. */
3751
    DBUG_ASSERT(thd->transaction->stmt.is_empty());
3752 3753 3754
    if (!(thd->variables.option_bits & OPTION_GTID_BEGIN))
    {
      /* Commit the normal transaction if one is active. */
3755 3756
      bool commit_failed= trans_commit_implicit(thd);
      /* Release metadata locks acquired in this transaction. */
3757
      thd->release_transactional_locks();
3758
      if (commit_failed)
3759
      {
3760 3761
        WSREP_DEBUG("implicit commit failed, MDL released: %lld",
                    (longlong) thd->thread_id);
3762
        goto error;
3763
      }
3764
    }
3765
    thd->transaction->stmt.mark_trans_did_ddl();
Brave Galera Crew's avatar
Brave Galera Crew committed
3766 3767
#ifdef WITH_WSREP
    /* Clean up the previous transaction on implicit commit */
3768 3769
    if (WSREP_NNULL(thd) && wsrep_thd_is_local(thd) &&
        wsrep_after_statement(thd))
Brave Galera Crew's avatar
Brave Galera Crew committed
3770 3771 3772 3773
    {
      goto error;
    }
#endif /* WITH_WSREP */
3774
  }
3775

3776 3777 3778 3779 3780
#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION)
    DEBUG_SYNC(thd,"before_execute_sql_command");
#endif

3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
  /*
    Check if we are in a read-only transaction and we're trying to
    execute a statement which should always be disallowed in such cases.

    Note that this check is done after any implicit commits.
  */
  if (thd->tx_read_only &&
      (sql_command_flags[lex->sql_command] & CF_DISALLOW_IN_RO_TRANS))
  {
    my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
    goto error;
  }

Michael Widenius's avatar
Michael Widenius committed
3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814
  /*
    Close tables open by HANDLERs before executing DDL statement
    which is going to affect those tables.

    This should happen before temporary tables are pre-opened as
    otherwise we will get errors about attempt to re-open tables
    if table to be changed is open through HANDLER.

    Note that even although this is done before any privilege
    checks there is no security problem here as closing open
    HANDLER doesn't require any privileges anyway.
  */
  if (sql_command_flags[lex->sql_command] & CF_HA_CLOSE)
    mysql_ha_rm_tables(thd, all_tables);

  /*
    Pre-open temporary tables to simplify privilege checking
    for statements which need this.
  */
  if (sql_command_flags[lex->sql_command] & CF_PREOPEN_TMP_TABLES)
  {
3815
    if (thd->open_temporary_tables(all_tables))
Michael Widenius's avatar
Michael Widenius committed
3816 3817
      goto error;
  }
unknown's avatar
unknown committed
3818

3819 3820 3821 3822 3823
  if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
    thd->query_plan_flags|= QPLAN_STATUS;
  if (sql_command_flags[lex->sql_command] & CF_ADMIN_COMMAND)
    thd->query_plan_flags|= QPLAN_ADMIN;

Monty's avatar
Monty committed
3824 3825 3826
  /* Start timeouts */
  thd->set_query_timer();

Brave Galera Crew's avatar
Brave Galera Crew committed
3827
#ifdef WITH_WSREP
mkaruza's avatar
mkaruza committed
3828
  /* Check wsrep_mode rules before command execution. */
3829
  if (WSREP_NNULL(thd) &&
mkaruza's avatar
mkaruza committed
3830 3831 3832
      wsrep_thd_is_local(thd) && !wsrep_check_mode_before_cmd_execute(thd))
    goto error;

Brave Galera Crew's avatar
Brave Galera Crew committed
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
  /*
    Always start a new transaction for a wsrep THD unless the
    current command is DDL or explicit BEGIN. This will guarantee that
    the THD is BF abortable even if it does not generate any
    changes and takes only read locks. If the statement does not
    start a multi STMT transaction, the wsrep_transaction is
    committed as empty at the end of this function.

    Transaction is started for BEGIN in trans_begin(), for DDL the
    implicit commit took care of committing previous transaction
    above and a new transaction should not be started.

    Do not start transaction for stored procedures, it will be handled
    internally in SP processing.
  */
3848
  if (WSREP_NNULL(thd)                    &&
Brave Galera Crew's avatar
Brave Galera Crew committed
3849 3850 3851 3852
      wsrep_thd_is_local(thd)             &&
      lex->sql_command != SQLCOM_BEGIN    &&
      lex->sql_command != SQLCOM_CALL     &&
      lex->sql_command != SQLCOM_EXECUTE  &&
3853
      lex->sql_command != SQLCOM_EXECUTE_IMMEDIATE &&
Brave Galera Crew's avatar
Brave Galera Crew committed
3854 3855 3856 3857 3858 3859
      !(sql_command_flags[lex->sql_command] & CF_AUTO_COMMIT_TRANS))
  {
    wsrep_start_trx_if_not_started(thd);
  }
#endif /* WITH_WSREP */

unknown's avatar
unknown committed
3860
  switch (lex->sql_command) {
3861

3862
  case SQLCOM_SHOW_EVENTS:
3863 3864 3865 3866
#ifndef HAVE_EVENT_SCHEDULER
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
    break;
#endif
3867 3868
  case SQLCOM_SHOW_STATUS:
  {
3869
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
3870
    execute_show_status(thd, all_tables);
3871

3872 3873
    break;
  }
3874
  case SQLCOM_SHOW_EXPLAIN:
3875
  case SQLCOM_SHOW_ANALYZE:
3876 3877
  {
    if (!thd->security_ctx->priv_user[0] &&
3878
        check_global_access(thd, PRIV_STMT_SHOW_EXPLAIN))
3879 3880 3881 3882 3883 3884 3885
      break;

    /*
      The select should use only one table, it's the SHOW EXPLAIN pseudo-table
    */
    if (lex->sroutines.records || lex->query_tables->next_global)
    {
3886
      my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
3887 3888
		 MYF(0));
      goto error;
3889 3890
    }

3891
    Item **it= lex->value_list.head_ref();
3892
    if (!(*it)->basic_const_item() ||
3893
        (*it)->fix_fields_if_needed_for_scalar(lex->thd, it))
3894
    {
3895
      my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
3896 3897 3898 3899
		 MYF(0));
      goto error;
    }
  }
3900
    /* fall through */
3901 3902
  case SQLCOM_SHOW_STATUS_PROC:
  case SQLCOM_SHOW_STATUS_FUNC:
3903 3904
  case SQLCOM_SHOW_STATUS_PACKAGE:
  case SQLCOM_SHOW_STATUS_PACKAGE_BODY:
3905 3906 3907 3908 3909
  case SQLCOM_SHOW_DATABASES:
  case SQLCOM_SHOW_TABLES:
  case SQLCOM_SHOW_TRIGGERS:
  case SQLCOM_SHOW_TABLE_STATUS:
  case SQLCOM_SHOW_OPEN_TABLES:
3910
  case SQLCOM_SHOW_GENERIC:
3911 3912 3913
  case SQLCOM_SHOW_PLUGINS:
  case SQLCOM_SHOW_FIELDS:
  case SQLCOM_SHOW_KEYS:
3914 3915 3916 3917 3918
  case SQLCOM_SHOW_VARIABLES:
  case SQLCOM_SHOW_CHARSETS:
  case SQLCOM_SHOW_COLLATIONS:
  case SQLCOM_SHOW_STORAGE_ENGINES:
  case SQLCOM_SHOW_PROFILE:
3919
  case SQLCOM_SHOW_SLAVE_STAT:
3920
  case SQLCOM_SELECT:
Brave Galera Crew's avatar
Brave Galera Crew committed
3921
  {
3922
#ifdef WITH_WSREP
Brave Galera Crew's avatar
Brave Galera Crew committed
3923 3924 3925 3926 3927 3928 3929
    if (lex->sql_command == SQLCOM_SELECT)
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_READ);
    }
    else
    {
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
Marko Mäkelä's avatar
Marko Mäkelä committed
3930
# ifdef ENABLED_PROFILING
Marko Mäkelä's avatar
Marko Mäkelä committed
3931 3932
      if (lex->sql_command == SQLCOM_SHOW_PROFILE)
        thd->profiling.discard_current_query();
Marko Mäkelä's avatar
Marko Mäkelä committed
3933
# endif
Brave Galera Crew's avatar
Brave Galera Crew committed
3934
    }
3935 3936
#endif /* WITH_WSREP */

3937
    thd->status_var.last_query_cost= 0.0;
3938 3939 3940 3941 3942

    /*
      lex->exchange != NULL implies SELECT .. INTO OUTFILE and this
      requires FILE_ACL access.
    */
3943 3944
    privilege_t privileges_requested= lex->exchange ? SELECT_ACL | FILE_ACL :
                                                      SELECT_ACL;
3945

unknown's avatar
VIEW  
unknown committed
3946
    if (all_tables)
3947
      res= check_table_access(thd,
3948 3949
                              privileges_requested,
                              all_tables, FALSE, UINT_MAX, FALSE);
unknown's avatar
unknown committed
3950
    else
Alexey Botchkov's avatar
Alexey Botchkov committed
3951
      res= check_access(thd, privileges_requested, any_db.str, NULL,NULL,0,0);
3952

3953 3954
    if (!res)
      res= execute_sqlcom_select(thd, all_tables);
3955

unknown's avatar
unknown committed
3956
    break;
3957
  }
3958 3959 3960 3961 3962
  case SQLCOM_EXECUTE_IMMEDIATE:
  {
    mysql_sql_stmt_execute_immediate(thd);
    break;
  }
3963
  case SQLCOM_PREPARE:
3964
  {
3965
    mysql_sql_stmt_prepare(thd);
unknown's avatar
unknown committed
3966 3967 3968 3969
    break;
  }
  case SQLCOM_EXECUTE:
  {
3970
    mysql_sql_stmt_execute(thd);
unknown's avatar
unknown committed
3971 3972 3973 3974
    break;
  }
  case SQLCOM_DEALLOCATE_PREPARE:
  {
3975
    mysql_sql_stmt_close(thd);
unknown's avatar
unknown committed
3976 3977
    break;
  }
unknown's avatar
unknown committed
3978
  case SQLCOM_DO:
3979
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
3980
        || open_and_lock_tables(thd, all_tables, TRUE, 0))
unknown's avatar
unknown committed
3981
      goto error;
unknown's avatar
unknown committed
3982 3983

    res= mysql_do(thd, *lex->insert_list);
unknown's avatar
unknown committed
3984 3985
    break;

3986
  case SQLCOM_EMPTY_QUERY:
3987
    my_ok(thd);
3988 3989
    break;

unknown's avatar
unknown committed
3990 3991 3992 3993
  case SQLCOM_HELP:
    res= mysqld_help(thd,lex->help_arg);
    break;

3994
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
3995
  case SQLCOM_PURGE:
3996
  {
3997
    if (check_global_access(thd, PRIV_STMT_PURGE_BINLOG))
3998
      goto error;
unknown's avatar
unknown committed
3999
    /* PURGE MASTER LOGS TO 'file' */
4000 4001 4002
    res = purge_master_logs(thd, lex->to_log);
    break;
  }
4003 4004
  case SQLCOM_PURGE_BEFORE:
  {
4005 4006
    Item *it;

4007
    if (check_global_access(thd, PRIV_STMT_PURGE_BINLOG))
4008
      goto error;
unknown's avatar
unknown committed
4009
    /* PURGE MASTER LOGS BEFORE 'data' */
4010
    it= (Item *)lex->value_list.head();
4011
    if (it->fix_fields_if_needed_for_scalar(lex->thd, &it))
4012 4013 4014 4015
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE");
      goto error;
    }
Monty's avatar
Monty committed
4016
    it= new (thd->mem_root) Item_func_unix_timestamp(thd, it);
4017
    it->fix_fields(thd, &it);
4018
    res = purge_master_logs_before_date(thd, (ulong)it->val_int());
4019 4020
    break;
  }
4021
#endif
unknown's avatar
unknown committed
4022 4023
  case SQLCOM_SHOW_WARNS:
  {
4024
    res= mysqld_show_warnings(thd, (ulong)
4025 4026 4027
			      ((1L << (uint) Sql_condition::WARN_LEVEL_NOTE) |
			       (1L << (uint) Sql_condition::WARN_LEVEL_WARN) |
			       (1L << (uint) Sql_condition::WARN_LEVEL_ERROR)
4028
			       ));
unknown's avatar
unknown committed
4029 4030 4031 4032
    break;
  }
  case SQLCOM_SHOW_ERRORS:
  {
4033
    res= mysqld_show_warnings(thd, (ulong)
4034
			      (1L << (uint) Sql_condition::WARN_LEVEL_ERROR));
unknown's avatar
unknown committed
4035 4036
    break;
  }
unknown's avatar
unknown committed
4037 4038
  case SQLCOM_SHOW_PROFILES:
  {
4039
#if defined(ENABLED_PROFILING)
4040
    thd->profiling.discard_current_query();
unknown's avatar
unknown committed
4041
    res= thd->profiling.show_profiles();
4042 4043 4044
    if (res)
      goto error;
#else
4045
    my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
4046 4047
    goto error;
#endif
unknown's avatar
unknown committed
4048 4049
    break;
  }
4050

unknown's avatar
unknown committed
4051
#ifdef HAVE_REPLICATION
4052 4053
  case SQLCOM_SHOW_SLAVE_HOSTS:
  {
4054
    if (check_global_access(thd, PRIV_STMT_SHOW_SLAVE_HOSTS))
4055 4056 4057 4058
      goto error;
    res = show_slave_hosts(thd);
    break;
  }
4059 4060 4061 4062 4063 4064 4065 4066
  case SQLCOM_SHOW_RELAYLOG_EVENTS:
  {
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    if (check_global_access(thd, PRIV_STMT_SHOW_RELAYLOG_EVENTS))
      goto error;
    res = mysql_show_binlog_events(thd);
    break;
  }
unknown's avatar
unknown committed
4067 4068
  case SQLCOM_SHOW_BINLOG_EVENTS:
  {
4069
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
4070
    if (check_global_access(thd, PRIV_STMT_SHOW_BINLOG_EVENTS))
unknown's avatar
unknown committed
4071
      goto error;
4072
    res = mysql_show_binlog_events(thd);
unknown's avatar
unknown committed
4073 4074
    break;
  }
4075 4076
#endif

unknown's avatar
unknown committed
4077 4078
  case SQLCOM_ASSIGN_TO_KEYCACHE:
  {
unknown's avatar
VIEW  
unknown committed
4079
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4080
    if (check_access(thd, INDEX_ACL, first_table->db.str,
Marc Alff's avatar
Marc Alff committed
4081 4082 4083
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
unknown's avatar
unknown committed
4084
      goto error;
4085
    res= mysql_assign_to_keycache(thd, first_table, &lex->ident);
unknown's avatar
unknown committed
4086 4087
    break;
  }
unknown's avatar
unknown committed
4088 4089
  case SQLCOM_PRELOAD_KEYS:
  {
unknown's avatar
VIEW  
unknown committed
4090
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4091
    if (check_access(thd, INDEX_ACL, first_table->db.str,
Marc Alff's avatar
Marc Alff committed
4092 4093 4094
                     &first_table->grant.privilege,
                     &first_table->grant.m_internal,
                     0, 0))
4095
      goto error;
unknown's avatar
VIEW  
unknown committed
4096
    res = mysql_preload_keys(thd, first_table);
unknown's avatar
unknown committed
4097 4098
    break;
  }
unknown's avatar
unknown committed
4099
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
4100
  case SQLCOM_CHANGE_MASTER:
4101
  {
4102 4103 4104
    LEX_MASTER_INFO *lex_mi= &thd->lex->mi;
    Master_info *mi;
    bool new_master= 0;
4105
    bool master_info_added;
4106

4107
    if (check_global_access(thd, PRIV_STMT_CHANGE_MASTER))
4108
      goto error;
4109 4110 4111 4112
    /*
      In this code it's ok to use LOCK_active_mi as we are adding new things
      into master_info_index
    */
Marc Alff's avatar
Marc Alff committed
4113
    mysql_mutex_lock(&LOCK_active_mi);
4114
    if (!master_info_index)
4115 4116 4117
    {
      mysql_mutex_unlock(&LOCK_active_mi);
      my_error(ER_SERVER_SHUTDOWN, MYF(0));
4118
      goto error;
4119
    }
4120

4121
    mi= master_info_index->get_master_info(&lex_mi->connection_name,
4122
                                           Sql_condition::WARN_LEVEL_NOTE);
4123 4124 4125 4126 4127

    if (mi == NULL)
    {
      /* New replication created */
      mi= new Master_info(&lex_mi->connection_name, relay_log_recovery); 
4128
      if (unlikely(!mi || mi->error()))
4129 4130 4131 4132 4133 4134 4135 4136 4137
      {
        delete mi;
        res= 1;
        mysql_mutex_unlock(&LOCK_active_mi);
        break;
      }
      new_master= 1;
    }

4138
    res= change_master(thd, mi, &master_info_added);
4139 4140 4141
    if (res && new_master)
    {
      /*
4142 4143 4144 4145
        If the new master was added by change_master(), remove it as it didn't
        work (this will free mi as well).

        If new master was not added, we still need to free mi.
4146
      */
4147
      if (master_info_added)
4148
        master_info_index->remove_master_info(mi, 1);
4149 4150
      else
        delete mi;
4151
    }
4152 4153 4154 4155 4156
    else
    {
      mi->rpl_filter= get_or_create_rpl_filter(lex_mi->connection_name.str,
                                               lex_mi->connection_name.length);
    }
4157

Marc Alff's avatar
Marc Alff committed
4158
    mysql_mutex_unlock(&LOCK_active_mi);
4159 4160
    break;
  }
4161

4162
  case SQLCOM_SHOW_BINLOG_STAT:
4163
  {
4164
    /* Accept one of two privileges */
4165
    if (check_global_access(thd, PRIV_STMT_SHOW_BINLOG_STATUS))
4166 4167 4168 4169
      goto error;
    res = show_binlog_info(thd);
    break;
  }
unknown's avatar
unknown committed
4170

unknown's avatar
unknown committed
4171
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
4172
  case SQLCOM_SHOW_ENGINE_STATUS:
unknown's avatar
unknown committed
4173
    {
4174
      if (check_global_access(thd, PRIV_STMT_SHOW_ENGINE_STATUS))
unknown's avatar
unknown committed
4175 4176
        goto error;
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS);
unknown's avatar
unknown committed
4177 4178
      break;
    }
unknown's avatar
unknown committed
4179
  case SQLCOM_SHOW_ENGINE_MUTEX:
unknown's avatar
unknown committed
4180
    {
4181
      if (check_global_access(thd, PRIV_STMT_SHOW_ENGINE_MUTEX))
unknown's avatar
unknown committed
4182
        goto error;
unknown's avatar
unknown committed
4183
      res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX);
unknown's avatar
unknown committed
4184 4185
      break;
    }
4186
  case SQLCOM_DROP_INDEX:
4187 4188 4189 4190
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
    /* fall through */
  case SQLCOM_CREATE_INDEX:
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200
  /*
    CREATE INDEX and DROP INDEX are implemented by calling ALTER
    TABLE with proper arguments.

    In the future ALTER TABLE will notice that the request is to
    only add indexes and create these one by one for the existing
    table without having to do a full rebuild.
  */
  {
    /* Prepare stack copies to be re-execution safe */
4201
    Table_specification_st create_info;
4202 4203
    Alter_info alter_info(lex->alter_info, thd->mem_root);

4204
    if (unlikely(thd->is_fatal_error)) /* out of memory creating alter_info */
4205 4206
      goto error;

unknown's avatar
VIEW  
unknown committed
4207 4208
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    if (check_one_table_access(thd, INDEX_ACL, all_tables))
unknown's avatar
unknown committed
4209
      goto error; /* purecov: inspected */
4210

4211
    create_info.init();
4212 4213
    create_info.db_type= 0;
    create_info.row_type= ROW_TYPE_NOT_USED;
4214
    create_info.alter_info= &alter_info;
unknown's avatar
unknown committed
4215

4216 4217
    WSREP_TO_ISOLATION_BEGIN(first_table->db.str, first_table->table_name.str, NULL);

4218
    Recreate_info recreate_info;
4219
    res= mysql_alter_table(thd, &first_table->db, &first_table->table_name,
4220 4221
                           &create_info, first_table,
                           &recreate_info, &alter_info,
4222
                           0, (ORDER*) 0, 0, lex->if_exists());
4223 4224
    break;
  }
unknown's avatar
unknown committed
4225
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
4226
  case SQLCOM_SLAVE_START:
4227
  {
4228 4229
    LEX_MASTER_INFO* lex_mi= &thd->lex->mi;
    Master_info *mi;
unknown's avatar
unknown committed
4230 4231 4232 4233
    int load_error;

    load_error= rpl_load_gtid_slave_state(thd);

4234 4235 4236 4237
    /*
      We don't need to ensure that only one user is using master_info
      as start_slave is protected against simultaneous usage
    */
4238 4239
    if (unlikely((mi= get_master_info(&lex_mi->connection_name,
                                      Sql_condition::WARN_LEVEL_ERROR))))
unknown's avatar
unknown committed
4240 4241 4242 4243
    {
      if (load_error)
      {
        /*
4244 4245 4246
          We cannot start a slave using GTID if we cannot load the
          GTID position from the mysql.gtid_slave_pos table. But we
          can allow non-GTID replication (useful eg. during upgrade).
unknown's avatar
unknown committed
4247 4248 4249
        */
        if (mi->using_gtid != Master_info::USE_GTID_NO)
        {
4250
          mi->release();
unknown's avatar
unknown committed
4251 4252 4253 4254 4255
          break;
        }
        else
          thd->clear_error();
      }
4256 4257
      if (!start_slave(thd, mi, 1 /* net report*/))
        my_ok(thd);
4258
      mi->release();
unknown's avatar
unknown committed
4259
    }
unknown's avatar
unknown committed
4260
    break;
4261
  }
unknown's avatar
unknown committed
4262
  case SQLCOM_SLAVE_STOP:
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
  {
    LEX_MASTER_INFO *lex_mi;
    Master_info *mi;
    /*
      If the client thread has locked tables, a deadlock is possible.
      Assume that
      - the client thread does LOCK TABLE t READ.
      - then the master updates t.
      - then the SQL slave thread wants to update t,
        so it waits for the client thread because t is locked by it.
4273
    - then the client thread does SLAVE STOP.
4274 4275
      SLAVE STOP waits for the SQL slave thread to terminate its
      update t, which waits for the client thread because t is locked by it.
4276 4277 4278 4279 4280 4281 4282 4283
      To prevent that, refuse SLAVE STOP if the
      client thread has locked tables
    */
    if (thd->locked_tables_mode ||
        thd->in_active_multi_stmt_transaction() ||
        thd->global_read_lock.is_acquired())
    {
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
4284
                 ER_THD(thd, ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
4285 4286 4287 4288
      goto error;
    }

    lex_mi= &thd->lex->mi;
4289 4290 4291 4292 4293 4294 4295 4296 4297
    if ((mi= get_master_info(&lex_mi->connection_name,
                             Sql_condition::WARN_LEVEL_ERROR)))
    {
      if (stop_slave(thd, mi, 1/* net report*/))
        res= 1;
      mi->release();
      if (rpl_parallel_resize_pool_if_no_slaves())
        res= 1;
      if (!res)
4298
        my_ok(thd);
4299
    }
4300 4301 4302
    break;
  }
  case SQLCOM_SLAVE_ALL_START:
4303
  {
4304
    mysql_mutex_lock(&LOCK_active_mi);
4305
    if (master_info_index && !master_info_index->start_all_slaves(thd))
4306 4307 4308
      my_ok(thd);
    mysql_mutex_unlock(&LOCK_active_mi);
    break;
4309
  }
4310
  case SQLCOM_SLAVE_ALL_STOP:
4311
  {
4312 4313 4314 4315 4316
    if (thd->locked_tables_mode ||
        thd->in_active_multi_stmt_transaction() ||
        thd->global_read_lock.is_acquired())
    {
      my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
4317
                 ER_THD(thd, ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
4318 4319
      goto error;
    }
Marc Alff's avatar
Marc Alff committed
4320
    mysql_mutex_lock(&LOCK_active_mi);
4321
    if (master_info_index && !master_info_index->stop_all_slaves(thd))
4322
      my_ok(thd);      
Marc Alff's avatar
Marc Alff committed
4323
    mysql_mutex_unlock(&LOCK_active_mi);
unknown's avatar
unknown committed
4324
    break;
4325
  }
unknown's avatar
unknown committed
4326
#endif /* HAVE_REPLICATION */
unknown's avatar
unknown committed
4327
  case SQLCOM_RENAME_TABLE:
unknown's avatar
unknown committed
4328
  {
4329 4330 4331
    if (check_rename_table(thd, first_table, all_tables))
      goto error;

4332
    WSREP_TO_ISOLATION_BEGIN(0, 0, first_table);
4333

4334 4335 4336
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

4337
    if (mysql_rename_tables(thd, first_table, 0, lex->if_exists()))
unknown's avatar
unknown committed
4338
      goto error;
unknown's avatar
unknown committed
4339
    break;
unknown's avatar
unknown committed
4340
  }
4341
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
4342 4343
  case SQLCOM_SHOW_BINLOGS:
#ifdef DONT_ALLOW_SHOW_COMMANDS
4344
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
unknown's avatar
unknown committed
4345
               MYF(0)); /* purecov: inspected */
4346
    goto error;
unknown's avatar
unknown committed
4347 4348
#else
    {
4349
      if (check_global_access(thd, PRIV_STMT_SHOW_BINARY_LOGS))
unknown's avatar
unknown committed
4350
	goto error;
4351
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
unknown's avatar
unknown committed
4352 4353 4354
      res = show_binlogs(thd);
      break;
    }
unknown's avatar
unknown committed
4355
#endif
4356
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
4357
  case SQLCOM_SHOW_CREATE:
4358
  {
Jan Lindström's avatar
Jan Lindström committed
4359
     DBUG_ASSERT(first_table == all_tables && first_table != 0);
unknown's avatar
unknown committed
4360
#ifdef DONT_ALLOW_SHOW_COMMANDS
4361
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
unknown's avatar
unknown committed
4362
               MYF(0)); /* purecov: inspected */
4363
    goto error;
unknown's avatar
unknown committed
4364
#else
4365
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
4366

4367 4368 4369 4370 4371 4372 4373 4374 4375
     /*
        Access check:
        SHOW CREATE TABLE require any privileges on the table level (ie
        effecting all columns in the table).
        SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table
        level.
        NOTE: SHOW_VIEW ACL is checked when the view is created.
      */

4376
      DBUG_PRINT("debug", ("lex->only_view: %d, table: %s.%s",
4377
                           lex->table_type == TABLE_TYPE_VIEW,
4378
                           first_table->db.str, first_table->table_name.str));
unknown's avatar
unknown committed
4379
      res= mysqld_show_create(thd, first_table);
unknown's avatar
unknown committed
4380
      break;
unknown's avatar
unknown committed
4381
#endif
4382
  }
4383 4384
  case SQLCOM_CHECKSUM:
  {
unknown's avatar
VIEW  
unknown committed
4385
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4386
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_READ);
4387

4388 4389
    if (check_table_access(thd, SELECT_ACL, all_tables,
                           FALSE, UINT_MAX, FALSE))
4390
      goto error; /* purecov: inspected */
4391

unknown's avatar
VIEW  
unknown committed
4392
    res = mysql_checksum_table(thd, first_table, &lex->check_opt);
4393 4394
    break;
  }
unknown's avatar
unknown committed
4395
  case SQLCOM_UPDATE:
4396
  case SQLCOM_UPDATE_MULTI:
4397 4398
  case SQLCOM_DELETE:
  case SQLCOM_DELETE_MULTI:
unknown's avatar
unknown committed
4399 4400
  {
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4401
    DBUG_ASSERT(lex->m_sql_cmd != NULL);
unknown's avatar
unknown committed
4402

4403 4404
    res = lex->m_sql_cmd->execute(thd);
    thd->abort_on_warning= 0;
unknown's avatar
unknown committed
4405
    break;
unknown's avatar
unknown committed
4406
  }
unknown's avatar
unknown committed
4407
  case SQLCOM_REPLACE:
4408 4409
    if ((res= generate_incident_event(thd)))
      break;
4410
    /* fall through */
4411 4412
  case SQLCOM_INSERT:
  {
4413
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);
4414
    select_result *sel_result= NULL;
unknown's avatar
VIEW  
unknown committed
4415
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
Michael Widenius's avatar
Michael Widenius committed
4416

Brave Galera Crew's avatar
Brave Galera Crew committed
4417
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);
4418

Michael Widenius's avatar
Michael Widenius committed
4419 4420 4421 4422 4423 4424 4425
    /*
      Since INSERT DELAYED doesn't support temporary tables, we could
      not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE.
      Open them here instead.
    */
    if (first_table->lock_type != TL_WRITE_DELAYED)
    {
4426 4427
      res= (thd->open_temporary_tables(all_tables)) ? TRUE : FALSE;
      if (res)
Michael Widenius's avatar
Michael Widenius committed
4428 4429 4430
        break;
    }

unknown's avatar
unknown committed
4431
    if ((res= insert_precheck(thd, all_tables)))
unknown's avatar
unknown committed
4432
      break;
4433

4434
    MYSQL_INSERT_START(thd->query());
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
    Protocol* save_protocol=NULL;

    if (lex->has_returning())
    {
      status_var_increment(thd->status_var.feature_insert_returning);

      /* This is INSERT ... RETURNING. It will return output to the client */
      if (thd->lex->analyze_stmt)
      {
        /*
          Actually, it is ANALYZE .. INSERT .. RETURNING. We need to produce
          output and then discard it.
        */
        sel_result= new (thd->mem_root) select_send_analyze(thd);
        save_protocol= thd->protocol;
        thd->protocol= new Protocol_discard(thd);
      }
      else
      {
        if (!(sel_result= new (thd->mem_root) select_send(thd)))
          goto error;
      }
    }

unknown's avatar
VIEW  
unknown committed
4459
    res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values,
4460 4461
                      lex->update_list, lex->value_list,
                      lex->duplicates, lex->ignore, sel_result);
4462
    status_var_add(thd->status_var.rows_sent, thd->get_sent_row_count());
4463 4464 4465 4466 4467 4468
    if (save_protocol)
    {
      delete thd->protocol;
      thd->protocol= save_protocol;
    }
    if (!res && thd->lex->analyze_stmt)
4469 4470 4471 4472
    {
      bool extended= thd->lex->describe & DESCRIBE_EXTENDED;
      res= thd->lex->explain->send_explain(thd, extended);
    }
4473
    delete sel_result;
4474
    MYSQL_INSERT_DONE(res, (ulong) thd->get_row_count_func());
4475 4476 4477 4478 4479 4480
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
unknown's avatar
VIEW  
unknown committed
4481
    if (first_table->view && !first_table->contain_auto_increment)
4482 4483
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
4484

4485
#ifdef ENABLED_DEBUG_SYNC
4486 4487
    DBUG_EXECUTE_IF("after_mysql_insert",
                    {
Sergei Golubchik's avatar
Sergei Golubchik committed
4488 4489
                      const char act1[]= "now wait_for signal.continue";
                      const char act2[]= "now signal signal.continued";
4490
                      DBUG_ASSERT(debug_sync_service);
4491 4492 4493 4494
                      DBUG_ASSERT(!debug_sync_set_action(thd,
                                                         STRING_WITH_LEN(act1)));
                      DBUG_ASSERT(!debug_sync_set_action(thd,
                                                         STRING_WITH_LEN(act2)));
4495
                    };);
4496
    DEBUG_SYNC(thd, "after_mysql_insert");
4497
#endif
unknown's avatar
unknown committed
4498
    break;
4499
  }
unknown's avatar
unknown committed
4500 4501 4502
  case SQLCOM_REPLACE_SELECT:
  case SQLCOM_INSERT_SELECT:
  {
4503
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE);
4504
    select_insert *sel_result;
4505
    select_result *result= NULL;
4506
    bool explain= MY_TEST(lex->describe);
unknown's avatar
VIEW  
unknown committed
4507
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
Brave Galera Crew's avatar
Brave Galera Crew committed
4508
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE);
4509

unknown's avatar
unknown committed
4510
    if ((res= insert_precheck(thd, all_tables)))
4511
      break;
4512

4513
#ifdef WITH_WSREP
4514 4515 4516 4517
    bool wsrep_toi= false;
    const bool wsrep= WSREP(thd);

    if (wsrep && thd->wsrep_consistency_check == CONSISTENCY_CHECK_DECLARED)
4518 4519
    {
      thd->wsrep_consistency_check = CONSISTENCY_CHECK_RUNNING;
4520
      wsrep_toi= true;
4521
      WSREP_TO_ISOLATION_BEGIN(first_table->db.str, first_table->table_name.str, NULL);
4522 4523 4524
    }
#endif /* WITH_WSREP */

4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541
    /*
      INSERT...SELECT...ON DUPLICATE KEY UPDATE/REPLACE SELECT/
      INSERT...IGNORE...SELECT can be unsafe, unless ORDER BY PRIMARY KEY
      clause is used in SELECT statement. We therefore use row based
      logging if mixed or row based logging is available.
      TODO: Check if the order of the output of the select statement is
      deterministic. Waiting for BUG#42415
    */
    if (lex->sql_command == SQLCOM_INSERT_SELECT &&
        lex->duplicates == DUP_UPDATE)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE);

    if (lex->sql_command == SQLCOM_INSERT_SELECT && lex->ignore)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT);

    if (lex->sql_command == SQLCOM_REPLACE_SELECT)
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_REPLACE_SELECT);
unknown's avatar
unknown committed
4542

4543
    /* Fix lock for first table */
unknown's avatar
VIEW  
unknown committed
4544 4545
    if (first_table->lock_type == TL_WRITE_DELAYED)
      first_table->lock_type= TL_WRITE;
4546

4547 4548
    /* Don't unlock tables until command is written to binary log */
    select_lex->options|= SELECT_NO_UNLOCK;
unknown's avatar
unknown committed
4549

4550
    unit->set_limit(select_lex);
4551

4552
    if (!(res=open_and_lock_tables(thd, all_tables, TRUE, 0)))
4553
    {
4554
      MYSQL_INSERT_SELECT_START(thd->query());
4555 4556 4557 4558

#ifdef WITH_WSREP
      if (wsrep && !first_table->view)
      {
4559
        bool is_innodb= first_table->table->file->partition_ht()->db_type == DB_TYPE_INNODB;
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572

        // For consistency check inserted table needs to be InnoDB
        if (!is_innodb && thd->wsrep_consistency_check != NO_CONSISTENCY_CHECK)
        {
          push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                              HA_ERR_UNSUPPORTED,
                              "Galera cluster does support consistency check only"
                              " for InnoDB tables.");
          thd->wsrep_consistency_check= NO_CONSISTENCY_CHECK;
        }

        // For !InnoDB we start TOI if it is not yet started and hope for the best
        if (!is_innodb && !wsrep_toi)
4573 4574 4575 4576
        {
          const legacy_db_type db_type= first_table->table->file->partition_ht()->db_type;

          /* Currently we support TOI for MyISAM only. */
Marko Mäkelä's avatar
Marko Mäkelä committed
4577 4578
          if (db_type == DB_TYPE_MYISAM &&
              wsrep_check_mode(WSREP_MODE_REPLICATE_MYISAM))
4579 4580
            WSREP_TO_ISOLATION_BEGIN(first_table->db.str, first_table->table_name.str, NULL);
        }
4581 4582
      }
#endif /* WITH_WSREP */
4583 4584 4585 4586
      /*
        Only the INSERT table should be merged. Other will be handled by
        select.
      */
4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611

      Protocol* save_protocol=NULL;

      if (lex->has_returning())
      {
        status_var_increment(thd->status_var.feature_insert_returning);

        /* This is INSERT ... RETURNING. It will return output to the client */
        if (thd->lex->analyze_stmt)
        {
          /*
            Actually, it is ANALYZE .. INSERT .. RETURNING. We need to produce
            output and then discard it.
          */
          result= new (thd->mem_root) select_send_analyze(thd);
          save_protocol= thd->protocol;
          thd->protocol= new Protocol_discard(thd);
        }
        else
        {
          if (!(result= new (thd->mem_root) select_send(thd)))
            goto error;
        }
      }

4612
      /* Skip first table, which is the table we are inserting in */
unknown's avatar
unknown committed
4613
      TABLE_LIST *second_table= first_table->next_local;
4614 4615 4616 4617 4618 4619 4620
      /*
        This is a hack: this leaves select_lex->table_list in an inconsistent
        state as 'elements' does not contain number of elements in the list.
        Moreover, if second_table == NULL then 'next' becomes invalid.
        TODO: fix it by removing the front element (restoring of it should
        be done properly as well)
      */
4621
      select_lex->table_list.first= second_table;
4622
      select_lex->context.table_list=
4623
        select_lex->context.first_name_resolution_table= second_table;
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
      res= mysql_insert_select_prepare(thd, result);
      if (!res &&
          (sel_result= new (thd->mem_root)
                       select_insert(thd, first_table,
                                    first_table->table,
                                    &lex->field_list,
                                    &lex->update_list,
                                    &lex->value_list,
                                    lex->duplicates,
                                    lex->ignore,
                                    result)))
4635
      {
4636 4637 4638
        if (lex->analyze_stmt)
          ((select_result_interceptor*)sel_result)->disable_my_ok_calls();

4639 4640 4641 4642
        if (explain)
          res= mysql_explain_union(thd, &thd->lex->unit, sel_result);
        else
          res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE);
4643 4644 4645 4646 4647 4648
        /*
          Invalidate the table in the query cache if something changed
          after unlocking when changes become visible.
          TODO: this is workaround. right way will be move invalidating in
          the unlock procedure.
        */
4649
        if (!res && first_table->lock_type ==  TL_WRITE_CONCURRENT_INSERT &&
4650 4651
            thd->lock)
        {
4652 4653 4654
          /* INSERT ... SELECT should invalidate only the very first table */
          TABLE_LIST *save_table= first_table->next_local;
          first_table->next_local= 0;
4655
          query_cache_invalidate3(thd, first_table, 1);
4656
          first_table->next_local= save_table;
4657
        }
4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
        if (explain)
        {
          /*
            sel_result needs to be cleaned up properly.
            INSERT... SELECT statement will call either send_eof() or
            abort_result_set(). EXPLAIN doesn't call either, so we need
            to cleanup manually.
          */
          sel_result->abort_result_set();
        }
unknown's avatar
unknown committed
4668
        delete sel_result;
4669
      }
4670 4671 4672 4673 4674 4675 4676 4677
      else if (res < 0)
      {
        /*
          Insert should be ignored but we have to log the query in statement
          format in the binary log
        */
        res= thd->binlog_current_query_unfiltered();
      }
4678 4679 4680 4681 4682 4683
      delete result;
      if (save_protocol)
      {
        delete thd->protocol;
        thd->protocol= save_protocol;
      }
4684
      if (!res && (explain || lex->analyze_stmt))
4685 4686 4687 4688
      {
        bool extended= thd->lex->describe & DESCRIBE_EXTENDED;
        res= thd->lex->explain->send_explain(thd, extended);
      }
4689

4690
      /* revert changes for SP */
4691
      MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->get_row_count_func());
4692
      select_lex->table_list.first= first_table;
4693 4694

      status_var_add(thd->status_var.rows_sent, thd->get_sent_row_count());
4695
    }
4696 4697 4698 4699 4700 4701
    /*
      If we have inserted into a VIEW, and the base table has
      AUTO_INCREMENT column, but this column is not accessible through
      a view, then we should restore LAST_INSERT_ID to the value it
      had before the statement.
    */
unknown's avatar
VIEW  
unknown committed
4702
    if (first_table->view && !first_table->contain_auto_increment)
4703 4704
      thd->first_successful_insert_id_in_cur_stmt=
        thd->first_successful_insert_id_in_prev_stmt;
4705

unknown's avatar
unknown committed
4706 4707
    break;
  }
4708
  case SQLCOM_DROP_SEQUENCE:
unknown's avatar
unknown committed
4709
  case SQLCOM_DROP_TABLE:
unknown's avatar
unknown committed
4710
  {
Michael Widenius's avatar
Michael Widenius committed
4711
    int result;
unknown's avatar
VIEW  
unknown committed
4712
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
Michael Widenius's avatar
Michael Widenius committed
4713 4714 4715 4716 4717 4718

    thd->open_options|= HA_OPEN_FOR_REPAIR;
    result= thd->open_temporary_tables(all_tables);
    thd->open_options&= ~HA_OPEN_FOR_REPAIR;
    if (result)
      goto error;
4719
    if (!lex->tmp_table())
4720
    {
4721
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
4722 4723
	goto error;				/* purecov: inspected */
    }
unknown's avatar
unknown committed
4724
    else
unknown's avatar
unknown committed
4725
    {
4726 4727
      if (thd->transaction->xid_state.check_has_uncommitted_xa())
        goto error;
4728
      status_var_decrement(thd->status_var.com_stat[lex->sql_command]);
4729 4730
      status_var_increment(thd->status_var.com_drop_tmp_table);

unknown's avatar
unknown committed
4731
      /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */
4732
      thd->variables.option_bits|= OPTION_BINLOG_THIS_TRX;
unknown's avatar
unknown committed
4733
    }
4734 4735 4736 4737 4738 4739
    /*
      If we are a slave, we should add IF EXISTS if the query executed
      on the master without an error. This will help a slave to
      recover from multi-table DROP TABLE that was aborted in the
      middle.
    */
4740 4741 4742
    if ((thd->slave_thread && !thd->slave_expected_error &&
         slave_ddl_exec_mode_options == SLAVE_EXEC_MODE_IDEMPOTENT) ||
        thd->variables.option_bits & OPTION_IF_EXISTS)
4743
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
4744

4745
#ifdef WITH_WSREP
4746 4747 4748 4749 4750 4751
    if (WSREP(thd))
    {
      for (TABLE_LIST *table= all_tables; table; table= table->next_global)
      {
        if (!lex->tmp_table() &&
           (!thd->is_current_stmt_binlog_format_row() ||
4752
	    !is_temporary_table(table)))
4753 4754 4755 4756 4757 4758
        {
          WSREP_TO_ISOLATION_BEGIN(NULL, NULL, all_tables);
          break;
        }
      }
    }
4759 4760
#endif /* WITH_WSREP */

4761
    /* DDL and binlog write order are protected by metadata locks. */
4762
    res= mysql_rm_table(thd, first_table, lex->if_exists(), lex->tmp_table(),
4763
                        lex->table_type == TABLE_TYPE_SEQUENCE, 0);
4764

4765 4766 4767 4768
    /*
      When dropping temporary tables if @@session_track_state_change is ON
      then send the boolean tracker in the OK packet
    */
4769 4770
    if(!res && (lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
    {
Sergey Vojtovich's avatar
Sergey Vojtovich committed
4771
      thd->session_tracker.state_change.mark_as_changed(thd);
4772
    }
4773
    break;
unknown's avatar
unknown committed
4774
  }
unknown's avatar
unknown committed
4775
  case SQLCOM_SHOW_PROCESSLIST:
4776
    if (!thd->security_ctx->priv_user[0] &&
4777
        check_global_access(thd, PRIV_STMT_SHOW_PROCESSLIST))
unknown's avatar
unknown committed
4778
      break;
unknown's avatar
unknown committed
4779
    mysqld_list_processes(thd,
4780 4781 4782 4783
                (thd->security_ctx->master_access & PRIV_STMT_SHOW_PROCESSLIST ?
                 NullS :
                 thd->security_ctx->priv_user),
                lex->verbose);
unknown's avatar
unknown committed
4784
    break;
unknown's avatar
unknown committed
4785 4786 4787
  case SQLCOM_SHOW_AUTHORS:
    res= mysqld_show_authors(thd);
    break;
4788 4789 4790
  case SQLCOM_SHOW_CONTRIBUTORS:
    res= mysqld_show_contributors(thd);
    break;
unknown's avatar
unknown committed
4791 4792 4793
  case SQLCOM_SHOW_PRIVILEGES:
    res= mysqld_show_privileges(thd);
    break;
unknown's avatar
unknown committed
4794
  case SQLCOM_SHOW_ENGINE_LOGS:
unknown's avatar
unknown committed
4795
#ifdef DONT_ALLOW_SHOW_COMMANDS
4796
    my_message(ER_NOT_ALLOWED_COMMAND, ER_THD(thd, ER_NOT_ALLOWED_COMMAND),
unknown's avatar
unknown committed
4797
               MYF(0));	/* purecov: inspected */
4798
    goto error;
unknown's avatar
unknown committed
4799 4800
#else
    {
Alexey Botchkov's avatar
Alexey Botchkov committed
4801
      if (check_access(thd, FILE_ACL, any_db.str, NULL, NULL, 0, 0))
unknown's avatar
unknown committed
4802
	goto error;
unknown's avatar
unknown committed
4803
      res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS);
unknown's avatar
unknown committed
4804 4805
      break;
    }
unknown's avatar
unknown committed
4806 4807
#endif
  case SQLCOM_CHANGE_DB:
4808
  {
4809
    if (!mysql_change_db(thd, &select_lex->db, FALSE))
4810
      my_ok(thd);
4811

unknown's avatar
unknown committed
4812
    break;
4813
  }
4814

unknown's avatar
unknown committed
4815 4816
  case SQLCOM_LOAD:
  {
unknown's avatar
VIEW  
unknown committed
4817
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
4818 4819 4820
    privilege_t privilege= (lex->duplicates == DUP_REPLACE ?
                            INSERT_ACL | DELETE_ACL : INSERT_ACL) |
                           (lex->local_file ? NO_ACL : FILE_ACL);
4821

unknown's avatar
unknown committed
4822
    if (lex->local_file)
unknown's avatar
unknown committed
4823
    {
4824
      if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) ||
4825
          !opt_local_infile)
4826
      {
4827 4828 4829
        my_message(ER_LOAD_INFILE_CAPABILITY_DISABLED, 
                   ER_THD(thd, ER_LOAD_INFILE_CAPABILITY_DISABLED), MYF(0));
        goto error;
4830
      }
unknown's avatar
unknown committed
4831
    }
unknown's avatar
unknown committed
4832 4833 4834 4835

    if (check_one_table_access(thd, privilege, all_tables))
      goto error;

unknown's avatar
VIEW  
unknown committed
4836
    res= mysql_load(thd, lex->exchange, first_table, lex->field_list,
unknown's avatar
unknown committed
4837
                    lex->update_list, lex->value_list, lex->duplicates,
4838
                    lex->ignore, (bool) lex->local_file);
unknown's avatar
unknown committed
4839 4840
    break;
  }
4841

unknown's avatar
unknown committed
4842
  case SQLCOM_SET_OPTION:
4843 4844
  {
    List<set_var_base> *lex_var_list= &lex->var_list;
4845

4846
    if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)
4847
         || open_and_lock_tables(thd, all_tables, TRUE, 0)))
unknown's avatar
unknown committed
4848
      goto error;
4849
    if (likely(!(res= sql_set_variables(thd, lex_var_list, true))))
4850
    {
4851
      if (likely(!thd->is_error()))
4852
        my_ok(thd);
4853
    }
4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865
    else
    {
      /*
        We encountered some sort of error, but no message was sent.
        Send something semi-generic here since we don't know which
        assignment in the list caused the error.
      */
      if (!thd->is_error())
        my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET");
      goto error;
    }

unknown's avatar
unknown committed
4866
    break;
4867
  }
unknown's avatar
unknown committed
4868

unknown's avatar
unknown committed
4869
  case SQLCOM_UNLOCK_TABLES:
4870 4871 4872 4873 4874 4875
    /*
      It is critical for mysqldump --single-transaction --master-data that
      UNLOCK TABLES does not implicitely commit a connection which has only
      done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes
      false, mysqldump will not work.
    */
4876
    if (thd->variables.option_bits & OPTION_TABLE_LOCK)
unknown's avatar
unknown committed
4877
    {
4878
      res= trans_commit_implicit(thd);
4879 4880
      if (thd->locked_tables_list.unlock_locked_tables(thd))
        res= 1;
4881
      thd->release_transactional_locks();
4882
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
4883
      thd->reset_binlog_for_next_statement();
unknown's avatar
unknown committed
4884
    }
4885 4886
    if (thd->global_read_lock.is_acquired() &&
        thd->current_backup_stage == BACKUP_FINISHED)
4887
      thd->global_read_lock.unlock_global_read_lock(thd);
4888 4889
    if (res)
      goto error;
4890
    my_ok(thd);
unknown's avatar
unknown committed
4891 4892
    break;
  case SQLCOM_LOCK_TABLES:
4893 4894
    /* We must end the transaction first, regardless of anything */
    res= trans_commit_implicit(thd);
4895 4896
    if (thd->locked_tables_list.unlock_locked_tables(thd))
      res= 1;
4897
    /* Release transactional metadata locks. */
4898
    thd->release_transactional_locks();
4899 4900
    if (res)
      goto error;
Michael Widenius's avatar
Michael Widenius committed
4901

4902 4903 4904 4905 4906 4907
#ifdef WITH_WSREP
    /* Clean up the previous transaction on implicit commit. */
    if (wsrep_on(thd) && !wsrep_not_committed(thd) && wsrep_after_statement(thd))
      goto error;
#endif

4908 4909 4910 4911 4912 4913 4914
    /* We can't have any kind of table locks while backup is active */
    if (thd->current_backup_stage != BACKUP_FINISHED)
    {
      my_error(ER_BACKUP_LOCK_IS_ACTIVE, MYF(0));
      goto error;
    }

4915 4916 4917 4918 4919 4920 4921
    /* Should not lock tables while BACKUP LOCK is active */
    if (thd->mdl_backup_lock)
    {
      my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
      goto error;
    }

Michael Widenius's avatar
Michael Widenius committed
4922 4923 4924 4925 4926 4927 4928 4929 4930
    /*
      Here we have to pre-open temporary tables for LOCK TABLES.

      CF_PREOPEN_TMP_TABLES is not set for this SQL statement simply
      because LOCK TABLES calls close_thread_tables() as a first thing
      (it's called from unlock_locked_tables() above). So even if
      CF_PREOPEN_TMP_TABLES was set and the tables would be pre-opened
      in a usual way, they would have been closed.
    */
4931
    if (thd->open_temporary_tables(all_tables))
Michael Widenius's avatar
Michael Widenius committed
4932 4933
      goto error;

4934
    if (lock_tables_precheck(thd, all_tables))
4935
      goto error;
Konstantin Osipov's avatar
Konstantin Osipov committed
4936

4937
    thd->variables.option_bits|= OPTION_TABLE_LOCK;
Konstantin Osipov's avatar
Konstantin Osipov committed
4938

4939
    res= lock_tables_open_and_lock_tables(thd, all_tables);
Konstantin Osipov's avatar
Konstantin Osipov committed
4940 4941

    if (res)
4942
    {
4943
      thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
4944
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
4945 4946 4947
    else
    {
      if (thd->variables.query_cache_wlock_invalidate)
Sergei Golubchik's avatar
Sergei Golubchik committed
4948
	query_cache_invalidate_locked_for_write(thd, first_table);
Konstantin Osipov's avatar
Konstantin Osipov committed
4949 4950
      my_ok(thd);
    }
unknown's avatar
unknown committed
4951
    break;
4952 4953 4954 4955 4956 4957
  case SQLCOM_BACKUP:
    if (check_global_access(thd, RELOAD_ACL))
      goto error;
    if (!(res= run_backup_stage(thd, lex->backup_stage)))
      my_ok(thd);
    break;
4958
  case SQLCOM_BACKUP_LOCK:
4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007
    if (check_global_access(thd, RELOAD_ACL, true))
    {
#ifndef NO_EMBEDDED_ACCESS_CHECKS
      /*
        In case there is no global privilege, check DB privilege for LOCK TABLES.
      */
      if (first_table) // BACKUP LOCK
      {
        if (check_single_table_access(thd, LOCK_TABLES_ACL, first_table, true))
        {
          char command[30];
          get_privilege_desc(command, sizeof(command), RELOAD_ACL|LOCK_TABLES_ACL);
          my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
          goto error;
        }
      }
      else // BACKUP UNLOCK
      {
        /*
          We test mdl_backup_lock here because, if a user could obtain a lock
          it would be silly to error and say `you can't BACKUP UNLOCK`
          (because its obvious you did a `BACKUP LOCK`).
          As `BACKUP UNLOCK` doesn't have a database reference,
          there's no way we can check if the `BACKUP LOCK` privilege is missing.
          Testing `thd->db` would involve faking a `TABLE_LIST` structure,
          which because of the depth of inspection
          in `check_single_table_access` makes the faking likely to cause crashes,
          or unintended effects. The outcome of this is,
          if a user does an `BACKUP UNLOCK` without a `BACKUP LOCKED` table,
          there may be a` ER_SPECIFIC_ACCESS_DENIED` error even though
          user has the privilege.
          Its a bit different to what happens if the user has RELOAD_ACL,
          where the error is silently ignored.
        */
        if (!thd->mdl_backup_lock)
        {

          char command[30];
          get_privilege_desc(command, sizeof(command), RELOAD_ACL|LOCK_TABLES_ACL);
          my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
          goto error;
        }
      }
#endif
    }
    /*
      There is reload privilege, first table is set for lock.
      For unlock the list is empty
    */
5008 5009 5010 5011 5012 5013 5014
    if (first_table)
      res= backup_lock(thd, first_table);
    else
      backup_unlock(thd);
    if (!res)
      my_ok(thd);
    break;
unknown's avatar
unknown committed
5015
  case SQLCOM_CREATE_DB:
5016
  {
5017
    const DBNameBuffer dbbuf(lex->name, lower_case_table_names == 1);
5018
    const Lex_ident_db db= dbbuf.to_lex_ident_db_with_error();
5019

5020 5021 5022 5023 5024
    if (!db.str ||
        prepare_db_action(thd, lex->create_info.or_replace() ?
                          (CREATE_ACL | DROP_ACL) : CREATE_ACL,
                          db) ||
        (res= lex->create_info.resolve_to_charset_collation_context(thd,
5025 5026 5027
                                 thd->charset_collation_context_create_db())))
      break;

5028
    WSREP_TO_ISOLATION_BEGIN(db.str, NULL, NULL);
5029

5030
    res= mysql_create_db(thd, db, lex->create_info, &lex->create_info);
5031 5032
    break;
  }
unknown's avatar
unknown committed
5033
  case SQLCOM_DROP_DB:
5034
  {
5035 5036 5037
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

5038
    const DBNameBuffer dbbuf(lex->name, lower_case_table_names == 1);
5039 5040 5041
    const Lex_ident_db db= dbbuf.to_lex_ident_db_with_error();

    if (!db.str || prepare_db_action(thd, DROP_ACL, db))
5042
      break;
5043

5044
    WSREP_TO_ISOLATION_BEGIN(db.str, NULL, NULL);
5045

5046
    res= mysql_rm_db(thd, db, lex->if_exists());
5047 5048
    break;
  }
5049
  case SQLCOM_ALTER_DB_UPGRADE:
unknown's avatar
unknown committed
5050
  {
5051
    const DBNameBuffer dbbuf(lex->name, lower_case_table_names == 1);
5052 5053 5054 5055 5056 5057 5058
    const Lex_ident_db db= dbbuf.to_lex_ident_db_with_error();

    if (!db.str ||
        thd->check_slave_ignored_db_with_error(db) ||
        check_access(thd, ALTER_ACL, db.str, NULL, NULL, 1, 0) ||
        check_access(thd, DROP_ACL, db.str, NULL, NULL, 1, 0) ||
        check_access(thd, CREATE_ACL, db.str, NULL, NULL, 1, 0))
unknown's avatar
unknown committed
5059 5060 5061 5062
    {
      res= 1;
      break;
    }
5063

5064
    WSREP_TO_ISOLATION_BEGIN(db.str, NULL, NULL);
5065

5066
    res= mysql_upgrade_db(thd, db);
unknown's avatar
unknown committed
5067
    if (!res)
5068
      my_ok(thd);
unknown's avatar
unknown committed
5069 5070
    break;
  }
5071 5072
  case SQLCOM_ALTER_DB:
  {
5073
    const DBNameBuffer dbbuf(lex->name, lower_case_table_names == 1);
5074
    const Lex_ident_db db= dbbuf.to_lex_ident_db_with_error();
5075

5076 5077 5078 5079
    if (!db.str ||
        prepare_db_action(thd, ALTER_ACL, db) ||
        (res= lex->create_info.resolve_to_charset_collation_context(thd,
                     thd->charset_collation_context_alter_db(db.str))))
5080 5081
      break;

5082
    WSREP_TO_ISOLATION_BEGIN(db.str, NULL, NULL);
5083

5084
    res= mysql_alter_db(thd, db, &lex->create_info);
5085 5086
    break;
  }
unknown's avatar
unknown committed
5087
  case SQLCOM_SHOW_CREATE_DB:
5088
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
5089
    res= show_create_db(thd, lex);
unknown's avatar
unknown committed
5090
    break;
5091 5092 5093 5094
  case SQLCOM_SHOW_CREATE_SERVER:
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
    res= mysql_show_create_server(thd, &lex->name);
    break;
unknown's avatar
unknown committed
5095 5096
  case SQLCOM_CREATE_EVENT:
  case SQLCOM_ALTER_EVENT:
5097
  #ifdef HAVE_EVENT_SCHEDULER
5098
  do
unknown's avatar
unknown committed
5099
  {
unknown's avatar
unknown committed
5100
    DBUG_ASSERT(lex->event_parse_data);
unknown's avatar
unknown committed
5101 5102
    if (lex->table_or_sp_used())
    {
5103
      my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), "CREATE/ALTER EVENT");
unknown's avatar
unknown committed
5104 5105
      break;
    }
5106 5107 5108 5109 5110

    res= sp_process_definer(thd);
    if (res)
      break;

unknown's avatar
unknown committed
5111 5112
    switch (lex->sql_command) {
    case SQLCOM_CREATE_EVENT:
5113
    {
5114
      res= Events::create_event(thd, lex->event_parse_data);
unknown's avatar
unknown committed
5115
      break;
5116
    }
unknown's avatar
unknown committed
5117
    case SQLCOM_ALTER_EVENT:
5118 5119 5120
      res= Events::update_event(thd, lex->event_parse_data,
                                lex->spname ? &lex->spname->m_db : NULL,
                                lex->spname ? &lex->spname->m_name : NULL);
unknown's avatar
unknown committed
5121
      break;
5122 5123
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
5124
    }
5125
    DBUG_PRINT("info",("DDL error code=%d", res));
unknown's avatar
unknown committed
5126
    if (!res)
5127
      my_ok(thd);
unknown's avatar
unknown committed
5128

5129 5130
  } while (0);
  /* Don't do it, if we are inside a SP */
5131
  if (!thd->spcont && !is_called_from_prepared_stmt)
5132
  {
5133
    sp_head::destroy(lex->sphead);
5134
    lex->sphead= NULL;
unknown's avatar
unknown committed
5135
  }
5136 5137
  /* lex->unit.cleanup() is called outside, no need to call it here */
  break;
unknown's avatar
unknown committed
5138
  case SQLCOM_SHOW_CREATE_EVENT:
5139
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
5140 5141
    res= Events::show_create_event(thd, &lex->spname->m_db,
                                   &lex->spname->m_name);
5142 5143 5144
    break;
  case SQLCOM_DROP_EVENT:
    if (!(res= Events::drop_event(thd,
5145
                                  &lex->spname->m_db, &lex->spname->m_name,
5146
                                  lex->if_exists())))
5147
      my_ok(thd);
5148
    break;
5149 5150 5151 5152
#else
    my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server");
    break;
#endif
unknown's avatar
unknown committed
5153
  case SQLCOM_CREATE_FUNCTION:                  // UDF function
unknown's avatar
unknown committed
5154
  {
5155 5156 5157
    if (check_access(thd, lex->create_info.or_replace() ?
                          (INSERT_ACL | DELETE_ACL) : INSERT_ACL,
                     "mysql", NULL, NULL, 1, 0))
unknown's avatar
unknown committed
5158
      break;
unknown's avatar
unknown committed
5159
#ifdef HAVE_DLOPEN
5160
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5161

5162
    if (!(res = mysql_create_function(thd, &lex->udf)))
5163
      my_ok(thd);
unknown's avatar
unknown committed
5164
#else
unknown's avatar
unknown committed
5165
    my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled");
unknown's avatar
unknown committed
5166
    res= TRUE;
unknown's avatar
unknown committed
5167 5168
#endif
    break;
unknown's avatar
unknown committed
5169
  }
unknown's avatar
unknown committed
5170
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5171
  case SQLCOM_CREATE_USER:
5172
  case SQLCOM_CREATE_ROLE:
5173
  {
5174 5175 5176
    if (check_access(thd, lex->create_info.or_replace() ?
                          INSERT_ACL | DELETE_ACL : INSERT_ACL,
                     "mysql", NULL, NULL, 1, 1) &&
5177
        check_global_access(thd,CREATE_USER_ACL))
5178
      break;
5179

5180
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5181

5182
    /* Conditionally writes to binlog */
5183 5184
    if (!(res= mysql_create_user(thd, lex->users_list,
                                 lex->sql_command == SQLCOM_CREATE_ROLE)))
5185
      my_ok(thd);
5186 5187
    break;
  }
5188
  case SQLCOM_DROP_USER:
5189
  case SQLCOM_DROP_ROLE:
5190
  {
Marc Alff's avatar
Marc Alff committed
5191
    if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) &&
5192
        check_global_access(thd,CREATE_USER_ACL))
5193
      break;
5194

5195
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5196 5197

    /* Conditionally writes to binlog */
5198 5199
    if (!(res= mysql_drop_user(thd, lex->users_list,
                               lex->sql_command == SQLCOM_DROP_ROLE)))
5200
      my_ok(thd);
5201 5202
    break;
  }
5203
  case SQLCOM_ALTER_USER:
5204 5205
  case SQLCOM_RENAME_USER:
  {
Marc Alff's avatar
Marc Alff committed
5206
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
5207
        check_global_access(thd,CREATE_USER_ACL))
5208
      break;
5209

5210
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5211 5212

    /* Conditionally writes to binlog */
5213 5214 5215 5216 5217
    if (lex->sql_command == SQLCOM_ALTER_USER)
      res= mysql_alter_user(thd, lex->users_list);
    else
      res= mysql_rename_user(thd, lex->users_list);
    if (!res)
5218
      my_ok(thd);
5219 5220 5221 5222
    break;
  }
  case SQLCOM_REVOKE_ALL:
  {
Marc Alff's avatar
Marc Alff committed
5223
    if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
5224
        check_global_access(thd,CREATE_USER_ACL))
5225
      break;
5226

5227
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5228 5229

    /* Conditionally writes to binlog */
5230
    if (!(res = mysql_revoke_all(thd, lex->users_list)))
5231
      my_ok(thd);
5232 5233
    break;
  }
5234

5235
  case SQLCOM_REVOKE_ROLE:
5236 5237
  case SQLCOM_GRANT_ROLE:
  {
5238
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5239

5240 5241
    if (!(res= mysql_grant_role(thd, lex->users_list,
                                lex->sql_command != SQLCOM_GRANT_ROLE)))
5242
      my_ok(thd);
5243 5244
    break;
  }
unknown's avatar
SCRUM  
unknown committed
5245
#endif /*!NO_EMBEDDED_ACCESS_CHECKS*/
unknown's avatar
unknown committed
5246
  case SQLCOM_RESET:
5247 5248 5249
    /*
      RESET commands are never written to the binary log, so we have to
      initialize this variable because RESET shares the same code as FLUSH
5250 5251
    */
    lex->no_write_to_binlog= 1;
5252
    /* fall through */
5253 5254
  case SQLCOM_FLUSH:
  {
5255
    int write_to_binlog;
Monty's avatar
Monty committed
5256 5257
    if ((lex->type & ~REFRESH_SESSION_STATUS) &&
        check_global_access(thd,RELOAD_ACL))
unknown's avatar
unknown committed
5258
      goto error;
5259

5260
    if (first_table && lex->type & (REFRESH_READ_LOCK|REFRESH_FOR_EXPORT))
5261
    {
5262
      /* Check table-level privileges. */
5263
      if (check_table_access(thd, PRIV_LOCK_TABLES, all_tables,
5264 5265
                             FALSE, UINT_MAX, FALSE))
        goto error;
5266

5267 5268
      if (flush_tables_with_read_lock(thd, all_tables))
        goto error;
5269

5270 5271 5272
      my_ok(thd);
      break;
    }
5273

5274 5275
#ifdef WITH_WSREP
    if (lex->type & (
5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291
    REFRESH_GRANT                           |
    REFRESH_HOSTS                           |
#ifdef HAVE_OPENSSL
    REFRESH_DES_KEY_FILE                    |
#endif
    /*
      Write all flush log statements except
      FLUSH LOGS
      FLUSH BINARY LOGS
      Check reload_acl_and_cache for why.
    */
    REFRESH_RELAY_LOG                       |
    REFRESH_SLOW_LOG                        |
    REFRESH_GENERAL_LOG                     |
    REFRESH_ENGINE_LOG                      |
    REFRESH_ERROR_LOG                       |
5292
#ifdef HAVE_QUERY_CACHE
5293
    REFRESH_QUERY_CACHE_FREE                |
5294
#endif /* HAVE_QUERY_CACHE */
5295
    REFRESH_STATUS                          |
Monty's avatar
Monty committed
5296 5297
    REFRESH_SESSION_STATUS                  |
    REFRESH_GLOBAL_STATUS                   |
5298
    REFRESH_USER_RESOURCES))
5299
    {
5300
      WSREP_TO_ISOLATION_BEGIN_WRTCHK(WSREP_MYSQL_DB, NULL, NULL);
5301 5302 5303
    }
#endif /* WITH_WSREP*/

5304
#ifdef HAVE_REPLICATION
5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315
    if (lex->type & REFRESH_READ_LOCK)
    {
      /*
        We need to pause any parallel replication slave workers during FLUSH
        TABLES WITH READ LOCK. Otherwise we might cause a deadlock, as
        worker threads eun run in arbitrary order but need to commit in a
        specific given order.
      */
      if (rpl_pause_for_ftwrl(thd))
        goto error;
    }
5316
#endif
5317 5318 5319 5320
    /*
      reload_acl_and_cache() will tell us if we are allowed to write to the
      binlog or not.
    */
unknown's avatar
unknown committed
5321
    if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog))
5322
    {
5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333
#ifdef WITH_WSREP
      if ((lex->type & REFRESH_TABLES) && !(lex->type & (REFRESH_FOR_EXPORT|REFRESH_READ_LOCK)))
      {
        /*
          This is done after reload_acl_and_cache is because
          LOCK TABLES is not replicated in galera, the upgrade of which
          is checked in reload_acl_and_cache.
          Hence, done after/if we are able to upgrade locks.
        */
        if (first_table)
        {
5334
          WSREP_TO_ISOLATION_BEGIN_WRTCHK(NULL, NULL, first_table);
5335 5336 5337
        }
        else
        {
5338
          WSREP_TO_ISOLATION_BEGIN_WRTCHK(WSREP_MYSQL_DB, NULL, NULL);
5339 5340 5341
        }
      }
#endif /* WITH_WSREP */
5342 5343 5344 5345
      /*
        We WANT to write and we CAN write.
        ! we write after unlocking the table.
      */
5346 5347 5348
      /*
        Presumably, RESET and binlog writing doesn't require synchronization
      */
5349 5350 5351 5352 5353 5354

      if (write_to_binlog > 0)  // we should write
      { 
        if (!lex->no_write_to_binlog)
          res= write_bin_log(thd, FALSE, thd->query(), thd->query_length());
      } else if (write_to_binlog < 0) 
5355
      {
5356 5357 5358 5359 5360
        /* 
           We should not write, but rather report error because 
           reload_acl_and_cache binlog interactions failed 
         */
        res= 1;
5361
      }
5362 5363 5364

      if (!res)
        my_ok(thd);
5365
    } 
5366 5367
    else
      res= 1;                                   // reload_acl_and_cache failed
5368
#ifdef HAVE_REPLICATION
5369 5370
    if (lex->type & REFRESH_READ_LOCK)
      rpl_unpause_after_ftwrl(thd);
5371
#endif
5372
    
unknown's avatar
unknown committed
5373
    break;
5374
  }
unknown's avatar
unknown committed
5375
  case SQLCOM_KILL:
5376
  {
unknown's avatar
unknown committed
5377 5378
    if (lex->table_or_sp_used())
    {
5379
      my_error(ER_SUBQUERIES_NOT_SUPPORTED, MYF(0), "KILL");
unknown's avatar
unknown committed
5380 5381 5382
      break;
    }

5383
    if (lex->kill_type == KILL_TYPE_ID || lex->kill_type == KILL_TYPE_QUERY)
5384
    {
5385
      Item *it= (Item *)lex->value_list.head();
5386
      if (it->fix_fields_if_needed_for_scalar(lex->thd, &it))
5387
      {
5388
        my_message(ER_SET_CONSTANTS_ONLY, ER_THD(thd, ER_SET_CONSTANTS_ONLY),
5389 5390 5391
                   MYF(0));
        goto error;
      }
5392
      sql_kill(thd, (my_thread_id) it->val_int(), lex->kill_signal, lex->kill_type);
5393
    }
5394 5395 5396
    else
      sql_kill_user(thd, get_current_user(thd, lex->users_list.head()),
                    lex->kill_signal);
unknown's avatar
unknown committed
5397
    break;
5398
  }
5399 5400
  case SQLCOM_SHUTDOWN:
#ifndef EMBEDDED_LIBRARY
5401
    DBUG_EXECUTE_IF("crash_shutdown", DBUG_SUICIDE(););
5402 5403
    if (check_global_access(thd,SHUTDOWN_ACL))
      goto error;
5404
    kill_mysql(thd);
5405 5406 5407 5408 5409 5410
    my_ok(thd);
#else
    my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server");
#endif
    break;

unknown's avatar
unknown committed
5411
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5412
  case SQLCOM_SHOW_CREATE_USER:
5413
  {
5414
    LEX_USER *grant_user= lex->grant_user;
5415 5416
    if (!grant_user)
      goto error;
5417

5418 5419 5420
    res = mysql_show_create_user(thd, grant_user);
    break;
  }
unknown's avatar
unknown committed
5421
  case SQLCOM_SHOW_GRANTS:
5422
  {
5423
    LEX_USER *grant_user= lex->grant_user;
5424 5425
    if (!grant_user)
      goto error;
5426

5427
    WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
5428
    res = mysql_show_grants(thd, grant_user);
unknown's avatar
unknown committed
5429
    break;
5430
  }
unknown's avatar
unknown committed
5431
#endif
5432
  case SQLCOM_HA_OPEN:
unknown's avatar
VIEW  
unknown committed
5433
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
5434
    if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))
5435
      goto error;
unknown's avatar
unknown committed
5436 5437 5438
    /* Close temporary tables which were pre-opened for privilege checking. */
    close_thread_tables(thd);
    all_tables->table= NULL;
unknown's avatar
unknown committed
5439
    res= mysql_ha_open(thd, first_table, 0);
5440 5441
    break;
  case SQLCOM_HA_CLOSE:
unknown's avatar
VIEW  
unknown committed
5442 5443
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
    res= mysql_ha_close(thd, first_table);
5444 5445
    break;
  case SQLCOM_HA_READ:
unknown's avatar
VIEW  
unknown committed
5446
    DBUG_ASSERT(first_table == all_tables && first_table != 0);
5447 5448 5449 5450 5451
    /*
      There is no need to check for table permissions here, because
      if a user has no permissions to read a table, he won't be
      able to open it (with SQLCOM_HA_OPEN) in the first place.
    */
5452
    unit->set_limit(select_lex);
5453

5454
    res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str,
unknown's avatar
VIEW  
unknown committed
5455
                       lex->insert_list, lex->ha_rkey_mode, select_lex->where,
5456 5457
                       unit->lim.get_select_limit(),
                       unit->lim.get_offset_limit());
5458 5459
    break;

unknown's avatar
unknown committed
5460
  case SQLCOM_BEGIN:
Michael Widenius's avatar
Michael Widenius committed
5461
    DBUG_PRINT("info", ("Executing SQLCOM_BEGIN  thd: %p", thd));
Konstantin Osipov's avatar
Konstantin Osipov committed
5462
    if (trans_begin(thd, lex->start_transaction_opt))
5463
    {
5464
      thd->release_transactional_locks();
5465 5466
      WSREP_DEBUG("BEGIN failed, MDL released: %lld",
                  (longlong) thd->thread_id);
Brave Galera Crew's avatar
Brave Galera Crew committed
5467
      WSREP_DEBUG("stmt_da, sql_errno: %d", (thd->get_stmt_da()->is_error()) ? thd->get_stmt_da()->sql_errno() : 0);
unknown's avatar
unknown committed
5468
      goto error;
5469
    }
5470
    my_ok(thd);
unknown's avatar
unknown committed
5471 5472
    break;
  case SQLCOM_COMMIT:
5473
  {
5474 5475
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
5476 5477 5478 5479 5480 5481
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
5482
    bool commit_failed= trans_commit(thd);
5483
    thd->release_transactional_locks();
5484
    if (commit_failed)
5485
    {
5486 5487
      WSREP_DEBUG("COMMIT failed, MDL released: %lld",
                  (longlong) thd->thread_id);
Konstantin Osipov's avatar
Konstantin Osipov committed
5488
      goto error;
5489
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
5490
    /* Begin transaction with the same isolation level. */
5491 5492 5493
    if (tx_chain)
    {
      if (trans_begin(thd))
5494
        goto error;
5495 5496 5497
    }
    else
    {
Sergei Golubchik's avatar
Sergei Golubchik committed
5498
      /* Reset the isolation level and access mode if no chaining transaction.*/
5499
      trans_reset_one_shot_chistics(thd);
5500
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
5501
    /* Disconnect the current client connection. */
5502
    if (tx_release)
5503
    {
5504
      thd->set_killed(KILL_CONNECTION);
Sergei Golubchik's avatar
Sergei Golubchik committed
5505
      thd->print_aborted_warning(3, "RELEASE");
unknown's avatar
unknown committed
5506
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
5507
    my_ok(thd);
unknown's avatar
unknown committed
5508
    break;
5509
  }
unknown's avatar
unknown committed
5510
  case SQLCOM_ROLLBACK:
5511
  {
5512 5513
    DBUG_ASSERT(thd->lock == NULL ||
                thd->locked_tables_mode == LTM_LOCK_TABLES);
5514 5515 5516 5517 5518 5519
    bool tx_chain= (lex->tx_chain == TVL_YES ||
                    (thd->variables.completion_type == 1 &&
                     lex->tx_chain != TVL_NO));
    bool tx_release= (lex->tx_release == TVL_YES ||
                      (thd->variables.completion_type == 2 &&
                       lex->tx_release != TVL_NO));
5520
    bool rollback_failed= trans_rollback(thd);
5521
    thd->release_transactional_locks();
5522

5523
    if (rollback_failed)
5524
    {
5525 5526
      WSREP_DEBUG("rollback failed, MDL released: %lld",
                  (longlong) thd->thread_id);
unknown's avatar
unknown committed
5527
      goto error;
5528
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
5529
    /* Begin transaction with the same isolation level. */
5530 5531
    if (tx_chain)
    {
5532 5533 5534 5535 5536
#ifdef WITH_WSREP
      /* If there are pending changes after rollback we should clear them */
      if (wsrep_on(thd) && wsrep_has_changes(thd))
        wsrep_after_statement(thd);
#endif
5537 5538 5539 5540 5541
      if (trans_begin(thd))
        goto error;
    }
    else
    {
Sergei Golubchik's avatar
Sergei Golubchik committed
5542
      /* Reset the isolation level and access mode if no chaining transaction.*/
5543
      trans_reset_one_shot_chistics(thd);
5544
    }
Konstantin Osipov's avatar
Konstantin Osipov committed
5545
    /* Disconnect the current client connection. */
5546
    if (tx_release)
5547
      thd->set_killed(KILL_CONNECTION);
Brave Galera Crew's avatar
Brave Galera Crew committed
5548
    my_ok(thd);
5549
   break;
5550
  }
unknown's avatar
unknown committed
5551
  case SQLCOM_RELEASE_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
5552 5553 5554
    if (trans_release_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
5555
    break;
unknown's avatar
unknown committed
5556
  case SQLCOM_ROLLBACK_TO_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
5557 5558 5559
    if (trans_rollback_to_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
5560
    break;
5561
  case SQLCOM_SAVEPOINT:
Konstantin Osipov's avatar
Konstantin Osipov committed
5562 5563 5564
    if (trans_savepoint(thd, lex->ident))
      goto error;
    my_ok(thd);
unknown's avatar
unknown committed
5565
    break;
5566 5567
  case SQLCOM_CREATE_PROCEDURE:
  case SQLCOM_CREATE_SPFUNCTION:
5568 5569
  case SQLCOM_CREATE_PACKAGE:
  case SQLCOM_CREATE_PACKAGE_BODY:
unknown's avatar
unknown committed
5570
  {
5571
    if (mysql_create_routine(thd, lex))
5572
      goto error;
5573
    my_ok(thd);
5574 5575
    break; /* break super switch */
  } /* end case group bracket */
5576
  case SQLCOM_COMPOUND:
5577 5578
  {
    sp_head *sp= lex->sphead;
5579 5580
    DBUG_ASSERT(all_tables == 0);
    DBUG_ASSERT(thd->in_sub_stmt == 0);
5581 5582
    sp->m_sql_mode= thd->variables.sql_mode;
    sp->m_sp_share= MYSQL_GET_SP_SHARE(sp->m_handler->type(),
5583 5584
                                       sp->m_db.str, static_cast<uint>(sp->m_db.length),
                                       sp->m_name.str, static_cast<uint>(sp->m_name.length));
5585 5586 5587
    if (do_execute_sp(thd, lex->sphead))
      goto error;
    break;
5588
  }
5589

5590
  case SQLCOM_ALTER_PROCEDURE:
5591
  case SQLCOM_ALTER_FUNCTION:
5592 5593
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
5594 5595 5596
    if (alter_routine(thd, lex))
      goto error;
    break;
5597
  case SQLCOM_DROP_PROCEDURE:
5598
  case SQLCOM_DROP_FUNCTION:
5599 5600
  case SQLCOM_DROP_PACKAGE:
  case SQLCOM_DROP_PACKAGE_BODY:
5601 5602
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
5603 5604 5605
    if (drop_routine(thd, lex))
      goto error;
    break;
unknown's avatar
unknown committed
5606 5607
  case SQLCOM_SHOW_CREATE_PROC:
  case SQLCOM_SHOW_CREATE_FUNC:
5608 5609
  case SQLCOM_SHOW_CREATE_PACKAGE:
  case SQLCOM_SHOW_CREATE_PACKAGE_BODY:
unknown's avatar
unknown committed
5610
    {
5611
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
5612 5613 5614
      const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
      if (sph->sp_show_create_routine(thd, lex->spname))
        goto error;
unknown's avatar
unknown committed
5615 5616
      break;
    }
unknown's avatar
unknown committed
5617 5618
  case SQLCOM_SHOW_PROC_CODE:
  case SQLCOM_SHOW_FUNC_CODE:
5619
  case SQLCOM_SHOW_PACKAGE_BODY_CODE:
unknown's avatar
unknown committed
5620
    {
5621
#ifndef DBUG_OFF
5622
      Database_qualified_name pkgname;
unknown's avatar
unknown committed
5623
      sp_head *sp;
5624
      const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
5625
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
5626 5627 5628
      if (sph->sp_resolve_package_routine(thd, thd->lex->sphead,
                                          lex->spname, &sph, &pkgname))
        return true;
5629
      if (sph->sp_cache_routine(thd, lex->spname, &sp))
Konstantin Osipov's avatar
Konstantin Osipov committed
5630
        goto error;
5631
      if (!sp || sp->show_routine_code(thd))
5632 5633
      {
        /* We don't distinguish between errors for now */
unknown's avatar
unknown committed
5634
        my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
5635
                 sph->type_str(), lex->spname->m_name.str);
unknown's avatar
unknown committed
5636 5637 5638
        goto error;
      }
      break;
5639 5640 5641 5642
#else
      my_error(ER_FEATURE_DISABLED, MYF(0),
               "SHOW PROCEDURE|FUNCTION CODE", "--with-debug");
      goto error;
unknown's avatar
unknown committed
5643
#endif // ifndef DBUG_OFF
5644
    }
unknown's avatar
unknown committed
5645 5646
  case SQLCOM_SHOW_CREATE_TRIGGER:
    {
5647
      if (check_ident_length(&lex->spname->m_name))
unknown's avatar
unknown committed
5648 5649
        goto error;

5650
      WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
unknown's avatar
unknown committed
5651 5652 5653 5654 5655
      if (show_create_trigger(thd, lex->spname))
        goto error; /* Error has been already logged. */

      break;
    }
unknown's avatar
VIEW  
unknown committed
5656 5657
  case SQLCOM_CREATE_VIEW:
    {
5658 5659
      /*
        Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands
5660
        as specified through the thd->lex->create_view->mode flag.
5661
      */
5662
      res= mysql_create_view(thd, first_table, thd->lex->create_view->mode);
unknown's avatar
VIEW  
unknown committed
5663 5664 5665 5666
      break;
    }
  case SQLCOM_DROP_VIEW:
    {
Konstantin Osipov's avatar
Konstantin Osipov committed
5667
      if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
5668
        goto error;
5669

5670
      WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5671

5672 5673 5674
      if (thd->variables.option_bits & OPTION_IF_EXISTS)
        lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

5675
      /* Conditionally writes to binlog. */
5676
      res= mysql_drop_view(thd, first_table, thd->lex->drop_mode);
unknown's avatar
VIEW  
unknown committed
5677 5678
      break;
    }
5679 5680
  case SQLCOM_CREATE_TRIGGER:
  {
5681
    /* Conditionally writes to binlog. */
5682 5683
    res= mysql_create_or_drop_trigger(thd, all_tables, 1);

5684 5685 5686 5687
    break;
  }
  case SQLCOM_DROP_TRIGGER:
  {
5688 5689 5690
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);

5691
    /* Conditionally writes to binlog. */
5692 5693 5694
    res= mysql_create_or_drop_trigger(thd, all_tables, 0);
    break;
  }
5695
  case SQLCOM_XA_START:
5696
#ifdef WITH_WSREP
5697
    if (WSREP_ON)
5698 5699 5700 5701 5702 5703
    {
      my_error(ER_NOT_SUPPORTED_YET, MYF(0),
               "XA transactions with Galera replication");
      break;
    }
#endif /* WITH_WSREP */
Konstantin Osipov's avatar
Konstantin Osipov committed
5704 5705
    if (trans_xa_start(thd))
      goto error;
5706
    my_ok(thd);
5707 5708
    break;
  case SQLCOM_XA_END:
Konstantin Osipov's avatar
Konstantin Osipov committed
5709 5710
    if (trans_xa_end(thd))
      goto error;
5711
    my_ok(thd);
5712 5713
    break;
  case SQLCOM_XA_PREPARE:
Konstantin Osipov's avatar
Konstantin Osipov committed
5714 5715
    if (trans_xa_prepare(thd))
      goto error;
5716
    my_ok(thd);
5717 5718
    break;
  case SQLCOM_XA_COMMIT:
5719 5720 5721
  {
    bool commit_failed= trans_xa_commit(thd);
    if (commit_failed)
5722
    {
5723 5724
      WSREP_DEBUG("XA commit failed, MDL released: %lld",
                  (longlong) thd->thread_id);
Konstantin Osipov's avatar
Konstantin Osipov committed
5725
      goto error;
5726
    }
5727 5728
    /*
      We've just done a commit, reset transaction
Sergei Golubchik's avatar
Sergei Golubchik committed
5729
      isolation level and access mode to the session default.
5730
    */
5731
    trans_reset_one_shot_chistics(thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
5732
    my_ok(thd);
5733
    break;
5734
  }
5735
  case SQLCOM_XA_ROLLBACK:
5736 5737 5738
  {
    bool rollback_failed= trans_xa_rollback(thd);
    if (rollback_failed)
5739
    {
5740 5741
      WSREP_DEBUG("XA rollback failed, MDL released: %lld",
                  (longlong) thd->thread_id);
Konstantin Osipov's avatar
Konstantin Osipov committed
5742
      goto error;
5743
    }
5744 5745
    /*
      We've just done a rollback, reset transaction
Sergei Golubchik's avatar
Sergei Golubchik committed
5746
      isolation level and access mode to the session default.
5747
    */
5748
    trans_reset_one_shot_chistics(thd);
Konstantin Osipov's avatar
Konstantin Osipov committed
5749
    my_ok(thd);
5750
    break;
5751
  }
5752
  case SQLCOM_XA_RECOVER:
5753
    res= mysql_xa_recover(thd);
5754
    break;
unknown's avatar
unknown committed
5755 5756 5757
  case SQLCOM_INSTALL_PLUGIN:
    if (! (res= mysql_install_plugin(thd, &thd->lex->comment,
                                     &thd->lex->ident)))
5758
      my_ok(thd);
unknown's avatar
unknown committed
5759 5760
    break;
  case SQLCOM_UNINSTALL_PLUGIN:
5761 5762
    if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment,
                                       &thd->lex->ident)))
5763
      my_ok(thd);
unknown's avatar
unknown committed
5764 5765 5766 5767 5768 5769 5770 5771 5772 5773
    break;
  case SQLCOM_BINLOG_BASE64_EVENT:
  {
#ifndef EMBEDDED_LIBRARY
    mysql_client_binlog_statement(thd);
#else /* EMBEDDED_LIBRARY */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded");
#endif /* EMBEDDED_LIBRARY */
    break;
  }
unknown's avatar
unknown committed
5774 5775 5776
  case SQLCOM_CREATE_SERVER:
  {
    DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
unknown's avatar
unknown committed
5777

5778
    if (check_global_access(thd, PRIV_STMT_CREATE_SERVER))
unknown's avatar
unknown committed
5779 5780
      break;

5781
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5782

5783
    res= create_server(thd, &lex->server_options);
unknown's avatar
unknown committed
5784 5785 5786 5787 5788 5789
    break;
  }
  case SQLCOM_ALTER_SERVER:
  {
    int error;
    DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
unknown's avatar
unknown committed
5790

5791
    if (check_global_access(thd, PRIV_STMT_ALTER_SERVER))
unknown's avatar
unknown committed
5792 5793
      break;

5794
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5795

5796
    if (unlikely((error= alter_server(thd, &lex->server_options))))
unknown's avatar
unknown committed
5797
    {
5798
      DBUG_PRINT("info", ("problem altering server <%s>",
5799 5800
                          lex->server_options.server_name.str));
      my_error(error, MYF(0), lex->server_options.server_name.str);
unknown's avatar
unknown committed
5801 5802
      break;
    }
5803
    my_ok(thd, 1);
unknown's avatar
unknown committed
5804 5805 5806 5807 5808 5809
    break;
  }
  case SQLCOM_DROP_SERVER:
  {
    int err_code;
    DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
unknown's avatar
unknown committed
5810

5811
    if (check_global_access(thd, PRIV_STMT_DROP_SERVER))
unknown's avatar
unknown committed
5812 5813
      break;

5814
    WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);
5815

unknown's avatar
unknown committed
5816 5817
    if ((err_code= drop_server(thd, &lex->server_options)))
    {
5818
      if (! lex->if_exists() && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
unknown's avatar
unknown committed
5819 5820
      {
        DBUG_PRINT("info", ("problem dropping server %s",
5821 5822
                            lex->server_options.server_name.str));
        my_error(err_code, MYF(0), lex->server_options.server_name.str);
unknown's avatar
unknown committed
5823 5824 5825
      }
      else
      {
5826
        my_ok(thd, 0);
unknown's avatar
unknown committed
5827 5828 5829
      }
      break;
    }
5830
    my_ok(thd, 1);
unknown's avatar
unknown committed
5831 5832
    break;
  }
5833 5834 5835 5836 5837
  case SQLCOM_ANALYZE:
  case SQLCOM_CHECK:
  case SQLCOM_OPTIMIZE:
  case SQLCOM_REPAIR:
  case SQLCOM_TRUNCATE:
5838
  case SQLCOM_CREATE_TABLE:
5839
  case SQLCOM_CREATE_SEQUENCE:
5840 5841 5842
  case SQLCOM_ALTER_TABLE:
      DBUG_ASSERT(first_table == all_tables && first_table != 0);
    /* fall through */
5843
  case SQLCOM_ALTER_SEQUENCE:
Marc Alff's avatar
Marc Alff committed
5844 5845
  case SQLCOM_SIGNAL:
  case SQLCOM_RESIGNAL:
5846
  case SQLCOM_GET_DIAGNOSTICS:
5847
  case SQLCOM_CALL:
5848 5849
  case SQLCOM_REVOKE:
  case SQLCOM_GRANT:
5850 5851
    if (thd->variables.option_bits & OPTION_IF_EXISTS)
      lex->create_info.set(DDL_options_st::OPT_IF_EXISTS);
5852 5853
    DBUG_ASSERT(lex->m_sql_cmd != NULL);
    res= lex->m_sql_cmd->execute(thd);
Monty's avatar
Monty committed
5854
    DBUG_PRINT("result", ("res: %d  killed: %d  is_error(): %d",
Monty's avatar
Monty committed
5855
                          res, thd->killed, thd->is_error()));
Marc Alff's avatar
Marc Alff committed
5856
    break;
5857
  default:
5858

5859
#ifndef EMBEDDED_LIBRARY
5860
    DBUG_ASSERT(0);                             /* Impossible */
5861
#endif
5862
    my_ok(thd);
unknown's avatar
unknown committed
5863 5864
    break;
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
5865
  THD_STAGE_INFO(thd, stage_query_end);
5866
  thd->update_stats();
5867

5868
  goto finish;
unknown's avatar
unknown committed
5869 5870

error:
Marko Mäkelä's avatar
Marko Mäkelä committed
5871 5872 5873 5874
#ifdef WITH_WSREP
wsrep_error_label:
#endif
  res= true;
5875

5876
finish:
Konstantin Osipov's avatar
Konstantin Osipov committed
5877

Monty's avatar
Monty committed
5878
  thd->reset_query_timer();
5879 5880 5881
  DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() ||
               thd->in_multi_stmt_transaction_mode());

5882
  lex->unit.cleanup();
5883

5884
  /* close/reopen tables that were marked to need reopen under LOCK TABLES */
5885 5886
  if (unlikely(thd->locked_tables_list.some_table_marked_for_reopen) &&
      !thd->lex->requires_prelocking())
5887 5888
    thd->locked_tables_list.reopen_tables(thd, true);

5889 5890
  if (! thd->in_sub_stmt)
  {
5891
    if (thd->killed != NOT_KILLED)
5892
    {
5893 5894 5895 5896
      /* report error issued during command execution */
      if (thd->killed_errno())
      {
        /* If we already sent 'ok', we can ignore any kill query statements */
5897
        if (! thd->get_stmt_da()->is_set())
5898 5899
          thd->send_kill_message();
      }
5900
      thd->reset_kill_query();
5901
    }
5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927

    /*
      Binary logging is now done. Unset the "used" flags to avoid
      flags leaking to the next event (and to the COMMIT statement
      in the end of the current event).

      Example:

      Suppose a non-default collation (in @@character_set_collations)
      was used during the statement, the mysqlbinlog output for
      the current statement will contain a sequence like this:

        SET character_set_collations='utf8mb3=utf8mb3_bin';
        INSERT INTO t1 VALUES (_utf8mb3'test');
        COMMIT;

      The statment (INSERT in this example) is already in binlog at this point, and the
      and the "SET character_set_collations" is written inside a
      Q_CHARACTER_SET_COLLATIONS chunk in its log entry header.
      The flag CHARACTER_SET_COLLATIONS_USED is not needed any more.
      The COMMIT can be printed without "SET character_set_collations".

      The same logic applies to the other _USED flags.
    */
    thd->used= 0;

5928 5929
    if (unlikely(thd->is_error()) ||
        (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR))
5930
    {
5931
      trans_rollback_stmt(thd);
5932
    }
5933 5934 5935
    else
    {
      /* If commit fails, we should be able to reset the OK status. */
5936
      thd->get_stmt_da()->set_overwrite_status(true);
5937
      trans_commit_stmt(thd);
5938
      thd->get_stmt_da()->set_overwrite_status(false);
5939 5940
    }
  }
5941

5942
  /* Free tables. Set stage 'closing tables' */
5943
  close_thread_tables_for_query(thd);
5944

5945 5946 5947 5948
#ifndef DBUG_OFF
  if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt)
    DEBUG_SYNC(thd, "execute_command_after_close_tables");
#endif
5949 5950 5951 5952 5953
  if (!(sql_command_flags[lex->sql_command] &
        (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT |
         CF_STATUS_COMMAND)))
    thd->set_binlog_format(orig_binlog_format,
                           orig_current_stmt_binlog_format);
5954

5955 5956 5957 5958 5959 5960 5961 5962
  if (! thd->in_sub_stmt && thd->transaction_rollback_request)
  {
    /*
      We are not in sub-statement and transaction rollback was requested by
      one of storage engines (e.g. due to deadlock). Rollback transaction in
      all storage engines including binary log.
    */
    trans_rollback_implicit(thd);
5963
    thd->release_transactional_locks();
5964 5965
  }
  else if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
5966
  {
5967 5968
    /* No transaction control allowed in sub-statements. */
    DBUG_ASSERT(! thd->in_sub_stmt);
5969 5970 5971 5972 5973 5974 5975
    if (!(thd->variables.option_bits & OPTION_GTID_BEGIN))
    {
      /* If commit fails, we should be able to reset the OK status. */
      thd->get_stmt_da()->set_overwrite_status(true);
      /* Commit the normal transaction if one is active. */
      trans_commit_implicit(thd);
      thd->get_stmt_da()->set_overwrite_status(false);
5976
      thd->release_transactional_locks();
5977
    }
5978
  }
5979
  else if (! thd->in_sub_stmt && ! thd->in_active_multi_stmt_transaction())
5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990
  {
    /*
      - If inside a multi-statement transaction,
      defer the release of metadata locks until the current
      transaction is either committed or rolled back. This prevents
      other statements from modifying the table for the entire
      duration of this transaction.  This provides commit ordering
      and guarantees serializability across multiple transactions.
      - If in autocommit mode, or outside a transactional context,
      automatically release metadata locks of the current statement.
    */
5991
    thd->release_transactional_locks();
5992
  }
5993 5994 5995 5996
  else if (! thd->in_sub_stmt)
  {
    thd->mdl_context.release_statement_locks();
  }
5997

5998 5999
  THD_STAGE_INFO(thd, stage_starting_cleanup);

6000 6001
  TRANSACT_TRACKER(add_trx_state_from_thd(thd));

6002
#ifdef WITH_WSREP
Brave Galera Crew's avatar
Brave Galera Crew committed
6003
  thd->wsrep_consistency_check= NO_CONSISTENCY_CHECK;
6004

6005
  if (wsrep_thd_is_toi(thd) || wsrep_thd_is_in_rsu(thd))
6006 6007 6008
  {
    WSREP_DEBUG("mysql_execute_command for %s", wsrep_thd_query(thd));
    THD_STAGE_INFO(thd, stage_waiting_isolation);
6009
    wsrep_to_isolation_end(thd);
6010 6011
  }

6012 6013 6014 6015 6016 6017 6018 6019
  /*
    Force release of transactional locks if not in active MST and wsrep is on.
  */
  if (WSREP(thd) &&
      ! thd->in_sub_stmt &&
      ! thd->in_active_multi_stmt_transaction() &&
      thd->mdl_context.has_transactional_locks())
  {
6020 6021
    WSREP_DEBUG("Forcing release of transactional locks for thd: %lld",
                (longlong) thd->thread_id);
6022
    thd->release_transactional_locks();
6023
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039

  /*
    Current command did not start multi STMT transaction and the command
    did not cause commit to happen (e.g. read only). Commit the wsrep
    transaction as empty.
  */
  if (!thd->in_active_multi_stmt_transaction() &&
      !thd->in_sub_stmt &&
      thd->wsrep_trx().active() &&
      thd->wsrep_trx().state() == wsrep::transaction::s_executing)
  {
    wsrep_commit_empty(thd, true);
  }

  /* assume PA safety for next transaction */
  thd->wsrep_PA_safe= true;
6040
#endif /* WITH_WSREP */
Konstantin Osipov's avatar
Konstantin Osipov committed
6041

6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059
  /*
    Reset the connection_name to contain a null string, if the
    pointer points to the same space as that of the system variable
    default_master_connection.

    We do this because the system variable may be updated which could
    free the pointer and create a new one, causing use-after-free for
    re-execution of prepared statements and stored procedures where
    the LEX may be reused.

    This allows connection_name to be set again be to the system
    variable pointer in the next call of this function (see earlier in
    this function), after any possible updates to the system variable.
  */
  if (thd->lex->mi.connection_name.str ==
      thd->variables.default_master_connection.str)
    thd->lex->mi.connection_name= null_clex_str;

6060 6061
  if (lex->sql_command != SQLCOM_SET_OPTION)
    DEBUG_SYNC(thd, "end_of_statement");
6062
  DBUG_RETURN(res || thd->is_error());
Brave Galera Crew's avatar
Brave Galera Crew committed
6063
 }
unknown's avatar
unknown committed
6064

6065 6066 6067 6068 6069 6070 6071
static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
{
  LEX	*lex= thd->lex;
  select_result *result=lex->result;
  bool res;
  /* assign global limit variable if limit is not given */
  {
6072
    SELECT_LEX *param= lex->unit.global_parameters();
6073 6074
    if (!param->limit_params.explicit_limit)
      param->limit_params.select_limit=
6075 6076
        new (thd->mem_root) Item_int(thd,
                                     (ulonglong) thd->variables.select_limit);
6077
  }
6078

6079
  if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0)))
6080 6081 6082 6083 6084 6085 6086 6087 6088
  {
    if (lex->describe)
    {
      /*
        We always use select_send for EXPLAIN, even if it's an EXPLAIN
        for SELECT ... INTO OUTFILE: a user application should be able
        to prepend EXPLAIN to any query and receive output for it,
        even if the query itself redirects the output.
      */
6089
      if (unlikely(!(result= new (thd->mem_root) select_send(thd))))
6090
        return 1;                               /* purecov: inspected */
6091
      thd->send_explain_fields(result, lex->describe, lex->analyze_stmt);
Sergey Petrunya's avatar
Sergey Petrunya committed
6092
        
6093
      /*
Sergey Petrunya's avatar
Sergey Petrunya committed
6094 6095
        This will call optimize() for all parts of query. The query plan is
        printed out below.
6096
      */
6097
      res= mysql_explain_union(thd, &lex->unit, result);
Sergey Petrunya's avatar
Sergey Petrunya committed
6098 6099
      
      /* Print EXPLAIN only if we don't have an error */
6100
      if (likely(!res))
6101
      {
6102 6103 6104
        /* 
          Do like the original select_describe did: remove OFFSET from the
          top-level LIMIT
6105 6106
        */
        result->remove_offset_limit();
Sergei Petrunia's avatar
Sergei Petrunia committed
6107
        if (lex->explain_json)
Sergey Petrunya's avatar
Sergey Petrunya committed
6108
        {
6109
          lex->explain->print_explain_json(result, lex->analyze_stmt);
Sergei Petrunia's avatar
Sergei Petrunia committed
6110 6111 6112
        }
        else
        {
6113 6114
          lex->explain->print_explain(result, thd->lex->describe,
                                      thd->lex->analyze_stmt);
Sergei Petrunia's avatar
Sergei Petrunia committed
6115 6116 6117 6118 6119 6120 6121 6122 6123
          if (lex->describe & DESCRIBE_EXTENDED)
          {
            char buff[1024];
            String str(buff,(uint32) sizeof(buff), system_charset_info);
            str.length(0);
            /*
              The warnings system requires input in utf8, @see
              mysqld_show_warnings().
            */
6124
            lex->unit.print(&str, QT_EXPLAIN_EXTENDED);
Sergei Petrunia's avatar
Sergei Petrunia committed
6125 6126 6127
            push_warning(thd, Sql_condition::WARN_LEVEL_NOTE,
                         ER_YES, str.c_ptr_safe());
          }
Sergey Petrunya's avatar
Sergey Petrunya committed
6128
        }
6129
      }
Sergey Petrunya's avatar
Sergey Petrunya committed
6130

6131
      if (res)
6132
        result->abort_result_set();
6133 6134
      else
        result->send_eof();
6135 6136 6137 6138
      delete result;
    }
    else
    {
6139
      Protocol *save_protocol= NULL;
Sergei Petrunia's avatar
Sergei Petrunia committed
6140 6141
      if (lex->analyze_stmt)
      {
Sergei Golubchik's avatar
Sergei Golubchik committed
6142 6143
        if (result && result->result_interceptor())
          result->result_interceptor()->disable_my_ok_calls();
6144 6145 6146
        else 
        {
          DBUG_ASSERT(thd->protocol);
6147
          result= new (thd->mem_root) select_send_analyze(thd);
6148 6149 6150
          save_protocol= thd->protocol;
          thd->protocol= new Protocol_discard(thd);
        }
Sergei Petrunia's avatar
Sergei Petrunia committed
6151 6152 6153
      }
      else
      {
6154
        if (!result && !(result= new (thd->mem_root) select_send(thd)))
Sergei Petrunia's avatar
Sergei Petrunia committed
6155 6156
          return 1;                               /* purecov: inspected */
      }
6157 6158 6159 6160
      query_cache_store_query(thd, all_tables);
      res= handle_select(thd, lex, result, 0);
      if (result != lex->result)
        delete result;
Sergei Petrunia's avatar
Sergei Petrunia committed
6161 6162 6163

      if (lex->analyze_stmt)
      {
6164 6165 6166 6167 6168
        if (save_protocol)
        {
          delete thd->protocol;
          thd->protocol= save_protocol;
        }
6169
        if (!res)
6170 6171 6172 6173
	{
          bool extended= thd->lex->describe & DESCRIBE_EXTENDED;
          res= thd->lex->explain->send_explain(thd, extended);
        }
Sergei Petrunia's avatar
Sergei Petrunia committed
6174
      }
6175 6176
    }
  }
6177
  /* Count number of empty select queries */
6178
  if (!thd->get_sent_row_count() && !res)
6179
    status_var_increment(thd->status_var.empty_queries);
6180
  else
unknown's avatar
unknown committed
6181
    status_var_add(thd->status_var.rows_sent, thd->get_sent_row_count());
6182

6183 6184 6185 6186
  return res;
}


6187 6188 6189 6190 6191 6192 6193 6194 6195
/**
   SHOW STATUS

   Notes: This is noinline as we don't want to have system_status_var (> 3K)
   to be on the stack of mysql_execute_command()
*/

static bool __attribute__ ((noinline))
execute_show_status(THD *thd, TABLE_LIST *all_tables)
6196 6197 6198 6199
{
  bool res;
  system_status_var old_status_var= thd->status_var;
  thd->initial_status_var= &old_status_var;
Brave Galera Crew's avatar
Brave Galera Crew committed
6200
  WSREP_SYNC_WAIT(thd, WSREP_SYNC_WAIT_BEFORE_SHOW);
Sergei Golubchik's avatar
Sergei Golubchik committed
6201 6202
  if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE,
                                UINT_MAX, FALSE)))
6203
    res= execute_sqlcom_select(thd, all_tables);
6204

6205
  thd->initial_status_var= NULL;
6206 6207 6208 6209 6210 6211 6212
  /* Don't log SHOW STATUS commands to slow query log */
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED |
                         SERVER_QUERY_NO_GOOD_INDEX_USED);
  /*
    restore status variables, as we don't want 'show status' to cause
    changes
  */
Sergei Golubchik's avatar
Sergei Golubchik committed
6213
  mysql_mutex_lock(&LOCK_status);
6214 6215
  add_diff_to_status(&global_status_var, &thd->status_var,
                     &old_status_var);
6216
  memcpy(&thd->status_var, &old_status_var, last_restored_status_var);
Sergei Golubchik's avatar
Sergei Golubchik committed
6217
  mysql_mutex_unlock(&LOCK_status);
6218
  thd->initial_status_var= NULL;
6219
  return res;
Brave Galera Crew's avatar
Brave Galera Crew committed
6220 6221
#ifdef WITH_WSREP
wsrep_error_label: /* see WSREP_SYNC_WAIT() macro above */
6222
  thd->initial_status_var= NULL;
Brave Galera Crew's avatar
Brave Galera Crew committed
6223 6224
  return true;
#endif /* WITH_WSREP */
6225 6226 6227
}


6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257
/*
  Find out if a table is a temporary table

  A table is a temporary table if it's a temporary table or
  there has been before a temporary table that has been renamed
  to the current name.

  Some examples:
  A->B          B is a temporary table if and only if A is a temp.
  A->B, B->C    Second B is temp if A is temp
  A->B, A->C    Second A can't be temp as if A was temp then B is temp
                and Second A can only be a normal table. C is also not temp
*/

static TABLE *find_temporary_table_for_rename(THD *thd,
                                              TABLE_LIST *first_table,
                                              TABLE_LIST *cur_table)
{
  TABLE_LIST *table;
  TABLE *res= 0;
  bool found= 0;
  DBUG_ENTER("find_temporary_table_for_rename");

  /* Find last instance when cur_table is in TO part */
  for (table= first_table;
       table != cur_table;
       table= table->next_local->next_local)
  {
    TABLE_LIST *next= table->next_local;

6258
    if (!strcmp(table->get_db_name().str,    cur_table->get_db_name().str) &&
6259
        !strcmp(table->get_table_name().str, cur_table->get_table_name().str))
6260 6261 6262 6263 6264
    {
      /* Table was moved away, can't be same as 'table' */
      found= 1;
      res= 0;                      // Table can't be a temporary table
    }
6265 6266
    if (!strcmp(next->get_db_name().str,    cur_table->get_db_name().str) &&
        !strcmp(next->get_table_name().str, cur_table->get_table_name().str))
6267 6268 6269 6270 6271 6272 6273 6274 6275 6276
    {
      /*
        Table has matching name with new name of this table. cur_table should
        have same temporary type as this table.
      */
      found= 1;
      res= table->table;
    }
  }
  if (!found)
6277
    res= thd->find_temporary_table(table, THD::TMP_TABLE_ANY);
6278 6279 6280 6281
  DBUG_RETURN(res);
}


6282 6283 6284
static bool __attribute__ ((noinline))
check_rename_table(THD *thd, TABLE_LIST *first_table,
                   TABLE_LIST *all_tables)
6285 6286 6287 6288 6289
{
  DBUG_ASSERT(first_table == all_tables && first_table != 0);
  TABLE_LIST *table;
  for (table= first_table; table; table= table->next_local->next_local)
  {
6290
    if (check_access(thd, ALTER_ACL | DROP_ACL, table->db.str,
Sergei Golubchik's avatar
Sergei Golubchik committed
6291 6292 6293
                     &table->grant.privilege,
                     &table->grant.m_internal,
                     0, 0) ||
6294
        check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db.str,
Sergei Golubchik's avatar
Sergei Golubchik committed
6295 6296 6297
                     &table->next_local->grant.privilege,
                     &table->next_local->grant.m_internal,
                     0, 0))
6298
      return 1;
6299

Chris Calender's avatar
Chris Calender committed
6300
    /* check if these are referring to temporary tables */
6301 6302 6303
    table->table= find_temporary_table_for_rename(thd, first_table, table);
    table->next_local->table= table->table;

6304 6305 6306
    TABLE_LIST old_list, new_list;
    /*
      we do not need initialize old_list and new_list because we will
6307
      copy table[0] and table->next[0] there
6308 6309 6310
    */
    old_list= table[0];
    new_list= table->next_local[0];
6311

Sergei Golubchik's avatar
Sergei Golubchik committed
6312 6313 6314 6315 6316
    if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) ||
       (!test_all_bits(table->next_local->grant.privilege,
                       INSERT_ACL | CREATE_ACL) &&
        check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1,
                    FALSE)))
6317 6318 6319
      return 1;
  }

6320
  return 0;
6321 6322
}

6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369
/*
  Generate an incident log event before writing the real event
  to the binary log.  We put this event is before the statement
  since that makes it simpler to check that the statement was
  not executed on the slave (since incidents usually stop the
  slave).

  Observe that any row events that are generated will be generated before.

  This is only for testing purposes and will not be present in a release build.
*/

#ifndef DBUG_OFF
static bool __attribute__ ((noinline)) generate_incident_event(THD *thd)
{
  if (mysql_bin_log.is_open())
  {

    Incident incident= INCIDENT_NONE;
    DBUG_PRINT("debug", ("Just before generate_incident()"));
    DBUG_EXECUTE_IF("incident_database_resync_on_replace",
                    incident= INCIDENT_LOST_EVENTS;);
    if (incident)
    {
      Incident_log_event ev(thd, incident);
      (void) mysql_bin_log.write(&ev);        /* error is ignored */
      if (mysql_bin_log.rotate_and_purge(true))
        return 1;
    }
    DBUG_PRINT("debug", ("Just after generate_incident()"));
  }
  return 0;
}
#else
static bool generate_incident_event(THD *thd)
{
  return 0;
}
#endif


static int __attribute__ ((noinline))
show_create_db(THD *thd, LEX *lex)
{
  DBUG_EXECUTE_IF("4x_server_emul",
                  my_error(ER_UNKNOWN_ERROR, MYF(0)); return 1;);

6370
  const DBNameBuffer dbbuf(lex->name, lower_case_table_names == 1);
6371
  if (Lex_ident_db::check_name_with_error(dbbuf.to_lex_cstring()))
6372
    return 1;
6373 6374
  LEX_CSTRING db= dbbuf.to_lex_cstring();
  return mysqld_show_create_db(thd, &db, &lex->name, lex->create_info);
6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423
}


/**
   Called on SQLCOM_ALTER_PROCEDURE and SQLCOM_ALTER_FUNCTION
*/

static bool __attribute__ ((noinline))
alter_routine(THD *thd, LEX *lex)
{
  int sp_result;
  const Sp_handler *sph= Sp_handler::handler(lex->sql_command);
  if (check_routine_access(thd, ALTER_PROC_ACL, &lex->spname->m_db,
                           &lex->spname->m_name, sph, 0))
    return 1;
  /*
    Note that if you implement the capability of ALTER FUNCTION to
    alter the body of the function, this command should be made to
    follow the restrictions that log-bin-trust-function-creators=0
    already puts on CREATE FUNCTION.
  */
  /* Conditionally writes to binlog */
  sp_result= sph->sp_update_routine(thd, lex->spname, &lex->sp_chistics);
  switch (sp_result) {
  case SP_OK:
    my_ok(thd);
    return 0;
  case SP_KEY_NOT_FOUND:
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  default:
    my_error(ER_SP_CANT_ALTER, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  }
  return 0;                                     /* purecov: deadcode */
}


static bool __attribute__ ((noinline))
drop_routine(THD *thd, LEX *lex)
{
  int sp_result;
#ifdef HAVE_DLOPEN
  if (lex->sql_command == SQLCOM_DROP_FUNCTION &&
      ! lex->spname->m_explicit_name)
  {
    /* DROP FUNCTION <non qualified name> */
Marko Mäkelä's avatar
Marko Mäkelä committed
6424 6425 6426 6427 6428 6429
    enum drop_udf_result rc= mysql_drop_function(thd, &lex->spname->m_name);
    switch (rc) {
    case UDF_DEL_RESULT_DELETED:
      my_ok(thd);
      return 0;
    case UDF_DEL_RESULT_ERROR:
6430
      return 1;
Marko Mäkelä's avatar
Marko Mäkelä committed
6431 6432
    case UDF_DEL_RESULT_ABSENT:
      goto absent;
6433 6434
    }

Marko Mäkelä's avatar
Marko Mäkelä committed
6435 6436 6437 6438
    DBUG_ASSERT("wrong return code" == 0);
absent:
    // If there was no current database, so it cannot be SP
    if (!lex->spname->m_db.str)
6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482
    {
      if (lex->if_exists())
      {
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                            ER_SP_DOES_NOT_EXIST,
                            ER_THD(thd, ER_SP_DOES_NOT_EXIST),
                            "FUNCTION (UDF)", lex->spname->m_name.str);
        my_ok(thd);
        return 0;
      }
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
               "FUNCTION (UDF)", lex->spname->m_name.str);
      return 1;
    }
    /* Fall trough to test for a stored function */
  }
#endif /* HAVE_DLOPEN */

  const Sp_handler *sph= Sp_handler::handler(lex->sql_command);

  if (check_routine_access(thd, ALTER_PROC_ACL, &lex->spname->m_db,
                           &lex->spname->m_name,
                           Sp_handler::handler(lex->sql_command), 0))
    return 1;

  WSREP_TO_ISOLATION_BEGIN(WSREP_MYSQL_DB, NULL, NULL);

  /* Conditionally writes to binlog */
  sp_result= sph->sp_drop_routine(thd, lex->spname);

#ifndef NO_EMBEDDED_ACCESS_CHECKS
  /*
    We're going to issue an implicit REVOKE statement so we close all
    open tables. We have to keep metadata locks as this ensures that
    this statement is atomic against concurent FLUSH TABLES WITH READ
    LOCK. Deadlocks which can arise due to fact that this implicit
    statement takes metadata locks should be detected by a deadlock
    detector in MDL subsystem and reported as errors.

    TODO: Long-term we should either ensure that implicit REVOKE statement
    is written into binary log as a separate statement or make both
    dropping of routine and implicit REVOKE parts of one fully atomic
    statement.
  */
6483 6484
  if (trans_commit_stmt(thd))
    sp_result= SP_INTERNAL_ERROR;
6485 6486 6487 6488
  close_thread_tables(thd);

  if (sp_result != SP_KEY_NOT_FOUND &&
      sp_automatic_privileges && !opt_noacl &&
6489 6490
      sp_revoke_privileges(thd, lex->spname->m_db,
                           Lex_ident_routine(lex->spname->m_name),
6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533
                           Sp_handler::handler(lex->sql_command)))
  {
    push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
                 ER_PROC_AUTO_REVOKE_FAIL,
                 ER_THD(thd, ER_PROC_AUTO_REVOKE_FAIL));
    /* If this happens, an error should have been reported. */
    return 1;
  }
#endif /* NO_EMBEDDED_ACCESS_CHECKS */

  switch (sp_result) {
  case SP_OK:
    my_ok(thd);
    return 0;
  case SP_KEY_NOT_FOUND:
    int res;
    if (lex->if_exists())
    {
      res= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
      push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
                          ER_SP_DOES_NOT_EXIST,
                          ER_THD(thd, ER_SP_DOES_NOT_EXIST),
                          sph->type_str(),
                          ErrConvDQName(lex->spname).ptr());
      if (res)
        return 1;
      my_ok(thd);
      return 0;
    }
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  default:
    my_error(ER_SP_DROP_FAILED, MYF(0),
             sph->type_str(), ErrConvDQName(lex->spname).ptr());
    return 1;
  }

#ifdef WITH_WSREP
wsrep_error_label:
  return 1;
#endif
}
6534

unknown's avatar
unknown committed
6535
/**
6536 6537 6538 6539 6540 6541
  @brief Compare requested privileges with the privileges acquired from the
    User- and Db-tables.
  @param thd          Thread handler
  @param want_access  The requested access privileges.
  @param db           A pointer to the Db name.
  @param[out] save_priv A pointer to the granted privileges will be stored.
Marc Alff's avatar
Marc Alff committed
6542
  @param grant_internal_info A pointer to the internal grant cache.
6543 6544 6545 6546 6547 6548 6549 6550
  @param dont_check_global_grants True if no global grants are checked.
  @param no_error     True if no errors should be sent to the client.

  'save_priv' is used to save the User-table (global) and Db-table grants for
  the supplied db name. Note that we don't store db level grants if the global
  grants is enough to satisfy the request AND the global grants contains a
  SELECT grant.

Marc Alff's avatar
Marc Alff committed
6551 6552
  For internal databases (INFORMATION_SCHEMA, PERFORMANCE_SCHEMA),
  additional rules apply, see ACL_internal_schema_access.
6553 6554 6555 6556 6557 6558 6559

  @see check_grant

  @return Status of denial of access by exclusive ACLs.
    @retval FALSE Access can't exclusively be denied by Db- and User-table
      access unless Column- and Table-grants are checked too.
    @retval TRUE Access denied.
unknown's avatar
unknown committed
6560
*/
6561

unknown's avatar
unknown committed
6562
bool
6563 6564
check_access(THD *thd, privilege_t want_access,
             const char *db, privilege_t *save_priv,
Marc Alff's avatar
Marc Alff committed
6565 6566
             GRANT_INTERNAL_INFO *grant_internal_info,
             bool dont_check_global_grants, bool no_errors)
unknown's avatar
unknown committed
6567
{
6568 6569 6570 6571 6572
#ifdef NO_EMBEDDED_ACCESS_CHECKS
  if (save_priv)
    *save_priv= GLOBAL_ACLS;
  return false;
#else
6573
  Security_context *sctx= thd->security_ctx;
6574
  privilege_t db_access(NO_ACL);
6575

6576 6577 6578 6579 6580
  /*
    GRANT command:
    In case of database level grant the database name may be a pattern,
    in case of table|column level grant the database name can not be a pattern.
    We use 'dont_check_global_grants' as a flag to determine
6581
    if it's database level grant command
6582 6583 6584
    (see SQLCOM_GRANT case, mysql_execute_command() function) and
    set db_is_pattern according to 'dont_check_global_grants' value.
  */
6585
  bool  db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants);
6586
  privilege_t dummy(NO_ACL);
6587
  DBUG_ENTER("check_access");
6588 6589 6590 6591
  DBUG_PRINT("enter",("db: %s  want_access: %llx  master_access: %llx",
                      db ? db : "",
                      (longlong) want_access,
                      (longlong) sctx->master_access));
6592

unknown's avatar
unknown committed
6593
  if (save_priv)
6594
    *save_priv= NO_ACL;
unknown's avatar
unknown committed
6595
  else
Marc Alff's avatar
Marc Alff committed
6596
  {
unknown's avatar
unknown committed
6597
    save_priv= &dummy;
6598
    dummy= NO_ACL;
Marc Alff's avatar
Marc Alff committed
6599
  }
unknown's avatar
unknown committed
6600

6601 6602 6603
  /* check access may be called twice in a row. Don't change to same stage */
  if (thd->proc_info != stage_checking_permissions.m_name)
    THD_STAGE_INFO(thd, stage_checking_permissions);
6604
  if (unlikely((!db || !db[0]) && !thd->db.str && !dont_check_global_grants))
unknown's avatar
unknown committed
6605
  {
6606
    DBUG_RETURN(FALSE); // CTE reference or an error later
unknown's avatar
unknown committed
6607 6608
  }

Alexey Botchkov's avatar
Alexey Botchkov committed
6609
  if (likely((db != NULL) && (db != any_db.str)))
6610
  {
Michael Widenius's avatar
Michael Widenius committed
6611 6612 6613 6614
    /*
      Check if this is reserved database, like information schema or
      performance schema
    */
Marc Alff's avatar
Marc Alff committed
6615 6616 6617
    const ACL_internal_schema_access *access;
    access= get_cached_schema_access(grant_internal_info, db);
    if (access)
6618
    {
Marc Alff's avatar
Marc Alff committed
6619
      switch (access->check(want_access, save_priv))
6620
      {
Marc Alff's avatar
Marc Alff committed
6621 6622 6623 6624 6625 6626 6627 6628 6629
      case ACL_INTERNAL_ACCESS_GRANTED:
        /*
          All the privileges requested have been granted internally.
          [out] *save_privileges= Internal privileges.
        */
        DBUG_RETURN(FALSE);
      case ACL_INTERNAL_ACCESS_DENIED:
        if (! no_errors)
        {
Sergei Golubchik's avatar
Sergei Golubchik committed
6630
          status_var_increment(thd->status_var.access_denied_errors);
Marc Alff's avatar
Marc Alff committed
6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641
          my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
                   sctx->priv_user, sctx->priv_host, db);
        }
        DBUG_RETURN(TRUE);
      case ACL_INTERNAL_ACCESS_CHECK_GRANT:
        /*
          Only some of the privilege requested have been granted internally,
          proceed with the remaining bits of the request (want_access).
        */
        want_access&= ~(*save_priv);
        break;
6642
      }
6643 6644 6645
    }
  }

6646
  if ((sctx->master_access & want_access) == want_access)
unknown's avatar
unknown committed
6647
  {
6648
    /*
6649 6650
      1. If we don't have a global SELECT privilege, we have to get the
      database specific access rights to be able to handle queries of type
6651
      UPDATE t1 SET a=1 WHERE b > 0
6652
      2. Change db access if it isn't current db which is being addressed
6653
    */
Marc Alff's avatar
Marc Alff committed
6654 6655
    if (!(sctx->master_access & SELECT_ACL))
    {
6656
      if (db && (!thd->db.str || db_is_pattern || strcmp(db, thd->db.str)))
6657
      {
6658
        db_access= acl_get_all3(sctx, db, db_is_pattern);
6659
      }
Marc Alff's avatar
Marc Alff committed
6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673
      else
      {
        /* get access for current db */
        db_access= sctx->db_access;
      }
      /*
        The effective privileges are the union of the global privileges
        and the intersection of db- and host-privileges,
        plus the internal privileges.
      */
      *save_priv|= sctx->master_access | db_access;
    }
    else
      *save_priv|= sctx->master_access;
unknown's avatar
unknown committed
6674
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
6675
  }
6676 6677
  if (unlikely(((want_access & ~sctx->master_access) & ~DB_ACLS) ||
               (! db && dont_check_global_grants)))
unknown's avatar
unknown committed
6678
  {						// We can never grant this
6679
    DBUG_PRINT("error",("No possible access"));
6680
    if (!no_errors)
6681 6682
    {
      status_var_increment(thd->status_var.access_denied_errors);
Sergei Golubchik's avatar
Sergei Golubchik committed
6683
      my_error(access_denied_error_code(thd->password), MYF(0),
6684 6685
               sctx->priv_user,
               sctx->priv_host,
6686
               (thd->password ?
6687 6688
                ER_THD(thd, ER_YES) :
                ER_THD(thd, ER_NO)));                    /* purecov: tested */
6689
    }
unknown's avatar
unknown committed
6690
    DBUG_RETURN(TRUE);				/* purecov: tested */
unknown's avatar
unknown committed
6691 6692
  }

Alexey Botchkov's avatar
Alexey Botchkov committed
6693
  if (unlikely(db == any_db.str))
6694 6695 6696 6697 6698 6699 6700
  {
    /*
      Access granted; Allow select on *any* db.
      [out] *save_privileges= 0
    */
    DBUG_RETURN(FALSE);
  }
unknown's avatar
unknown committed
6701

6702
  if (db && (!thd->db.str || db_is_pattern || strcmp(db, thd->db.str)))
6703
    db_access= acl_get_all3(sctx, db, db_is_pattern);
unknown's avatar
unknown committed
6704
  else
6705
    db_access= sctx->db_access;
6706 6707
  DBUG_PRINT("info",("db_access: %llx  want_access: %llx",
                     (longlong) db_access, (longlong) want_access));
6708

6709 6710
  /*
    Save the union of User-table and the intersection between Db-table and
Marc Alff's avatar
Marc Alff committed
6711
    Host-table privileges, with the already saved internal privileges.
6712 6713
  */
  db_access= (db_access | sctx->master_access);
Marc Alff's avatar
Marc Alff committed
6714
  *save_priv|= db_access;
6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729

  /*
    We need to investigate column- and table access if all requested privileges
    belongs to the bit set of .
  */
  bool need_table_or_column_check=
    (want_access & (TABLE_ACLS | PROC_ACLS | db_access)) == want_access;

  /*
    Grant access if the requested access is in the intersection of
    host- and db-privileges (as retrieved from the acl cache),
    also grant access if all the requested privileges are in the union of
    TABLES_ACLS and PROC_ACLS; see check_grant.
  */
  if ( (db_access & want_access) == want_access ||
6730
      (!dont_check_global_grants &&
6731 6732 6733 6734
       need_table_or_column_check))
  {
    /*
       Ok; but need to check table- and column privileges.
Marc Alff's avatar
Marc Alff committed
6735
       [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
6736 6737 6738
    */
    DBUG_RETURN(FALSE);
  }
6739

6740 6741
  /*
    Access is denied;
Marc Alff's avatar
Marc Alff committed
6742
    [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv)
6743
  */
6744
  DBUG_PRINT("error",("Access denied"));
6745
  if (!no_errors)
6746 6747
  {
    status_var_increment(thd->status_var.access_denied_errors);
6748
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
6749
             sctx->priv_user, sctx->priv_host,
6750 6751
             (db ? db : (thd->db.str ?
                         thd->db.str :
6752
                         "unknown")));
6753
  }
6754
  DBUG_RETURN(TRUE);
6755 6756 6757 6758 6759 6760 6761 6762 6763 6764
#endif // NO_EMBEDDED_ACCESS_CHECKS
}


#ifndef NO_EMBEDDED_ACCESS_CHECKS
/**
  Check grants for commands which work only with one table.

  @param thd                    Thread handler
  @param privilege              requested privilege
6765
  @param tables                 global table list of query
6766 6767 6768 6769 6770 6771 6772 6773 6774
  @param no_errors              FALSE/TRUE - report/don't report error to
                            the client (using my_error() call).

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
*/

6775 6776
bool check_single_table_access(THD *thd, privilege_t privilege,
                               TABLE_LIST *tables, bool no_errors)
6777
{
6778
  if (tables->derived)
6779 6780
    return 0;

6781
  Switch_to_definer_security_ctx backup_sctx(thd, tables);
6782 6783

  const char *db_name;
6784 6785
  if ((tables->view || tables->field_translation) && !tables->schema_table)
    db_name= tables->view_db.str;
6786
  else
6787
    db_name= tables->db.str;
6788

6789 6790
  if (check_access(thd, privilege, db_name, &tables->grant.privilege,
                   &tables->grant.m_internal, 0, no_errors))
6791
    return 1;
6792 6793

  /* Show only 1 table for check_grant */
6794 6795 6796
  if (!(tables->belong_to_view &&
       (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
      check_grant(thd, privilege, tables, FALSE, 1, no_errors))
6797
    return 1;
6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815

  return 0;
}

/**
  Check grants for commands which work only with one table and all other
  tables belonging to subselects or implicitly opened tables.

  @param thd			Thread handler
  @param privilege		requested privilege
  @param all_tables		global table list of query

  @retval
    0   OK
  @retval
    1   access denied, error is sent to client
*/

6816 6817
bool check_one_table_access(THD *thd, privilege_t privilege,
                            TABLE_LIST *all_tables)
6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841
{
  if (check_single_table_access (thd,privilege,all_tables, FALSE))
    return 1;

  /* Check rights on tables of subselects and implictly opened tables */
  TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0;
  if ((subselects_tables= all_tables->next_global))
  {
    /*
      Access rights asked for the first table of a view should be the same
      as for the view
    */
    if (view && subselects_tables->belong_to_view == view)
    {
      if (check_single_table_access (thd, privilege, subselects_tables, FALSE))
        return 1;
      subselects_tables= subselects_tables->next_global;
    }
    if (subselects_tables &&
        (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE,
                            UINT_MAX, FALSE)))
      return 1;
  }
  return 0;
unknown's avatar
unknown committed
6842 6843 6844
}


6845 6846
static bool check_show_access(THD *thd, TABLE_LIST *table)
{
Marc Alff's avatar
Marc Alff committed
6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858
  /*
    This is a SHOW command using an INFORMATION_SCHEMA table.
    check_access() has not been called for 'table',
    and SELECT is currently always granted on the I_S, so we automatically
    grant SELECT on table here, to bypass a call to check_access().
    Note that not calling check_access(table) is an optimization,
    which needs to be revisited if the INFORMATION_SCHEMA does
    not always automatically grant SELECT but use the grant tables.
    See Bug#38837 need a way to disable information_schema for security
  */
  table->grant.privilege= SELECT_ACL;

unknown's avatar
unknown committed
6859
  switch (get_schema_table_idx(table->schema_table)) {
6860 6861
  case SCH_SCHEMATA:
    return (specialflag & SPECIAL_SKIP_SHOW_DB) &&
unknown's avatar
unknown committed
6862
      check_global_access(thd, SHOW_DB_ACL);
6863 6864 6865 6866 6867

  case SCH_TABLE_NAMES:
  case SCH_TABLES:
  case SCH_VIEWS:
  case SCH_TRIGGERS:
unknown's avatar
unknown committed
6868 6869
  case SCH_EVENTS:
  {
6870
    const char *dst_db_name= table->schema_select_lex->db.str;
6871

unknown's avatar
unknown committed
6872
    DBUG_ASSERT(dst_db_name);
6873

unknown's avatar
unknown committed
6874
    if (check_access(thd, SELECT_ACL, dst_db_name,
Marc Alff's avatar
Marc Alff committed
6875
                     &thd->col_access, NULL, FALSE, FALSE))
unknown's avatar
unknown committed
6876
      return TRUE;
6877

unknown's avatar
unknown committed
6878 6879
    if (!thd->col_access && check_grant_db(thd, dst_db_name))
    {
6880
      status_var_increment(thd->status_var.access_denied_errors);
unknown's avatar
unknown committed
6881 6882 6883 6884 6885
      my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
               thd->security_ctx->priv_user,
               thd->security_ctx->priv_host,
               dst_db_name);
      return TRUE;
6886 6887
    }

unknown's avatar
unknown committed
6888 6889 6890
    return FALSE;
  }

6891 6892
  case SCH_COLUMNS:
  case SCH_STATISTICS:
unknown's avatar
unknown committed
6893 6894
  {
    TABLE_LIST *dst_table;
6895
    dst_table= table->schema_select_lex->table_list.first;
6896

unknown's avatar
unknown committed
6897
    DBUG_ASSERT(dst_table);
6898

Michael Widenius's avatar
Michael Widenius committed
6899 6900 6901
    /*
      Open temporary tables to be able to detect them during privilege check.
    */
6902
    if (thd->open_temporary_tables(dst_table))
Michael Widenius's avatar
Michael Widenius committed
6903 6904
      return TRUE;

6905
    if (check_access(thd, SELECT_ACL, dst_table->db.str,
Marc Alff's avatar
Marc Alff committed
6906 6907 6908
                     &dst_table->grant.privilege,
                     &dst_table->grant.m_internal,
                     FALSE, FALSE))
6909 6910
          return TRUE; /* Access denied */

6911
    thd->col_access= dst_table->grant.privilege; // for sql_show.cc
6912 6913 6914 6915
    /*
      Check_grant will grant access if there is any column privileges on
      all of the tables thanks to the fourth parameter (bool show_table).
    */
6916
    if (check_grant(thd, SELECT_ACL, dst_table, TRUE, 1, FALSE))
6917
      return TRUE; /* Access denied */
6918

unknown's avatar
unknown committed
6919 6920 6921
    close_thread_tables(thd);
    dst_table->table= NULL;

6922 6923
    /* Access granted */
    return FALSE;
unknown's avatar
unknown committed
6924 6925
  }
  default:
6926 6927 6928 6929 6930 6931 6932
    break;
  }

  return FALSE;
}


6933

6934 6935 6936 6937
/**
  @brief Check if the requested privileges exists in either User-, Host- or
    Db-tables.
  @param thd          Thread context
6938
  @param requirements Privileges requested
6939 6940 6941 6942 6943
  @param tables       List of tables to be compared against
  @param any_combination_of_privileges_will_do TRUE if any privileges on any
    column combination is enough.
  @param number       Only the first 'number' tables in the linked list are
                      relevant.
6944
  @param no_errors    Don't report error to the client (using my_error() call).
6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961

  The suppled table list contains cached privileges. This functions calls the
  help functions check_access and check_grant to verify the first three steps
  in the privileges check queue:
  1. Global privileges
  2. OR (db privileges AND host privileges)
  3. OR table privileges
  4. OR column privileges (not checked by this function!)
  5. OR routine privileges (not checked by this function!)

  @see check_access
  @see check_grant

  @note This functions assumes that table list used and
  thd->lex->query_tables_own_last value correspond to each other
  (the latter should be either 0 or point to next_global member
  of one of elements of this table list).
6962

6963 6964 6965 6966
  @return
    @retval FALSE OK
    @retval TRUE  Access denied; But column or routine privileges might need to
      be checked also.
unknown's avatar
unknown committed
6967 6968
*/

6969
bool
6970
check_table_access(THD *thd, privilege_t requirements, TABLE_LIST *tables,
6971
                   bool any_combination_of_privileges_will_do,
6972
                   uint number, bool no_errors)
unknown's avatar
unknown committed
6973
{
6974 6975
  TABLE_LIST *org_tables= tables;
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
Sergei Golubchik's avatar
Sergei Golubchik committed
6976
  uint i= 0;
6977
  /*
unknown's avatar
unknown committed
6978 6979 6980
    The check that first_not_own_table is not reached is for the case when
    the given table list refers to the list for prelocking (contains tables
    of other queries). For simple queries first_not_own_table is 0.
6981
  */
6982
  for (; i < number && tables != first_not_own_table && tables;
6983
       tables= tables->next_global, i++)
unknown's avatar
unknown committed
6984
  {
6985 6986
    TABLE_LIST *const table_ref= tables->correspondent_table ?
      tables->correspondent_table : tables;
6987
    Switch_to_definer_security_ctx backup_ctx(thd, table_ref);
6988

6989
    privilege_t want_access(requirements);
6990

6991 6992 6993 6994
    /*
       Register access for view underlying table.
       Remove SHOW_VIEW_ACL, because it will be checked during making view
     */
6995
    table_ref->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
unknown's avatar
unknown committed
6996

6997
    if (table_ref->schema_table_reformed)
unknown's avatar
unknown committed
6998
    {
6999
      if (check_show_access(thd, table_ref))
7000
        return 1;
unknown's avatar
unknown committed
7001 7002 7003
      continue;
    }

7004 7005
    DBUG_PRINT("info", ("derived: %d  view: %d", table_ref->derived != 0,
                        table_ref->view != 0));
unknown's avatar
unknown committed
7006

7007
    if (table_ref->is_anonymous_derived_table())
unknown's avatar
unknown committed
7008
      continue;
unknown's avatar
unknown committed
7009

Monty's avatar
Monty committed
7010 7011 7012 7013 7014
    if (table_ref->sequence)
    {
      /* We want to have either SELECT or INSERT rights to sequences depending
         on how they are accessed
      */
7015
      want_access= ((table_ref->lock_type >= TL_FIRST_WRITE) ?
Monty's avatar
Monty committed
7016 7017 7018
                    INSERT_ACL : SELECT_ACL);
    }

7019
    if (check_access(thd, want_access, table_ref->get_db_name().str,
7020 7021
                     &table_ref->grant.privilege,
                     &table_ref->grant.m_internal,
Marc Alff's avatar
Marc Alff committed
7022
                     0, no_errors))
7023
      return 1;
unknown's avatar
unknown committed
7024
  }
7025 7026 7027
  return check_grant(thd,requirements,org_tables,
                     any_combination_of_privileges_will_do,
                     number, no_errors);
unknown's avatar
unknown committed
7028 7029
}

7030

7031
bool
7032
check_routine_access(THD *thd, privilege_t want_access, const LEX_CSTRING *db,
7033
                     const LEX_CSTRING *name,
7034
                     const Sp_handler *sph, bool no_errors)
7035 7036 7037 7038
{
  TABLE_LIST tables[1];
  
  bzero((char *)tables, sizeof(TABLE_LIST));
7039 7040
  tables->db= Lex_ident_db(*db);
  tables->table_name= tables->alias= Lex_ident_table(*name);
7041
  
unknown's avatar
unknown committed
7042 7043 7044 7045 7046
  /*
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access) under the assumption that it's common to
    give persons global right to execute all stored SP (but not
    necessary to create them).
Marc Alff's avatar
Marc Alff committed
7047 7048 7049 7050 7051 7052
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
    as long as this code path is not abused to create routines.
    The assert enforce that.
unknown's avatar
unknown committed
7053
  */
7054
  DBUG_ASSERT((want_access & CREATE_PROC_ACL) == NO_ACL);
unknown's avatar
unknown committed
7055
  if ((thd->security_ctx->master_access & want_access) == want_access)
7056
    tables->grant.privilege= want_access;
7057
  else if (check_access(thd, want_access, db->str,
Marc Alff's avatar
Marc Alff committed
7058 7059 7060
                        &tables->grant.privilege,
                        &tables->grant.m_internal,
                        0, no_errors))
7061 7062
    return TRUE;
  
7063
  return check_grant_routine(thd, want_access, tables, sph, no_errors);
7064 7065
}

7066

unknown's avatar
unknown committed
7067 7068
/**
  Check if the routine has any of the routine privileges.
7069

unknown's avatar
unknown committed
7070 7071 7072
  @param thd	       Thread handler
  @param db           Database name
  @param name         Routine name
7073

unknown's avatar
unknown committed
7074
  @retval
7075
    0            ok
unknown's avatar
unknown committed
7076
  @retval
7077 7078 7079
    1            error
*/

7080
bool check_some_routine_access(THD *thd, const char *db, const char *name,
7081
                               const Sp_handler *sph)
7082
{
7083
  privilege_t save_priv(NO_ACL);
7084
  /*
Marc Alff's avatar
Marc Alff committed
7085 7086 7087 7088 7089 7090
    The following test is just a shortcut for check_access() (to avoid
    calculating db_access)
    Note that this effectively bypasses the ACL_internal_schema_access checks
    that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA,
    which are located in check_access().
    Since the I_S and P_S do not contain routines, this bypass is ok,
7091
    as it only opens SHOW_PROC_WITHOUT_DEFINITION_ACLS.
7092
  */
7093
  if (thd->security_ctx->master_access & SHOW_PROC_WITHOUT_DEFINITION_ACLS)
Marc Alff's avatar
Marc Alff committed
7094
    return FALSE;
7095 7096 7097
  if (!check_access(thd, SHOW_PROC_WITHOUT_DEFINITION_ACLS,
                    db, &save_priv, NULL, 0, 1) ||
      (save_priv & SHOW_PROC_WITHOUT_DEFINITION_ACLS))
7098
    return FALSE;
7099 7100
  return check_routine_level_acl(thd, SHOW_PROC_WITHOUT_DEFINITION_ACLS,
                                 db, name, sph);
7101 7102 7103
}


7104 7105 7106
/*
  Check if the given table has any of the asked privileges

unknown's avatar
unknown committed
7107 7108
  @param thd		 Thread handler
  @param want_access	 Bitmap of possible privileges to check for
7109

unknown's avatar
unknown committed
7110
  @retval
7111
    0  ok
unknown's avatar
unknown committed
7112
  @retval
7113 7114 7115
    1  error
*/

7116
bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table)
7117 7118 7119
{
  DBUG_ENTER("check_some_access");

7120
  for (ulonglong bit= 1; bit < (ulonglong) want_access ; bit<<= 1)
7121
  {
7122
    if (bit & want_access)
7123
    {
7124
      privilege_t access= ALL_KNOWN_ACL & bit;
7125
      if (!check_access(thd, access, table->db.str,
Marc Alff's avatar
Marc Alff committed
7126 7127 7128
                        &table->grant.privilege,
                        &table->grant.m_internal,
                        0, 1) &&
7129
           !check_grant(thd, access, table, FALSE, 1, TRUE))
7130 7131 7132 7133 7134 7135 7136
        DBUG_RETURN(0);
    }
  }
  DBUG_PRINT("exit",("no matching access rights"));
  DBUG_RETURN(1);
}

unknown's avatar
unknown committed
7137
#endif /*NO_EMBEDDED_ACCESS_CHECKS*/
7138

7139 7140 7141 7142 7143 7144 7145 7146

/**
  check for global access and give descriptive error message if it fails.

  @param thd			Thread handler
  @param want_access		Use should have any of these global rights

  @warning
7147 7148
    Starting from 10.5.2 only one bit is allowed in want_access.
    Access denied error is returned if want_access has multiple bits set.
7149 7150 7151 7152 7153 7154 7155

  @retval
    0	ok
  @retval
    1	Access denied.  In this case an error is sent to the client
*/

7156
bool check_global_access(THD *thd, privilege_t want_access, bool no_errors)
7157 7158 7159
{
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  char command[128];
7160
  if (thd->security_ctx->master_access & want_access)
7161
    return 0;
7162
  if (unlikely(!no_errors))
7163 7164 7165 7166
  {
    get_privilege_desc(command, sizeof(command), want_access);
    my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command);
  }
7167
  status_var_increment(thd->status_var.access_denied_errors);
7168 7169 7170 7171 7172 7173
  return 1;
#else
  return 0;
#endif
}

7174 7175 7176 7177 7178 7179 7180 7181 7182

/**
  Checks foreign key's parent table access.

  @param thd	       [in]	Thread handler
  @param create_info   [in]     Create information (like MAX_ROWS, ENGINE or
                                temporary table flag)
  @param alter_info    [in]     Initial list of columns and indexes for the
                                table to be created
7183
  @param create_db     [in]     Database of the created table
7184 7185 7186 7187 7188 7189 7190 7191

  @retval
   false  ok.
  @retval
   true	  error or access denied. Error is sent to client in this case.
*/
bool check_fk_parent_table_access(THD *thd,
                                  HA_CREATE_INFO *create_info,
7192
                                  Alter_info *alter_info,
7193
                                  const LEX_CSTRING &create_db)
7194 7195 7196 7197 7198 7199 7200 7201 7202 7203
{
  Key *key;
  List_iterator<Key> key_iterator(alter_info->key_list);

  while ((key= key_iterator++))
  {
    if (key->type == Key::FOREIGN_KEY)
    {
      TABLE_LIST parent_table;
      Foreign_key *fk_key= (Foreign_key *)key;
7204 7205
      LEX_CSTRING db_name;
      LEX_CSTRING table_name= { fk_key->ref_table.str,
Sergei Golubchik's avatar
Sergei Golubchik committed
7206
                               fk_key->ref_table.length };
7207
      const privilege_t privileges(COL_DML_ACLS | REFERENCES_ACL);
7208 7209 7210

      // Check if tablename is valid or not.
      DBUG_ASSERT(table_name.str != NULL);
7211
      if (Lex_ident_table::check_name(table_name, false))
7212 7213 7214 7215
      {
        my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str);
        return true;
      }
7216 7217 7218 7219
      // if lower_case_table_names is set then convert tablename to lower case.
      if (lower_case_table_names &&
          !(table_name= thd->make_ident_casedn(fk_key->ref_table)).str)
        return true;
7220

Sergei Golubchik's avatar
Sergei Golubchik committed
7221
      if (fk_key->ref_db.str)
7222
      {
7223
        if (Lex_ident_db::check_name_with_error(fk_key->ref_db) ||
7224 7225
            !(db_name= thd->make_ident_opt_casedn(fk_key->ref_db,
                                                  lower_case_table_names)).str)
7226 7227 7228
          return true;
      }
      else
7229
      {
7230
        if (!thd->db.str)
7231
        {
7232
          DBUG_ASSERT(create_db.str);
7233
          if (Lex_ident_db::check_name_with_error(create_db) ||
7234 7235
              !(db_name= thd->make_ident_opt_casedn(create_db,
                                                 lower_case_table_names)).str)
7236 7237 7238 7239
            return true;
        }
        else
        {
7240 7241 7242
          if (thd->lex->copy_db_to(&db_name) ||
              (lower_case_table_names &&
               !(db_name= thd->make_ident_casedn(db_name)).str))
7243 7244 7245
            return true;
        }
      }
7246

7247
      parent_table.init_one_table(&db_name, &table_name, 0, TL_IGNORE);
7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259

      /*
       Check if user has any of the "privileges" at table level on
       "parent_table".
       Having privilege on any of the parent_table column is not
       enough so checking whether user has any of the "privileges"
       at table level only here.
      */
      if (check_some_access(thd, privileges, &parent_table) ||
          parent_table.grant.want_privilege)
      {
        my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0),
7260 7261 7262 7263
                "REFERENCES",
                thd->security_ctx->priv_user,
                thd->security_ctx->host_or_ip,
                db_name.str, table_name.str);
7264 7265 7266 7267 7268 7269 7270 7271 7272
        return true;
      }
    }
  }

  return false;
}


unknown's avatar
unknown committed
7273 7274 7275 7276
/****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue
****************************************************************************/

7277

unknown's avatar
unknown committed
7278 7279 7280 7281
#ifndef DBUG_OFF
long max_stack_used;
#endif

unknown's avatar
unknown committed
7282 7283
/**
  @note
7284 7285 7286 7287
  Note: The 'buf' parameter is necessary, even if it is unused here.
  - fix_fields functions has a "dummy" buffer large enough for the
    corresponding exec. (Thus we only have to check in fix_fields.)
  - Passing to check_stack_overrun() prevents the compiler from removing it.
unknown's avatar
unknown committed
7288
*/
7289 7290

bool
7291
#if defined __GNUC__ && !defined __clang__
7292 7293 7294 7295 7296 7297 7298 7299
/*
  Do not optimize the function in order to preserve a stack variable creation.
  Otherwise, the variable pointed as "buf" can be removed due to a missing
  usage.
 */
__attribute__((optimize("-O0")))
#endif
check_stack_overrun(THD *thd, long margin, uchar *buf __attribute__((unused)))
unknown's avatar
unknown committed
7300
{
7301
#ifndef __SANITIZE_ADDRESS__
unknown's avatar
unknown committed
7302
  long stack_used;
7303
  DBUG_ASSERT(thd == current_thd);
7304
  if ((stack_used= available_stack_size(thd->thread_stack, &stack_used)) >=
7305
      (long) (my_thread_stack_size - margin))
unknown's avatar
unknown committed
7306
  {
Monty's avatar
Monty committed
7307
    thd->is_fatal_error= 1;
7308 7309 7310 7311 7312 7313
    /*
      Do not use stack for the message buffer to ensure correct
      behaviour in cases we have close to no stack left.
    */
    char* ebuff= new char[MYSQL_ERRMSG_SIZE];
    if (ebuff) {
7314
      my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER_THD(thd, ER_STACK_OVERRUN_NEED_MORE),
7315
                  stack_used, my_thread_stack_size, margin);
7316
      my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATAL));
7317 7318
      delete [] ebuff;
    }
unknown's avatar
unknown committed
7319 7320
    return 1;
  }
unknown's avatar
unknown committed
7321
#ifndef DBUG_OFF
7322
  max_stack_used= MY_MAX(max_stack_used, stack_used);
unknown's avatar
unknown committed
7323
#endif
7324
#endif /* __SANITIZE_ADDRESS__ */
unknown's avatar
unknown committed
7325 7326
  return 0;
}
7327

unknown's avatar
unknown committed
7328 7329 7330 7331

#define MY_YACC_INIT 1000			// Start with big alloc
#define MY_YACC_MAX  32000			// Because of 'short'

7332
bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, size_t *yystacksize)
unknown's avatar
unknown committed
7333
{
7334
  Yacc_state *state= & current_thd->m_parser_state->m_yacc;
7335
  size_t old_info=0;
7336
  DBUG_ASSERT(state);
7337
  if ( *yystacksize >= MY_YACC_MAX)
unknown's avatar
unknown committed
7338
    return 1;
7339
  if (!state->yacc_yyvs)
unknown's avatar
unknown committed
7340
    old_info= *yystacksize;
7341
  *yystacksize= set_zone((int)(*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX);
7342
  if (!(state->yacc_yyvs= (uchar*)
7343
        my_realloc(key_memory_bison_stack, state->yacc_yyvs,
7344 7345 7346
                   *yystacksize*sizeof(**yyvs),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) ||
      !(state->yacc_yyss= (uchar*)
7347
        my_realloc(key_memory_bison_stack, state->yacc_yyss,
7348 7349
                   *yystacksize*sizeof(**yyss),
                   MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))))
unknown's avatar
unknown committed
7350 7351
    return 1;
  if (old_info)
7352 7353 7354 7355 7356 7357 7358 7359
  {
    /*
      Only copy the old stack on the first call to my_yyoverflow(),
      when replacing a static stack (YYINITDEPTH) by a dynamic stack.
      For subsequent calls, my_realloc already did preserve the old stack.
    */
    memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss));
    memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs));
unknown's avatar
unknown committed
7360
  }
7361 7362
  *yyss= (short*) state->yacc_yyss;
  *yyvs= (YYSTYPE*) state->yacc_yyvs;
unknown's avatar
unknown committed
7363 7364 7365 7366
  return 0;
}


unknown's avatar
unknown committed
7367
/**
7368 7369
  Reset the part of THD responsible for the state of command
  processing.
7370

7371 7372
  @param do_clear_error  Set if we should clear errors

7373 7374 7375
  This needs to be called before execution of every statement
  (prepared or conventional).  It is not called by substatements of
  routines.
7376

7377 7378
  @todo Call it after we use THD for queries, not before.
*/
7379

7380
void THD::reset_for_next_command(bool do_clear_error)
7381
{
7382
  DBUG_ENTER("THD::reset_for_next_command");
7383 7384
  DBUG_ASSERT(!spcont); /* not for substatements of routines */
  DBUG_ASSERT(!in_sub_stmt);
7385 7386
  /*
    Table maps should have been reset after previous statement except in the
7387
    case where we have locked tables
7388 7389 7390
  */
  DBUG_ASSERT(binlog_table_maps == 0 ||
              locked_tables_mode == LTM_LOCK_TABLES);
7391

7392
  if (likely(do_clear_error))
7393
  {
7394
    clear_error(1);
7395 7396 7397 7398 7399 7400
    /*
      The following variable can't be reset in clear_error() as
      clear_error() is called during auto_repair of table
    */
    error_printed_to_log= 0;
  }
7401
  free_list= 0;
7402
  /*
7403
    We also assign stmt_lex in lex_start(), but during bootstrap this
7404 7405
    code is executed first.
  */
7406
  DBUG_ASSERT(lex == &main_lex);
7407
  main_lex.stmt_lex= &main_lex; main_lex.current_select_number= 0;
7408 7409 7410 7411
  /*
    Those two lines below are theoretically unneeded as
    THD::cleanup_after_query() should take care of this already.
  */
7412 7413
  auto_inc_intervals_in_cur_stmt_for_binlog.empty();
  stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
7414

7415 7416 7417 7418
#ifdef WITH_WSREP
  /*
    Autoinc variables should be adjusted only for locally executed
    transactions. Appliers and replayers are either processing ROW
sjaakola's avatar
sjaakola committed
7419 7420 7421 7422
    events or get autoinc variable values from Query_log_event and
    mysql slave may be processing STATEMENT format events, but he should
    use autoinc values passed in binlog events, not the values forced by
    the cluster.
7423
  */
7424
  if (WSREP_NNULL(this) && wsrep_thd_is_local(this) &&
7425
      !slave_thread && wsrep_auto_increment_control)
7426
  {
7427
    variables.auto_increment_offset=
7428
      global_system_variables.auto_increment_offset;
7429
    variables.auto_increment_increment=
7430
      global_system_variables.auto_increment_increment;
7431 7432
  }
#endif /* WITH_WSREP */
7433

7434 7435
  used= 0;
  is_fatal_error= 0;
7436
  variables.option_bits&= ~OPTION_BINLOG_THIS_STMT;
7437

7438 7439 7440 7441
  /*
    Clear the status flag that are expected to be cleared at the
    beginning of each SQL statement.
  */
7442
  server_status&= ~SERVER_STATUS_CLEAR_SET;
7443 7444
  /*
    If in autocommit mode and not in a transaction, reset
7445
    OPTION_STATUS_NO_TRANS_UPDATE | OPTION_BINLOG_THIS_TRX to not get warnings
7446 7447
    in ha_rollback_trans() about some tables couldn't be rolled back.
  */
7448
  if (!in_multi_stmt_transaction_mode())
unknown's avatar
unknown committed
7449
  {
7450
    variables.option_bits&= ~OPTION_BINLOG_THIS_TRX;
7451
    transaction->all.reset();
unknown's avatar
unknown committed
7452
  }
7453
  DBUG_ASSERT(security_ctx== &main_security_ctx);
7454 7455

  if (opt_bin_log)
7456
    reset_dynamic(&user_var_events);
7457
  DBUG_ASSERT(user_var_events_alloc == &main_mem_root);
7458
  enable_slow_log= true;
7459
  get_stmt_da()->reset_for_next_command();
7460
  sent_row_count_for_statement= examined_row_count_for_statement= 0;
7461
  accessed_rows_and_keys= 0;
7462

7463
  reset_slow_query_state(0);
7464

7465 7466
  reset_current_stmt_binlog_format_row();
  binlog_unsafe_warning_flags= 0;
unknown's avatar
unknown committed
7467

7468
  save_prep_leaf_list= false;
7469

Monty's avatar
Monty committed
7470
#if defined(WITH_WSREP) && !defined(DBUG_OFF)
7471
  if (mysql_bin_log.is_open())
Monty's avatar
Monty committed
7472
    DBUG_PRINT("info",
7473 7474
               ("is_current_stmt_binlog_format_row(): %d",
                 is_current_stmt_binlog_format_row()));
Monty's avatar
Monty committed
7475
#endif
unknown's avatar
unknown committed
7476 7477 7478
  DBUG_VOID_RETURN;
}

7479

7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491
/**
  Used to allocate a new SELECT_LEX object on the current thd mem_root and
  link it into the relevant lists.

  This function is always followed by mysql_init_select.

  @see mysql_init_select

  @retval TRUE An error occurred
  @retval FALSE The new SELECT_LEX was successfully allocated.
*/

unknown's avatar
unknown committed
7492
bool
7493
mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *select_lex)
7494
{
7495
  THD *thd= lex->thd;
7496
  bool new_select= select_lex == NULL;
7497
  int old_nest_level= lex->current_select->nest_level;
unknown's avatar
unknown committed
7498 7499
  DBUG_ENTER("mysql_new_select");

7500 7501 7502 7503
  if (new_select)
  {
    if (!(select_lex= new (thd->mem_root) SELECT_LEX()))
      DBUG_RETURN(1);
7504
    select_lex->select_number= ++thd->lex->stmt_lex->current_select_number;
7505 7506 7507 7508
    select_lex->parent_lex= lex; /* Used in init_query. */
    select_lex->init_query();
    select_lex->init_select();
  }
unknown's avatar
unknown committed
7509
  select_lex->nest_level_base= &thd->lex->unit;
unknown's avatar
unknown committed
7510 7511
  if (move_down)
  {
7512 7513 7514
    lex->nest_level++;
    if (select_lex->set_nest_level(old_nest_level + 1))
      DBUG_RETURN(1);
unknown's avatar
unknown committed
7515
    SELECT_LEX_UNIT *unit;
unknown's avatar
unknown committed
7516
    /* first select_lex of subselect or derived table */
7517
    if (!(unit= lex->alloc_unit()))
unknown's avatar
unknown committed
7518
      DBUG_RETURN(1);
unknown's avatar
unknown committed
7519

unknown's avatar
unknown committed
7520
    unit->include_down(lex->current_select);
7521
    unit->return_to= lex->current_select;
unknown's avatar
unknown committed
7522
    select_lex->include_down(unit);
7523 7524 7525 7526
    /*
      By default we assume that it is usual subselect and we have outer name
      resolution context, if no we will assign it to 0 later
    */
7527
    select_lex->context.outer_context= &select_lex->outer_select()->context;
unknown's avatar
unknown committed
7528 7529
  }
  else
unknown's avatar
unknown committed
7530
  {
7531 7532 7533 7534 7535 7536
    bool const outer_most= (lex->current_select->master_unit() == &lex->unit);
    if (outer_most && lex->result)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "UNION", "INTO");
      DBUG_RETURN(TRUE);
    }
7537

7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553
    /*
      This type of query is not possible in the grammar:
        SELECT 1 FROM t1 PROCEDURE ANALYSE() UNION ... ;

      But this type of query is still possible:
        (SELECT 1 FROM t1 PROCEDURE ANALYSE()) UNION ... ;
      and it's not easy to disallow this grammatically,
      because there can be any parenthesis nest level:
        (((SELECT 1 FROM t1 PROCEDURE ANALYSE()))) UNION ... ;
    */
    if (lex->proc_list.elements!=0)
    {
      my_error(ER_WRONG_USAGE, MYF(0), "UNION",
               "SELECT ... PROCEDURE ANALYSE()");
      DBUG_RETURN(TRUE);
    }
7554

7555
    SELECT_LEX_NODE *save_slave= select_lex->slave;
7556
    select_lex->include_neighbour(lex->current_select);
7557 7558 7559 7560
    select_lex->slave= save_slave;
    SELECT_LEX_UNIT *unit= select_lex->master_unit();
    if (select_lex->set_nest_level(old_nest_level))
      DBUG_RETURN(1);
7561 7562 7563 7564
    if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd))
      DBUG_RETURN(1);
    select_lex->context.outer_context= 
                unit->first_select()->context.outer_context;
unknown's avatar
unknown committed
7565
  }
unknown's avatar
unknown committed
7566

7567 7568
  if (new_select)
    select_lex->include_global((st_select_lex_node**)&lex->all_selects_list);
7569
  lex->current_select= select_lex;
7570 7571 7572 7573 7574
  /*
    in subquery is SELECT query and we allow resolution of names in SELECT
    list
  */
  select_lex->context.resolve_in_select_list= TRUE;
unknown's avatar
unknown committed
7575
  DBUG_RETURN(0);
7576
}
unknown's avatar
unknown committed
7577

unknown's avatar
unknown committed
7578
/**
7579 7580
  Create a select to return the same output as 'SELECT @@var_name'.

unknown's avatar
unknown committed
7581
  Used for SHOW COUNT(*) [ WARNINGS | ERROR].
7582

unknown's avatar
unknown committed
7583
  This will crash with a core dump if the variable doesn't exists.
7584

unknown's avatar
unknown committed
7585
  @param var_name		Variable name
7586 7587
*/

Michael Widenius's avatar
Michael Widenius committed
7588
void create_select_for_variable(THD *thd, LEX_CSTRING *var_name)
7589 7590
{
  LEX *lex;
7591 7592
  Item *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end;
7593
  DBUG_ENTER("create_select_for_variable");
7594

unknown's avatar
unknown committed
7595
  lex= thd->lex;
Sergei Golubchik's avatar
Sergei Golubchik committed
7596
  lex->init_select();
7597
  lex->sql_command= SQLCOM_SELECT;
7598 7599 7600 7601
  /*
    We set the name of Item to @@session.var_name because that then is used
    as the column name in the output.
  */
Michael Widenius's avatar
Michael Widenius committed
7602
  if ((var= get_system_var(thd, OPT_SESSION, var_name, &null_clex_str)))
unknown's avatar
unknown committed
7603
  {
Michael Widenius's avatar
Michael Widenius committed
7604
    end= strxmov(buff, "@@session.", var_name->str, NullS);
7605
    var->set_name(thd, buff, (uint)(end-buff), system_charset_info);
unknown's avatar
unknown committed
7606 7607
    add_item_to_list(thd, var);
  }
7608 7609 7610
  DBUG_VOID_RETURN;
}

7611

7612
void mysql_init_delete(LEX *lex)
unknown's avatar
unknown committed
7613
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7614
  lex->init_select();
7615 7616
  lex->first_select_lex()->limit_params.clear();
  lex->unit.lim.clear();
7617 7618 7619 7620 7621
}

void mysql_init_multi_delete(LEX *lex)
{
  lex->sql_command=  SQLCOM_DELETE_MULTI;
7622 7623
  lex->first_select_lex()->table_list.
    save_and_clear(&lex->auxiliary_table_list);
unknown's avatar
VIEW  
unknown committed
7624 7625
  lex->query_tables= 0;
  lex->query_tables_last= &lex->query_tables;
unknown's avatar
unknown committed
7626
}
unknown's avatar
unknown committed
7627

Brave Galera Crew's avatar
Brave Galera Crew committed
7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680
#ifdef WITH_WSREP
static void wsrep_prepare_for_autocommit_retry(THD* thd,
                                               char* rawbuf,
                                               uint length,
                                               Parser_state* parser_state)
{
  thd->clear_error();
  close_thread_tables(thd);
  thd->wsrep_retry_counter++;            // grow
  wsrep_copy_query(thd);
  thd->set_time();
  parser_state->reset(rawbuf, length);

  /* PSI end */
  MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
  thd->m_statement_psi= NULL;
  thd->m_digest= NULL;

  /* DTRACE end */
  if (MYSQL_QUERY_DONE_ENABLED())
  {
    MYSQL_QUERY_DONE(thd->is_error());
  }

  /* SHOW PROFILE end */
#if defined(ENABLED_PROFILING)
  thd->profiling.finish_current_query();
#endif

  /* SHOW PROFILE begin */
#if defined(ENABLED_PROFILING)
  thd->profiling.start_new_query("continuing");
  thd->profiling.set_query_source(rawbuf, length);
#endif

  /* DTRACE begin */
  MYSQL_QUERY_START(rawbuf, thd->thread_id,
                    thd->get_db(),
                    &thd->security_ctx->priv_user[0],
                    (char *) thd->security_ctx->host_or_ip);

  /* Performance Schema Interface instrumentation, begin */
  thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                                               com_statement_info[thd->get_command()].m_key);
  MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(),
                           thd->query_length());
 
  DBUG_ASSERT(thd->wsrep_trx().active() == false);
  thd->wsrep_cs().reset_error();
  thd->set_query_id(next_query_id());
}

static bool wsrep_mysql_parse(THD *thd, char *rawbuf, uint length,
7681
                              Parser_state *parser_state)
7682 7683 7684
{
  bool is_autocommit=
    !thd->in_multi_stmt_transaction_mode()                  &&
7685
    !thd->wsrep_applier;
Brave Galera Crew's avatar
Brave Galera Crew committed
7686
  bool retry_autocommit;
7687 7688
  do
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
7689
    retry_autocommit= false;
7690
    mysql_parse(thd, rawbuf, length, parser_state);
7691

Brave Galera Crew's avatar
Brave Galera Crew committed
7692 7693 7694 7695 7696
    /*
      Convert all ER_QUERY_INTERRUPTED errors to ER_LOCK_DEADLOCK
      if the transaction was BF aborted. This can happen when the
      transaction is being BF aborted via thd->awake() while it is
      still executing.
7697

Brave Galera Crew's avatar
Brave Galera Crew committed
7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708
      Note that this must be done before wsrep_after_statement() call
      since it clears the transaction for autocommit queries.
     */
    if (((thd->get_stmt_da()->is_error() &&
          thd->get_stmt_da()->sql_errno() == ER_QUERY_INTERRUPTED) ||
         !thd->get_stmt_da()->is_set()) &&
        thd->wsrep_trx().bf_aborted())
    {
      WSREP_DEBUG("overriding error: %d with DEADLOCK",
                  (thd->get_stmt_da()->is_error()) ?
                   thd->get_stmt_da()->sql_errno() : 0);
7709

7710
      thd->reset_kill_query();
Brave Galera Crew's avatar
Brave Galera Crew committed
7711 7712
      wsrep_override_error(thd, ER_LOCK_DEADLOCK);
    }
7713

7714 7715 7716 7717 7718 7719 7720 7721 7722
#ifdef ENABLED_DEBUG_SYNC
    /* we need the test otherwise we get stuck in the "SET DEBUG_SYNC" itself */
    if (thd->lex->sql_command != SQLCOM_SET_OPTION)
      DEBUG_SYNC(thd, "wsrep_after_statement_enter");
#endif

    if (wsrep_after_statement(thd) &&
        is_autocommit              &&
        thd_is_connection_alive(thd))
Brave Galera Crew's avatar
Brave Galera Crew committed
7723 7724
    {
      thd->reset_for_next_command();
7725
      thd->reset_kill_query();
Brave Galera Crew's avatar
Brave Galera Crew committed
7726 7727 7728 7729
      if (is_autocommit                           &&
          thd->lex->sql_command != SQLCOM_SELECT  &&
          thd->wsrep_retry_counter < thd->variables.wsrep_retry_autocommit)
      {
7730
#ifdef ENABLED_DEBUG_SYNC
7731
        DBUG_EXECUTE_IF("sync.wsrep_retry_autocommit",
Brave Galera Crew's avatar
Brave Galera Crew committed
7732 7733 7734 7735 7736 7737 7738
                    {
                      const char act[]=
                        "now "
                        "SIGNAL wsrep_retry_autocommit_reached "
                        "WAIT_FOR wsrep_retry_autocommit_continue";
                      DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act)));
                    });
7739
#endif
Brave Galera Crew's avatar
Brave Galera Crew committed
7740
        WSREP_DEBUG("wsrep retrying AC query: %lu  %s",
7741 7742
                    thd->wsrep_retry_counter,
                    wsrep_thd_query(thd));
Brave Galera Crew's avatar
Brave Galera Crew committed
7743 7744 7745 7746
        wsrep_prepare_for_autocommit_retry(thd, rawbuf, length, parser_state);
        if (thd->lex->explain)
          delete_explain_query(thd->lex);
        retry_autocommit= true;
7747 7748 7749
      }
      else
      {
Brave Galera Crew's avatar
Brave Galera Crew committed
7750 7751 7752 7753 7754 7755
        WSREP_DEBUG("%s, thd: %llu is_AC: %d, retry: %lu - %lu SQL: %s",
                    wsrep_thd_transaction_state_str(thd),
                    thd->thread_id,
                    is_autocommit,
                    thd->wsrep_retry_counter,
                    thd->variables.wsrep_retry_autocommit,
7756
                    wsrep_thd_query(thd));
Brave Galera Crew's avatar
Brave Galera Crew committed
7757
        my_error(ER_LOCK_DEADLOCK, MYF(0));
7758
        thd->reset_kill_query();
Brave Galera Crew's avatar
Brave Galera Crew committed
7759
        thd->wsrep_retry_counter= 0;             //  reset
7760 7761
      }
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
7762
    else
7763
    {
Brave Galera Crew's avatar
Brave Galera Crew committed
7764
      set_if_smaller(thd->wsrep_retry_counter, 0); // reset; eventually ok
7765
    }
Brave Galera Crew's avatar
Brave Galera Crew committed
7766
  }  while (retry_autocommit);
7767 7768 7769

  if (thd->wsrep_retry_query)
  {
Brave Galera Crew's avatar
Brave Galera Crew committed
7770 7771 7772 7773
    WSREP_DEBUG("releasing retry_query: "
                "conf %s sent %d kill %d  errno %d SQL %s",
                wsrep_thd_transaction_state_str(thd),
                thd->get_stmt_da()->is_sent(),
7774
                thd->killed,
Brave Galera Crew's avatar
Brave Galera Crew committed
7775 7776
                thd->get_stmt_da()->is_error() ?
                thd->get_stmt_da()->sql_errno() : 0,
7777 7778 7779 7780 7781
                thd->wsrep_retry_query);
    my_free(thd->wsrep_retry_query);
    thd->wsrep_retry_query      = NULL;
    thd->wsrep_retry_query_len  = 0;
    thd->wsrep_retry_command    = COM_CONNECT;
7782
    thd->proc_info= 0;
7783
  }
Brave Galera Crew's avatar
Brave Galera Crew committed
7784
  return false;
7785
}
Brave Galera Crew's avatar
Brave Galera Crew committed
7786
#endif /* WITH_WSREP */
7787

7788

7789
/*
7790
  When you modify mysql_parse(), you may need to modify
7791 7792
  mysql_test_parse_for_slave() in this same file.
*/
unknown's avatar
unknown committed
7793

7794 7795
/**
  Parse a query.
unknown's avatar
unknown committed
7796 7797

  @param       thd     Current thread
7798
  @param       rawbuf  Begining of the query text
unknown's avatar
unknown committed
7799
  @param       length  Length of the query text
7800 7801
*/

7802
void mysql_parse(THD *thd, char *rawbuf, uint length,
7803
                 Parser_state *parser_state)
unknown's avatar
unknown committed
7804 7805
{
  DBUG_ENTER("mysql_parse");
7806 7807
  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on_MYSQLparse(););
  DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on_ORAparse(););
7808

7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819
  /*
    Warning.
    The purpose of query_cache_send_result_to_client() is to lookup the
    query in the query cache first, to avoid parsing and executing it.
    So, the natural implementation would be to:
    - first, call query_cache_send_result_to_client,
    - second, if caching failed, initialise the lexical and syntactic parser.
    The problem is that the query cache depends on a clean initialization
    of (among others) lex->safe_to_cache_query and thd->server_status,
    which are reset respectively in
    - lex_start()
7820
    - THD::reset_for_next_command()
7821 7822 7823 7824 7825
    So, initializing the lexical analyser *before* using the query cache
    is required for the cache to work properly.
    FIXME: cleanup the dependencies in the code to simplify this.
  */
  lex_start(thd);
7826
  thd->reset_for_next_command();
7827

7828
  if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0)
unknown's avatar
unknown committed
7829
  {
unknown's avatar
unknown committed
7830
    LEX *lex= thd->lex;
7831

Sergei Golubchik's avatar
Sergei Golubchik committed
7832
    bool err= parse_sql(thd, parser_state, NULL, true);
7833

7834
    if (likely(!err))
unknown's avatar
unknown committed
7835
    {
7836 7837 7838 7839
      thd->m_statement_psi=
        MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                               sql_statement_info[thd->lex->sql_command].
                               m_key);
unknown's avatar
unknown committed
7840
#ifndef NO_EMBEDDED_ACCESS_CHECKS
7841
      if (mqh_used && thd->user_connect &&
7842
	  check_mqh(thd, lex->sql_command))
7843 7844 7845 7846
      {
	thd->net.error = 0;
      }
      else
unknown's avatar
unknown committed
7847
#endif
7848
      {
7849
	if (likely(! thd->is_error()))
unknown's avatar
unknown committed
7850
	{
7851
          const char *found_semicolon= parser_state->m_lip.found_semicolon;
7852 7853 7854 7855 7856 7857 7858 7859 7860
          /*
            Binlog logs a string starting from thd->query and having length
            thd->query_length; so we set thd->query_length correctly (to not
            log several statements in one event, when we executed only first).
            We set it to not see the ';' (otherwise it would get into binlog
            and Query_log_event::print() would give ';;' output).
            This also helps display only the current query in SHOW
            PROCESSLIST.
          */
7861
          if (found_semicolon && (ulong) (found_semicolon - thd->query()))
7862 7863 7864
            thd->set_query(thd->query(),
                           (uint32) (found_semicolon - thd->query() - 1),
                           thd->charset());
7865
          /* Actually execute the query */
7866
          if (found_semicolon)
7867 7868 7869 7870
          {
            lex->safe_to_cache_query= 0;
            thd->server_status|= SERVER_MORE_RESULTS_EXISTS;
          }
7871
          lex->set_trg_event_type_for_tables();
7872
          MYSQL_QUERY_EXEC_START(thd->query(),
7873
                                 thd->thread_id,
7874
                                 thd->get_db(),
7875
                                 &thd->security_ctx->priv_user[0],
7876 7877 7878
                                 (char *) thd->security_ctx->host_or_ip,
                                 0);

7879
          int error __attribute__((unused));
7880 7881
          error= mysql_execute_command(thd);
          MYSQL_QUERY_EXEC_DONE(error);
unknown's avatar
unknown committed
7882
	}
7883
      }
unknown's avatar
unknown committed
7884 7885
    }
    else
7886
    {
7887 7888 7889 7890
      /* Instrument this broken statement as "statement/sql/error" */
      thd->m_statement_psi=
        MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                               sql_statement_info[SQLCOM_END].m_key);
7891
      DBUG_ASSERT(thd->is_error());
7892
      DBUG_PRINT("info",("Command aborted. Fatal_error: %d",
7893
			 thd->is_fatal_error));
7894

7895
      query_cache_abort(thd, &thd->query_cache_tls);
7896
    }
Sergei Golubchik's avatar
Sergei Golubchik committed
7897
    THD_STAGE_INFO(thd, stage_freeing_items);
7898 7899
    sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size);
    sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size);
7900 7901
    sp_cache_enforce_limit(thd->sp_package_spec_cache, stored_program_cache_size);
    sp_cache_enforce_limit(thd->sp_package_body_cache, stored_program_cache_size);
7902
    thd->end_statement();
7903
    thd->Item_change_list::rollback_item_tree_changes();
7904
    thd->cleanup_after_query();
unknown's avatar
unknown committed
7905
  }
7906 7907
  else
  {
7908 7909
    /* Update statistics for getting the query from the cache */
    thd->lex->sql_command= SQLCOM_SELECT;
7910 7911 7912
    thd->m_statement_psi=
      MYSQL_REFINE_STATEMENT(thd->m_statement_psi,
                             sql_statement_info[SQLCOM_SELECT].m_key);
7913
    status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]);
7914
    thd->update_stats();
7915 7916 7917 7918 7919 7920
#ifdef WITH_WSREP
    if (WSREP_CLIENT(thd))
    {
      thd->wsrep_sync_wait_gtid= WSREP_GTID_UNDEFINED;
    }
#endif /* WITH_WSREP */
7921
  }
unknown's avatar
unknown committed
7922 7923 7924 7925
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
7926
#ifdef HAVE_REPLICATION
7927 7928 7929 7930
/*
  Usable by the replication SQL thread only: just parse a query to know if it
  can be ignored because of replicate-*-table rules.

unknown's avatar
unknown committed
7931
  @retval
7932
    0	cannot be ignored
unknown's avatar
unknown committed
7933
  @retval
7934 7935 7936
    1	can be ignored
*/

7937
bool mysql_test_parse_for_slave(THD *thd, char *rawbuf, uint length)
7938
{
unknown's avatar
unknown committed
7939
  LEX *lex= thd->lex;
7940
  bool error= 0;
unknown's avatar
unknown committed
7941
  DBUG_ENTER("mysql_test_parse_for_slave");
7942

7943
  Parser_state parser_state;
7944
  if (likely(!(error= parser_state.init(thd, rawbuf, length))))
7945 7946
  {
    lex_start(thd);
7947
    thd->reset_for_next_command();
7948

Sergei Golubchik's avatar
Sergei Golubchik committed
7949
    if (!parse_sql(thd, & parser_state, NULL, true) &&
7950
        all_tables_not_ok(thd, lex->first_select_lex()->table_list.first))
7951 7952 7953
      error= 1;                  /* Ignore question */
    thd->end_statement();
  }
7954
  thd->cleanup_after_query();
unknown's avatar
unknown committed
7955
  DBUG_RETURN(error);
7956
}
unknown's avatar
unknown committed
7957
#endif
unknown's avatar
unknown committed
7958

7959

unknown's avatar
unknown committed
7960
bool
unknown's avatar
unknown committed
7961
add_proc_to_list(THD* thd, Item *item)
unknown's avatar
unknown committed
7962 7963 7964 7965
{
  ORDER *order;
  Item	**item_ptr;

7966
  if (unlikely(!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*)))))
unknown's avatar
unknown committed
7967 7968 7969 7970
    return 1;
  item_ptr = (Item**) (order+1);
  *item_ptr= item;
  order->item=item_ptr;
7971
  thd->lex->proc_list.link_in_list(order, &order->next);
unknown's avatar
unknown committed
7972 7973 7974 7975
  return 0;
}


unknown's avatar
unknown committed
7976 7977 7978
/**
  save order by and tables in own lists.
*/
unknown's avatar
unknown committed
7979

7980
bool add_to_list(THD *thd, SQL_I_List<ORDER> &list, Item *item,bool asc)
unknown's avatar
unknown committed
7981 7982 7983
{
  ORDER *order;
  DBUG_ENTER("add_to_list");
7984
  if (unlikely(!(order = (ORDER *) thd->alloc(sizeof(ORDER)))))
unknown's avatar
unknown committed
7985
    DBUG_RETURN(1);
unknown's avatar
unknown committed
7986 7987
  order->item_ptr= item;
  order->item= &order->item_ptr;
7988
  order->direction= (asc ? ORDER::ORDER_ASC : ORDER::ORDER_DESC);
unknown's avatar
unknown committed
7989
  order->used=0;
7990
  order->counter_used= 0;
7991
  order->fast_field_copier_setup= 0; 
7992
  list.link_in_list(order, &order->next);
unknown's avatar
unknown committed
7993 7994 7995 7996
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
7997 7998 7999 8000 8001 8002 8003 8004 8005 8006
/**
  Add a table to list of used tables.

  @param table		Table to add
  @param alias		alias for table (or null if no alias)
  @param table_options	A set of the following bits:
                         - TL_OPTION_UPDATING : Table will be updated
                         - TL_OPTION_FORCE_INDEX : Force usage of index
                         - TL_OPTION_ALIAS : an alias in multi table DELETE
  @param lock_type	How table should be locked
8007
  @param mdl_type       Type of metadata lock to acquire on the table.
unknown's avatar
unknown committed
8008 8009 8010 8011
  @param use_index	List of indexed used in USE INDEX
  @param ignore_index	List of indexed used in IGNORE INDEX

  @retval
unknown's avatar
unknown committed
8012
      0		Error
unknown's avatar
unknown committed
8013 8014
  @retval
    \#	Pointer to TABLE_LIST element added to the total table list
8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033


  This method can be called in contexts when the "table" argument has a longer
  life cycle than TABLE_LIST and belongs to a different MEM_ROOT than
  the current THD::mem_root.

  For example, it's called from Table_ident::resolve_table_rowtype_ref()
  during sp_head::rcontext_create() during a CALL statement.
  "table" in this case belongs to sp_pcontext, which must stay valid
  (inside its SP cache sp_head entry) after the end of the current statement.

  Let's allocate normalized copies of table.db and table.table on the current
  THD::mem_root and store them in the TABLE_LIST.

  We should not touch "table" and replace table.db and table.table to their
  normalized copies allocated on the current THD::mem_root, because it'll be
  freed at the end of the current statement, while table.db and table.table
  should stay valid. Let's keep them in the original state.

unknown's avatar
unknown committed
8034 8035
*/

unknown's avatar
unknown committed
8036 8037
TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
					     Table_ident *table,
8038
					     const LEX_CSTRING *alias,
unknown's avatar
unknown committed
8039 8040
					     ulong table_options,
					     thr_lock_type lock_type,
8041
					     enum_mdl_type mdl_type,
unknown's avatar
unknown committed
8042
					     List<Index_hint> *index_hints_arg,
8043
                                             List<String> *partition_names,
Alexey Botchkov's avatar
Alexey Botchkov committed
8044
                                             LEX_STRING *option)
unknown's avatar
unknown committed
8045 8046
{
  DBUG_ENTER("add_table_to_list");
8047 8048 8049 8050
  DBUG_PRINT("enter", ("Table '%s' (%p)  Select %p (%u)",
                        (alias ? alias->str : table->table.str),
                        table,
                        this, select_number));
8051
  DBUG_ASSERT(!is_service_select  || (table_options & TL_OPTION_SEQUENCE));
unknown's avatar
unknown committed
8052

8053
  if (unlikely(!table))
unknown's avatar
unknown committed
8054
    DBUG_RETURN(0);				// End of memory
8055
  if (!(table_options & TL_OPTION_ALIAS) &&
8056
      unlikely(Lex_ident_table::check_name(table->table, FALSE)))
unknown's avatar
unknown committed
8057
  {
8058
    my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str);
unknown's avatar
unknown committed
8059 8060
    DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
8061

8062
  if (unlikely(table->is_derived_table() == FALSE && table->db.str &&
8063
               !(table_options & TL_OPTION_TABLE_FUNCTION) &&
8064
               Lex_ident_db::check_name_with_error(table->db)))
unknown's avatar
unknown committed
8065
    DBUG_RETURN(0);
unknown's avatar
unknown committed
8066

8067
  Lex_ident_db db{0, 0};
8068 8069 8070 8071 8072
  bool fqtn= false;
  LEX *lex= thd->lex;
  if (table->db.str)
  {
    fqtn= TRUE;
8073
    db= Lex_ident_db(table->db);
8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092
  }
  else if (!lex->with_cte_resolution && lex->copy_db_to(&db))
    DBUG_RETURN(0);
  else
    fqtn= FALSE;
  bool info_schema= is_infoschema_db(&db);
  if (!table->sel && info_schema &&
      (table_options & TL_OPTION_UPDATING) &&
      /* Special cases which are processed by commands itself */
      lex->sql_command != SQLCOM_CHECK &&
      lex->sql_command != SQLCOM_CHECKSUM)
  {
    my_error(ER_DBACCESS_DENIED_ERROR, MYF(0),
             thd->security_ctx->priv_user,
             thd->security_ctx->priv_host,
             INFORMATION_SCHEMA_NAME.str);
    DBUG_RETURN(0);
  }

8093 8094
  Lex_ident_table alias_str= alias ? Lex_ident_table(*alias) :
                                     Lex_ident_table(table->table);
8095
  DBUG_ASSERT(alias_str.str);
8096
  if (!alias)                            /* Alias is case sensitive */
8097
  {
8098
    if (unlikely(table->sel))
8099
    {
unknown's avatar
unknown committed
8100
      my_message(ER_DERIVED_MUST_HAVE_ALIAS,
8101
                 ER_THD(thd, ER_DERIVED_MUST_HAVE_ALIAS), MYF(0));
8102 8103
      DBUG_RETURN(0);
    }
8104
    /* alias_str points to table->table;  Let's make a copy */
8105
    if (unlikely(!(alias_str.str= (char*) thd->memdup(alias_str.str, alias_str.length+1))))
unknown's avatar
unknown committed
8106
      DBUG_RETURN(0);
8107
  }
8108

8109
  bool has_alias_ptr= alias != nullptr;
8110
  void *memregion= thd->alloc(sizeof(TABLE_LIST));
8111 8112 8113 8114 8115
  TABLE_LIST *ptr= new (memregion) TABLE_LIST(thd, db, fqtn, alias_str,
                                              has_alias_ptr, table, lock_type,
                                              mdl_type, table_options,
                                              info_schema, this,
                                              index_hints_arg, option);
8116 8117
  if (!ptr->table_name.str)
    DBUG_RETURN(0); // EOM
Marko Mäkelä's avatar
Marko Mäkelä committed
8118

8119 8120
  /* check that used name is unique. Sequences are ignored */
  if (lock_type != TL_IGNORE && !ptr->sequence)
unknown's avatar
unknown committed
8121
  {
8122
    TABLE_LIST *first_table= table_list.first;
unknown's avatar
unknown committed
8123 8124 8125
    if (lex->sql_command == SQLCOM_CREATE_VIEW)
      first_table= first_table ? first_table->next_local : NULL;
    for (TABLE_LIST *tables= first_table ;
unknown's avatar
unknown committed
8126
	 tables ;
unknown's avatar
VIEW  
unknown committed
8127
	 tables=tables->next_local)
unknown's avatar
unknown committed
8128
    {
8129
      if (unlikely(alias_str.streq(tables->alias) &&
Alexey Botchkov's avatar
Alexey Botchkov committed
8130
                   (tables->db.str == any_db.str || ptr->db.str == any_db.str ||
8131 8132
                    !cmp(&ptr->db, &tables->db)) &&
                   !tables->sequence))
unknown's avatar
unknown committed
8133
      {
Anel Husakovic's avatar
Anel Husakovic committed
8134 8135
        my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str.str); /* purecov: tested */
        DBUG_RETURN(0);				/* purecov: tested */
unknown's avatar
unknown committed
8136
      }
unknown's avatar
unknown committed
8137 8138
    }
  }
unknown's avatar
unknown committed
8139
  /* Store the table reference preceding the current one. */
8140
  TABLE_LIST *UNINIT_VAR(previous_table_ref); /* The table preceding the current one. */
8141
  if (table_list.elements > 0 && likely(!ptr->sequence))
unknown's avatar
unknown committed
8142
  {
8143 8144 8145
    /*
      table_list.next points to the last inserted TABLE_LIST->next_local'
      element
8146
      We don't use the offsetof() macro here to avoid warnings from gcc
8147
    */
8148 8149 8150
    previous_table_ref= (TABLE_LIST*) ((char*) table_list.next -
                                       ((char*) &(ptr->next_local) -
                                        (char*) ptr));
8151 8152 8153 8154 8155 8156 8157 8158
    /*
      Set next_name_resolution_table of the previous table reference to point
      to the current table reference. In effect the list
      TABLE_LIST::next_name_resolution_table coincides with
      TABLE_LIST::next_local. Later this may be changed in
      store_top_level_join_columns() for NATURAL/USING joins.
    */
    previous_table_ref->next_name_resolution_table= ptr;
unknown's avatar
unknown committed
8159
  }
8160

unknown's avatar
unknown committed
8161 8162 8163 8164 8165
  /*
    Link the current table reference in a local list (list for current select).
    Notice that as a side effect here we set the next_local field of the
    previous table reference to 'ptr'. Here we also add one element to the
    list 'table_list'.
8166 8167
    We don't store sequences into the local list to hide them from INSERT
    and SELECT.
unknown's avatar
unknown committed
8168
  */
8169
  if (likely(!ptr->sequence))
8170
    table_list.link_in_list(ptr, &ptr->next_local);
unknown's avatar
unknown committed
8171
  ptr->next_name_resolution_table= NULL;
8172 8173 8174
#ifdef WITH_PARTITION_STORAGE_ENGINE
  ptr->partition_names= partition_names;
#endif /* WITH_PARTITION_STORAGE_ENGINE */
8175
  /* Link table in global list (all used tables) */
8176
  lex->add_to_query_tables(ptr);
8177 8178

  // Pure table aliases do not need to be locked:
8179
  if (ptr->db.str && !(table_options & TL_OPTION_ALIAS))
8180
  {
8181 8182
    MDL_REQUEST_INIT(&ptr->mdl_request, MDL_key::TABLE, ptr->db.str,
                     ptr->table_name.str, mdl_type, MDL_TRANSACTION);
8183
  }
unknown's avatar
unknown committed
8184 8185 8186
  DBUG_RETURN(ptr);
}

unknown's avatar
unknown committed
8187

unknown's avatar
unknown committed
8188 8189
/**
  Initialize a new table list for a nested join.
8190

8191 8192 8193 8194 8195 8196 8197 8198
    The function initializes a structure of the TABLE_LIST type
    for a nested join. It sets up its nested join list as empty.
    The created structure is added to the front of the current
    join list in the st_select_lex object. Then the function
    changes the current nest level for joins to refer to the newly
    created empty list after having saved the info on the old level
    in the initialized structure.

unknown's avatar
unknown committed
8199 8200 8201 8202 8203 8204
  @param thd         current thread

  @retval
    0   if success
  @retval
    1   otherwise
8205 8206 8207 8208 8209 8210 8211
*/

bool st_select_lex::init_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
  DBUG_ENTER("init_nested_join");
8212

8213 8214
  if (unlikely(!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                                sizeof(NESTED_JOIN)))))
8215
    DBUG_RETURN(1);
8216
  nested_join= ptr->nested_join=
8217
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
8218

8219 8220
  ptr->embedding= embedding;
  ptr->join_list= join_list;
8221 8222
  ptr->alias.str="(nested_join)";
  ptr->alias.length= sizeof("(nested_join)")-1;
8223 8224 8225 8226 8227 8228 8229
  embedding= ptr;
  join_list= &nested_join->join_list;
  join_list->empty();
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
8230 8231
/**
  End a nested join table list.
8232 8233 8234

    The function returns to the previous join nest level.
    If the current level contains only one member, the function
8235
    moves it one level up, eliminating the nest.
8236

unknown's avatar
unknown committed
8237 8238 8239 8240 8241
  @param thd         current thread

  @return
    - Pointer to TABLE_LIST element added to the total table list, if success
    - 0, otherwise
8242 8243 8244 8245 8246
*/

TABLE_LIST *st_select_lex::end_nested_join(THD *thd)
{
  TABLE_LIST *ptr;
8247
  NESTED_JOIN *nested_join;
8248
  DBUG_ENTER("end_nested_join");
8249

unknown's avatar
unknown committed
8250
  DBUG_ASSERT(embedding);
8251 8252 8253
  ptr= embedding;
  join_list= ptr->join_list;
  embedding= ptr->embedding;
8254
  nested_join= ptr->nested_join;
8255 8256 8257 8258 8259 8260
  if (nested_join->join_list.elements == 1)
  {
    TABLE_LIST *embedded= nested_join->join_list.head();
    join_list->pop();
    embedded->join_list= join_list;
    embedded->embedding= embedding;
8261
    join_list->push_front(embedded, thd->mem_root);
8262
    ptr= embedded;
Igor Babaev's avatar
Igor Babaev committed
8263
    embedded->lifted= 1;
8264
  }
8265
  else if (nested_join->join_list.elements == 0)
unknown's avatar
unknown committed
8266 8267
  {
    join_list->pop();
8268
    ptr= 0;                                     // return value
unknown's avatar
unknown committed
8269
  }
8270 8271 8272 8273
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
8274 8275
/**
  Nest last join operation.
8276 8277 8278

    The function nest last join operation as if it was enclosed in braces.

unknown's avatar
unknown committed
8279
  @param thd         current thread
8280

unknown's avatar
unknown committed
8281
  @retval
8282
    0  Error
unknown's avatar
unknown committed
8283 8284
  @retval
    \#  Pointer to TABLE_LIST element created for the new nested join
8285 8286 8287 8288 8289 8290
*/

TABLE_LIST *st_select_lex::nest_last_join(THD *thd)
{
  TABLE_LIST *ptr;
  NESTED_JOIN *nested_join;
8291
  List<TABLE_LIST> *embedded_list;
8292
  DBUG_ENTER("nest_last_join");
8293

8294
  TABLE_LIST *head= join_list->head();
8295
  if (head->nested_join && (head->nested_join->nest_type & REBALANCED_NEST))
8296
  {
8297
    head= join_list->pop();
8298 8299
    DBUG_RETURN(head);
  }
8300

8301 8302
  if (unlikely(!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                                sizeof(NESTED_JOIN)))))
8303
    DBUG_RETURN(0);
8304
  nested_join= ptr->nested_join=
8305
    ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST))));
8306

8307 8308
  ptr->embedding= embedding;
  ptr->join_list= join_list;
8309 8310
  ptr->alias.str= "(nest_last_join)";
  ptr->alias.length= sizeof("(nest_last_join)")-1;
8311
  embedded_list= &nested_join->join_list;
8312
  embedded_list->empty();
8313
  nested_join->nest_type= JOIN_OP_NEST;
8314 8315

  for (uint i=0; i < 2; i++)
8316 8317
  {
    TABLE_LIST *table= join_list->pop();
8318
    if (unlikely(!table))
8319
      DBUG_RETURN(NULL);
8320 8321 8322
    table->join_list= embedded_list;
    table->embedding= ptr;
    embedded_list->push_back(table);
unknown's avatar
unknown committed
8323 8324 8325 8326 8327 8328 8329
    if (table->natural_join)
    {
      ptr->is_natural_join= TRUE;
      /*
        If this is a JOIN ... USING, move the list of joined fields to the
        table reference that describes the join.
      */
unknown's avatar
unknown committed
8330 8331
      if (prev_join_using)
        ptr->join_using_fields= prev_join_using;
unknown's avatar
unknown committed
8332
    }
8333 8334 8335 8336 8337 8338
  }
  nested_join->used_tables= nested_join->not_null_tables= (table_map) 0;
  DBUG_RETURN(ptr);
}


unknown's avatar
unknown committed
8339 8340
/**
  Add a table to the current join list.
8341 8342 8343 8344 8345 8346

    The function puts a table in front of the current join list
    of st_select_lex object.
    Thus, joined tables are put into this list in the reverse order
    (the most outer join operation follows first).

unknown's avatar
unknown committed
8347 8348 8349
  @param table       the table to add

  @return
8350 8351 8352 8353 8354 8355
    None
*/

void st_select_lex::add_joined_table(TABLE_LIST *table)
{
  DBUG_ENTER("add_joined_table");
8356
  join_list->push_front(table, parent_lex->thd->mem_root);
8357 8358 8359 8360 8361 8362
  table->join_list= join_list;
  table->embedding= embedding;
  DBUG_VOID_RETURN;
}


8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380
/**
  @brief
    Create a node for JOIN/INNER JOIN/CROSS JOIN/STRAIGHT_JOIN operation

  @param left_op     the node for the left operand constructed by the parser
  @param right_op    the node for the right operand constructed by the parser
  @param straight_fl TRUE if STRAIGHT_JOIN is used

  @retval
    false on success
    true  otherwise

  @details

    JOIN operator can be left-associative with other join operators in one
    context and right-associative in another context.

    In this query
8381
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a  (Q1)
8382
    JOIN is left-associative and the query Q1 is interpreted as
8383
      SELECT * FROM (t1 JOIN t2) LEFT JOIN t3 ON t2.a=t3.a.
8384
    While in this query
8385
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a ON t1.b=t2.b (Q2)
8386
    JOIN is right-associative and the query Q2 is interpreted as
8387
      SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) ON t1.b=t2.b
8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432

    JOIN is right-associative if it is used with ON clause or with USING clause.
    Otherwise it is left-associative.
    When parsing a join expression with JOIN operator we can't determine
    whether this operation left or right associative until either we read the
    corresponding ON clause or we reach the end of the expression. This creates
    a problem for the parser to build a proper internal representation of the
    used join expression.

    For Q1 and Q2 the trees representing the used join expressions look like

            LJ - ON                   J - ON
           /  \                      / \
          J    t3   (TQ1)          t1   LJ - ON      (TQ2)
         / \                           /  \
       t1   t2                       t2    t3

    To build TQ1 the parser has to reduce the expression for JOIN right after
    it has read the reference to t2. To build TQ2 the parser reduces JOIN
    when he has read the whole join expression. There is no way to determine
    whether an early reduction is needed until the whole join expression is
    read.
    A solution here is always to do a late reduction. In this case the parser
    first builds an incorrect tree TQ1* that has to be rebalanced right after
    it has been constructed.

             J                               LJ - ON
            / \                             /  \
          t1   LJ - ON    (TQ1*)    =>     J    t3
              /  \                        / \
            t2    t3                    t1   t2

    Actually the transformation is performed over the nodes t1 and LJ before the
    node for J is created in the function st_select_lex::add_cross_joined_table.
    The function creates a node for J which replaces the node t2. Then it
    attaches the nodes t1 and t2 to this newly created node. The node LJ becomes
    the top node of the tree.

    For the query
      SELECT * FROM t1 JOIN t2 RIGHT JOIN t3 ON t2.a=t3.a  (Q3)
    the transformation looks slightly differently because the parser
    replaces the RIGHT JOIN tree for an equivalent LEFT JOIN tree.

             J                               LJ - ON
            / \                             /  \
8433 8434 8435
          t1   LJ - ON    (TQ3*)    =>    t3    J
              /  \                             / \
            t3    t2                         t1   t2
8436 8437 8438 8439 8440 8441 8442

    With several left associative JOINs
      SELECT * FROM t1 JOIN t2 JOIN t3 LEFT JOIN t4 ON t3.a=t4.a (Q4)
    the newly created node for JOIN replaces the left most node of the tree:

          J1                         LJ - ON
         /  \                       /  \
8443
       t1    J2                    J2   t4
8444
            /  \          =>      /  \
8445 8446 8447
           t2  LJ - ON          J1    t3
              /  \             /  \
            t3   t4          t1    t2
8448

8449 8450 8451
    Here's another example:
      SELECT *
      FROM t1 JOIN t2 LEFT JOIN t3 JOIN t4 ON t3.a=t4.a ON t2.b=t3.b (Q5)
8452 8453 8454 8455 8456 8457 8458 8459 8460

          J                       LJ - ON
         / \                     /   \
       t1   LJ - ON             J     J - ON
           /  \          =>    / \   / \
         t2    J - ON         t1 t2 t3 t4
              / \
            t3   t4

8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512
    If the transformed nested join node node is a natural join node like in
    the following query
      SELECT * FROM t1 JOIN t2 LEFT JOIN t3 USING(a)  (Q6)
    the transformation additionally has to take care about setting proper
    references in the field natural_join for both operands of the natural
    join operation.

    The queries that combine comma syntax for join operation with
    JOIN expression require a special care. Consider the query
      SELECT * FROM t1, t2 JOIN t3 LEFT JOIN t4 ON t3.a=t4.a (Q7)
    This query is equivalent to the query
      SELECT * FROM (t1, t2) JOIN t3 LEFT JOIN t4 ON t3.a=t4.a
    The latter is transformed in the same way as query Q1

             J                               LJ - ON
            / \                             /  \
      (t1,t2)  LJ - ON      =>             J    t4
              /  \                        / \
            t3    t4                (t1,t2)   t3

    A transformation similar to the transformation for Q3 is done for
    the following query with RIGHT JOIN
      SELECT * FROM t1, t2 JOIN t3 RIGHT JOIN t4 ON t3.a=t4.a (Q8)

             J                               LJ - ON
            / \                             /  \
          t3   LJ - ON      =>            t4    J
              /  \                             / \
            t4   (t1,t2)                 (t1,t2)  t3

    The function also has to change the name resolution context for ON
    expressions used in the transformed join expression to take into
    account the tables of the left_op node.

  TODO:
    A more elegant solution would be to implement the transformation that
    eliminates nests for cross join operations. For Q7 it would work like this:

             J                               LJ - ON
            / \                             /  \
      (t1,t2)  LJ - ON      =>     (t1,t2,t3)   t4
              /  \
            t3    t4

    For Q8 with RIGHT JOIN the transformation would work similarly:

             J                               LJ - ON
            / \                             /  \
          t3   LJ - ON      =>            t4   (t1,t2,t3)
              /  \
            t4   (t1,t2)

8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529
*/

bool st_select_lex::add_cross_joined_table(TABLE_LIST *left_op,
                                           TABLE_LIST *right_op,
                                           bool straight_fl)
{
  DBUG_ENTER("add_cross_joined_table");
  THD *thd= parent_lex->thd;
  if (!(right_op->nested_join &&
	(right_op->nested_join->nest_type & JOIN_OP_NEST)))
  {
    /*
      This handles the cases when the right operand is not a nested join.
      like in queries
        SELECT * FROM t1 JOIN t2;
        SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.a JOIN t3
    */
8530 8531
    add_joined_table(left_op);
    add_joined_table(right_op);
8532 8533 8534 8535 8536
    right_op->straight= straight_fl;
    DBUG_RETURN(false);
  }

  TABLE_LIST *tbl;
8537
  List<TABLE_LIST> *right_op_jl= right_op->join_list;
8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553
  TABLE_LIST *cj_nest;

  /*
    Create the node NJ for a new nested join for the future inclusion
    of left_op in it. Initially the nest is empty.
  */
  if (unlikely(!(cj_nest=
                 (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
                                           sizeof(NESTED_JOIN)))))
    DBUG_RETURN(true);
  cj_nest->nested_join=
    ((NESTED_JOIN*) ((uchar*) cj_nest + ALIGN_SIZE(sizeof(TABLE_LIST))));
  cj_nest->nested_join->nest_type= JOIN_OP_NEST;
  List<TABLE_LIST> *cjl=  &cj_nest->nested_join->join_list;
  cjl->empty();

8554 8555
  List<TABLE_LIST> *jl= &right_op->nested_join->join_list;
  DBUG_ASSERT(jl->elements == 2);
8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588
  /* Look for the left most node tbl of the right_op tree */
  for ( ; ; )
  {
    TABLE_LIST *pair_tbl= 0;  /* useful only for operands of natural joins */

    List_iterator<TABLE_LIST> li(*jl);
    tbl= li++;

    /* Expand name resolution context */
    Name_resolution_context *on_context;
    if ((on_context= tbl->on_context))
    {
      on_context->first_name_resolution_table=
        left_op->first_leaf_for_name_resolution();
    }

    if (!(tbl->outer_join & JOIN_TYPE_RIGHT))
    {
      pair_tbl= tbl;
      tbl= li++;
    }
    if (tbl->nested_join &&
        tbl->nested_join->nest_type & JOIN_OP_NEST)
    {
      jl= &tbl->nested_join->join_list;
      continue;
    }

    /* Replace the tbl node in the tree for the newly created NJ node */
    cj_nest->outer_join= tbl->outer_join;
    cj_nest->on_expr= tbl->on_expr;
    cj_nest->embedding= tbl->embedding;
    cj_nest->join_list= jl;
Oleksandr Byelkin's avatar
Oleksandr Byelkin committed
8589
    cj_nest->alias.str= "(nest_last_join)";
8590
    cj_nest->alias.length= sizeof("(nest_last_join)")-1;
8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627
    li.replace(cj_nest);

    /*
      If tbl is an operand of a natural join set properly the references
      in the fields natural_join for both operands of the operation.
    */
    if(tbl->embedding && tbl->embedding->is_natural_join)
    {
      if (!pair_tbl)
        pair_tbl= li++;
      pair_tbl->natural_join= cj_nest;
      cj_nest->natural_join= pair_tbl;
    }
    break;
  }

  /* Attach tbl as the right operand of NJ */
  if (unlikely(cjl->push_back(tbl, thd->mem_root)))
    DBUG_RETURN(true);
  tbl->outer_join= 0;
  tbl->on_expr= 0;
  tbl->straight= straight_fl;
  tbl->natural_join= 0;
  tbl->embedding= cj_nest;
  tbl->join_list= cjl;

  /* Add left_op as the left operand of NJ */
  if (unlikely(cjl->push_back(left_op, thd->mem_root)))
    DBUG_RETURN(true);
  left_op->embedding= cj_nest;
  left_op->join_list= cjl;

  /*
    Mark right_op as a rebalanced nested join in order not to
    create a new top level nested join node.
  */
  right_op->nested_join->nest_type|= REBALANCED_NEST;
8628 8629
  if (unlikely(right_op_jl->push_front(right_op)))
    DBUG_RETURN(true);
8630 8631 8632 8633
  DBUG_RETURN(false);
}


unknown's avatar
unknown committed
8634 8635
/**
  Convert a right join into equivalent left join.
8636 8637

    The function takes the current join list t[0],t[1] ... and
8638 8639 8640 8641 8642 8643
    effectively converts it into the list t[1],t[0] ...
    Although the outer_join flag for the new nested table contains
    JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join
    operation.

  EXAMPLES
unknown's avatar
unknown committed
8644
  @verbatim
8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655
    SELECT * FROM t1 RIGHT JOIN t2 ON on_expr =>
      SELECT * FROM t2 LEFT JOIN t1 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr =>
      SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr

    SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr =>
      SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr

    SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3  ON on_expr2 =>
      SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1
unknown's avatar
unknown committed
8656
   @endverbatim
8657

unknown's avatar
unknown committed
8658
  @param thd         current thread
8659

unknown's avatar
unknown committed
8660 8661 8662
  @return
    - Pointer to the table representing the inner table, if success
    - 0, otherwise
8663 8664
*/

8665
TABLE_LIST *st_select_lex::convert_right_join()
8666 8667
{
  TABLE_LIST *tab2= join_list->pop();
8668
  TABLE_LIST *tab1= join_list->pop();
8669 8670
  DBUG_ENTER("convert_right_join");

8671 8672
  join_list->push_front(tab2, parent_lex->thd->mem_root);
  join_list->push_front(tab1, parent_lex->thd->mem_root);
8673 8674 8675 8676 8677
  tab1->outer_join|= JOIN_TYPE_RIGHT;

  DBUG_RETURN(tab1);
}

8678 8679 8680 8681

void st_select_lex::prepare_add_window_spec(THD *thd)
{
  LEX *lex= thd->lex;
8682 8683
  save_group_list= group_list;
  save_order_list= order_list;
8684 8685 8686 8687 8688 8689 8690 8691 8692
  lex->win_ref= NULL;
  lex->win_frame= NULL;
  lex->frame_top_bound= NULL;
  lex->frame_bottom_bound= NULL;
  group_list.empty();
  order_list.empty();
}

bool st_select_lex::add_window_def(THD *thd,
8693 8694
                                   LEX_CSTRING *win_name,
                                   LEX_CSTRING *win_ref,
8695 8696 8697 8698
                                   SQL_I_List<ORDER> win_partition_list,
                                   SQL_I_List<ORDER> win_order_list,
                                   Window_frame *win_frame)
{
8699 8700 8701 8702 8703 8704
  SQL_I_List<ORDER> *win_part_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_partition_list);
  SQL_I_List<ORDER> *win_order_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_order_list);
  if (!(win_part_list_ptr && win_order_list_ptr))
    return true;
8705 8706
  Window_def *win_def= new (thd->mem_root) Window_def(win_name,
                                                      win_ref,
8707 8708
                                                      win_part_list_ptr,
                                                      win_order_list_ptr,
8709
                                                      win_frame);
8710 8711
  group_list= save_group_list;
  order_list= save_order_list;
8712 8713 8714 8715 8716
  if (parsing_place != SELECT_LIST)
  {
    fields_in_window_functions+= win_part_list_ptr->elements +
                                 win_order_list_ptr->elements;
  }
8717
  win_def->win_spec_number= window_specs.elements;
8718 8719 8720 8721
  return (win_def == NULL || window_specs.push_back(win_def));
}

bool st_select_lex::add_window_spec(THD *thd, 
8722
                                    LEX_CSTRING *win_ref,
8723 8724 8725 8726
                                    SQL_I_List<ORDER> win_partition_list,
                                    SQL_I_List<ORDER> win_order_list,
                                    Window_frame *win_frame)
{
8727 8728 8729 8730 8731 8732
  SQL_I_List<ORDER> *win_part_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_partition_list);
  SQL_I_List<ORDER> *win_order_list_ptr=
    new (thd->mem_root) SQL_I_List<ORDER> (win_order_list);
  if (!(win_part_list_ptr && win_order_list_ptr))
    return true;
8733
  Window_spec *win_spec= new (thd->mem_root) Window_spec(win_ref,
8734 8735
                                                         win_part_list_ptr,
                                                         win_order_list_ptr,
8736
                                                         win_frame);
8737 8738
  group_list= save_group_list;
  order_list= save_order_list;
8739 8740 8741 8742 8743
  if (parsing_place != SELECT_LIST)
  {
    fields_in_window_functions+= win_part_list_ptr->elements +
                                 win_order_list_ptr->elements;
  }
8744
  thd->lex->win_spec= win_spec;
8745
  win_spec->win_spec_number= window_specs.elements;
8746 8747 8748
  return (win_spec == NULL || window_specs.push_back(win_spec));
}

unknown's avatar
unknown committed
8749 8750
/**
  Set lock for all tables in current select level.
unknown's avatar
unknown committed
8751

8752 8753
  @param lock_type		Lock to set for tables
  @param skip_locked		(SELECT {FOR UPDATE/LOCK IN SHARED MODE} SKIP LOCKED)
unknown's avatar
unknown committed
8754

unknown's avatar
unknown committed
8755
  @note
unknown's avatar
unknown committed
8756 8757 8758 8759 8760
    If lock is a write lock, then tables->updating is set 1
    This is to get tables_ok to know that the table is updated by the
    query
*/

8761 8762
void st_select_lex::set_lock_for_tables(thr_lock_type lock_type, bool for_update,
					bool skip_locked_arg)
unknown's avatar
unknown committed
8763 8764
{
  DBUG_ENTER("set_lock_for_tables");
8765 8766 8767
  DBUG_PRINT("enter", ("lock_type: %d  for_update: %d  skip_locked %d",
                       lock_type, for_update, skip_locked));
  skip_locked= skip_locked_arg;
8768
  for (TABLE_LIST *tables= table_list.first;
unknown's avatar
VIEW  
unknown committed
8769 8770
       tables;
       tables= tables->next_local)
unknown's avatar
unknown committed
8771 8772
  {
    tables->lock_type= lock_type;
8773
    tables->skip_locked= skip_locked;
unknown's avatar
unknown committed
8774
    tables->updating=  for_update;
8775

Marko Mäkelä's avatar
Marko Mäkelä committed
8776
    if (tables->db.length)
Marko Mäkelä's avatar
Marko Mäkelä committed
8777
      tables->mdl_request.set_type((lock_type >= TL_FIRST_WRITE) ?
8778
                                   MDL_SHARED_WRITE : MDL_SHARED_READ);
unknown's avatar
unknown committed
8779 8780 8781 8782
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
8783

unknown's avatar
unknown committed
8784 8785
/**
  Create a fake SELECT_LEX for a unit.
unknown's avatar
unknown committed
8786 8787 8788 8789

    The method create a fake SELECT_LEX object for a unit.
    This object is created for any union construct containing a union
    operation and also for any single select union construct of the form
unknown's avatar
unknown committed
8790
    @verbatim
unknown's avatar
unknown committed
8791
    (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... 
unknown's avatar
unknown committed
8792
    @endvarbatim
unknown's avatar
unknown committed
8793
    or of the form
unknown's avatar
unknown committed
8794
    @varbatim
unknown's avatar
unknown committed
8795
    (SELECT ... ORDER BY LIMIT n) ORDER BY ...
unknown's avatar
unknown committed
8796
    @endvarbatim
unknown's avatar
unknown committed
8797
  
unknown's avatar
unknown committed
8798 8799 8800
  @param thd_arg		   thread handle

  @note
unknown's avatar
unknown committed
8801 8802 8803
    The object is used to retrieve rows from the temporary table
    where the result on the union is obtained.

unknown's avatar
unknown committed
8804
  @retval
unknown's avatar
unknown committed
8805
    1     on failure to create the object
unknown's avatar
unknown committed
8806
  @retval
unknown's avatar
unknown committed
8807 8808 8809
    0     on success
*/

unknown's avatar
unknown committed
8810
bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg)
unknown's avatar
unknown committed
8811 8812
{
  SELECT_LEX *first_sl= first_select();
8813
  DBUG_ENTER("st_select_lex_unit::add_fake_select_lex");
unknown's avatar
unknown committed
8814
  DBUG_ASSERT(!fake_select_lex);
unknown's avatar
unknown committed
8815

unknown's avatar
unknown committed
8816
  if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX()))
unknown's avatar
unknown committed
8817 8818 8819
      DBUG_RETURN(1);
  fake_select_lex->include_standalone(this, 
                                      (SELECT_LEX_NODE**)&fake_select_lex);
8820
  fake_select_lex->select_number= FAKE_SELECT_LEX_ID;
unknown's avatar
unknown committed
8821
  fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */
unknown's avatar
unknown committed
8822
  fake_select_lex->make_empty_select();
8823
  fake_select_lex->set_linkage(GLOBAL_OPTIONS_TYPE);
8824

8825 8826
  fake_select_lex->no_table_names_allowed= 1;

unknown's avatar
unknown committed
8827
  fake_select_lex->context.outer_context=first_sl->context.outer_context;
8828 8829
  /* allow item list resolving in fake select for ORDER BY */
  fake_select_lex->context.resolve_in_select_list= TRUE;
8830
  fake_select_lex->context.select_lex= fake_select_lex;  
unknown's avatar
unknown committed
8831

8832
  fake_select_lex->nest_level_base= first_select()->nest_level_base;
8833 8834
  if (fake_select_lex->set_nest_level(first_select()->nest_level))
    DBUG_RETURN(1);
8835

8836
  if (!is_unit_op())
unknown's avatar
unknown committed
8837 8838 8839 8840 8841 8842 8843 8844
  {
    /* 
      This works only for 
      (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m],
      (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m]
      just before the parser starts processing order_list
    */ 
    fake_select_lex->no_table_names_allowed= 1;
unknown's avatar
unknown committed
8845
    thd_arg->lex->current_select= fake_select_lex;
unknown's avatar
unknown committed
8846
  }
8847
  //thd_arg->lex->pop_context("add fake");
unknown's avatar
unknown committed
8848 8849 8850
  DBUG_RETURN(0);
}

8851

unknown's avatar
unknown committed
8852
/**
8853 8854
  Push a new name resolution context for a JOIN ... ON clause to the
  context stack of a query block.
unknown's avatar
unknown committed
8855 8856

    Create a new name resolution context for a JOIN ... ON clause,
8857 8858 8859
    set the first and last leaves of the list of table references
    to be used for name resolution, and push the newly created
    context to the stack of contexts of the query.
unknown's avatar
unknown committed
8860

unknown's avatar
unknown committed
8861 8862 8863 8864
  @param thd       pointer to current thread
  @param left_op   left  operand of the JOIN
  @param right_op  rigth operand of the JOIN

8865 8866 8867 8868
  @seealso
    push_table_function_arg_context() serves similar purpose for table
    functions

unknown's avatar
unknown committed
8869
  @retval
8870
    FALSE  if all is OK
unknown's avatar
unknown committed
8871
  @retval
8872
    TRUE   if a memory allocation error occurred
unknown's avatar
unknown committed
8873 8874
*/

8875 8876 8877
bool
push_new_name_resolution_context(THD *thd,
                                 TABLE_LIST *left_op, TABLE_LIST *right_op)
unknown's avatar
unknown committed
8878 8879
{
  Name_resolution_context *on_context;
8880
  if (!(on_context= new (thd->mem_root) Name_resolution_context))
8881
    return TRUE;
unknown's avatar
unknown committed
8882 8883 8884 8885
  on_context->first_name_resolution_table=
    left_op->first_leaf_for_name_resolution();
  on_context->last_name_resolution_table=
    right_op->last_leaf_for_name_resolution();
Marko Mäkelä's avatar
Marko Mäkelä committed
8886 8887
  LEX *lex= thd->lex;
  on_context->select_lex = lex->current_select;
8888
  st_select_lex *outer_sel= lex->parser_current_outer_select();
Marko Mäkelä's avatar
Marko Mäkelä committed
8889 8890
  on_context->outer_context = outer_sel ? &outer_sel->context : 0;
  return lex->push_context(on_context);
unknown's avatar
unknown committed
8891 8892 8893
}


unknown's avatar
unknown committed
8894 8895
/**
  Fix condition which contains only field (f turns to  f <> 0 )
8896
    or only contains the function NOT field (not f turns to  f == 0)
unknown's avatar
unknown committed
8897 8898 8899 8900 8901 8902

  @param cond            The condition to fix

  @return fixed condition
*/

8903
Item *normalize_cond(THD *thd, Item *cond)
unknown's avatar
unknown committed
8904 8905 8906 8907 8908 8909
{
  if (cond)
  {
    Item::Type type= cond->type();
    if (type == Item::FIELD_ITEM || type == Item::REF_ITEM)
    {
Monty's avatar
Monty committed
8910
      cond= new (thd->mem_root) Item_func_ne(thd, cond, new (thd->mem_root) Item_int(thd, 0));
unknown's avatar
unknown committed
8911
    }
8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926
    else
    {
      if (type == Item::FUNC_ITEM)
      {
        Item_func *func_item= (Item_func *)cond;
        if (func_item->functype() == Item_func::NOT_FUNC)
        {
          Item *arg= func_item->arguments()[0];
          if (arg->type() == Item::FIELD_ITEM ||
              arg->type() == Item::REF_ITEM)
            cond= new (thd->mem_root) Item_func_eq(thd, arg,
                                          new (thd->mem_root) Item_int(thd, 0));
        }
      }
    }
unknown's avatar
unknown committed
8927 8928 8929 8930 8931
  }
  return cond;
}


unknown's avatar
unknown committed
8932
/**
unknown's avatar
unknown committed
8933 8934 8935 8936
  Add an ON condition to the second operand of a JOIN ... ON.

    Add an ON condition to the right operand of a JOIN ... ON clause.

unknown's avatar
unknown committed
8937 8938
  @param b     the second operand of a JOIN ... ON
  @param expr  the condition to be added to the ON clause
unknown's avatar
unknown committed
8939

unknown's avatar
unknown committed
8940
  @retval
unknown's avatar
unknown committed
8941
    FALSE  if there was some error
unknown's avatar
unknown committed
8942
  @retval
unknown's avatar
unknown committed
8943 8944 8945
    TRUE   if all is OK
*/

8946
void add_join_on(THD *thd, TABLE_LIST *b, Item *expr)
unknown's avatar
unknown committed
8947
{
8948
  if (expr)
8949
  {
8950
    expr= normalize_cond(thd, expr);
8951
    if (!b->on_expr)
unknown's avatar
unknown committed
8952
      b->on_expr= expr;
8953 8954
    else
    {
unknown's avatar
unknown committed
8955 8956 8957 8958 8959
      /*
        If called from the parser, this happens if you have both a
        right and left join. If called later, it happens if we add more
        than one condition to the ON clause.
      */
Monty's avatar
Monty committed
8960
      b->on_expr= new (thd->mem_root) Item_cond_and(thd, b->on_expr,expr);
8961 8962
    }
    b->on_expr->top_level_item();
8963
  }
unknown's avatar
unknown committed
8964 8965 8966
}


unknown's avatar
unknown committed
8967
/**
unknown's avatar
unknown committed
8968 8969
  Mark that there is a NATURAL JOIN or JOIN ... USING between two
  tables.
8970

unknown's avatar
unknown committed
8971 8972 8973 8974 8975 8976 8977 8978 8979 8980
    This function marks that table b should be joined with a either via
    a NATURAL JOIN or via JOIN ... USING. Both join types are special
    cases of each other, so we treat them together. The function
    setup_conds() creates a list of equal condition between all fields
    of the same name for NATURAL JOIN or the fields in 'using_fields'
    for JOIN ... USING. The list of equality conditions is stored
    either in b->on_expr, or in JOIN::conds, depending on whether there
    was an outer join.

  EXAMPLE
unknown's avatar
unknown committed
8981
  @verbatim
8982 8983 8984
    SELECT * FROM t1 NATURAL LEFT JOIN t2
     <=>
    SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... )
unknown's avatar
unknown committed
8985

unknown's avatar
unknown committed
8986 8987 8988
    SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>)
unknown's avatar
unknown committed
8989

unknown's avatar
unknown committed
8990 8991 8992
    SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond>
     <=>
    SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>)
unknown's avatar
unknown committed
8993 8994
   @endverbatim

8995
  @param a		  Left join argumentex
unknown's avatar
unknown committed
8996 8997
  @param b		  Right join argument
  @param using_fields    Field names from USING clause
8998 8999
*/

unknown's avatar
unknown committed
9000 9001
void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields,
                      SELECT_LEX *lex)
unknown's avatar
unknown committed
9002
{
unknown's avatar
unknown committed
9003
  b->natural_join= a;
unknown's avatar
unknown committed
9004
  lex->prev_join_using= using_fields;
unknown's avatar
unknown committed
9005 9006
}

unknown's avatar
unknown committed
9007

unknown's avatar
unknown committed
9008
/**
9009
  Find a thread by id and return it, locking it LOCK_thd_kill
9010

9011
  @param id  Identifier of the thread we're looking for
9012
  @param query_id If true, search by query_id instead of thread_id
9013

9014
  @return NULL    - not found
9015
          pointer - thread found, and its LOCK_thd_kill is locked.
9016 9017
*/

9018
struct find_thread_callback_arg
unknown's avatar
unknown committed
9019
{
9020 9021 9022 9023 9024 9025 9026 9027
  find_thread_callback_arg(longlong id_arg, bool query_id_arg):
    thd(0), id(id_arg), query_id(query_id_arg) {}
  THD *thd;
  longlong id;
  bool query_id;
};


9028
static my_bool find_thread_callback(THD *thd, find_thread_callback_arg *arg)
9029
{
9030
  if (arg->id == (arg->query_id ? thd->query_id : (longlong) thd->thread_id))
unknown's avatar
unknown committed
9031
  {
9032 9033 9034
    mysql_mutex_lock(&thd->LOCK_thd_kill);    // Lock from delete
    arg->thd= thd;
    return 1;
unknown's avatar
unknown committed
9035
  }
9036 9037 9038 9039 9040 9041 9042 9043 9044
  return 0;
}


THD *find_thread_by_id(longlong id, bool query_id)
{
  find_thread_callback_arg arg(id, query_id);
  server_threads.iterate(find_thread_callback, &arg);
  return arg.thd;
9045 9046
}

9047

9048
/**
9049
  kill one thread.
9050 9051

  @param thd			Thread class
9052 9053 9054
  @param id                     Thread id or query id
  @param kill_signal            Should it kill the query or the connection
  @param type                   Type of id: thread id or query id
9055 9056
*/

9057 9058 9059 9060 9061 9062
static uint
kill_one_thread(THD *thd, my_thread_id id, killed_state kill_signal, killed_type type
#ifdef WITH_WSREP
                , bool &wsrep_high_priority
#endif
)
9063 9064
{
  THD *tmp;
9065
  uint error= (type == KILL_TYPE_QUERY ? ER_NO_SUCH_QUERY : ER_NO_SUCH_THREAD);
9066
  DBUG_ENTER("kill_one_thread");
9067
  DBUG_PRINT("enter", ("id: %lld  signal: %d", (long long) id, kill_signal));
9068
  tmp= find_thread_by_id(id, type == KILL_TYPE_QUERY);
9069 9070
  if (!tmp)
    DBUG_RETURN(error);
9071
  DEBUG_SYNC(thd, "found_killee");
9072
  if (tmp->get_command() != COM_DAEMON)
9073
  {
9074 9075 9076 9077
    /*
      If we're SUPER, we can KILL anything, including system-threads.
      No further checks.

9078 9079 9080
      KILLer: thd->security_ctx->user could in theory be NULL while
      we're still in "unauthenticated" state. This is a theoretical
      case (the code suggests this could happen, so we play it safe).
9081

9082
      KILLee: tmp->security_ctx->user will be NULL for system threads.
9083
      We need to check so Jane Random User doesn't crash the server
9084 9085
      when trying to kill a) system threads or b) unauthenticated users'
      threads (Bug#43748).
9086

9087
      If user of both killer and killee are non-NULL, proceed with
9088
      slayage if both are string-equal.
9089 9090 9091 9092

      It's ok to also kill DELAYED threads with KILL_CONNECTION instead of
      KILL_SYSTEM_THREAD; The difference is that KILL_CONNECTION may be
      faster and do a harder kill than KILL_SYSTEM_THREAD;
9093 9094
    */

9095 9096
    mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from concurrent usage

9097
    if ((thd->security_ctx->master_access & PRIV_KILL_OTHER_USER_PROCESS) ||
Brave Galera Crew's avatar
Brave Galera Crew committed
9098
        thd->security_ctx->user_matches(tmp->security_ctx))
9099
    {
9100
#ifdef WITH_WSREP
9101 9102
      if (wsrep_thd_is_BF(tmp, false) || tmp->wsrep_applier)
      {
9103 9104
        error= ER_KILL_DENIED_ERROR;
        wsrep_high_priority= true;
9105
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
9106
                            ER_KILL_DENIED_ERROR,
9107 9108 9109 9110 9111 9112
                            "Thread %lld is %s and cannot be killed",
                            tmp->thread_id,
                           (tmp->wsrep_applier ? "wsrep applier" : "high priority"));
      }
      else
      {
9113 9114 9115 9116 9117 9118
        if (WSREP(tmp))
        {
          error = wsrep_kill_thd(thd, tmp, kill_signal);
        }
        else
        {
9119 9120 9121
#endif /* WITH_WSREP */
        tmp->awake_no_mutex(kill_signal);
        error= 0;
9122 9123
#ifdef WITH_WSREP
        }
9124
      }
9125
#endif /* WITH_WSREP */
9126 9127
    }
    else
9128 9129
      error= (type == KILL_TYPE_QUERY ? ER_KILL_QUERY_DENIED_ERROR :
                                        ER_KILL_DENIED_ERROR);
9130

9131
    mysql_mutex_unlock(&tmp->LOCK_thd_data);
9132
  }
9133
  mysql_mutex_unlock(&tmp->LOCK_thd_kill);
9134
  DBUG_PRINT("exit", ("%u", error));
9135 9136 9137
  DBUG_RETURN(error);
}

9138

9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150
/**
  kill all threads from one user

  @param thd			Thread class
  @param user_name		User name for threads we should kill
  @param only_kill_query        Should it kill the query or the connection

  @note
    If we can't kill all threads because of security issues, no threads
    are killed.
*/

9151
struct kill_threads_callback_arg
9152
{
9153 9154 9155
  kill_threads_callback_arg(THD *thd_arg, LEX_USER *user_arg,
                            killed_state kill_signal_arg):
    thd(thd_arg), user(user_arg), kill_signal(kill_signal_arg), counter(0) {}
9156 9157
  THD *thd;
  LEX_USER *user;
9158 9159
  killed_state kill_signal;
  uint counter;
9160
};
9161 9162


9163 9164 9165
static my_bool kill_threads_callback(THD *thd, kill_threads_callback_arg *arg)
{
  if (thd->security_ctx->user)
9166 9167 9168 9169 9170 9171
  {
    /*
      Check that hostname (if given) and user name matches.

      host.str[0] == '%' means that host name was not given. See sql_yacc.yy
    */
9172 9173 9174
    if (((arg->user->host.str[0] == '%' && !arg->user->host.str[1]) ||
         !strcmp(thd->security_ctx->host_or_ip, arg->user->host.str)) &&
        !strcmp(thd->security_ctx->user, arg->user->user.str))
9175
    {
9176 9177
      if (!(arg->thd->security_ctx->master_access &
            PRIV_KILL_OTHER_USER_PROCESS) &&
9178
          !arg->thd->security_ctx->user_matches(thd->security_ctx))
9179 9180 9181
      {
        return MY_TEST(arg->thd->security_ctx->master_access & PROCESS_ACL);
      }
9182 9183 9184 9185 9186 9187
      arg->counter++;
      mysql_mutex_lock(&thd->LOCK_thd_kill); // Lock from delete
      mysql_mutex_lock(&thd->LOCK_thd_data);
      thd->awake_no_mutex(arg->kill_signal);
      mysql_mutex_unlock(&thd->LOCK_thd_data);
      mysql_mutex_unlock(&thd->LOCK_thd_kill);
9188 9189
    }
  }
9190 9191 9192 9193 9194 9195 9196
  return 0;
}


static uint kill_threads_for_user(THD *thd, LEX_USER *user,
                                  killed_state kill_signal, ha_rows *rows)
{
9197
  kill_threads_callback_arg arg(thd, user, kill_signal);
9198 9199 9200 9201
  DBUG_ENTER("kill_threads_for_user");
  DBUG_PRINT("enter", ("user: %s  signal: %u", user->user.str,
                       (uint) kill_signal));

9202 9203
  *rows= 0;

9204 9205 9206
  if (server_threads.iterate(kill_threads_callback, &arg))
    DBUG_RETURN(ER_KILL_DENIED_ERROR);

9207
  *rows= arg.counter;
9208 9209 9210 9211
  DBUG_RETURN(0);
}


9212 9213
/**
  kills a thread and sends response.
9214

9215 9216 9217 9218
  @param thd                    Thread class
  @param id                     Thread id or query id
  @param state                  Should it kill the query or the connection
  @param type                   Type of id: thread id or query id
9219 9220
*/

9221
static
9222
void sql_kill(THD *thd, my_thread_id id, killed_state state, killed_type type)
9223
{
9224 9225 9226 9227 9228 9229 9230 9231 9232 9233
#ifdef WITH_WSREP
  bool wsrep_high_priority= false;
#endif
  uint error= kill_one_thread(thd, id, state, type
#ifdef WITH_WSREP
                              , wsrep_high_priority
#endif
                              );

  if (likely(!error))
9234
  {
9235
    if (!thd->killed)
9236
      my_ok(thd);
9237
    else
9238
      thd->send_kill_message();
9239
  }
9240 9241 9242 9243 9244 9245
#ifdef WITH_WSREP
  else if (wsrep_high_priority)
    my_printf_error(error, "This is a high priority thread/query and"
                    " cannot be killed without compromising"
                    " the consistency of the cluster", MYF(0));
#endif
unknown's avatar
unknown committed
9246
  else
9247
  {
unknown's avatar
unknown committed
9248
    my_error(error, MYF(0), id);
9249
  }
unknown's avatar
unknown committed
9250 9251
}

unknown's avatar
unknown committed
9252

9253 9254
static void __attribute__ ((noinline))
sql_kill_user(THD *thd, LEX_USER *user, killed_state state)
9255 9256 9257
{
  uint error;
  ha_rows rows;
9258
  switch (error= kill_threads_for_user(thd, user, state, &rows))
9259
  {
9260 9261 9262 9263
  case 0:
    my_ok(thd, rows);
    break;
  case ER_KILL_DENIED_ERROR:
9264
    char buf[DEFINER_LENGTH+1];
9265
    strxnmov(buf, sizeof(buf)-1, user->user.str, "@", user->host.str, NULL);
9266 9267
    my_printf_error(ER_KILL_DENIED_ERROR, ER_THD(thd, ER_CANNOT_USER), MYF(0),
                    "KILL USER", buf);
9268 9269 9270 9271
    break;
  case ER_OUT_OF_RESOURCES:
  default:
    my_error(error, MYF(0));
9272 9273 9274 9275
  }
}


unknown's avatar
unknown committed
9276
/** If pointer is not a null pointer, append filename to it. */
9277

unknown's avatar
unknown committed
9278
bool append_file_to_dir(THD *thd, const char **filename_ptr,
9279
                        const LEX_CSTRING *table_name)
9280
{
9281
  char buff[FN_REFLEN],*ptr, *end;
9282 9283 9284 9285
  if (!*filename_ptr)
    return 0;					// nothing to do

  /* Check that the filename is not too long and it's a hard path */
9286
  if (strlen(*filename_ptr)+table_name->length >= FN_REFLEN-1 ||
9287 9288
      !test_if_hard_path(*filename_ptr))
  {
9289
    my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr);
9290 9291 9292 9293
    return 1;
  }
  /* Fix is using unix filename format on dos */
  strmov(buff,*filename_ptr);
9294
  end=convert_dirname(buff, *filename_ptr, NullS);
9295 9296
  if (unlikely(!(ptr= (char*) thd->alloc((size_t) (end-buff) +
                                         table_name->length + 1))))
9297 9298
    return 1;					// End of memory
  *filename_ptr=ptr;
9299
  strxmov(ptr,buff,table_name->str,NullS);
9300 9301
  return 0;
}
9302

9303

unknown's avatar
unknown committed
9304
Comp_creator *comp_eq_creator(bool invert)
unknown's avatar
unknown committed
9305
{
unknown's avatar
unknown committed
9306
  return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator;
unknown's avatar
unknown committed
9307 9308
}

unknown's avatar
unknown committed
9309

unknown's avatar
unknown committed
9310
Comp_creator *comp_ge_creator(bool invert)
unknown's avatar
unknown committed
9311
{
unknown's avatar
unknown committed
9312
  return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator;
unknown's avatar
unknown committed
9313 9314
}

unknown's avatar
unknown committed
9315

unknown's avatar
unknown committed
9316
Comp_creator *comp_gt_creator(bool invert)
unknown's avatar
unknown committed
9317
{
unknown's avatar
unknown committed
9318
  return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator;
unknown's avatar
unknown committed
9319 9320
}

unknown's avatar
unknown committed
9321

unknown's avatar
unknown committed
9322
Comp_creator *comp_le_creator(bool invert)
unknown's avatar
unknown committed
9323
{
unknown's avatar
unknown committed
9324
  return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator;
unknown's avatar
unknown committed
9325 9326
}

unknown's avatar
unknown committed
9327

unknown's avatar
unknown committed
9328
Comp_creator *comp_lt_creator(bool invert)
unknown's avatar
unknown committed
9329
{
unknown's avatar
unknown committed
9330
  return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator;
unknown's avatar
unknown committed
9331 9332
}

unknown's avatar
unknown committed
9333

unknown's avatar
unknown committed
9334
Comp_creator *comp_ne_creator(bool invert)
unknown's avatar
unknown committed
9335
{
unknown's avatar
unknown committed
9336
  return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator;
unknown's avatar
unknown committed
9337
}
unknown's avatar
unknown committed
9338 9339


unknown's avatar
unknown committed
9340 9341
/**
  Construct ALL/ANY/SOME subquery Item.
unknown's avatar
unknown committed
9342

unknown's avatar
unknown committed
9343 9344 9345 9346
  @param left_expr   pointer to left expression
  @param cmp         compare function creator
  @param all         true if we create ALL subquery
  @param select_lex  pointer on parsed subquery structure
unknown's avatar
unknown committed
9347

unknown's avatar
unknown committed
9348
  @return
unknown's avatar
unknown committed
9349 9350
    constructed Item (or 0 if out of memory)
*/
9351
Item * all_any_subquery_creator(THD *thd, Item *left_expr,
unknown's avatar
unknown committed
9352 9353 9354 9355
				chooser_compare_func_creator cmp,
				bool all,
				SELECT_LEX *select_lex)
{
unknown's avatar
unknown committed
9356
  if ((cmp == &comp_eq_creator) && !all)       //  = ANY <=> IN
9357
    return new (thd->mem_root) Item_in_subselect(thd, left_expr, select_lex);
unknown's avatar
unknown committed
9358 9359

  if ((cmp == &comp_ne_creator) && all)        // <> ALL <=> NOT IN
9360
    return new (thd->mem_root) Item_func_not(thd,
9361
             new (thd->mem_root) Item_in_subselect(thd, left_expr, select_lex));
unknown's avatar
unknown committed
9362 9363

  Item_allany_subselect *it=
9364 9365
    new (thd->mem_root) Item_allany_subselect(thd, left_expr, cmp, select_lex,
                                              all);
9366 9367
  if (all) /* ALL */
    return it->upper_item= new (thd->mem_root) Item_func_not_all(thd, it);
unknown's avatar
unknown committed
9368

9369 9370
  /* ANY/SOME */
  return it->upper_item= new (thd->mem_root) Item_func_nop_all(thd, it);
unknown's avatar
unknown committed
9371
}
9372 9373


unknown's avatar
unknown committed
9374 9375
/**
  Multi update query pre-check.
9376

unknown's avatar
unknown committed
9377 9378
  @param thd		Thread handler
  @param tables	Global/local table list (have to be the same)
9379

unknown's avatar
unknown committed
9380
  @retval
unknown's avatar
unknown committed
9381
    FALSE OK
unknown's avatar
unknown committed
9382
  @retval
unknown's avatar
unknown committed
9383
    TRUE  Error
9384
*/
unknown's avatar
unknown committed
9385

unknown's avatar
unknown committed
9386
bool multi_update_precheck(THD *thd, TABLE_LIST *tables)
9387 9388 9389
{
  TABLE_LIST *table;
  LEX *lex= thd->lex;
9390
  SELECT_LEX *select_lex= lex->first_select_lex();
unknown's avatar
VIEW  
unknown committed
9391
  DBUG_ENTER("multi_update_precheck");
9392 9393 9394

  if (select_lex->item_list.elements != lex->value_list.elements)
  {
9395
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
9396
    DBUG_RETURN(TRUE);
9397 9398 9399 9400 9401
  }
  /*
    Ensure that we have UPDATE or SELECT privilege for each table
    The exact privilege is checked in mysql_multi_update()
  */
unknown's avatar
VIEW  
unknown committed
9402
  for (table= tables; table; table= table->next_local)
9403
  {
9404 9405
    if (table->is_jtbm())
      continue;
9406 9407
    if (table->derived)
      table->grant.privilege= SELECT_ACL;
9408
    else if ((check_access(thd, UPDATE_ACL, table->db.str,
Marc Alff's avatar
Marc Alff committed
9409 9410 9411
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 1) ||
9412
              check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) &&
9413
             (check_access(thd, SELECT_ACL, table->db.str,
Marc Alff's avatar
Marc Alff committed
9414 9415 9416
                           &table->grant.privilege,
                           &table->grant.m_internal,
                           0, 0) ||
9417
              check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)))
unknown's avatar
unknown committed
9418
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
9419

9420
    table->grant.orig_want_privilege= NO_ACL;
unknown's avatar
VIEW  
unknown committed
9421
    table->table_in_first_from_clause= 1;
9422
  }
unknown's avatar
unknown committed
9423 9424 9425
  /*
    Is there tables of subqueries?
  */
9426
  if (lex->first_select_lex() != lex->all_selects_list)
9427
  {
9428
    DBUG_PRINT("info",("Checking sub query list"));
unknown's avatar
VIEW  
unknown committed
9429
    for (table= tables; table; table= table->next_global)
9430
    {
9431
      if (!table->table_in_first_from_clause)
9432
      {
9433
	if (check_access(thd, SELECT_ACL, table->db.str,
Marc Alff's avatar
Marc Alff committed
9434 9435 9436
                         &table->grant.privilege,
                         &table->grant.m_internal,
                         0, 0) ||
9437
	    check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))
unknown's avatar
unknown committed
9438
	  DBUG_RETURN(TRUE);
9439 9440 9441 9442
      }
    }
  }

unknown's avatar
unknown committed
9443
  DBUG_RETURN(FALSE);
9444 9445
}

unknown's avatar
unknown committed
9446 9447
/**
  Multi delete query pre-check.
9448

unknown's avatar
unknown committed
9449 9450
  @param thd			Thread handler
  @param tables		Global/local table list
9451

unknown's avatar
unknown committed
9452
  @retval
unknown's avatar
unknown committed
9453
    FALSE OK
unknown's avatar
unknown committed
9454
  @retval
unknown's avatar
unknown committed
9455
    TRUE  error
9456
*/
unknown's avatar
unknown committed
9457

9458
bool multi_delete_precheck(THD *thd, TABLE_LIST *tables)
9459
{
9460
  SELECT_LEX *select_lex= thd->lex->first_select_lex();
9461
  TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first;
9462
  TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last;
unknown's avatar
VIEW  
unknown committed
9463
  DBUG_ENTER("multi_delete_precheck");
unknown's avatar
unknown committed
9464

unknown's avatar
unknown committed
9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477
  /*
    Temporary tables are pre-opened in 'tables' list only. Here we need to
    initialize TABLE instances in 'aux_tables' list.
  */
  for (TABLE_LIST *tl= aux_tables; tl; tl= tl->next_global)
  {
    if (tl->table)
      continue;

    if (tl->correspondent_table)
      tl->table= tl->correspondent_table->table;
  }

9478 9479
  /* sql_yacc guarantees that tables and aux_tables are not zero */
  DBUG_ASSERT(aux_tables != 0);
9480
  if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
9481 9482 9483 9484 9485 9486 9487 9488
    DBUG_RETURN(TRUE);

  /*
    Since aux_tables list is not part of LEX::query_tables list we
    have to juggle with LEX::query_tables_own_last value to be able
    call check_table_access() safely.
  */
  thd->lex->query_tables_own_last= 0;
9489
  if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE))
9490 9491
  {
    thd->lex->query_tables_own_last= save_query_tables_own_last;
unknown's avatar
unknown committed
9492
    DBUG_RETURN(TRUE);
9493 9494 9495
  }
  thd->lex->query_tables_own_last= save_query_tables_own_last;

9496
  if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where)
9497
  {
unknown's avatar
unknown committed
9498
    my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
9499
               ER_THD(thd, ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
unknown's avatar
unknown committed
9500
    DBUG_RETURN(TRUE);
9501
  }
9502 9503 9504 9505
  DBUG_RETURN(FALSE);
}


9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530
/*
  Given a table in the source list, find a correspondent table in the
  table references list.

  @param lex Pointer to LEX representing multi-delete.
  @param src Source table to match.
  @param ref Table references list.

  @remark The source table list (tables listed before the FROM clause
  or tables listed in the FROM clause before the USING clause) may
  contain table names or aliases that must match unambiguously one,
  and only one, table in the target table list (table references list,
  after FROM/USING clause).

  @return Matching table, NULL otherwise.
*/

static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl,
                                            TABLE_LIST *tables)
{
  TABLE_LIST *match= NULL;
  DBUG_ENTER("multi_delete_table_match");

  for (TABLE_LIST *elem= tables; elem; elem= elem->next_local)
  {
9531
    int res;
9532 9533 9534 9535

    if (tbl->is_fqtn && elem->is_alias)
      continue; /* no match */
    if (tbl->is_fqtn && elem->is_fqtn)
9536
      res= (!tbl->table_name.streq(elem->table_name) ||
9537
            cmp(&tbl->db, &elem->db));
9538
    else if (elem->is_alias)
9539
      res= !tbl->alias.streq(elem->alias);
9540
    else
9541
      res= (!tbl->table_name.streq(elem->table_name) ||
9542
            cmp(&tbl->db, &elem->db));
9543

9544
    if (res)
9545 9546 9547 9548
      continue;

    if (match)
    {
9549
      my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias.str);
9550 9551 9552 9553 9554 9555 9556
      DBUG_RETURN(NULL);
    }

    match= elem;
  }

  if (!match)
9557
    my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name.str, "MULTI DELETE");
9558 9559 9560 9561 9562

  DBUG_RETURN(match);
}


unknown's avatar
unknown committed
9563
/**
9564 9565 9566
  Link tables in auxilary table list of multi-delete with corresponding
  elements in main table list, and set proper locks for them.

unknown's avatar
unknown committed
9567
  @param lex   pointer to LEX representing multi-delete
9568

unknown's avatar
unknown committed
9569 9570 9571 9572
  @retval
    FALSE   success
  @retval
    TRUE    error
9573 9574 9575 9576
*/

bool multi_delete_set_locks_and_link_aux_tables(LEX *lex)
{
9577
  TABLE_LIST *tables= lex->first_select_lex()->table_list.first;
9578 9579 9580
  TABLE_LIST *target_tbl;
  DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables");

9581
  lex->table_count_update= 0;
9582

9583
  for (target_tbl= lex->auxiliary_table_list.first;
9584
       target_tbl; target_tbl= target_tbl->next_local)
9585
  {
9586
    lex->table_count_update++;
9587
    /* All tables in aux_tables must be found in FROM PART */
9588
    TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables);
9589
    if (!walk)
unknown's avatar
unknown committed
9590
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
9591 9592
    if (!walk->derived)
      target_tbl->table_name= walk->table_name;
unknown's avatar
unknown committed
9593
    walk->updating= target_tbl->updating;
unknown's avatar
unknown committed
9594
    walk->lock_type= target_tbl->lock_type;
9595
    /* We can assume that tables to be deleted from are locked for write. */
9596
    DBUG_ASSERT(walk->lock_type >= TL_FIRST_WRITE);
9597
    walk->mdl_request.set_type(MDL_SHARED_WRITE);
unknown's avatar
VIEW  
unknown committed
9598
    target_tbl->correspondent_table= walk;	// Remember corresponding table
9599
  }
unknown's avatar
unknown committed
9600
  DBUG_RETURN(FALSE);
9601 9602 9603
}


unknown's avatar
unknown committed
9604 9605
/**
  simple UPDATE query pre-check.
unknown's avatar
unknown committed
9606

unknown's avatar
unknown committed
9607 9608
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
9609

unknown's avatar
unknown committed
9610
  @retval
unknown's avatar
unknown committed
9611
    FALSE OK
unknown's avatar
unknown committed
9612
  @retval
unknown's avatar
unknown committed
9613
    TRUE  Error
unknown's avatar
unknown committed
9614
*/
unknown's avatar
unknown committed
9615

unknown's avatar
unknown committed
9616
bool update_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
9617 9618
{
  DBUG_ENTER("update_precheck");
9619 9620
  if (thd->lex->first_select_lex()->item_list.elements !=
      thd->lex->value_list.elements)
unknown's avatar
unknown committed
9621
  {
9622
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
9623
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
9624
  }
unknown's avatar
unknown committed
9625
  DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables));
unknown's avatar
unknown committed
9626 9627 9628
}


unknown's avatar
unknown committed
9629 9630
/**
  simple DELETE query pre-check.
unknown's avatar
unknown committed
9631

unknown's avatar
unknown committed
9632 9633
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
9634

unknown's avatar
unknown committed
9635
  @retval
unknown's avatar
unknown committed
9636
    FALSE  OK
unknown's avatar
unknown committed
9637
  @retval
unknown's avatar
unknown committed
9638
    TRUE   error
unknown's avatar
unknown committed
9639
*/
unknown's avatar
unknown committed
9640

unknown's avatar
unknown committed
9641
bool delete_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
9642 9643
{
  DBUG_ENTER("delete_precheck");
9644
  if (tables->vers_conditions.delete_history)
9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655
  {
    if (check_one_table_access(thd, DELETE_HISTORY_ACL, tables))
      DBUG_RETURN(TRUE);
  }
  else
  {
    if (check_one_table_access(thd, DELETE_ACL, tables))
      DBUG_RETURN(TRUE);
    /* Set privilege for the WHERE clause */
    tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege);
  }
unknown's avatar
unknown committed
9656
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
9657 9658 9659
}


unknown's avatar
unknown committed
9660 9661
/**
  simple INSERT query pre-check.
unknown's avatar
unknown committed
9662

unknown's avatar
unknown committed
9663 9664
  @param thd		Thread handler
  @param tables	Global table list
unknown's avatar
unknown committed
9665

unknown's avatar
unknown committed
9666
  @retval
unknown's avatar
unknown committed
9667
    FALSE  OK
unknown's avatar
unknown committed
9668
  @retval
unknown's avatar
unknown committed
9669
    TRUE   error
unknown's avatar
unknown committed
9670
*/
unknown's avatar
unknown committed
9671

unknown's avatar
merge  
unknown committed
9672
bool insert_precheck(THD *thd, TABLE_LIST *tables)
unknown's avatar
unknown committed
9673 9674 9675 9676
{
  LEX *lex= thd->lex;
  DBUG_ENTER("insert_precheck");

unknown's avatar
unknown committed
9677 9678 9679 9680
  /*
    Check that we have modify privileges for the first table and
    select privileges for the rest
  */
9681 9682 9683
  privilege_t privilege= (INSERT_ACL |
                    (lex->duplicates == DUP_REPLACE ? DELETE_ACL : NO_ACL) |
                    (lex->value_list.elements ? UPDATE_ACL : NO_ACL));
unknown's avatar
unknown committed
9684 9685

  if (check_one_table_access(thd, privilege, tables))
unknown's avatar
unknown committed
9686
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
9687

unknown's avatar
unknown committed
9688
  if (lex->update_list.elements != lex->value_list.elements)
unknown's avatar
unknown committed
9689
  {
9690
    my_message(ER_WRONG_VALUE_COUNT, ER_THD(thd, ER_WRONG_VALUE_COUNT), MYF(0));
unknown's avatar
unknown committed
9691
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
9692
  }
unknown's avatar
unknown committed
9693
  DBUG_RETURN(FALSE);
9694
}
unknown's avatar
unknown committed
9695 9696


9697 9698 9699 9700 9701 9702 9703 9704 9705
/**
   Set proper open mode and table type for element representing target table
   of CREATE TABLE statement, also adjust statement table list if necessary.
*/

void create_table_set_open_action_and_adjust_tables(LEX *lex)
{
  TABLE_LIST *create_table= lex->query_tables;

9706
  if (lex->tmp_table())
9707
    create_table->open_type= OT_TEMPORARY_ONLY;
9708
  else
9709 9710
    create_table->open_type= OT_BASE_ONLY;

9711
  if (!lex->first_select_lex()->item_list.elements)
9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724
  {
    /*
      Avoid opening and locking target table for ordinary CREATE TABLE
      or CREATE TABLE LIKE for write (unlike in CREATE ... SELECT we
      won't do any insertions in it anyway). Not doing this causes
      problems when running CREATE TABLE IF NOT EXISTS for already
      existing log table.
    */
    create_table->lock_type= TL_READ;
  }
}


unknown's avatar
unknown committed
9725 9726
/**
  CREATE TABLE query pre-check.
unknown's avatar
unknown committed
9727

unknown's avatar
unknown committed
9728 9729 9730
  @param thd			Thread handler
  @param tables		Global table list
  @param create_table	        Table which will be created
unknown's avatar
unknown committed
9731

unknown's avatar
unknown committed
9732
  @retval
unknown's avatar
unknown committed
9733
    FALSE   OK
unknown's avatar
unknown committed
9734
  @retval
unknown's avatar
unknown committed
9735
    TRUE   Error
unknown's avatar
unknown committed
9736
*/
unknown's avatar
unknown committed
9737

unknown's avatar
unknown committed
9738 9739
bool create_table_precheck(THD *thd, TABLE_LIST *tables,
                           TABLE_LIST *create_table)
unknown's avatar
unknown committed
9740 9741
{
  LEX *lex= thd->lex;
9742
  SELECT_LEX *select_lex= lex->first_select_lex();
Marko Mäkelä's avatar
Marko Mäkelä committed
9743
  privilege_t want_priv{CREATE_ACL};
unknown's avatar
merge  
unknown committed
9744
  bool error= TRUE;                                 // Error message is given
unknown's avatar
unknown committed
9745
  DBUG_ENTER("create_table_precheck");
9746

9747 9748 9749 9750 9751
  /*
    Require CREATE [TEMPORARY] privilege on new table; for
    CREATE TABLE ... SELECT, also require INSERT.
  */

9752 9753 9754
  if (lex->tmp_table())
    want_priv= CREATE_TMP_ACL;
  else if (select_lex->item_list.elements || select_lex->tvc)
9755
    want_priv|= INSERT_ACL;
9756

9757
  /* CREATE OR REPLACE on not temporary tables require DROP_ACL */
9758
  if (lex->create_info.or_replace() && !lex->tmp_table())
9759
    want_priv|= DROP_ACL;
9760
                          
9761
  if (check_access(thd, want_priv, create_table->db.str,
Marc Alff's avatar
Marc Alff committed
9762 9763
                   &create_table->grant.privilege,
                   &create_table->grant.m_internal,
9764
                   0, 0))
9765
    goto err;
9766 9767

  /* If it is a merge table, check privileges for merge children. */
9768
  if (lex->create_info.merge_list)
unknown's avatar
unknown committed
9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796
  {
    /*
      The user must have (SELECT_ACL | UPDATE_ACL | DELETE_ACL) on the
      underlying base tables, even if there are temporary tables with the same
      names.

      From user's point of view, it might look as if the user must have these
      privileges on temporary tables to create a merge table over them. This is
      one of two cases when a set of privileges is required for operations on
      temporary tables (see also CREATE TABLE).

      The reason for this behavior stems from the following facts:

        - For merge tables, the underlying table privileges are checked only
          at CREATE TABLE / ALTER TABLE time.

          In other words, once a merge table is created, the privileges of
          the underlying tables can be revoked, but the user will still have
          access to the merge table (provided that the user has privileges on
          the merge table itself). 

        - Temporary tables shadow base tables.

          I.e. there might be temporary and base tables with the same name, and
          the temporary table takes the precedence in all operations.

        - For temporary MERGE tables we do not track if their child tables are
          base or temporary. As result we can't guarantee that privilege check
9797 9798
          which was done in presence of temporary child will stay relevant
          later as this temporary table might be removed.
unknown's avatar
unknown committed
9799 9800 9801 9802 9803 9804 9805

      If SELECT_ACL | UPDATE_ACL | DELETE_ACL privileges were not checked for
      the underlying *base* tables, it would create a security breach as in
      Bug#12771903.
    */

    if (check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
9806
                           lex->create_info.merge_list, FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
9807 9808
      goto err;
  }
9809

9810
  if (want_priv != CREATE_TMP_ACL &&
9811
      check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
9812 9813 9814 9815 9816
    goto err;

  if (select_lex->item_list.elements)
  {
    /* Check permissions for used tables in CREATE TABLE ... SELECT */
9817 9818
    if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE,
                                     UINT_MAX, FALSE))
9819 9820
      goto err;
  }
9821
  else if (lex->create_info.like())
unknown's avatar
unknown committed
9822
  {
9823
    if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE))
unknown's avatar
unknown committed
9824 9825
      goto err;
  }
9826

9827
  if (check_fk_parent_table_access(thd, &lex->create_info, &lex->alter_info,
9828
                                   create_table->db))
9829
    goto err;
9830

9831
  error= FALSE;
Sergei Golubchik's avatar
Sergei Golubchik committed
9832

9833 9834
err:
  DBUG_RETURN(error);
unknown's avatar
unknown committed
9835
}
unknown's avatar
unknown committed
9836 9837


9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857
/**
  Check privileges for LOCK TABLES statement.

  @param thd     Thread context.
  @param tables  List of tables to be locked.

  @retval FALSE - Success.
  @retval TRUE  - Failure.
*/

static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables)
{
  TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();

  for (TABLE_LIST *table= tables; table != first_not_own_table && table;
       table= table->next_global)
  {
    if (is_temporary_table(table))
      continue;

9858
    if (check_table_access(thd, PRIV_LOCK_TABLES, table,
9859 9860 9861 9862 9863 9864 9865 9866
                           FALSE, 1, FALSE))
      return TRUE;
  }

  return FALSE;
}


unknown's avatar
unknown committed
9867 9868
/**
  negate given expression.
unknown's avatar
unknown committed
9869

unknown's avatar
unknown committed
9870 9871
  @param thd  thread handler
  @param expr expression for negation
unknown's avatar
unknown committed
9872

unknown's avatar
unknown committed
9873
  @return
unknown's avatar
unknown committed
9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884
    negated expression
*/

Item *negate_expression(THD *thd, Item *expr)
{
  Item *negated;
  if (expr->type() == Item::FUNC_ITEM &&
      ((Item_func *) expr)->functype() == Item_func::NOT_FUNC)
  {
    /* it is NOT(NOT( ... )) */
    Item *arg= ((Item_func *) expr)->arguments()[0];
9885
    const Type_handler *fh= arg->fixed_type_handler();
unknown's avatar
unknown committed
9886
    enum_parsing_place place= thd->lex->current_select->parsing_place;
9887
    if ((fh && fh->is_bool_type()) || place == IN_WHERE || place == IN_HAVING)
unknown's avatar
unknown committed
9888 9889 9890 9891 9892
      return arg;
    /*
      if it is not boolean function then we have to emulate value of
      not(not(a)), it will be a != 0
    */
Monty's avatar
Monty committed
9893
    return new (thd->mem_root) Item_func_ne(thd, arg, new (thd->mem_root) Item_int(thd, (char*) "0", 0, 1));
unknown's avatar
unknown committed
9894 9895 9896 9897
  }

  if ((negated= expr->neg_transformer(thd)) != 0)
    return negated;
Monty's avatar
Monty committed
9898
  return new (thd->mem_root) Item_func_not(thd, expr);
unknown's avatar
unknown committed
9899
}
9900

unknown's avatar
unknown committed
9901 9902 9903
/**
  Set the specified definer to the default value, which is the
  current user in the thread.
9904
 
unknown's avatar
unknown committed
9905 9906
  @param[in]  thd       thread handler
  @param[out] definer   definer
9907 9908
*/
 
9909
void get_default_definer(THD *thd, LEX_USER *definer, bool role)
9910 9911 9912
{
  const Security_context *sctx= thd->security_ctx;

9913 9914 9915
  if (role)
  {
    definer->user.str= const_cast<char*>(sctx->priv_role);
9916
    definer->host= empty_clex_str;
9917 9918 9919 9920 9921 9922 9923
  }
  else
  {
    definer->user.str= const_cast<char*>(sctx->priv_user);
    definer->host.str= const_cast<char*>(sctx->priv_host);
    definer->host.length= strlen(definer->host.str);
  }
9924
  definer->user.length= strlen(definer->user.str);
9925
  definer->auth= NULL;
9926 9927
}

9928

unknown's avatar
unknown committed
9929
/**
9930
  Create default definer for the specified THD.
9931

unknown's avatar
unknown committed
9932
  @param[in] thd         thread handler
9933

unknown's avatar
unknown committed
9934 9935
  @return
    - On success, return a valid pointer to the created and initialized
9936
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
9937
    - On error, return 0.
9938 9939
*/

9940
LEX_USER *create_default_definer(THD *thd, bool role)
9941 9942 9943
{
  LEX_USER *definer;

9944
  if (unlikely(! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))))
9945 9946
    return 0;

9947
  thd->get_definer(definer, role);
9948

9949 9950 9951 9952 9953 9954 9955
  if (role && definer->user.length == 0)
  {
    my_error(ER_MALFORMED_DEFINER, MYF(0));
    return 0;
  }
  else
    return definer;
9956 9957 9958
}


unknown's avatar
unknown committed
9959
/**
9960
  Create definer with the given user and host names.
9961

unknown's avatar
unknown committed
9962 9963 9964
  @param[in] thd          thread handler
  @param[in] user_name    user name
  @param[in] host_name    host name
9965

unknown's avatar
unknown committed
9966 9967
  @return
    - On success, return a valid pointer to the created and initialized
9968
    LEX_USER, which contains definer information.
unknown's avatar
unknown committed
9969
    - On error, return 0.
9970 9971
*/

9972 9973
LEX_USER *create_definer(THD *thd, LEX_CSTRING *user_name,
                         LEX_CSTRING *host_name)
9974
{
9975 9976 9977 9978
  LEX_USER *definer;

  /* Create and initialize. */

9979
  if (unlikely(!(definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))))
9980 9981 9982 9983
    return 0;

  definer->user= *user_name;
  definer->host= *host_name;
9984
  definer->auth= NULL;
9985 9986

  return definer;
9987
}
9988 9989


unknown's avatar
unknown committed
9990
/**
9991
  Check that byte length of a string does not exceed some limit.
9992

unknown's avatar
unknown committed
9993
  @param str         string to be checked
9994 9995
  @param err_msg     Number of error message to be displayed if the string
		     is too long.  0 if empty error message.
unknown's avatar
unknown committed
9996
  @param max_length  max length
9997

unknown's avatar
unknown committed
9998
  @retval
9999
    FALSE   the passed string is not longer than max_length
unknown's avatar
unknown committed
10000
  @retval
10001
    TRUE    the passed string is longer than max_length
10002 10003 10004

  NOTE
    The function is not used in existing code but can be useful later?
10005 10006
*/

10007
bool check_string_byte_length(const LEX_CSTRING *str, uint err_msg,
10008
                              size_t max_byte_length)
10009
{
10010
  if (str->length <= max_byte_length)
unknown's avatar
unknown committed
10011
    return FALSE;
10012

10013 10014
  my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str,
           err_msg ? ER(err_msg) : "", max_byte_length);
10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025

  return TRUE;
}


/*
  Check that char length of a string does not exceed some limit.

  SYNOPSIS
  check_string_char_length()
      str              string to be checked
10026 10027
      err_msg          Number of error message to be displayed if the string
		       is too long.  0 if empty error message.
10028 10029 10030 10031 10032 10033 10034 10035 10036
      max_char_length  max length in symbols
      cs               string charset

  RETURN
    FALSE   the passed string is not longer than max_char_length
    TRUE    the passed string is longer than max_char_length
*/


10037
bool check_string_char_length(const LEX_CSTRING *str, uint err_msg,
10038
                              size_t max_char_length, CHARSET_INFO *cs,
10039 10040
                              bool no_error)
{
10041
  Well_formed_prefix prefix(cs, str->str, str->length, max_char_length);
10042 10043
  if (likely(!prefix.well_formed_error_pos() &&
             str->length == prefix.length()))
10044
    return FALSE;
unknown's avatar
unknown committed
10045

10046
  if (!no_error)
10047 10048
  {
    ErrConvString err(str->str, str->length, cs);
10049 10050 10051
    my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(),
             err_msg ? ER(err_msg) : "",
             max_char_length);
10052
  }
10053 10054
  return TRUE;
}
10055 10056


10057
bool check_ident_length(const LEX_CSTRING *ident)
10058
{
10059 10060
  if (check_string_char_length(ident, 0, NAME_CHAR_LEN,
                               Lex_ident_ci::charset_info(), 1))
10061 10062 10063 10064 10065 10066 10067 10068
  {
    my_error(ER_TOO_LONG_IDENT, MYF(0), ident->str);
    return 1;
  }
  return 0;
}


10069 10070
/*
  Check if path does not contain mysql data home directory
10071

10072
  SYNOPSIS
10073 10074
    path_starts_from_data_home_dir()
    dir                     directory, with all symlinks resolved
10075 10076 10077

  RETURN VALUES
    0	ok
10078
    1	error ;  Given path contains data directory
10079
*/
10080
extern "C" {
10081

10082
int path_starts_from_data_home_dir(const char *path)
10083
{
10084
  size_t dir_len= strlen(path);
10085
  DBUG_ENTER("path_starts_from_data_home_dir");
10086

10087
  if (mysql_unpacked_real_data_home_len<= dir_len)
10088
  {
10089 10090 10091 10092
    if (dir_len > mysql_unpacked_real_data_home_len &&
        path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR)
      DBUG_RETURN(0);

10093 10094
    if (lower_case_file_system)
    {
10095 10096 10097 10098
      if (!default_charset_info->strnncoll(path,
                                           mysql_unpacked_real_data_home_len,
                                           mysql_unpacked_real_data_home,
                                           mysql_unpacked_real_data_home_len))
10099 10100
      {
        DBUG_PRINT("error", ("Path is part of mysql_real_data_home"));
10101
        DBUG_RETURN(1);
10102
      }
10103
    }
10104 10105
    else if (!memcmp(path, mysql_unpacked_real_data_home,
                     mysql_unpacked_real_data_home_len))
10106 10107
    {
      DBUG_PRINT("error", ("Path is part of mysql_real_data_home"));
10108
      DBUG_RETURN(1);
10109
    }
10110 10111 10112 10113
  }
  DBUG_RETURN(0);
}

10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138
}

/*
  Check if path does not contain mysql data home directory

  SYNOPSIS
    test_if_data_home_dir()
    dir                     directory

  RETURN VALUES
    0	ok
    1	error ;  Given path contains data directory
*/

int test_if_data_home_dir(const char *dir)
{
  char path[FN_REFLEN];
  DBUG_ENTER("test_if_data_home_dir");

  if (!dir)
    DBUG_RETURN(0);

  (void) fn_format(path, dir, "", "", MY_RETURN_REAL_PATH);
  DBUG_RETURN(path_starts_from_data_home_dir(path));
}
10139

10140

Sergei Golubchik's avatar
Sergei Golubchik committed
10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156
int error_if_data_home_dir(const char *path, const char *what)
{
  size_t dirlen;
  char   dirpath[FN_REFLEN];
  if (path)
  {
    dirname_part(dirpath, path, &dirlen);
    if (test_if_data_home_dir(dirpath))
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), what);
      return 1;
    }
  }
  return 0;
}

10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167
/**
  Check that host name string is valid.

  @param[in] str string to be checked

  @return             Operation status
    @retval  FALSE    host name is ok
    @retval  TRUE     host name string is longer than max_length or
                      has invalid symbols
*/

10168
bool check_host_name(LEX_CSTRING *str)
10169 10170 10171
{
  const char *name= str->str;
  const char *end= str->str + str->length;
10172
  if (check_string_byte_length(str, ER_HOSTNAME, HOSTNAME_LENGTH))
10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187
    return TRUE;

  while (name != end)
  {
    if (*name == '@')
    {
      my_printf_error(ER_UNKNOWN_ERROR, 
                      "Malformed hostname (illegal symbol: '%c')", MYF(0),
                      *name);
      return TRUE;
    }
    name++;
  }
  return FALSE;
}
Sergey Glukhov's avatar
Sergey Glukhov committed
10188 10189


10190 10191
extern int MYSQLparse(THD *thd); // from yy_mariadb.cc
extern int ORAparse(THD *thd);   // from yy_oracle.cc
10192 10193 10194 10195 10196 10197 10198


/**
  This is a wrapper of MYSQLparse(). All the code should call parse_sql()
  instead of MYSQLparse().

  @param thd Thread context.
10199
  @param parser_state Parser state.
unknown's avatar
unknown committed
10200
  @param creation_ctx Object creation context.
10201 10202 10203 10204 10205 10206

  @return Error status.
    @retval FALSE on success.
    @retval TRUE on parsing error.
*/

Sergei Golubchik's avatar
Sergei Golubchik committed
10207 10208
bool parse_sql(THD *thd, Parser_state *parser_state,
               Object_creation_ctx *creation_ctx, bool do_pfs_digest)
10209
{
10210
  bool ret_value;
10211
  DBUG_ENTER("parse_sql");
10212
  DBUG_ASSERT(thd->m_parser_state == NULL);
10213
  DBUG_ASSERT(thd->lex->m_sql_cmd == NULL);
10214

10215
  MYSQL_QUERY_PARSE_START(thd->query());
unknown's avatar
unknown committed
10216 10217 10218 10219 10220 10221 10222
  /* Backup creation context. */

  Object_creation_ctx *backup_ctx= NULL;

  if (creation_ctx)
    backup_ctx= creation_ctx->set_n_backup(thd);

10223
  /* Set parser state. */
unknown's avatar
unknown committed
10224

10225
  thd->m_parser_state= parser_state;
10226

Sergei Golubchik's avatar
Sergei Golubchik committed
10227 10228 10229 10230 10231 10232 10233 10234
  parser_state->m_digest_psi= NULL;
  parser_state->m_lip.m_digest= NULL;

  if (do_pfs_digest)
  {
    /* Start Digest */
    parser_state->m_digest_psi= MYSQL_DIGEST_START(thd->m_statement_psi);

Eugene Kosov's avatar
Eugene Kosov committed
10235
    if (parser_state->m_digest_psi != NULL)
Sergei Golubchik's avatar
Sergei Golubchik committed
10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246
    {
      /*
        If either:
        - the caller wants to compute a digest
        - the performance schema wants to compute a digest
        set the digest listener in the lexer.
      */
      parser_state->m_lip.m_digest= thd->m_digest;
      parser_state->m_lip.m_digest->m_digest_storage.m_charset_number= thd->charset()->number;
    }
  }
10247

unknown's avatar
unknown committed
10248 10249
  /* Parse the query. */

Sergei Golubchik's avatar
Sergei Golubchik committed
10250 10251
  bool mysql_parse_status= thd->variables.sql_mode & MODE_ORACLE
                           ? ORAparse(thd) : MYSQLparse(thd);
10252 10253 10254 10255 10256 10257 10258 10259 10260

  if (mysql_parse_status)
    /*
      Restore the original LEX if it was replaced when parsing
      a stored procedure. We must ensure that a parsing error
      does not leave any side effects in the THD.
    */
    LEX::cleanup_lex_after_parse_error(thd);

10261 10262
  DBUG_ASSERT(opt_bootstrap || mysql_parse_status ||
              thd->lex->select_stack_top == 0);
10263
  thd->lex->current_select= thd->lex->first_select_lex();
10264

10265 10266 10267 10268 10269 10270 10271 10272 10273 10274
  /*
    Check that if MYSQLparse() failed either thd->is_error() is set, or an
    internal error handler is set.

    The assert will not catch a situation where parsing fails without an
    error reported if an error handler exists. The problem is that the
    error handler might have intercepted the error, so thd->is_error() is
    not set. However, there is no way to be 100% sure here (the error
    handler might be for other errors than parsing one).
  */
10275 10276

  DBUG_ASSERT(!mysql_parse_status ||
10277 10278
              thd->is_error() ||
              thd->get_internal_handler());
unknown's avatar
unknown committed
10279

10280
  /* Reset parser state. */
10281

10282
  thd->m_parser_state= NULL;
10283

unknown's avatar
unknown committed
10284 10285 10286 10287 10288 10289 10290
  /* Restore creation context. */

  if (creation_ctx)
    creation_ctx->restore_env(thd, backup_ctx);

  /* That's it. */

10291
  ret_value= mysql_parse_status || thd->is_fatal_error;
Sergei Golubchik's avatar
Sergei Golubchik committed
10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303

  if ((ret_value == 0) && (parser_state->m_digest_psi != NULL))
  {
    /*
      On parsing success, record the digest in the performance schema.
    */
    DBUG_ASSERT(do_pfs_digest);
    DBUG_ASSERT(thd->m_digest != NULL);
    MYSQL_DIGEST_END(parser_state->m_digest_psi,
                     & thd->m_digest->m_digest_storage);
  }

10304
  MYSQL_QUERY_PARSE_DONE(ret_value);
10305
  DBUG_RETURN(ret_value);
10306
}
10307 10308 10309 10310

/**
  @} (end of group Runtime_Environment)
*/
Alexander Barkov's avatar
#  
Alexander Barkov committed
10311 10312


10313 10314
void LEX::mark_first_table_as_inserting()
{
Marko Mäkelä's avatar
Marko Mäkelä committed
10315
  TABLE_LIST *t= first_select_lex()->table_list.first;
10316 10317 10318 10319 10320 10321 10322
  DBUG_ENTER("Query_tables_list::mark_tables_with_important_flags");
  DBUG_ASSERT(sql_command_flags[sql_command] & CF_INSERTS_DATA);
  t->for_insert_data= TRUE;
  DBUG_PRINT("info", ("table_list: %p  name: %s  db: %s  command: %u",
                      t, t->table_name.str,t->db.str, sql_command));
  DBUG_VOID_RETURN;
}