sql_class.cc 236 KB
Newer Older
1
/*
2
   Copyright (c) 2000, 2015, Oracle and/or its affiliates.
3
   Copyright (c) 2008, 2021, MariaDB Corporation.
unknown's avatar
unknown committed
4

unknown's avatar
unknown committed
5 6
   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
7
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
8

unknown's avatar
unknown committed
9 10 11 12
   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.
unknown's avatar
unknown committed
13

unknown's avatar
unknown committed
14 15
   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
16
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA
17
*/
unknown's avatar
unknown committed
18 19 20 21 22 23 24 25 26


/*****************************************************************************
**
** This file implements classes defined in sql_class.h
** Especially the classes to handle a result from a select
**
*****************************************************************************/

27
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
28 29 30
#pragma implementation				// gcc: Class implementation
#endif

31
#include "mariadb.h"
32 33 34 35 36
#include "sql_priv.h"
#include "sql_class.h"
#include "sql_cache.h"                          // query_cache_abort
#include "sql_base.h"                           // close_thread_tables
#include "sql_time.h"                         // date_time_format_copy
37
#include "tztime.h"                           // MYSQL_TIME <-> my_time_t
38 39
#include "sql_acl.h"                          // NO_ACCESS,
                                              // acl_getroot_no_password
40
#include "sql_base.h"
41
#include "sql_handler.h"                      // mysql_ha_cleanup
42
#include "rpl_rli.h"
43
#include "rpl_filter.h"
unknown's avatar
unknown committed
44
#include "rpl_record.h"
45
#include "slave.h"
46 47
#include <my_bitmap.h>
#include "log_event.h"
48
#include "sql_audit.h"
unknown's avatar
unknown committed
49 50
#include <m_ctype.h>
#include <sys/stat.h>
51
#include <thr_alarm.h>
52
#ifdef	__WIN__0
unknown's avatar
unknown committed
53 54
#include <io.h>
#endif
55
#include <mysys_err.h>
56
#include <limits.h>
unknown's avatar
unknown committed
57

58
#include "sp_head.h"
unknown's avatar
unknown committed
59 60
#include "sp_rcontext.h"
#include "sp_cache.h"
61
#include "sql_show.h"                           // append_identifier
Konstantin Osipov's avatar
Konstantin Osipov committed
62
#include "transaction.h"
63
#include "sql_select.h" /* declares create_tmp_table() */
64
#include "debug_sync.h"
65
#include "sql_parse.h"                          // is_update_query
66
#include "sql_callback.h"
Michael Widenius's avatar
Michael Widenius committed
67
#include "lock.h"
68 69
#include "wsrep_mysqld.h"
#include "wsrep_thd.h"
70
#include "sql_connect.h"
71
#include "my_atomic.h"
72

73 74 75
#ifdef HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif
76
#include "repl_failsafe.h"
77

78 79 80 81 82
/*
  The following is used to initialise Table_ident with a internal
  table name
*/
char internal_table_name[2]= "*";
83
char empty_c_string[1]= {0};    /* used for not defined db */
84

85 86
const char * const THD::DEFAULT_WHERE= "field list";

unknown's avatar
unknown committed
87 88 89 90
/****************************************************************************
** User variables
****************************************************************************/

91 92
extern "C" uchar *get_var_key(user_var_entry *entry, size_t *length,
                              my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
93
{
94 95
  *length= entry->name.length;
  return (uchar*) entry->name.str;
unknown's avatar
unknown committed
96 97
}

98
extern "C" void free_user_var(user_var_entry *entry)
unknown's avatar
unknown committed
99 100 101
{
  char *pos= (char*) entry+ALIGN_SIZE(sizeof(*entry));
  if (entry->value && entry->value != pos)
102 103
    my_free(entry->value);
  my_free(entry);
unknown's avatar
unknown committed
104 105
}

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
/* Functions for last-value-from-sequence hash */

extern "C" uchar *get_sequence_last_key(SEQUENCE_LAST_VALUE *entry,
                                        size_t *length,
                                        my_bool not_used
                                        __attribute__((unused)))
{
  *length= entry->length;
  return (uchar*) entry->key;
}

extern "C" void free_sequence_last(SEQUENCE_LAST_VALUE *entry)
{
  delete entry;
}


unknown's avatar
unknown committed
123
bool Key_part_spec::operator==(const Key_part_spec& other) const
124
{
125
  return length == other.length &&
126 127
         !lex_string_cmp(system_charset_info, &field_name,
                         &other.field_name);
128 129
}

130 131 132 133 134 135 136 137
/**
  Construct an (almost) deep copy of this key. Only those
  elements that are known to never change are not copied.
  If out of memory, a partial copy is returned and an error is set
  in THD.
*/

Key::Key(const Key &rhs, MEM_ROOT *mem_root)
138
  :DDL_options(rhs),type(rhs.type),
139 140 141
  key_create_info(rhs.key_create_info),
  columns(rhs.columns, mem_root),
  name(rhs.name),
142
  option_list(rhs.option_list),
143
  generated(rhs.generated), invisible(false)
144 145 146 147 148 149 150 151 152 153 154
{
  list_copy_and_replace_each_value(columns, mem_root);
}

/**
  Construct an (almost) deep copy of this foreign key. Only those
  elements that are known to never change are not copied.
  If out of memory, a partial copy is returned and an error is set
  in THD.
*/

unknown's avatar
unknown committed
155
Foreign_key::Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root)
156
  :Key(rhs,mem_root),
157
  ref_db(rhs.ref_db),
158
  ref_table(rhs.ref_table),
159
  ref_columns(rhs.ref_columns,mem_root),
160 161 162 163 164 165
  delete_opt(rhs.delete_opt),
  update_opt(rhs.update_opt),
  match_opt(rhs.match_opt)
{
  list_copy_and_replace_each_value(ref_columns, mem_root);
}
166 167

/*
168
  Test if a foreign key (= generated key) is a prefix of the given key
169 170 171 172 173 174 175 176 177 178 179 180 181 182
  (ignoring key name, key type and order of columns)

  NOTES:
    This is only used to test if an index for a FOREIGN KEY exists

  IMPLEMENTATION
    We only compare field names

  RETURN
    0	Generated key is a prefix of other key
    1	Not equal
*/

bool foreign_key_prefix(Key *a, Key *b)
183
{
184 185 186 187
  /* Ensure that 'a' is the generated key */
  if (a->generated)
  {
    if (b->generated && a->columns.elements > b->columns.elements)
188
      swap_variables(Key*, a, b);               // Put shorter key in 'a'
189 190
  }
  else
191
  {
192 193
    if (!b->generated)
      return TRUE;                              // No foreign key
194
    swap_variables(Key*, a, b);                 // Put generated key in 'a'
195 196 197 198 199 200
  }

  /* Test if 'a' is a prefix of 'b' */
  if (a->columns.elements > b->columns.elements)
    return TRUE;                                // Can't be prefix

unknown's avatar
unknown committed
201 202 203
  List_iterator<Key_part_spec> col_it1(a->columns);
  List_iterator<Key_part_spec> col_it2(b->columns);
  const Key_part_spec *col1, *col2;
204 205 206 207 208 209 210

#ifdef ENABLE_WHEN_INNODB_CAN_HANDLE_SWAPED_FOREIGN_KEY_COLUMNS
  while ((col1= col_it1++))
  {
    bool found= 0;
    col_it2.rewind();
    while ((col2= col_it2++))
211
    {
212 213 214 215 216
      if (*col1 == *col2)
      {
        found= TRUE;
	break;
      }
217
    }
218 219 220 221 222 223 224 225 226 227
    if (!found)
      return TRUE;                              // Error
  }
  return FALSE;                                 // Is prefix
#else
  while ((col1= col_it1++))
  {
    col2= col_it2++;
    if (!(*col1 == *col2))
      return TRUE;
228
  }
229 230
  return FALSE;                                 // Is prefix
#endif
231 232
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/*
  @brief
  Check if the foreign key options are compatible with the specification
  of the columns on which the key is created

  @retval
    FALSE   The foreign key options are compatible with key columns
  @retval
    TRUE    Otherwise
*/
bool Foreign_key::validate(List<Create_field> &table_fields)
{
  Create_field  *sql_field;
  Key_part_spec *column;
  List_iterator<Key_part_spec> cols(columns);
  List_iterator<Create_field> it(table_fields);
  DBUG_ENTER("Foreign_key::validate");
  while ((column= cols++))
  {
    it.rewind();
    while ((sql_field= it++) &&
254 255 256
           lex_string_cmp(system_charset_info,
                          &column->field_name,
                          &sql_field->field_name)) {}
257 258
    if (!sql_field)
    {
259
      my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.str);
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
      DBUG_RETURN(TRUE);
    }
    if (type == Key::FOREIGN_KEY && sql_field->vcol_info)
    {
      if (delete_opt == FK_OPTION_SET_NULL)
      {
        my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0), 
                 "ON DELETE SET NULL");
        DBUG_RETURN(TRUE);
      }
      if (update_opt == FK_OPTION_SET_NULL)
      {
        my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0), 
                 "ON UPDATE SET NULL");
        DBUG_RETURN(TRUE);
      }
      if (update_opt == FK_OPTION_CASCADE)
      {
        my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0), 
                 "ON UPDATE CASCADE");
        DBUG_RETURN(TRUE);
      }
    }
  }
  DBUG_RETURN(FALSE);
}
286

unknown's avatar
unknown committed
287 288 289
/****************************************************************************
** Thread specific functions
****************************************************************************/
Mikael Ronström's avatar
Mikael Ronström committed
290

291 292 293 294 295 296 297 298 299 300
/**
  Get current THD object from thread local data

  @retval     The THD object for the thread, NULL if not connection thread
*/
THD *thd_get_current_thd()
{
  return current_thd;
}

Monty's avatar
Monty committed
301 302 303 304 305 306 307 308 309 310 311 312
/**
  Clear errors from the previous THD

  @param thd              THD object
*/
void thd_clear_errors(THD *thd)
{
  my_errno= 0;
  thd->mysys_var->abort= 0;
}


Mikael Ronström's avatar
Mikael Ronström committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
/**
  Get thread attributes for connection threads

  @retval      Reference to thread attribute for connection threads
*/
pthread_attr_t *get_connection_attrib(void)
{
  return &connection_attrib;
}

/**
  Get max number of connections

  @retval         Max number of connections for MySQL Server
*/
ulong get_max_connections(void)
{
  return max_connections;
}

unknown's avatar
unknown committed
333 334 335 336
/*
  The following functions form part of the C plugin API
*/

337 338 339
extern "C" int mysql_tmpfile(const char *prefix)
{
  char filename[FN_REFLEN];
340 341 342
  File fd= create_temp_file(filename, mysql_tmpdir, prefix,
                            O_BINARY | O_SEQUENTIAL,
                            MYF(MY_WME | MY_TEMPORARY));
343 344 345 346
  return fd;
}


unknown's avatar
unknown committed
347
extern "C"
unknown's avatar
unknown committed
348
int thd_in_lock_tables(const THD *thd)
349
{
350
  return MY_TEST(thd->in_lock_tables);
351 352 353
}


unknown's avatar
unknown committed
354
extern "C"
unknown's avatar
unknown committed
355
int thd_tablespace_op(const THD *thd)
356
{
357
  return MY_TEST(thd->tablespace_op);
358 359
}

unknown's avatar
unknown committed
360
extern "C"
361
const char *set_thd_proc_info(THD *thd_arg, const char *info,
Konstantin Osipov's avatar
Konstantin Osipov committed
362 363
                              const char *calling_function,
                              const char *calling_file,
364
                              const unsigned int calling_line)
365
{
366 367 368
  PSI_stage_info old_stage;
  PSI_stage_info new_stage;

369 370
  new_stage.m_key= 0;
  new_stage.m_name= info;
371

372
  set_thd_stage_info(thd_arg, & new_stage, & old_stage,
373 374
                     calling_function, calling_file, calling_line);

375
  return old_stage.m_name;
376 377 378
}

extern "C"
Sergei Golubchik's avatar
Sergei Golubchik committed
379
void set_thd_stage_info(void *thd_arg,
380 381 382 383 384 385
                        const PSI_stage_info *new_stage,
                        PSI_stage_info *old_stage,
                        const char *calling_func,
                        const char *calling_file,
                        const unsigned int calling_line)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
386
  THD *thd= (THD*) thd_arg;
387
  if (thd == NULL)
Konstantin Osipov's avatar
Konstantin Osipov committed
388 389
    thd= current_thd;

390 391
  if (old_stage)
    thd->backup_stage(old_stage);
392

393 394
  if (new_stage)
    thd->enter_stage(new_stage, calling_func, calling_file, calling_line);
395 396
}

Sergei Golubchik's avatar
Sergei Golubchik committed
397 398 399 400
void thd_enter_cond(MYSQL_THD thd, mysql_cond_t *cond, mysql_mutex_t *mutex,
                    const PSI_stage_info *stage, PSI_stage_info *old_stage,
                    const char *src_function, const char *src_file,
                    int src_line)
He Zhenxing's avatar
He Zhenxing committed
401 402 403 404
{
  if (!thd)
    thd= current_thd;

Sergei Golubchik's avatar
Sergei Golubchik committed
405 406
  return thd->enter_cond(cond, mutex, stage, old_stage, src_function, src_file,
                         src_line);
He Zhenxing's avatar
He Zhenxing committed
407 408
}

Sergei Golubchik's avatar
Sergei Golubchik committed
409 410 411
void thd_exit_cond(MYSQL_THD thd, const PSI_stage_info *stage,
                   const char *src_function, const char *src_file,
                   int src_line)
He Zhenxing's avatar
He Zhenxing committed
412 413 414 415
{
  if (!thd)
    thd= current_thd;

Sergei Golubchik's avatar
Sergei Golubchik committed
416
  thd->exit_cond(stage, src_function, src_file, src_line);
He Zhenxing's avatar
He Zhenxing committed
417 418 419
  return;
}

unknown's avatar
unknown committed
420
extern "C"
unknown's avatar
unknown committed
421 422
void **thd_ha_data(const THD *thd, const struct handlerton *hton)
{
423
  return (void **) &thd->ha_data[hton->slot].ha_ptr;
unknown's avatar
unknown committed
424 425
}

426 427 428 429 430
extern "C"
void thd_storage_lock_wait(THD *thd, long long value)
{
  thd->utime_after_lock+= value;
}
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

/**
  Provide a handler data getter to simplify coding
*/
extern "C"
void *thd_get_ha_data(const THD *thd, const struct handlerton *hton)
{
  return *thd_ha_data(thd, hton);
}


/**
  Provide a handler data setter to simplify coding
  @see thd_set_ha_data() definition in plugin.h
*/
extern "C"
void thd_set_ha_data(THD *thd, const struct handlerton *hton,
                     const void *ha_data)
{
  plugin_ref *lock= &thd->ha_data[hton->slot].lock;
451
  DBUG_ASSERT(thd == current_thd);
452 453 454 455 456 457 458
  if (ha_data && !*lock)
    *lock= ha_lock_engine(NULL, (handlerton*) hton);
  else if (!ha_data && *lock)
  {
    plugin_unlock(NULL, *lock);
    *lock= NULL;
  }
459
  mysql_mutex_lock(&thd->LOCK_thd_data);
460
  *thd_ha_data(thd, hton)= (void*) ha_data;
461
  mysql_mutex_unlock(&thd->LOCK_thd_data);
462 463 464
}


465 466 467 468 469
/**
  Allow storage engine to wakeup commits waiting in THD::wait_for_prior_commit.
  @see thd_wakeup_subsequent_commits() definition in plugin.h
*/
extern "C"
470
void thd_wakeup_subsequent_commits(THD *thd, int wakeup_error)
471
{
472
  thd->wakeup_subsequent_commits(wakeup_error);
473 474 475
}


unknown's avatar
unknown committed
476
extern "C"
unknown's avatar
unknown committed
477 478
long long thd_test_options(const THD *thd, long long test_options)
{
479
  return thd->variables.option_bits & test_options;
unknown's avatar
unknown committed
480 481
}

unknown's avatar
unknown committed
482
extern "C"
unknown's avatar
unknown committed
483 484 485 486 487
int thd_sql_command(const THD *thd)
{
  return (int) thd->lex->sql_command;
}

488 489 490
extern "C"
int thd_tx_isolation(const THD *thd)
{
491
  return (int) thd->tx_isolation;
492 493
}

494 495 496 497 498 499
extern "C"
int thd_tx_is_read_only(const THD *thd)
{
  return (int) thd->tx_read_only;
}

500

501
extern "C"
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
{ /* Functions for thd_error_context_service */

  const char *thd_get_error_message(const THD *thd)
  {
    return thd->get_stmt_da()->message();
  }

  uint thd_get_error_number(const THD *thd)
  {
    return thd->get_stmt_da()->sql_errno();
  }

  ulong thd_get_error_row(const THD *thd)
  {
    return thd->get_stmt_da()->current_row_for_warning();
  }

  void thd_inc_error_row(THD *thd)
  {
    thd->get_stmt_da()->inc_current_row_for_warning();
  }
523
}
unknown's avatar
unknown committed
524

525

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
#if MARIA_PLUGIN_INTERFACE_VERSION < 0x0200
/**
  TODO: This function is for API compatibility, remove it eventually.
  All engines should switch to use thd_get_error_context_description()
  plugin service function.
*/
extern "C"
char *thd_security_context(THD *thd,
                           char *buffer, unsigned int length,
                           unsigned int max_query_len)
{
  return thd_get_error_context_description(thd, buffer, length, max_query_len);
}
#endif

541
/**
542
  Implementation of Drop_table_error_handler::handle_condition().
543 544 545 546 547 548 549 550 551 552 553 554
  The reason in having this implementation is to silence technical low-level
  warnings during DROP TABLE operation. Currently we don't want to expose
  the following warnings during DROP TABLE:
    - Some of table files are missed or invalid (the table is going to be
      deleted anyway, so why bother that something was missed);
    - A trigger associated with the table does not have DEFINER (One of the
      MySQL specifics now is that triggers are loaded for the table being
      dropped. So, we may have a warning that trigger does not have DEFINER
      attribute during DROP TABLE operation).

  @return TRUE if the condition is handled.
*/
555 556 557
bool Drop_table_error_handler::handle_condition(THD *thd,
                                                uint sql_errno,
                                                const char* sqlstate,
558
                                                Sql_condition::enum_warning_level *level,
559
                                                const char* msg,
560
                                                Sql_condition ** cond_hdl)
561 562
{
  *cond_hdl= NULL;
563 564 565 566 567
  return ((sql_errno == EE_DELETE && my_errno == ENOENT) ||
          sql_errno == ER_TRG_NO_DEFINER);
}


568 569 570 571 572 573 574 575 576 577
/**
  Handle an error from MDL_context::upgrade_lock() and mysql_lock_tables().
  Ignore ER_LOCK_ABORTED and ER_LOCK_DEADLOCK errors.
*/

bool
MDL_deadlock_and_lock_abort_error_handler::
handle_condition(THD *thd,
                 uint sql_errno,
                 const char *sqlstate,
578
                 Sql_condition::enum_warning_level *level,
579 580 581 582 583 584 585 586 587 588 589
                 const char* msg,
                 Sql_condition **cond_hdl)
{
  *cond_hdl= NULL;
  if (sql_errno == ER_LOCK_ABORTED || sql_errno == ER_LOCK_DEADLOCK)
    m_need_reopen= true;

  return m_need_reopen;
}


Monty's avatar
Monty committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603
/**
   Send timeout to thread.

   Note that this is always safe as the thread will always remove it's
   timeouts at end of query (and thus before THD is destroyed)
*/

extern "C" void thd_kill_timeout(THD* thd)
{
  thd->status_var.max_statement_time_exceeded++;
  /* Kill queries that can't cause data corruptions */
  thd->awake(KILL_TIMEOUT);
}

604
THD::THD(my_thread_id id, bool is_wsrep_applier)
605 606
  :Statement(&main_lex, &main_mem_root, STMT_CONVENTIONAL_EXECUTION,
             /* statement id */ 0),
607
   rli_fake(0), rgi_fake(0), rgi_slave(NULL),
608
   protocol_text(this), protocol_binary(this),
andrelkin's avatar
andrelkin committed
609
   m_current_stage_key(0),
Sergei Golubchik's avatar
Sergei Golubchik committed
610
   in_sub_stmt(0), log_all_errors(0),
611
   binlog_unsafe_warning_flags(0),
612
   current_stmt_binlog_format(BINLOG_FORMAT_MIXED),
613
   binlog_table_maps(0),
614
   bulk_param(0),
He Zhenxing's avatar
He Zhenxing committed
615
   table_map_for_update(0),
Sergei Golubchik's avatar
Sergei Golubchik committed
616
   m_examined_row_count(0),
617
   accessed_rows_and_keys(0),
Sergei Golubchik's avatar
Sergei Golubchik committed
618
   m_digest(NULL),
619 620
   m_statement_psi(NULL),
   m_idle_psi(NULL),
Monty's avatar
Monty committed
621 622
   thread_id(id),
   thread_dbug_id(id),
623
   os_thread_id(0),
624
   global_disable_checkpoint(0),
625
   failed_com_change_user(0),
unknown's avatar
unknown committed
626
   is_fatal_error(0),
unknown's avatar
unknown committed
627
   transaction_rollback_request(0),
628
   is_fatal_sub_stmt_error(false),
unknown's avatar
unknown committed
629 630
   rand_used(0),
   time_zone_used(0),
631
   in_lock_tables(0),
unknown's avatar
unknown committed
632 633
   bootstrap(0),
   derived_tables_processing(FALSE),
634
   waiting_on_group_commit(FALSE), has_waiter(FALSE),
635
   spcont(NULL),
Marc Alff's avatar
Marc Alff committed
636
   m_parser_state(NULL),
637 638 639
#ifndef EMBEDDED_LIBRARY
   audit_plugin_version(-1),
#endif
640
#if defined(ENABLED_DEBUG_SYNC)
641
   debug_sync_control(0),
642
#endif /* defined(ENABLED_DEBUG_SYNC) */
643
   wait_for_commit_ptr(0),
644
   m_internal_handler(0),
645
   main_da(0, false, false),
646
   m_stmt_da(&main_da),
647
   tdc_hash_pins(0),
648 649
   xid_hash_pins(0),
   m_tmp_tables_locked(false)
650
#ifdef WITH_WSREP
651 652 653 654 655 656 657
  ,
   wsrep_applier(is_wsrep_applier),
   wsrep_applier_closing(false),
   wsrep_client_thread(false),
   wsrep_apply_toi(false),
   wsrep_po_handle(WSREP_PO_INITIALIZER),
   wsrep_po_cnt(0),
658
   wsrep_apply_format(0),
659
   wsrep_ignore_table(false)
660
#endif
unknown's avatar
unknown committed
661
{
662
  ulong tmp;
663
  bzero(&variables, sizeof(variables));
664

665 666 667 668 669 670
  /*
    We set THR_THD to temporally point to this THD to register all the
    variables that allocates memory for this THD
  */
  THD *old_THR_THD= current_thd;
  set_current_thd(this);
671
  status_var.local_memory_used= sizeof(THD);
672
  status_var.max_local_memory_used= status_var.local_memory_used;
673
  status_var.global_memory_used= 0;
Monty's avatar
Monty committed
674
  variables.pseudo_thread_id= thread_id;
675
  variables.max_mem_used= global_system_variables.max_mem_used;
676
  main_da.init();
677

678 679
  mdl_context.init(this);

680 681 682 683 684
  /*
    Pass nominal parameters to init_alloc_root only to ensure that
    the destructor works OK in case of an error. The main_mem_root
    will be re-initialized in init_for_queries().
  */
685 686
  init_sql_alloc(&main_mem_root, "THD::main_mem_root",
                 ALLOC_ROOT_MIN_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC));
687

688 689 690 691 692 693
  /*
    Allocation of user variables for binary logging is always done with main
    mem root
  */
  user_var_events_alloc= mem_root;

unknown's avatar
unknown committed
694
  stmt_arena= this;
695
  thread_stack= 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
696
  scheduler= thread_scheduler;                 // Will be fixed later
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
697 698
  event_scheduler.data= 0;
  event_scheduler.m_psi= 0;
699
  skip_wait_timeout= false;
700
  extra_port= 0;
701
  catalog= (char*)"std"; // the only catalog we have for now
702 703
  main_security_ctx.init();
  security_ctx= &main_security_ctx;
704 705
  no_errors= 0;
  password= 0;
706
  query_start_sec_part_used= 0;
707
  count_cuted_fields= CHECK_FIELD_IGNORE;
unknown's avatar
SCRUM  
unknown committed
708
  killed= NOT_KILLED;
709
  killed_err= 0;
710
  col_access=0;
711
  is_slave_error= thread_specific_used= FALSE;
Konstantin Osipov's avatar
Konstantin Osipov committed
712
  my_hash_clear(&handler_tables_hash);
713
  my_hash_clear(&ull_hash);
unknown's avatar
unknown committed
714
  tmp_table=0;
Marc Alff's avatar
Marc Alff committed
715
  cuted_fields= 0L;
Sergei Golubchik's avatar
Sergei Golubchik committed
716
  m_sent_row_count= 0L;
717
  limit_found_rows= 0;
718
  m_row_count_func= -1;
719
  statement_id_counter= 0UL;
720
  // Must be reset to handle error with THD's created for init of mysqld
unknown's avatar
unknown committed
721
  lex->current_select= 0;
722
  start_utime= utime_after_query= 0;
723
  system_time.start.val= system_time.sec= system_time.sec_part= 0;
724
  utime_after_lock= 0L;
725
  progress.arena= 0;
726 727
  progress.report_to_client= 0;
  progress.max_counter= 0;
unknown's avatar
unknown committed
728
  current_linfo =  0;
729
  slave_thread = 0;
730 731 732
  connection_name.str= 0;
  connection_name.length= 0;

733
  file_id = 0;
734
  query_id= 0;
735
  query_name_consts= 0;
736
  semisync_info= 0;
737
  db_charset= global_system_variables.collation_database;
738
  bzero((void*) ha_data, sizeof(ha_data));
unknown's avatar
unknown committed
739
  mysys_var=0;
740
  binlog_evt_union.do_union= FALSE;
741
  enable_slow_log= 0;
742
  durability_property= HA_REGULAR_DURABILITY;
743

744
#ifdef DBUG_ASSERT_EXISTS
745
  dbug_sentry=THD_SENTRY_MAGIC;
746
#endif
747
  mysql_audit_init_thd(this);
748
  net.vio=0;
749
  net.buff= 0;
750
  net.reading_or_writing= 0;
751
  client_capabilities= 0;                       // minimalistic client
752
  system_thread= NON_SYSTEM_THREAD;
Monty's avatar
Monty committed
753
  cleanup_done= free_connection_done= abort_on_warning= 0;
754
  peer_port= 0;					// For SHOW PROCESSLIST
755
  transaction.m_pending_rows_event= 0;
756
  transaction.on= 1;
757 758 759 760
  wt_thd_lazy_init(&transaction.wt, &variables.wt_deadlock_search_depth_short,
                                    &variables.wt_timeout_short,
                                    &variables.wt_deadlock_search_depth_long,
                                    &variables.wt_timeout_long);
761 762
#ifdef SIGNAL_WITH_VIO_CLOSE
  active_vio = 0;
763
#endif
Marc Alff's avatar
Marc Alff committed
764
  mysql_mutex_init(key_LOCK_thd_data, &LOCK_thd_data, MY_MUTEX_INIT_FAST);
Sergei Golubchik's avatar
Sergei Golubchik committed
765
  mysql_mutex_init(key_LOCK_wakeup_ready, &LOCK_wakeup_ready, MY_MUTEX_INIT_FAST);
766
  mysql_mutex_init(key_LOCK_thd_kill, &LOCK_thd_kill, MY_MUTEX_INIT_FAST);
Sergei Golubchik's avatar
Sergei Golubchik committed
767
  mysql_cond_init(key_COND_wakeup_ready, &COND_wakeup_ready, 0);
768 769 770 771 772
  /*
    LOCK_thread_count goes before LOCK_thd_data - the former is called around
    'delete thd', the latter - in THD::~THD
  */
  mysql_mutex_record_order(&LOCK_thread_count, &LOCK_thd_data);
unknown's avatar
unknown committed
773 774 775

  /* Variables with default values */
  proc_info="login";
776
  where= THD::DEFAULT_WHERE;
777
  slave_net = 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
778
  m_command=COM_CONNECT;
unknown's avatar
unknown committed
779
  *scramble= '\0';
unknown's avatar
unknown committed
780

781 782 783 784 785 786 787 788 789 790 791 792
#ifdef WITH_WSREP
  wsrep_ws_handle.trx_id = WSREP_UNDEFINED_TRX_ID;
  wsrep_ws_handle.opaque = NULL;
  wsrep_retry_counter     = 0;
  wsrep_PA_safe           = true;
  wsrep_retry_query       = NULL;
  wsrep_retry_query_len   = 0;
  wsrep_retry_command     = COM_CONNECT;
  wsrep_consistency_check = NO_CONSISTENCY_CHECK;
  wsrep_mysql_replicated  = 0;
  wsrep_TOI_pre_query     = NULL;
  wsrep_TOI_pre_query_len = 0;
793
  wsrep_info[sizeof(wsrep_info) - 1] = '\0'; /* make sure it is 0-terminated */
794
  wsrep_sync_wait_gtid    = WSREP_GTID_UNDEFINED;
795
  wsrep_affected_rows     = 0;
796 797
  wsrep_replicate_GTID    = false;
  wsrep_skip_wsrep_GTID   = false;
798
  wsrep_split_flag        = false;
799
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
800
  /* Call to init() below requires fully initialized Open_tables_state. */
801
  reset_open_tables_state(this);
Konstantin Osipov's avatar
Konstantin Osipov committed
802

803
  init();
804
#if defined(ENABLED_PROFILING)
unknown's avatar
unknown committed
805
  profiling.set_thd(this);
806
#endif
807
  user_connect=(USER_CONN *)0;
Konstantin Osipov's avatar
Konstantin Osipov committed
808 809
  my_hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
               (my_hash_get_key) get_var_key,
810
               (my_hash_free_key) free_user_var, HASH_THREAD_SPECIFIC);
811 812 813
  my_hash_init(&sequences, system_charset_info, SEQUENCES_HASH_SIZE, 0, 0,
               (my_hash_get_key) get_sequence_last_key,
               (my_hash_free_key) free_sequence_last, HASH_THREAD_SPECIFIC);
814

815 816
  sp_proc_cache= NULL;
  sp_func_cache= NULL;
817 818
  sp_package_spec_cache= NULL;
  sp_package_body_cache= NULL;
819

unknown's avatar
unknown committed
820 821 822
  /* For user vars replication*/
  if (opt_bin_log)
    my_init_dynamic_array(&user_var_events,
823
			  sizeof(BINLOG_USER_VAR_EVENT *), 16, 16, MYF(0));
unknown's avatar
unknown committed
824 825 826
  else
    bzero((char*) &user_var_events, sizeof(user_var_events));

827
  /* Protocol */
unknown's avatar
unknown committed
828 829 830
  protocol= &protocol_text;			// Default protocol
  protocol_text.init(this);
  protocol_binary.init(this);
831

Monty's avatar
Monty committed
832 833
  thr_timer_init(&query_timer, (void (*)(void*)) thd_kill_timeout, this);

unknown's avatar
unknown committed
834
  tablespace_op=FALSE;
Michael Widenius's avatar
Michael Widenius committed
835 836 837 838 839 840 841 842

  /*
    Initialize the random generator. We call my_rnd() without a lock as
    it's not really critical if two threads modifies the structure at the
    same time.  We ensure that we have an unique number foreach thread
    by adding the address of the stack.
  */
  tmp= (ulong) (my_rnd(&sql_rand) * 0xffffffff);
843
  my_rnd_init(&rand, tmp + (ulong)((size_t) &rand), tmp + (ulong) ::global_query_id);
844
  substitute_null_with_insert_id = FALSE;
845 846
  lock_info.mysql_thd= (void *)this;

Sergei Golubchik's avatar
Sergei Golubchik committed
847 848 849 850 851 852 853
  m_token_array= NULL;
  if (max_digest_length > 0)
  {
    m_token_array= (unsigned char*) my_malloc(max_digest_length,
                                              MYF(MY_WME|MY_THREAD_SPECIFIC));
  }

854
  m_binlog_invoker= INVOKER_NONE;
855
  invoker.init();
856
  prepare_derived_at_open= FALSE;
Igor Babaev's avatar
Igor Babaev committed
857
  create_tmp_table_for_derived= FALSE;
Igor Babaev's avatar
Igor Babaev committed
858
  save_prep_leaf_list= FALSE;
859
  org_charset= 0;
860 861
  /* Restore THR_THD */
  set_current_thd(old_THR_THD);
Sergei Golubchik's avatar
Sergei Golubchik committed
862
  inc_thread_count();
863 864 865 866 867
}


void THD::push_internal_handler(Internal_error_handler *handler)
{
868
  DBUG_ENTER("THD::push_internal_handler");
869 870 871 872 873 874 875 876 877
  if (m_internal_handler)
  {
    handler->m_prev_internal_handler= m_internal_handler;
    m_internal_handler= handler;
  }
  else
  {
    m_internal_handler= handler;
  }
878
  DBUG_VOID_RETURN;
879 880
}

Marc Alff's avatar
Marc Alff committed
881 882
bool THD::handle_condition(uint sql_errno,
                           const char* sqlstate,
883
                           Sql_condition::enum_warning_level *level,
Marc Alff's avatar
Marc Alff committed
884
                           const char* msg,
885
                           Sql_condition ** cond_hdl)
886
{
887
  if (!m_internal_handler)
Marc Alff's avatar
Marc Alff committed
888 889
  {
    *cond_hdl= NULL;
890
    return FALSE;
Marc Alff's avatar
Marc Alff committed
891
  }
892 893 894

  for (Internal_error_handler *error_handler= m_internal_handler;
       error_handler;
895
       error_handler= error_handler->m_prev_internal_handler)
896
  {
897 898
    if (error_handler->handle_condition(this, sql_errno, sqlstate, level, msg,
					cond_hdl))
Marc Alff's avatar
Marc Alff committed
899 900 901
    {
      return TRUE;
    }
902
  }
903
  return FALSE;
904 905 906
}


907
Internal_error_handler *THD::pop_internal_handler()
908
{
909
  DBUG_ENTER("THD::pop_internal_handler");
910
  DBUG_ASSERT(m_internal_handler != NULL);
911
  Internal_error_handler *popped_handler= m_internal_handler;
912
  m_internal_handler= m_internal_handler->m_prev_internal_handler;
Sergei Golubchik's avatar
Sergei Golubchik committed
913
  DBUG_RETURN(popped_handler);
unknown's avatar
unknown committed
914 915
}

Marc Alff's avatar
Marc Alff committed
916 917 918

void THD::raise_error(uint sql_errno)
{
919
  const char* msg= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
920 921
  (void) raise_condition(sql_errno,
                         NULL,
922
                         Sql_condition::WARN_LEVEL_ERROR,
Marc Alff's avatar
Marc Alff committed
923 924 925 926 927 928 929 930 931
                         msg);
}

void THD::raise_error_printf(uint sql_errno, ...)
{
  va_list args;
  char ebuff[MYSQL_ERRMSG_SIZE];
  DBUG_ENTER("THD::raise_error_printf");
  DBUG_PRINT("my", ("nr: %d  errno: %d", sql_errno, errno));
932
  const char* format= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
933 934 935 936 937
  va_start(args, sql_errno);
  my_vsnprintf(ebuff, sizeof(ebuff), format, args);
  va_end(args);
  (void) raise_condition(sql_errno,
                         NULL,
938
                         Sql_condition::WARN_LEVEL_ERROR,
Marc Alff's avatar
Marc Alff committed
939 940 941 942 943 944
                         ebuff);
  DBUG_VOID_RETURN;
}

void THD::raise_warning(uint sql_errno)
{
945
  const char* msg= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
946 947
  (void) raise_condition(sql_errno,
                         NULL,
948
                         Sql_condition::WARN_LEVEL_WARN,
Marc Alff's avatar
Marc Alff committed
949 950 951 952 953 954 955 956 957
                         msg);
}

void THD::raise_warning_printf(uint sql_errno, ...)
{
  va_list args;
  char    ebuff[MYSQL_ERRMSG_SIZE];
  DBUG_ENTER("THD::raise_warning_printf");
  DBUG_PRINT("enter", ("warning: %u", sql_errno));
958
  const char* format= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
959 960 961 962 963
  va_start(args, sql_errno);
  my_vsnprintf(ebuff, sizeof(ebuff), format, args);
  va_end(args);
  (void) raise_condition(sql_errno,
                         NULL,
964
                         Sql_condition::WARN_LEVEL_WARN,
Marc Alff's avatar
Marc Alff committed
965 966 967 968 969 970 971 972
                         ebuff);
  DBUG_VOID_RETURN;
}

void THD::raise_note(uint sql_errno)
{
  DBUG_ENTER("THD::raise_note");
  DBUG_PRINT("enter", ("code: %d", sql_errno));
973
  if (!(variables.option_bits & OPTION_SQL_NOTES))
Marc Alff's avatar
Marc Alff committed
974
    DBUG_VOID_RETURN;
975
  const char* msg= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
976 977
  (void) raise_condition(sql_errno,
                         NULL,
978
                         Sql_condition::WARN_LEVEL_NOTE,
Marc Alff's avatar
Marc Alff committed
979 980 981 982 983 984 985 986 987 988
                         msg);
  DBUG_VOID_RETURN;
}

void THD::raise_note_printf(uint sql_errno, ...)
{
  va_list args;
  char    ebuff[MYSQL_ERRMSG_SIZE];
  DBUG_ENTER("THD::raise_note_printf");
  DBUG_PRINT("enter",("code: %u", sql_errno));
989
  if (!(variables.option_bits & OPTION_SQL_NOTES))
Marc Alff's avatar
Marc Alff committed
990
    DBUG_VOID_RETURN;
991
  const char* format= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
992 993 994 995 996
  va_start(args, sql_errno);
  my_vsnprintf(ebuff, sizeof(ebuff), format, args);
  va_end(args);
  (void) raise_condition(sql_errno,
                         NULL,
997
                         Sql_condition::WARN_LEVEL_NOTE,
Marc Alff's avatar
Marc Alff committed
998 999 1000 1001
                         ebuff);
  DBUG_VOID_RETURN;
}

1002
Sql_condition* THD::raise_condition(uint sql_errno,
1003 1004 1005 1006
                                    const char* sqlstate,
                                    Sql_condition::enum_warning_level level,
                                    const Sql_user_condition_identity &ucid,
                                    const char* msg)
Marc Alff's avatar
Marc Alff committed
1007
{
1008 1009
  Diagnostics_area *da= get_stmt_da();
  Sql_condition *cond= NULL;
Marc Alff's avatar
Marc Alff committed
1010
  DBUG_ENTER("THD::raise_condition");
1011
  DBUG_ASSERT(level < Sql_condition::WARN_LEVEL_END);
Marc Alff's avatar
Marc Alff committed
1012

1013
  if (!(variables.option_bits & OPTION_SQL_NOTES) &&
1014
      (level == Sql_condition::WARN_LEVEL_NOTE))
Marc Alff's avatar
Marc Alff committed
1015 1016
    DBUG_RETURN(NULL);

1017
  da->opt_clear_warning_info(query_id);
Marc Alff's avatar
Marc Alff committed
1018 1019 1020 1021 1022 1023 1024 1025 1026

  /*
    TODO: replace by DBUG_ASSERT(sql_errno != 0) once all bugs similar to
    Bug#36768 are fixed: a SQL condition must have a real (!=0) error number
    so that it can be caught by handlers.
  */
  if (sql_errno == 0)
    sql_errno= ER_UNKNOWN_ERROR;
  if (msg == NULL)
1027
    msg= ER_THD(this, sql_errno);
Marc Alff's avatar
Marc Alff committed
1028 1029 1030
  if (sqlstate == NULL)
   sqlstate= mysql_errno_to_sqlstate(sql_errno);

1031
  if ((level == Sql_condition::WARN_LEVEL_WARN) &&
Marc Alff's avatar
Marc Alff committed
1032 1033 1034 1035 1036 1037
      really_abort_on_warning())
  {
    /*
      FIXME:
      push_warning and strict SQL_MODE case.
    */
1038
    level= Sql_condition::WARN_LEVEL_ERROR;
Marc Alff's avatar
Marc Alff committed
1039 1040
  }

1041 1042 1043 1044
  if (handle_condition(sql_errno, sqlstate, &level, msg, &cond))
    DBUG_RETURN(cond);

  switch (level) {
1045 1046
  case Sql_condition::WARN_LEVEL_NOTE:
  case Sql_condition::WARN_LEVEL_WARN:
Marc Alff's avatar
Marc Alff committed
1047 1048
    got_warning= 1;
    break;
1049
  case Sql_condition::WARN_LEVEL_ERROR:
Marc Alff's avatar
Marc Alff committed
1050
    break;
1051 1052 1053
  case Sql_condition::WARN_LEVEL_END:
    /* Impossible */
    break;
Marc Alff's avatar
Marc Alff committed
1054 1055
  }

1056
  if (level == Sql_condition::WARN_LEVEL_ERROR)
Marc Alff's avatar
Marc Alff committed
1057
  {
1058 1059
    mysql_audit_general(this, MYSQL_AUDIT_GENERAL_ERROR, sql_errno, msg);

Marc Alff's avatar
Marc Alff committed
1060 1061
    is_slave_error=  1; // needed to catch query errors during replication

1062
    if (!da->is_error())
Marc Alff's avatar
Marc Alff committed
1063
    {
Sergei Golubchik's avatar
Sergei Golubchik committed
1064
      set_row_count_func(-1);
1065
      da->set_error_status(sql_errno, msg, sqlstate, ucid, cond);
Marc Alff's avatar
Marc Alff committed
1066 1067 1068
    }
  }

1069
  query_cache_abort(this, &query_cache_tls);
Marc Alff's avatar
Marc Alff committed
1070

1071 1072 1073 1074 1075
  /* 
     Avoid pushing a condition for fatal out of memory errors as this will 
     require memory allocation and therefore might fail. Non fatal out of 
     memory errors can occur if raised by SIGNAL/RESIGNAL statement.
  */
1076 1077
  if (likely(!(is_fatal_error && (sql_errno == EE_OUTOFMEMORY ||
                                  sql_errno == ER_OUTOFMEMORY))))
1078
  {
1079
    cond= da->push_warning(this, sql_errno, sqlstate, level, ucid, msg);
1080
  }
Marc Alff's avatar
Marc Alff committed
1081 1082
  DBUG_RETURN(cond);
}
1083

1084
extern "C"
1085
void *thd_alloc(MYSQL_THD thd, size_t size)
1086 1087 1088 1089 1090
{
  return thd->alloc(size);
}

extern "C"
1091
void *thd_calloc(MYSQL_THD thd, size_t size)
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
{
  return thd->calloc(size);
}

extern "C"
char *thd_strdup(MYSQL_THD thd, const char *str)
{
  return thd->strdup(str);
}

extern "C"
1103
char *thd_strmake(MYSQL_THD thd, const char *str, size_t size)
1104 1105 1106 1107 1108
{
  return thd->strmake(str, size);
}

extern "C"
1109
LEX_CSTRING *thd_make_lex_string(THD *thd, LEX_CSTRING *lex_str,
1110
                                const char *str, size_t size,
1111 1112
                                int allocate_lex_string)
{
1113
  return allocate_lex_string ? thd->make_clex_string(str, size)
1114
                             : thd->make_lex_string(lex_str, str, size);
1115 1116 1117
}

extern "C"
1118
void *thd_memdup(MYSQL_THD thd, const void* str, size_t size)
1119 1120 1121 1122
{
  return thd->memdup(str, size);
}

1123
extern "C"
1124 1125 1126 1127
void thd_get_xid(const MYSQL_THD thd, MYSQL_XID *xid)
{
  *xid = *(MYSQL_XID *) &thd->transaction.xid_state.xid;
}
unknown's avatar
unknown committed
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

extern "C"
my_time_t thd_TIME_to_gmt_sec(MYSQL_THD thd, const MYSQL_TIME *ltime,
                              unsigned int *errcode)
{
  Time_zone *tz= thd ? thd->variables.time_zone :
                       global_system_variables.time_zone;
  return tz->TIME_to_gmt_sec(ltime, errcode);
}


extern "C"
void thd_gmt_sec_to_TIME(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t)
{
  Time_zone *tz= thd ? thd->variables.time_zone :
                       global_system_variables.time_zone;
  tz->gmt_sec_to_TIME(ltime, t);
}


1149 1150 1151 1152 1153
#ifdef _WIN32
extern "C"   THD *_current_thd_noinline(void)
{
  return my_pthread_getspecific_ptr(THD*,THR_THD);
}
1154 1155 1156 1157 1158 1159

extern "C" my_thread_id next_thread_id_noinline()
{
#undef next_thread_id
  return next_thread_id();
}
1160
#endif
Monty's avatar
Monty committed
1161

1162

1163
const Type_handler *THD::type_handler_for_datetime() const
1164 1165 1166 1167 1168 1169 1170
{
  if (opt_mysql56_temporal_format)
    return &type_handler_datetime2;
  return &type_handler_datetime;
}


unknown's avatar
unknown committed
1171 1172 1173 1174
/*
  Init common variables that has to be reset on start and on change_user
*/

1175
void THD::init()
unknown's avatar
unknown committed
1176
{
1177
  DBUG_ENTER("thd::init");
1178
  mysql_mutex_lock(&LOCK_global_system_variables);
unknown's avatar
unknown committed
1179
  plugin_thdvar_init(this);
1180
  /*
1181 1182
    plugin_thd_var_init() sets variables= global_system_variables, which
    has reset variables.pseudo_thread_id to 0. We need to correct it here to
1183 1184 1185
    avoid temporary tables replication failure.
  */
  variables.pseudo_thread_id= thread_id;
1186 1187

  variables.default_master_connection.str= default_master_connection_buff;
1188
  ::strmake(default_master_connection_buff,
1189 1190
            global_system_variables.default_master_connection.str,
            variables.default_master_connection.length);
1191
  mysql_mutex_unlock(&LOCK_global_system_variables);
1192

1193 1194
  user_time.val= start_time= start_time_sec_part= 0;

unknown's avatar
unknown committed
1195
  server_status= SERVER_STATUS_AUTOCOMMIT;
1196 1197
  if (variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)
    server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES;
1198 1199
  if (variables.sql_mode & MODE_ANSI_QUOTES)
    server_status|= SERVER_STATUS_ANSI_QUOTES;
1200

1201 1202
  transaction.all.modified_non_trans_table=
    transaction.stmt.modified_non_trans_table= FALSE;
1203 1204 1205
  transaction.all.m_unsafe_rollback_flags=
    transaction.stmt.m_unsafe_rollback_flags= 0;

unknown's avatar
unknown committed
1206
  open_options=ha_open_options;
1207 1208 1209
  update_lock_default= (variables.low_priority_updates ?
			TL_WRITE_LOW_PRIORITY :
			TL_WRITE);
1210
  tx_isolation= (enum_tx_isolation) variables.tx_isolation;
1211
  tx_read_only= variables.tx_read_only;
1212
  update_charset();             // plugin_thd_var() changed character sets
1213
  reset_current_stmt_binlog_format_row();
1214
  reset_binlog_local_stmt_filter();
1215
  set_status_var_init();
1216
  status_var.max_local_memory_used= status_var.local_memory_used;
1217
  bzero((char *) &org_status_var, sizeof(org_status_var));
Monty's avatar
Monty committed
1218
  status_in_global= 0;
1219
  start_bytes_received= 0;
1220
  m_last_commit_gtid.seq_no= 0;
1221
  last_stmt= NULL;
Monty's avatar
Monty committed
1222 1223 1224 1225 1226 1227
  /* Reset status of last insert id */
  arg_of_last_insert_id_function= FALSE;
  stmt_depends_on_first_successful_insert_id_in_prev_stmt= FALSE;
  first_successful_insert_id_in_prev_stmt= 0;
  first_successful_insert_id_in_prev_stmt_for_binlog= 0;
  first_successful_insert_id_in_cur_stmt= 0;
1228 1229 1230
#ifdef WITH_WSREP
  wsrep_exec_mode= wsrep_applier ? REPL_RECV :  LOCAL_STATE;
  wsrep_conflict_state= NO_CONFLICT;
1231
  wsrep_thd_set_query_state(this, QUERY_IDLE);
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  wsrep_last_query_id= 0;
  wsrep_trx_meta.gtid= WSREP_GTID_UNDEFINED;
  wsrep_trx_meta.depends_on= WSREP_SEQNO_UNDEFINED;
  wsrep_converted_lock_session= false;
  wsrep_retry_counter= 0;
  wsrep_rgi= NULL;
  wsrep_PA_safe= true;
  wsrep_consistency_check = NO_CONSISTENCY_CHECK;
  wsrep_mysql_replicated  = 0;
  wsrep_TOI_pre_query     = NULL;
  wsrep_TOI_pre_query_len = 0;
1243
  wsrep_sync_wait_gtid    = WSREP_GTID_UNDEFINED;
1244
  wsrep_affected_rows     = 0;
1245 1246
  wsrep_replicate_GTID    = false;
  wsrep_skip_wsrep_GTID   = false;
1247
  wsrep_split_flag        = false;
1248
#endif /* WITH_WSREP */
1249

1250 1251 1252 1253
  if (variables.sql_log_bin)
    variables.option_bits|= OPTION_BIN_LOG;
  else
    variables.option_bits&= ~OPTION_BIN_LOG;
1254

1255 1256
  variables.sql_log_bin_off= 0;

1257 1258 1259 1260
  select_commands= update_commands= other_commands= 0;
  /* Set to handle counting of aborted connections */
  userstat_running= opt_userstat_running;
  last_global_update_time= current_connect_time= time(NULL);
1261 1262 1263 1264
#if defined(ENABLED_DEBUG_SYNC)
  /* Initialize the Debug Sync Facility. See debug_sync.cc. */
  debug_sync_init_thread(this);
#endif /* defined(ENABLED_DEBUG_SYNC) */
1265

1266
#ifndef EMBEDDED_LIBRARY
1267
  session_tracker.enable(this);
1268
#endif //EMBEDDED_LIBRARY
1269

1270
  apc_target.init(&LOCK_thd_kill);
1271
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1272 1273
}

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

bool THD::restore_from_local_lex_to_old_lex(LEX *oldlex)
{
  DBUG_ASSERT(lex->sphead);
  if (lex->sphead->merge_lex(this, oldlex, lex))
    return true;
  lex= oldlex;
  return false;
}


1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
/* Updates some status variables to be used by update_global_user_stats */

void THD::update_stats(void)
{
  /* sql_command == SQLCOM_END in case of parse errors or quit */
  if (lex->sql_command != SQLCOM_END)
  {
    /* A SQL query. */
    if (lex->sql_command == SQLCOM_SELECT)
      select_commands++;
1295
    else if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
    {
      /* Ignore 'SHOW ' commands */
    }
    else if (is_update_query(lex->sql_command))
      update_commands++;
    else
      other_commands++;
  }
}


void THD::update_all_stats()
{
  ulonglong end_cpu_time, end_utime;
  double busy_time, cpu_time;

  /* This is set at start of query if opt_userstat_running was set */
  if (!userstat_running)
    return;

  end_cpu_time= my_getcputime();
1317 1318
  end_utime=    microsecond_interval_timer();
  busy_time= (end_utime - start_utime) / 1000000.0;
1319 1320 1321 1322 1323 1324 1325
  cpu_time=  (end_cpu_time - start_cpu_time) / 10000000.0;
  /* In case there are bad values, 2629743 is the #seconds in a month. */
  if (cpu_time > 2629743.0)
    cpu_time= 0;
  status_var_add(status_var.cpu_time, cpu_time);
  status_var_add(status_var.busy_time, busy_time);

1326 1327
  update_global_user_stats(this, TRUE, my_time(0));
  // Has to be updated after update_global_user_stats()
1328
  userstat_running= 0;
unknown's avatar
unknown committed
1329 1330
}

1331

1332 1333 1334 1335 1336 1337 1338 1339
/*
  Init THD for query processing.
  This has to be called once before we call mysql_parse.
  See also comments in sql_class.h.
*/

void THD::init_for_queries()
{
1340
  set_time(); 
1341
  ha_enable_transaction(this,TRUE);
1342

unknown's avatar
unknown committed
1343
  reset_root_defaults(mem_root, variables.query_alloc_block_size,
1344 1345 1346 1347
                      variables.query_prealloc_size);
  reset_root_defaults(&transaction.mem_root,
                      variables.trans_alloc_block_size,
                      variables.trans_prealloc_size);
1348
  transaction.xid_state.xid.null();
1349 1350 1351
}


unknown's avatar
unknown committed
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
/*
  Do what's needed when one invokes change user

  SYNOPSIS
    change_user()

  IMPLEMENTATION
    Reset all resources that are connection specific
*/


void THD::change_user(void)
{
Monty's avatar
Monty committed
1365 1366
  if (!status_in_global)                        // Reset in init()
    add_status_to_global();
1367

Monty's avatar
Monty committed
1368 1369
  if (!cleanup_done)
    cleanup();
unknown's avatar
unknown committed
1370
  cleanup_done= 0;
Monty's avatar
Monty committed
1371 1372
  reset_killed();
  thd_clear_errors(this);
1373 1374 1375 1376 1377

  /* Clear warnings. */
  if (!get_stmt_da()->is_warning_info_empty())
    get_stmt_da()->clear_warning_info(0);

unknown's avatar
unknown committed
1378
  init();
1379
  stmt_map.reset();
Konstantin Osipov's avatar
Konstantin Osipov committed
1380 1381 1382
  my_hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
               (my_hash_get_key) get_var_key,
               (my_hash_free_key) free_user_var, 0);
1383 1384 1385
  my_hash_init(&sequences, system_charset_info, SEQUENCES_HASH_SIZE, 0, 0,
               (my_hash_get_key) get_sequence_last_key,
               (my_hash_free_key) free_sequence_last, HASH_THREAD_SPECIFIC);
1386 1387
  sp_cache_clear(&sp_proc_cache);
  sp_cache_clear(&sp_func_cache);
1388 1389
  sp_cache_clear(&sp_package_spec_cache);
  sp_cache_clear(&sp_package_body_cache);
unknown's avatar
unknown committed
1390 1391
}

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
/**
   Change default database

   @note This is coded to have as few instructions as possible under
   LOCK_thd_data
*/

bool THD::set_db(const LEX_CSTRING *new_db)
{
  bool result= 0;
  /*
    Acquiring mutex LOCK_thd_data as we either free the memory allocated
    for the database and reallocating the memory for the new db or memcpy
    the new_db to the db.
  */
  /* Do not reallocate memory if current chunk is big enough. */
  if (db.str && new_db->str && db.length >= new_db->length)
  {
    mysql_mutex_lock(&LOCK_thd_data);
    db.length= new_db->length;
    memcpy((char*) db.str, new_db->str, new_db->length+1);
    mysql_mutex_unlock(&LOCK_thd_data);
  }
  else
  {
    const char *org_db= db.str;
    const char *tmp= NULL;
    if (new_db->str)
    {
      if (!(tmp= my_strndup(new_db->str, new_db->length, MYF(MY_WME | ME_FATALERROR))))
        result= 1;
    }

    mysql_mutex_lock(&LOCK_thd_data);
    db.str= tmp;
    db.length= tmp ? new_db->length : 0;
    mysql_mutex_unlock(&LOCK_thd_data);
    my_free((char*) org_db);
  }
  PSI_CALL_set_thread_db(db.str, (int) db.length);
  return result;
}


/**
   Set the current database

   @param new_db     a pointer to the new database name.
   @param new_db_len length of the new database name.

   @note This operation just sets {db, db_length}. Switching the current
   database usually involves other actions, like switching other database
   attributes including security context. In the future, this operation
   will be made private and more convenient interface will be provided.
*/

void THD::reset_db(const LEX_CSTRING *new_db)
{
  if (new_db->str != db.str || new_db->length != db.length)
  {
    if (db.str != 0)
      DBUG_PRINT("QQ", ("Overwriting: %p", db.str));
    mysql_mutex_lock(&LOCK_thd_data);
    db= *new_db;
    mysql_mutex_unlock(&LOCK_thd_data);
    PSI_CALL_set_thread_db(db.str, (int) db.length);
  }
}

unknown's avatar
unknown committed
1461

unknown's avatar
unknown committed
1462 1463
/* Do operations that may take a long time */

1464
void THD::cleanup(void)
unknown's avatar
unknown committed
1465
{
unknown's avatar
unknown committed
1466
  DBUG_ENTER("THD::cleanup");
unknown's avatar
unknown committed
1467 1468
  DBUG_ASSERT(cleanup_done == 0);

1469
  set_killed(KILL_CONNECTION);
unknown's avatar
unknown committed
1470
#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
1471 1472 1473 1474
  if (transaction.xid_state.xa_state == XA_PREPARED)
  {
#error xid_state in the cache should be replaced by the allocated value
  }
unknown's avatar
unknown committed
1475
#endif
1476

1477
  mysql_ha_cleanup(this);
1478
  locked_tables_list.unlock_locked_tables(this);
1479

1480
  delete_dynamic(&user_var_events);
1481
  close_temporary_tables();
1482 1483

  transaction.xid_state.xa_state= XA_NOTR;
1484
  transaction.xid_state.rm_error= 0;
1485
  trans_rollback(this);
1486
  xid_cache_delete(this, &transaction.xid_state);
1487

1488
  DBUG_ASSERT(open_tables == NULL);
1489 1490 1491 1492 1493 1494
  /*
    If the thread was in the middle of an ongoing transaction (rolled
    back a few lines above) or under LOCK TABLES (unlocked the tables
    and left the mode a few lines above), there will be outstanding
    metadata locks. Release them.
  */
1495
  mdl_context.release_transactional_locks();
1496

1497 1498 1499 1500
  /* Release the global read lock, if acquired. */
  if (global_read_lock.is_acquired())
    global_read_lock.unlock_global_read_lock(this);

1501 1502 1503 1504 1505
  if (user_connect)
  {
    decrease_user_connections(user_connect);
    user_connect= 0;                            // Safety
  }
1506
  wt_thd_destroy(&transaction.wt);
1507

1508 1509 1510 1511 1512
#if defined(ENABLED_DEBUG_SYNC)
  /* End the Debug Sync Facility. See debug_sync.cc. */
  debug_sync_end_thread(this);
#endif /* defined(ENABLED_DEBUG_SYNC) */

Konstantin Osipov's avatar
Konstantin Osipov committed
1513
  my_hash_free(&user_vars);
1514
  my_hash_free(&sequences);
1515
  sp_cache_clear(&sp_proc_cache);
1516
  sp_cache_clear(&sp_func_cache);
1517 1518
  sp_cache_clear(&sp_package_spec_cache);
  sp_cache_clear(&sp_package_body_cache);
Monty's avatar
Monty committed
1519 1520
  auto_inc_intervals_forced.empty();
  auto_inc_intervals_in_cur_stmt_for_binlog.empty();
1521

1522
  mysql_ull_cleanup(this);
1523
  stmt_map.reset();
1524 1525
  /* All metadata locks must have been released by now. */
  DBUG_ASSERT(!mdl_context.has_locks());
1526

1527
  apc_target.destroy();
1528 1529 1530 1531
#ifdef HAVE_REPLICATION
  unregister_slave(this, true, true);
#endif

unknown's avatar
unknown committed
1532 1533 1534 1535
  cleanup_done=1;
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
1536

Monty's avatar
Monty committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
/*
  Free all connection related resources associated with a THD.
  This is used when we put a thread into the thread cache.
  After this call should either call ~THD or reset_for_reuse() depending on
  circumstances.
*/

void THD::free_connection()
{
  DBUG_ASSERT(free_connection_done == 0);
1547
  my_free(const_cast<char*>(db.str));
1548
  db= null_clex_str;
Monty's avatar
Monty committed
1549 1550 1551 1552 1553 1554
#ifndef EMBEDDED_LIBRARY
  if (net.vio)
    vio_delete(net.vio);
  net.vio= 0;
  net_end(&net);
#endif
1555 1556
 if (!cleanup_done)
   cleanup();
Monty's avatar
Monty committed
1557 1558 1559 1560 1561 1562 1563
  ha_close_connection(this);
  plugin_thdvar_cleanup(this);
  mysql_audit_free_thd(this);
  main_security_ctx.destroy();
  /* close all prepared statements, to save memory */
  stmt_map.reset();
  free_connection_done= 1;
1564
#if defined(ENABLED_PROFILING)
Monty's avatar
Monty committed
1565
  profiling.restart();                          // Reset profiling
1566
#endif
Monty's avatar
Monty committed
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
}

/*
  Reset thd for reuse by another connection
  This is only used for user connections, so the following variables doesn't
  have to be reset:
  - Replication (slave) variables.
  - Variables not reset between each statements. See reset_for_next_command.
*/

void THD::reset_for_reuse()
{
  mysql_audit_init_thd(this);
  change_user();                                // Calls cleanup() & init()
  get_stmt_da()->reset_diagnostics_area();
  main_security_ctx.init();  
  failed_com_change_user= 0;
  is_fatal_error= 0;
  client_capabilities= 0;
  peer_port= 0;
  query_name_consts= 0;                         // Safety
  abort_on_warning= 0;
  free_connection_done= 0;
  m_command= COM_CONNECT;
1591
#if defined(ENABLED_PROFILING)
Monty's avatar
Monty committed
1592
  profiling.reset();
1593
#endif
1594 1595
#ifdef SIGNAL_WITH_VIO_CLOSE
  active_vio = 0;
Monty's avatar
Monty committed
1596 1597 1598 1599
#endif
}


unknown's avatar
unknown committed
1600 1601
THD::~THD()
{
1602
  THD *orig_thd= current_thd;
1603
  THD_CHECK_SENTRY(this);
unknown's avatar
unknown committed
1604
  DBUG_ENTER("~THD()");
1605 1606 1607 1608
  /* Check that we have already called thd->unlink() */
  DBUG_ASSERT(prev == 0 && next == 0);
  /* This takes a long time so we should not do this under LOCK_thread_count */
  mysql_mutex_assert_not_owner(&LOCK_thread_count);
1609 1610 1611 1612 1613 1614

  /*
    In error cases, thd may not be current thd. We have to fix this so
    that memory allocation counting is done correctly
  */
  set_current_thd(this);
1615 1616
  if (!status_in_global)
    add_status_to_global();
1617

1618 1619 1620 1621 1622 1623 1624
  /*
    Other threads may have a lock on LOCK_thd_kill to ensure that this
    THD is not deleted while they access it. The following mutex_lock
    ensures that no one else is using this THD and it's now safe to delete
  */
  mysql_mutex_lock(&LOCK_thd_kill);
  mysql_mutex_unlock(&LOCK_thd_kill);
1625

1626 1627 1628
#ifdef WITH_WSREP
  delete wsrep_rgi;
#endif
Monty's avatar
Monty committed
1629 1630
  if (!free_connection_done)
    free_connection();
1631

Konstantin Osipov's avatar
Konstantin Osipov committed
1632
  mdl_context.destroy();
unknown's avatar
unknown committed
1633

1634
  free_root(&transaction.mem_root,MYF(0));
Sergei Golubchik's avatar
Sergei Golubchik committed
1635 1636
  mysql_cond_destroy(&COND_wakeup_ready);
  mysql_mutex_destroy(&LOCK_wakeup_ready);
Marc Alff's avatar
Marc Alff committed
1637
  mysql_mutex_destroy(&LOCK_thd_data);
1638
  mysql_mutex_destroy(&LOCK_thd_kill);
1639
#ifdef DBUG_ASSERT_EXISTS
unknown's avatar
unknown committed
1640
  dbug_sentry= THD_SENTRY_GONE;
1641
#endif  
1642
#ifndef EMBEDDED_LIBRARY
1643 1644 1645 1646 1647
  if (rgi_fake)
  {
    delete rgi_fake;
    rgi_fake= NULL;
  }
1648
  if (rli_fake)
1649
  {
1650
    delete rli_fake;
1651 1652
    rli_fake= NULL;
  }
1653
  
1654 1655
  if (rgi_slave)
    rgi_slave->cleanup_after_session();
1656
  my_free(semisync_info);
1657
#endif
1658
  main_lex.free_set_stmt_mem_root();
1659
  free_root(&main_mem_root, MYF(0));
Sergei Golubchik's avatar
Sergei Golubchik committed
1660
  my_free(m_token_array);
1661
  main_da.free_memory();
1662 1663
  if (tdc_hash_pins)
    lf_hash_put_pins(tdc_hash_pins);
1664 1665
  if (xid_hash_pins)
    lf_hash_put_pins(xid_hash_pins);
1666
  /* Ensure everything is freed */
1667
  status_var.local_memory_used-= sizeof(THD);
1668 1669

  /* trick to make happy memory accounting system */
1670
#ifndef EMBEDDED_LIBRARY
1671
  session_tracker.sysvars.deinit();
1672
#endif //EMBEDDED_LIBRARY
1673

1674
  if (status_var.local_memory_used != 0)
1675
  {
1676
    DBUG_PRINT("error", ("memory_used: %lld", status_var.local_memory_used));
1677 1678 1679
    SAFEMALLOC_REPORT_MEMORY(thread_id);
    DBUG_ASSERT(status_var.local_memory_used == 0 ||
                !debug_assert_on_not_freed_memory);
1680
  }
1681
  update_global_memory_status(status_var.global_memory_used);
1682
  set_current_thd(orig_thd == this ? 0 : orig_thd);
Sergei Golubchik's avatar
Sergei Golubchik committed
1683
  dec_thread_count();
unknown's avatar
unknown committed
1684 1685 1686
  DBUG_VOID_RETURN;
}

1687

1688
/*
unknown's avatar
unknown committed
1689 1690 1691 1692 1693 1694
  Add all status variables to another status variable array

  SYNOPSIS
   add_to_status()
   to_var       add to this array
   from_var     from this array
1695 1696

  NOTES
1697
    This function assumes that all variables at start are long/ulong and
1698
    other types are handled explicitly
1699 1700 1701 1702
*/

void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var)
{
1703
  ulong *end= (ulong*) ((uchar*) to_var +
1704
                        offsetof(STATUS_VAR, last_system_status_var) +
1705 1706 1707 1708 1709
			sizeof(ulong));
  ulong *to= (ulong*) to_var, *from= (ulong*) from_var;

  while (to != end)
    *(to++)+= *(from++);
1710

1711
  /* Handle the not ulong variables. See end of system_status_var */
1712
  to_var->bytes_received+=      from_var->bytes_received;
1713
  to_var->bytes_sent+=          from_var->bytes_sent;
1714 1715
  to_var->rows_read+=           from_var->rows_read;
  to_var->rows_sent+=           from_var->rows_sent;
1716
  to_var->rows_tmp_read+=       from_var->rows_tmp_read;
1717
  to_var->binlog_bytes_written+= from_var->binlog_bytes_written;
1718 1719
  to_var->cpu_time+=            from_var->cpu_time;
  to_var->busy_time+=           from_var->busy_time;
1720 1721 1722
  to_var->table_open_cache_hits+= from_var->table_open_cache_hits;
  to_var->table_open_cache_misses+= from_var->table_open_cache_misses;
  to_var->table_open_cache_overflows+= from_var->table_open_cache_overflows;
1723 1724 1725 1726 1727

  /*
    Update global_memory_used. We have to do this with atomic_add as the
    global value can change outside of LOCK_status.
  */
1728 1729 1730 1731 1732
  if (to_var == &global_status_var)
  {
    DBUG_PRINT("info", ("global memory_used: %lld  size: %lld",
                        (longlong) global_status_var.global_memory_used,
                        (longlong) from_var->global_memory_used));
Sergei Golubchik's avatar
Sergei Golubchik committed
1733
    update_global_memory_status(from_var->global_memory_used);
1734
  }
Sergei Golubchik's avatar
Sergei Golubchik committed
1735 1736
  else
   to_var->global_memory_used+= from_var->global_memory_used;
1737 1738
}

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
/*
  Add the difference between two status variable arrays to another one.

  SYNOPSIS
    add_diff_to_status
    to_var       add to this array
    from_var     from this array
    dec_var      minus this array
  
  NOTE
1749
    This function assumes that all variables at start are long/ulong and
1750
    other types are handled explicitly
1751 1752 1753 1754 1755
*/

void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
                        STATUS_VAR *dec_var)
{
1756
  ulong *end= (ulong*) ((uchar*) to_var + offsetof(STATUS_VAR,
1757 1758 1759 1760 1761 1762
						  last_system_status_var) +
			sizeof(ulong));
  ulong *to= (ulong*) to_var, *from= (ulong*) from_var, *dec= (ulong*) dec_var;

  while (to != end)
    *(to++)+= *(from++) - *(dec++);
1763

Sergei Golubchik's avatar
Sergei Golubchik committed
1764 1765 1766
  to_var->bytes_received+=       from_var->bytes_received -
                                 dec_var->bytes_received;
  to_var->bytes_sent+=           from_var->bytes_sent - dec_var->bytes_sent;
1767 1768
  to_var->rows_read+=            from_var->rows_read - dec_var->rows_read;
  to_var->rows_sent+=            from_var->rows_sent - dec_var->rows_sent;
1769
  to_var->rows_tmp_read+=        from_var->rows_tmp_read - dec_var->rows_tmp_read;
Sergei Golubchik's avatar
Sergei Golubchik committed
1770 1771 1772 1773
  to_var->binlog_bytes_written+= from_var->binlog_bytes_written -
                                 dec_var->binlog_bytes_written;
  to_var->cpu_time+=             from_var->cpu_time - dec_var->cpu_time;
  to_var->busy_time+=            from_var->busy_time - dec_var->busy_time;
1774 1775 1776 1777 1778 1779
  to_var->table_open_cache_hits+= from_var->table_open_cache_hits -
                                  dec_var->table_open_cache_hits;
  to_var->table_open_cache_misses+= from_var->table_open_cache_misses -
                                    dec_var->table_open_cache_misses;
  to_var->table_open_cache_overflows+= from_var->table_open_cache_overflows -
                                       dec_var->table_open_cache_overflows;
1780 1781 1782 1783 1784

  /*
    We don't need to accumulate memory_used as these are not reset or used by
    the calling functions.  See execute_show_status().
  */
1785 1786
}

1787 1788 1789 1790 1791 1792 1793 1794
#define SECONDS_TO_WAIT_FOR_KILL 2
#if !defined(__WIN__) && defined(HAVE_SELECT)
/* my_sleep() can wait for sub second times */
#define WAIT_FOR_KILL_TRY_TIMES 20
#else
#define WAIT_FOR_KILL_TRY_TIMES 2
#endif

1795

1796 1797 1798 1799 1800 1801 1802
/**
  Awake a thread.

  @param[in]  state_to_set    value for THD::killed

  This is normally called from another thread's THD object.

1803
  @note Do always call this while holding LOCK_thd_kill.
Monty's avatar
Monty committed
1804
        NOT_KILLED is used to awake a thread for a slave
1805 1806
*/

1807
void THD::awake_no_mutex(killed_state state_to_set)
1808
{
1809
  DBUG_ENTER("THD::awake");
Monty's avatar
Monty committed
1810 1811
  DBUG_PRINT("enter", ("this: %p current_thd: %p  state: %d",
                       this, current_thd, (int) state_to_set));
1812
  THD_CHECK_SENTRY(this);
1813
  mysql_mutex_assert_owner(&LOCK_thd_kill);
1814

Sergei Golubchik's avatar
Sergei Golubchik committed
1815
  print_aborted_warning(3, "KILLED");
Sergei Golubchik's avatar
Sergei Golubchik committed
1816

Monty's avatar
Monty committed
1817 1818 1819 1820 1821 1822 1823
  /*
    Don't degrade killed state, for example from a KILL_CONNECTION to
    STATEMENT TIMEOUT
  */
  if (killed >= KILL_CONNECTION)
    state_to_set= killed;

1824
  set_killed_no_mutex(state_to_set);
1825

Sergei Golubchik's avatar
Sergei Golubchik committed
1826
  if (state_to_set >= KILL_CONNECTION || state_to_set == NOT_KILLED)
1827
  {
1828
#ifdef SIGNAL_WITH_VIO_CLOSE
1829
    if (this != current_thd)
1830
    {
1831 1832
      if(active_vio)
        vio_shutdown(active_vio, SHUT_RDWR);
1833
    }
1834
#endif
1835 1836 1837 1838 1839 1840

    /* Mark the target thread's alarm request expired, and signal alarm. */
    thr_alarm_kill(thread_id);

    /* Send an event to the scheduler that a thread should be killed. */
    if (!slave_thread)
Sergei Golubchik's avatar
Sergei Golubchik committed
1841
      MYSQL_CALLBACK(scheduler, post_kill_notification, (this));
1842
  }
1843

1844 1845
  /* Interrupt target waiting inside a storage engine. */
  if (state_to_set != NOT_KILLED)
1846
    ha_kill_query(this, thd_kill_level(this));
1847

1848
  /* Broadcast a condition to kick the target if it is waiting on it. */
1849
  if (mysys_var)
unknown's avatar
unknown committed
1850
  {
Marc Alff's avatar
Marc Alff committed
1851
    mysql_mutex_lock(&mysys_var->mutex);
unknown's avatar
unknown committed
1852 1853
    if (!system_thread)		// Don't abort locks
      mysys_var->abort=1;
Monty's avatar
Monty committed
1854

unknown's avatar
unknown committed
1855 1856 1857 1858 1859
    /*
      This broadcast could be up in the air if the victim thread
      exits the cond in the time between read and broadcast, but that is
      ok since all we want to do is to make the victim thread get out
      of waiting on current_cond.
1860 1861 1862 1863 1864
      If we see a non-zero current_cond: it cannot be an old value (because
      then exit_cond() should have run and it can't because we have mutex); so
      it is the true value but maybe current_mutex is not yet non-zero (we're
      in the middle of enter_cond() and there is a "memory order
      inversion"). So we test the mutex too to not lock 0.
1865

1866
      Note that there is a small chance we fail to kill. If victim has locked
1867 1868 1869 1870 1871
      current_mutex, but hasn't yet entered enter_cond() (which means that
      current_cond and current_mutex are 0), then the victim will not get
      a signal and it may wait "forever" on the cond (until
      we issue a second KILL or the status it's waiting for happens).
      It's true that we have set its thd->killed but it may not
1872
      see it immediately and so may have time to reach the cond_wait().
1873 1874 1875 1876 1877

      However, where possible, we test for killed once again after
      enter_cond(). This should make the signaling as safe as possible.
      However, there is still a small chance of failure on platforms with
      instruction or memory write reordering.
Sergei Golubchik's avatar
Sergei Golubchik committed
1878

1879 1880 1881 1882
      We have to do the loop with trylock, because if we would use
      pthread_mutex_lock(), we can cause a deadlock as we are here locking
      the mysys_var->mutex and mysys_var->current_mutex in a different order
      than in the thread we are trying to kill.
Sergey Petrunya's avatar
Sergey Petrunya committed
1883
      We only sleep for 2 seconds as we don't want to have LOCK_thd_data
1884 1885 1886 1887 1888 1889 1890
      locked too long time.

      There is a small change we may not succeed in aborting a thread that
      is not yet waiting for a mutex, but as this happens only for a
      thread that was doing something else when the kill was issued and
      which should detect the kill flag before it starts to wait, this
      should be good enough.
unknown's avatar
unknown committed
1891
    */
1892
    if (mysys_var->current_cond && mysys_var->current_mutex)
1893
    {
1894 1895 1896
      uint i;
      for (i= 0; i < WAIT_FOR_KILL_TRY_TIMES * SECONDS_TO_WAIT_FOR_KILL; i++)
      {
Sergei Golubchik's avatar
Sergei Golubchik committed
1897 1898
        int ret= mysql_mutex_trylock(mysys_var->current_mutex);
        mysql_cond_broadcast(mysys_var->current_cond);
1899 1900 1901
        if (!ret)
        {
          /* Signal is sure to get through */
Sergei Golubchik's avatar
Sergei Golubchik committed
1902
          mysql_mutex_unlock(mysys_var->current_mutex);
1903 1904
          break;
        }
1905
        my_sleep(1000000L / WAIT_FOR_KILL_TRY_TIMES);
1906
      }
1907
    }
Marc Alff's avatar
Marc Alff committed
1908
    mysql_mutex_unlock(&mysys_var->mutex);
unknown's avatar
unknown committed
1909
  }
1910
  DBUG_VOID_RETURN;
1911 1912
}

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

/**
  Close the Vio associated this session.

  @remark LOCK_thd_data is taken due to the fact that
          the Vio might be disassociated concurrently.
*/

void THD::disconnect()
{
  Vio *vio= NULL;

1925
  set_killed(KILL_CONNECTION);
1926

1927 1928
  mysql_mutex_lock(&LOCK_thd_data);

1929
#ifdef SIGNAL_WITH_VIO_CLOSE
1930 1931 1932 1933 1934
  /*
    Since a active vio might might have not been set yet, in
    any case save a reference to avoid closing a inexistent
    one or closing the vio twice if there is a active one.
  */
1935 1936 1937
  vio= active_vio;
  close_active_vio();
#endif
1938 1939 1940

  /* Disconnect even if a active vio is not associated. */
  if (net.vio != vio)
1941
    vio_close(net.vio);
1942
  net.thd= 0;                                   // Don't collect statistics
1943 1944 1945 1946 1947

  mysql_mutex_unlock(&LOCK_thd_data);
}


Michael Widenius's avatar
Michael Widenius committed
1948 1949 1950 1951 1952
bool THD::notify_shared_lock(MDL_context_owner *ctx_in_use,
                             bool needs_thr_lock_abort)
{
  THD *in_use= ctx_in_use->get_thd();
  bool signalled= FALSE;
1953 1954
  DBUG_ENTER("THD::notify_shared_lock");
  DBUG_PRINT("enter",("needs_thr_lock_abort: %d", needs_thr_lock_abort));
Michael Widenius's avatar
Michael Widenius committed
1955 1956 1957 1958

  if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
      !in_use->killed)
  {
1959 1960
    /* This code is similar to kill_delayed_threads() */
    DBUG_PRINT("info", ("kill delayed thread"));
1961
    mysql_mutex_lock(&in_use->LOCK_thd_kill);
1962
    if (in_use->killed < KILL_CONNECTION)
1963
      in_use->set_killed_no_mutex(KILL_CONNECTION);
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
    if (in_use->mysys_var)
    {
      mysql_mutex_lock(&in_use->mysys_var->mutex);
      if (in_use->mysys_var->current_cond)
        mysql_cond_broadcast(in_use->mysys_var->current_cond);

      /* Abort if about to wait in thr_upgrade_write_delay_lock */
      in_use->mysys_var->abort= 1;
      mysql_mutex_unlock(&in_use->mysys_var->mutex);
    }
1974
    mysql_mutex_unlock(&in_use->LOCK_thd_kill);
Michael Widenius's avatar
Michael Widenius committed
1975 1976 1977 1978 1979
    signalled= TRUE;
  }

  if (needs_thr_lock_abort)
  {
1980
    bool mutex_released= false;
Michael Widenius's avatar
Michael Widenius committed
1981
    mysql_mutex_lock(&in_use->LOCK_thd_data);
1982
    mysql_mutex_lock(&in_use->LOCK_thd_kill);
1983 1984
    /* If not already dying */
    if (in_use->killed != KILL_CONNECTION_HARD)
Michael Widenius's avatar
Michael Widenius committed
1985
    {
1986 1987 1988
      for (TABLE *thd_table= in_use->open_tables;
           thd_table ;
           thd_table= thd_table->next)
1989
      {
1990 1991 1992 1993 1994 1995 1996 1997 1998
        /*
          Check for TABLE::needs_reopen() is needed since in some
          places we call handler::close() for table instance (and set
          TABLE::db_stat to 0) and do not remove such instances from
          the THD::open_tables for some time, during which other
          thread can see those instances (e.g. see partitioning code).
        */
        if (!thd_table->needs_reopen())
          signalled|= mysql_lock_abort_for_thread(this, thd_table);
1999
      }
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
#ifdef WITH_WSREP
      if (WSREP(this) && wsrep_thd_is_BF(this, false))
      {
        WSREP_DEBUG("notify_shared_lock: BF thread %llu query %s"
                    " victim %llu query %s",
                    this->real_id, wsrep_thd_query(this),
                    in_use->real_id, wsrep_thd_query(in_use));
        wsrep_abort_thd((void *)this, (void *)in_use, false);
        mutex_released= true;
      }
#endif /* WITH_WSREP */
    }
    if (!mutex_released)
    {
      mysql_mutex_unlock(&in_use->LOCK_thd_kill);
      mysql_mutex_unlock(&in_use->LOCK_thd_data);
Michael Widenius's avatar
Michael Widenius committed
2016 2017
    }
  }
2018
  DBUG_RETURN(signalled);
Michael Widenius's avatar
Michael Widenius committed
2019 2020 2021
}


2022 2023 2024
/*
  Get error number for killed state
  Note that the error message can't have any parameters.
2025
  If one needs parameters, one should use THD::killed_err_msg
2026 2027 2028
  See thd::kill_message()
*/

2029
int THD::killed_errno()
2030
{
2031
  DBUG_ENTER("killed_errno");
2032 2033 2034 2035 2036 2037 2038 2039
  DBUG_PRINT("enter", ("killed: %d  killed_errno: %d",
                       killed, killed_err ? killed_err->no: 0));

  /* Ensure that killed_err is not set if we are not killed */
  DBUG_ASSERT(!killed_err || killed != NOT_KILLED);

  if (killed_err)
    DBUG_RETURN(killed_err->no);
2040

2041 2042 2043
  switch (killed) {
  case NOT_KILLED:
  case KILL_HARD_BIT:
2044
    DBUG_RETURN(0);                            // Probably wrong usage
2045 2046
  case KILL_BAD_DATA:
  case KILL_BAD_DATA_HARD:
2047 2048 2049
  case ABORT_QUERY_HARD:
  case ABORT_QUERY:
    DBUG_RETURN(0);                             // Not a real error
2050 2051 2052 2053
  case KILL_CONNECTION:
  case KILL_CONNECTION_HARD:
  case KILL_SYSTEM_THREAD:
  case KILL_SYSTEM_THREAD_HARD:
2054
    DBUG_RETURN(ER_CONNECTION_KILLED);
2055 2056
  case KILL_QUERY:
  case KILL_QUERY_HARD:
2057
    DBUG_RETURN(ER_QUERY_INTERRUPTED);
Monty's avatar
Monty committed
2058 2059 2060
  case KILL_TIMEOUT:
  case KILL_TIMEOUT_HARD:
    DBUG_RETURN(ER_STATEMENT_TIMEOUT);
2061 2062
  case KILL_SERVER:
  case KILL_SERVER_HARD:
2063
    DBUG_RETURN(ER_SERVER_SHUTDOWN);
2064 2065
  case KILL_SLAVE_SAME_ID:
    DBUG_RETURN(ER_SLAVE_SAME_ID);
2066 2067 2068
  case KILL_WAIT_TIMEOUT:
  case KILL_WAIT_TIMEOUT_HARD:
    DBUG_RETURN(ER_NET_READ_INTERRUPTED);
2069
  }
2070
  DBUG_RETURN(0);                               // Keep compiler happy
2071 2072 2073
}


Monty's avatar
Monty committed
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
void THD::reset_killed()
{
  /*
    Resetting killed has to be done under a mutex to ensure
    its not done during an awake() call.
  */
  DBUG_ENTER("reset_killed");
  if (killed != NOT_KILLED)
  {
    mysql_mutex_lock(&LOCK_thd_kill);
    killed= NOT_KILLED;
    killed_err= 0;
    mysql_mutex_unlock(&LOCK_thd_kill);
  }
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
2091 2092
/*
  Remember the location of thread info, the structure needed for
2093
  the structure for the net buffer
unknown's avatar
unknown committed
2094
*/
unknown's avatar
unknown committed
2095 2096 2097

bool THD::store_globals()
{
2098 2099 2100 2101
  /*
    Assert that thread_stack is initialized: it's necessary to be able
    to track stack overrun.
  */
unknown's avatar
unknown committed
2102
  DBUG_ASSERT(thread_stack);
2103

2104
  if (set_current_thd(this))
2105
    return 1;
2106 2107
  /*
    mysys_var is concurrently readable by a killer thread.
2108
    It is protected by LOCK_thd_kill, it is not needed to lock while the
2109 2110 2111 2112 2113 2114
    pointer is changing from NULL not non-NULL. If the kill thread reads
    NULL it doesn't refer to anything, but if it is non-NULL we need to
    ensure that the thread doesn't proceed to assign another thread to
    have the mysys_var reference (which in fact refers to the worker
    threads local storage with key THR_KEY_mysys. 
  */
2115
  mysys_var=my_thread_var;
unknown's avatar
unknown committed
2116
  /*
unknown's avatar
unknown committed
2117 2118
    Let mysqld define the thread id (not mysys)
    This allows us to move THD to different threads if needed.
unknown's avatar
unknown committed
2119
  */
Monty's avatar
Monty committed
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
  mysys_var->id=      thread_id;

  /* thread_dbug_id should not change for a THD */
  if (!thread_dbug_id)
    thread_dbug_id= mysys_var->dbug_id;
  else
  {
    /* This only changes if we are using pool-of-threads */
    mysys_var->dbug_id= thread_dbug_id;
  }
2130
#ifdef __NR_gettid
2131
  os_thread_id= (uint32)syscall(__NR_gettid);
2132 2133 2134
#else
  os_thread_id= 0;
#endif
unknown's avatar
unknown committed
2135
  real_id= pthread_self();                      // For debugging
Sergei Golubchik's avatar
Sergei Golubchik committed
2136 2137
  mysys_var->stack_ends_here= thread_stack +    // for consistency, see libevent_thread_proc
                              STACK_DIRECTION * (long)my_thread_stack_size;
2138 2139 2140 2141
  if (net.vio)
  {
    net.thd= this;
  }
2142 2143 2144 2145
  /*
    We have to call thr_lock_info_init() again here as THD may have been
    created in another thread
  */
Monty's avatar
Monty committed
2146
  thr_lock_info_init(&lock_info, mysys_var);
2147

2148
  return 0;
unknown's avatar
unknown committed
2149 2150
}

2151 2152 2153 2154 2155 2156 2157 2158
/**
   Untie THD from current thread

   Used when using --thread-handling=pool-of-threads
*/

void THD::reset_globals()
{
2159
  mysql_mutex_lock(&LOCK_thd_kill);
2160
  mysys_var= 0;
2161
  mysql_mutex_unlock(&LOCK_thd_kill);
Sergei Golubchik's avatar
Sergei Golubchik committed
2162

2163
  /* Undocking the thread specific data. */
2164
  set_current_thd(0);
2165
  net.thd= 0;
2166 2167
}

2168 2169 2170 2171 2172
/*
  Cleanup after query.

  SYNOPSIS
    THD::cleanup_after_query()
2173

2174
  DESCRIPTION
unknown's avatar
unknown committed
2175
    This function is used to reset thread data to its default state.
2176 2177 2178 2179 2180 2181 2182

  NOTE
    This function is not suitable for setting thread data to some
    non-default values, as there is only one replication thread, so
    different master threads may overwrite data of each other on
    slave.
*/
unknown's avatar
unknown committed
2183

2184 2185
void THD::cleanup_after_query()
{
2186
  DBUG_ENTER("THD::cleanup_after_query");
Sergei Golubchik's avatar
Sergei Golubchik committed
2187 2188 2189

  thd_progress_end(this);

2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
  /*
    Reset rand_used so that detection of calls to rand() will save random 
    seeds if needed by the slave.

    Do not reset rand_used if inside a stored function or trigger because 
    only the call to these operations is logged. Thus only the calling 
    statement needs to detect rand() calls made by its substatements. These
    substatements must not set rand_used to 0 because it would remove the
    detection of rand() by the calling statement. 
  */
2200 2201 2202 2203 2204
  if (!in_sub_stmt) /* stored functions and triggers are a special case */
  {
    /* Forget those values, for next binlogger: */
    stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
    auto_inc_intervals_in_cur_stmt_for_binlog.empty();
2205
    rand_used= 0;
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
#ifndef EMBEDDED_LIBRARY
    /*
      Clean possible unused INSERT_ID events by current statement.
      is_update_query() is needed to ignore SET statements:
        Statements that don't update anything directly and don't
        used stored functions. This is mostly necessary to ignore
        statements in binlog between SET INSERT_ID and DML statement
        which is intended to consume its event (there can be other
        SET statements between them).
    */
2216
    if ((rgi_slave || rli_fake) && is_update_query(lex->sql_command))
2217 2218
      auto_inc_intervals_forced.empty();
#endif
2219
  }
2220 2221 2222 2223 2224 2225 2226 2227
  /*
    Forget the binlog stmt filter for the next query.
    There are some code paths that:
    - do not call THD::decide_logging_format()
    - do call THD::binlog_query(),
    making this reset necessary.
  */
  reset_binlog_local_stmt_filter();
2228
  if (first_successful_insert_id_in_cur_stmt > 0)
2229
  {
2230 2231 2232 2233
    /* set what LAST_INSERT_ID() will return */
    first_successful_insert_id_in_prev_stmt= 
      first_successful_insert_id_in_cur_stmt;
    first_successful_insert_id_in_cur_stmt= 0;
unknown's avatar
unknown committed
2234
    substitute_null_with_insert_id= TRUE;
2235
  }
2236
  arg_of_last_insert_id_function= 0;
2237
  /* Free Items that were created during this execution */
2238
  free_items();
2239 2240
  /* Reset where. */
  where= THD::DEFAULT_WHERE;
2241 2242
  /* reset table map for multi-table update */
  table_map_for_update= 0;
2243
  m_binlog_invoker= INVOKER_NONE;
2244 2245 2246 2247 2248 2249
#ifdef WITH_WSREP
  if (TOTAL_ORDER == wsrep_exec_mode)
  {
    wsrep_exec_mode = LOCAL_STATE;
  }
#endif  /* WITH_WSREP */
2250

2251
#ifndef EMBEDDED_LIBRARY
2252 2253
  if (rgi_slave)
    rgi_slave->cleanup_after_query();
2254
#endif
unknown's avatar
unknown committed
2255

2256 2257
#ifdef WITH_WSREP
  wsrep_sync_wait_gtid= WSREP_GTID_UNDEFINED;
2258 2259
  if (!in_active_multi_stmt_transaction())
    wsrep_affected_rows= 0;
2260 2261
#endif /* WITH_WSREP */

2262
  DBUG_VOID_RETURN;
2263 2264
}

unknown's avatar
unknown committed
2265

unknown's avatar
unknown committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
/*
  Convert a string to another character set

  SYNOPSIS
    convert_string()
    to				Store new allocated string here
    to_cs			New character set for allocated string
    from			String to convert
    from_length			Length of string to convert
    from_cs			Original character set

  NOTES
    to will be 0-terminated to make it easy to pass to system funcs

  RETURN
    0	ok
    1	End of memory.
        In this case to->str will point to 0 and to->length will be 0.
*/

bool THD::convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
2287
			 const char *from, size_t from_length,
unknown's avatar
unknown committed
2288 2289
			 CHARSET_INFO *from_cs)
{
2290
  DBUG_ENTER("THD::convert_string");
2291
  size_t new_length= to_cs->mbmaxlen * from_length;
2292
  uint errors;
2293
  if (unlikely(alloc_lex_string(to, new_length + 1)))
2294
    DBUG_RETURN(true);                          // EOM
unknown's avatar
unknown committed
2295
  to->length= copy_and_convert((char*) to->str, new_length, to_cs,
2296
			       from, from_length, from_cs, &errors);
2297
  to->str[to->length]= 0;                       // Safety
2298
  if (unlikely(errors) && lex->parse_vcol_expr)
2299 2300 2301 2302 2303 2304
  {
    my_error(ER_BAD_DATA, MYF(0),
             ErrConvString(from, from_length, from_cs).ptr(),
             to_cs->csname);
    DBUG_RETURN(true);
  }
2305 2306 2307 2308 2309 2310 2311 2312 2313
  DBUG_RETURN(false);
}


/*
  Convert a string between two character sets.
  dstcs and srccs cannot be &my_charset_bin.
*/
bool THD::convert_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
2314
                      CHARSET_INFO *srccs, const char *src, size_t src_length,
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
                      String_copier *status)
{
  DBUG_ENTER("THD::convert_fix");
  size_t dst_length= dstcs->mbmaxlen * src_length;
  if (alloc_lex_string(dst, dst_length + 1))
    DBUG_RETURN(true);                           // EOM
  dst->length= status->convert_fix(dstcs, (char*) dst->str, dst_length,
                                   srccs, src, src_length, src_length);
  dst->str[dst->length]= 0;                      // Safety
  DBUG_RETURN(false);
}


/*
  Copy or convert a string.
*/
bool THD::copy_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
2332
                   CHARSET_INFO *srccs, const char *src, size_t src_length,
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
                   String_copier *status)
{
  DBUG_ENTER("THD::copy_fix");
  size_t dst_length= dstcs->mbmaxlen * src_length;
  if (alloc_lex_string(dst, dst_length + 1))
    DBUG_RETURN(true);                          // EOM
  dst->length= status->well_formed_copy(dstcs, dst->str, dst_length,
                                        srccs, src, src_length, src_length);
  dst->str[dst->length]= '\0';
  DBUG_RETURN(false);
}


class String_copier_with_error: public String_copier
{
public:
2349
  bool check_errors(CHARSET_INFO *srccs, const char *src, size_t src_length)
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
  {
    if (most_important_error_pos())
    {
      ErrConvString err(src, src_length, &my_charset_bin);
      my_error(ER_INVALID_CHARACTER_STRING, MYF(0), srccs->csname, err.ptr());
      return true;
    }
    return false;
  }
};


bool THD::convert_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
                             CHARSET_INFO *srccs,
2364
                             const char *src, size_t src_length)
2365 2366 2367 2368 2369 2370 2371 2372 2373
{
  String_copier_with_error status;
  return convert_fix(dstcs, dst, srccs, src, src_length, &status) ||
         status.check_errors(srccs, src, src_length);
}


bool THD::copy_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
                          CHARSET_INFO *srccs,
2374
                          const char *src, size_t src_length)
2375 2376 2377 2378
{
  String_copier_with_error status;
  return copy_fix(dstcs, dst, srccs, src, src_length, &status) ||
         status.check_errors(srccs, src, src_length);
unknown's avatar
unknown committed
2379 2380 2381
}


2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
/*
  Convert string from source character set to target character set inplace.

  SYNOPSIS
    THD::convert_string

  DESCRIPTION
    Convert string using convert_buffer - buffer for character set 
    conversion shared between all protocols.

  RETURN
    0   ok
   !0   out of memory
*/

bool THD::convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs)
{
2399
  uint dummy_errors;
2400 2401
  if (unlikely(convert_buffer.copy(s->ptr(), s->length(), from_cs, to_cs,
                                   &dummy_errors)))
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
    return TRUE;
  /* If convert_buffer >> s copying is more efficient long term */
  if (convert_buffer.alloced_length() >= convert_buffer.length() * 2 ||
      !s->is_alloced())
  {
    return s->copy(convert_buffer);
  }
  s->swap(convert_buffer);
  return FALSE;
}

2413

2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
bool THD::check_string_for_wellformedness(const char *str,
                                          size_t length,
                                          CHARSET_INFO *cs) const
{
  size_t wlen= Well_formed_prefix(cs, str, length).length();
  if (wlen < length)
  {
    ErrConvString err(str, length, &my_charset_bin);
    my_error(ER_INVALID_CHARACTER_STRING, MYF(0), cs->csname, err.ptr());
    return true;
  }
  return false;
}


bool THD::to_ident_sys_alloc(Lex_ident_sys_st *to, const Lex_ident_cli_st *ident)
{
  if (ident->is_quoted())
  {
    LEX_CSTRING unquoted;
    if (quote_unescape(&unquoted, ident, ident->quote()))
      return true;
    return charset_is_system_charset ?
           to->copy_sys(this, &unquoted) :
           to->convert(this, &unquoted, charset());
  }
  return charset_is_system_charset ?
         to->copy_sys(this, ident) :
         to->copy_or_convert(this, ident, charset());
}


2446 2447
Item_basic_constant *
THD::make_string_literal(const char *str, size_t length, uint repertoire)
2448
{
2449 2450
  if (!length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
    return new (mem_root) Item_null(this, 0, variables.collation_connection);
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
  if (!charset_is_collation_connection &&
      (repertoire != MY_REPERTOIRE_ASCII ||
       !my_charset_is_ascii_based(variables.collation_connection)))
  {
    LEX_STRING to;
    if (convert_string(&to, variables.collation_connection,
                       str, length, variables.character_set_client))
      return NULL;
    str= to.str;
    length= to.length;
  }
2462
  return new (mem_root) Item_string(this, str, (uint)length,
2463 2464 2465 2466 2467
                                    variables.collation_connection,
                                    DERIVATION_COERCIBLE, repertoire);
}


2468 2469
Item_basic_constant *
THD::make_string_literal_nchar(const Lex_string_with_metadata_st &str)
2470 2471 2472 2473 2474
{
  DBUG_ASSERT(my_charset_is_ascii_based(national_charset_info));
  if (!str.length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
    return new (mem_root) Item_null(this, 0, national_charset_info);

2475
  return new (mem_root) Item_string(this, str.str, (uint)str.length,
2476 2477 2478 2479 2480 2481
                                    national_charset_info,
                                    DERIVATION_COERCIBLE,
                                    str.repertoire());
}


2482 2483 2484
Item_basic_constant *
THD::make_string_literal_charset(const Lex_string_with_metadata_st &str,
                                 CHARSET_INFO *cs)
2485 2486 2487 2488
{
  if (!str.length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
    return new (mem_root) Item_null(this, 0, cs);
  return new (mem_root) Item_string_with_introducer(this,
2489
                                                    str.str, (uint)str.length, cs);
2490 2491 2492
}


unknown's avatar
unknown committed
2493 2494 2495 2496 2497 2498
/*
  Update some cache variables when character set changes
*/

void THD::update_charset()
{
2499
  uint32 not_used;
2500 2501 2502 2503 2504
  charset_is_system_charset=
    !String::needs_conversion(0,
                              variables.character_set_client,
                              system_charset_info,
                              &not_used);
2505
  charset_is_collation_connection= 
2506 2507 2508
    !String::needs_conversion(0,
                              variables.character_set_client,
                              variables.collation_connection,
2509
                              &not_used);
unknown's avatar
unknown committed
2510
  charset_is_character_set_filesystem= 
2511 2512 2513 2514
    !String::needs_conversion(0,
                              variables.character_set_client,
                              variables.character_set_filesystem,
                              &not_used);
unknown's avatar
unknown committed
2515 2516 2517
}


2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
/* routings to adding tables to list of changed in transaction tables */

inline static void list_include(CHANGED_TABLE_LIST** prev,
				CHANGED_TABLE_LIST* curr,
				CHANGED_TABLE_LIST* new_table)
{
  if (new_table)
  {
    *prev = new_table;
    (*prev)->next = curr;
  }
}

/* add table to list of changed in transaction tables */
2532

2533 2534
void THD::add_changed_table(TABLE *table)
{
2535
  DBUG_ENTER("THD::add_changed_table(table)");
2536

2537
  DBUG_ASSERT(in_multi_stmt_transaction_mode() && table->file->has_transactions());
unknown's avatar
unknown committed
2538
  add_changed_table(table->s->table_cache_key.str,
2539
                    (long) table->s->table_cache_key.length);
unknown's avatar
unknown committed
2540
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2541
}
2542

2543

2544
void THD::add_changed_table(const char *key, size_t key_length)
unknown's avatar
unknown committed
2545 2546
{
  DBUG_ENTER("THD::add_changed_table(key)");
2547 2548
  CHANGED_TABLE_LIST **prev_changed = &transaction.changed_tables;
  CHANGED_TABLE_LIST *curr = transaction.changed_tables;
2549

2550
  for (; curr; prev_changed = &(curr->next), curr = curr->next)
2551
  {
unknown's avatar
unknown committed
2552
    int cmp =  (long)curr->key_length - (long)key_length;
2553 2554
    if (cmp < 0)
    {
2555
      list_include(prev_changed, curr, changed_table_dup(key, key_length));
2556
      DBUG_PRINT("info", 
2557
		 ("key_length: %zu  %zu", key_length,
unknown's avatar
unknown committed
2558
                  (*prev_changed)->key_length));
2559 2560 2561 2562
      DBUG_VOID_RETURN;
    }
    else if (cmp == 0)
    {
unknown's avatar
unknown committed
2563
      cmp = memcmp(curr->key, key, curr->key_length);
2564 2565
      if (cmp < 0)
      {
2566
	list_include(prev_changed, curr, changed_table_dup(key, key_length));
2567
	DBUG_PRINT("info", 
2568
		   ("key_length:  %zu  %zu", key_length,
2569
		    (*prev_changed)->key_length));
2570 2571 2572 2573 2574 2575 2576 2577 2578
	DBUG_VOID_RETURN;
      }
      else if (cmp == 0)
      {
	DBUG_PRINT("info", ("already in list"));
	DBUG_VOID_RETURN;
      }
    }
  }
2579
  *prev_changed = changed_table_dup(key, key_length);
2580
  DBUG_PRINT("info", ("key_length: %zu  %zu", key_length,
2581
		      (*prev_changed)->key_length));
2582 2583 2584
  DBUG_VOID_RETURN;
}

2585

2586
CHANGED_TABLE_LIST* THD::changed_table_dup(const char *key, size_t key_length)
2587 2588 2589
{
  CHANGED_TABLE_LIST* new_table = 
    (CHANGED_TABLE_LIST*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST))+
unknown's avatar
unknown committed
2590
				      key_length + 1);
2591 2592
  if (!new_table)
  {
2593
    my_error(EE_OUTOFMEMORY, MYF(ME_BELL+ME_FATALERROR),
2594
             ALIGN_SIZE(sizeof(TABLE_LIST)) + key_length + 1);
2595
    set_killed(KILL_CONNECTION);
2596 2597 2598
    return 0;
  }

2599
  new_table->key= ((char*)new_table)+ ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST));
2600
  new_table->next = 0;
unknown's avatar
unknown committed
2601 2602
  new_table->key_length = key_length;
  ::memcpy(new_table->key, key, key_length);
2603 2604 2605
  return new_table;
}

2606

2607 2608
int THD::prepare_explain_fields(select_result *result, List<Item> *field_list,
                                 uint8 explain_flags, bool is_analyze)
unknown's avatar
unknown committed
2609
{
Sergei Petrunia's avatar
Sergei Petrunia committed
2610
  if (lex->explain_json)
2611
    make_explain_json_field_list(*field_list, is_analyze);
Sergei Petrunia's avatar
Sergei Petrunia committed
2612
  else
2613 2614
    make_explain_field_list(*field_list, explain_flags, is_analyze);

2615
  return result->prepare(*field_list, NULL);
2616
}
2617

2618 2619 2620 2621 2622 2623 2624

int THD::send_explain_fields(select_result *result,
                             uint8 explain_flags,
                             bool is_analyze)
{
  List<Item> field_list;
  int rc;
2625 2626 2627 2628
  rc= prepare_explain_fields(result, &field_list, explain_flags, is_analyze) ||
      result->send_result_set_metadata(field_list, Protocol::SEND_NUM_ROWS |
                                                   Protocol::SEND_EOF);
  return rc;
2629 2630 2631
}


2632
void THD::make_explain_json_field_list(List<Item> &field_list, bool is_analyze)
Sergei Petrunia's avatar
Sergei Petrunia committed
2633
{
Monty's avatar
Monty committed
2634 2635 2636
  Item *item= new (mem_root) Item_empty_string(this, (is_analyze ?
                                                      "ANALYZE" :
                                                      "EXPLAIN"),
2637 2638
                                              78, system_charset_info);
  field_list.push_back(item, mem_root);
Sergei Petrunia's avatar
Sergei Petrunia committed
2639 2640 2641
}


2642 2643 2644
/*
  Populate the provided field_list with EXPLAIN output columns.
  this->lex->describe has the EXPLAIN flags
Sergei Petrunia's avatar
Sergei Petrunia committed
2645 2646 2647

  The set/order of columns must be kept in sync with 
  Explain_query::print_explain and co.
2648 2649
*/

2650 2651
void THD::make_explain_field_list(List<Item> &field_list, uint8 explain_flags,
                                  bool is_analyze)
2652
{
unknown's avatar
unknown committed
2653
  Item *item;
2654
  CHARSET_INFO *cs= system_charset_info;
Monty's avatar
Monty committed
2655 2656
  field_list.push_back(item= new (mem_root)
                       Item_return_int(this, "id", 3,
2657
                                       MYSQL_TYPE_LONGLONG), mem_root);
2658
  item->maybe_null= 1;
Monty's avatar
Monty committed
2659
  field_list.push_back(new (mem_root)
2660 2661
                       Item_empty_string(this, "select_type", 19, cs),
                       mem_root);
Monty's avatar
Monty committed
2662
  field_list.push_back(item= new (mem_root)
2663 2664
                       Item_empty_string(this, "table", NAME_CHAR_LEN, cs),
                       mem_root);
unknown's avatar
unknown committed
2665
  item->maybe_null= 1;
2666
  if (explain_flags & DESCRIBE_PARTITIONS)
unknown's avatar
unknown committed
2667
  {
2668
    /* Maximum length of string that make_used_partitions_str() can produce */
Monty's avatar
Monty committed
2669 2670
    item= new (mem_root) Item_empty_string(this, "partitions",
                                           MAX_PARTITIONS * (1 + FN_LEN), cs);
2671
    field_list.push_back(item, mem_root);
unknown's avatar
unknown committed
2672 2673
    item->maybe_null= 1;
  }
Monty's avatar
Monty committed
2674
  field_list.push_back(item= new (mem_root)
2675 2676
                       Item_empty_string(this, "type", 10, cs),
                       mem_root);
unknown's avatar
unknown committed
2677
  item->maybe_null= 1;
Monty's avatar
Monty committed
2678 2679
  field_list.push_back(item= new (mem_root)
                       Item_empty_string(this, "possible_keys",
2680 2681
                                         NAME_CHAR_LEN*MAX_KEY, cs),
                       mem_root);
unknown's avatar
unknown committed
2682
  item->maybe_null=1;
Monty's avatar
Monty committed
2683
  field_list.push_back(item=new (mem_root)
2684 2685
                       Item_empty_string(this, "key", NAME_CHAR_LEN, cs),
                       mem_root);
unknown's avatar
unknown committed
2686
  item->maybe_null=1;
Monty's avatar
Monty committed
2687 2688
  field_list.push_back(item=new (mem_root)
                       Item_empty_string(this, "key_len",
2689 2690
                                         NAME_CHAR_LEN*MAX_KEY),
                       mem_root);
unknown's avatar
unknown committed
2691
  item->maybe_null=1;
Monty's avatar
Monty committed
2692 2693
  field_list.push_back(item=new (mem_root)
                       Item_empty_string(this, "ref",
2694 2695
                                         NAME_CHAR_LEN*MAX_REF_PARTS, cs),
                       mem_root);
unknown's avatar
unknown committed
2696
  item->maybe_null=1;
Monty's avatar
Monty committed
2697
  field_list.push_back(item= new (mem_root)
2698 2699
                       Item_return_int(this, "rows", 10, MYSQL_TYPE_LONGLONG),
                       mem_root);
2700
  if (is_analyze)
Sergei Petrunia's avatar
Sergei Petrunia committed
2701
  {
Monty's avatar
Monty committed
2702
    field_list.push_back(item= new (mem_root)
2703
                         Item_float(this, "r_rows", 0.1234, 2, 4),
2704
                         mem_root);
Sergei Petrunia's avatar
Sergei Petrunia committed
2705 2706 2707
    item->maybe_null=1;
  }

2708
  if (is_analyze || (explain_flags & DESCRIBE_EXTENDED))
2709
  {
Monty's avatar
Monty committed
2710
    field_list.push_back(item= new (mem_root)
2711 2712
                         Item_float(this, "filtered", 0.1234, 2, 4),
                         mem_root);
2713 2714
    item->maybe_null=1;
  }
Sergei Petrunia's avatar
Sergei Petrunia committed
2715

2716
  if (is_analyze)
Sergei Petrunia's avatar
Sergei Petrunia committed
2717
  {
Monty's avatar
Monty committed
2718
    field_list.push_back(item= new (mem_root)
2719 2720
                         Item_float(this, "r_filtered", 0.1234, 2, 4),
                         mem_root);
Sergei Petrunia's avatar
Sergei Petrunia committed
2721 2722 2723
    item->maybe_null=1;
  }

unknown's avatar
unknown committed
2724
  item->maybe_null= 1;
Monty's avatar
Monty committed
2725
  field_list.push_back(new (mem_root)
2726 2727
                       Item_empty_string(this, "Extra", 255, cs),
                       mem_root);
unknown's avatar
unknown committed
2728
}
2729

2730

2731 2732
#ifdef SIGNAL_WITH_VIO_CLOSE
void THD::close_active_vio()
unknown's avatar
unknown committed
2733
{
2734
  DBUG_ENTER("close_active_vio");
Marc Alff's avatar
Marc Alff committed
2735
  mysql_mutex_assert_owner(&LOCK_thd_data);
unknown's avatar
unknown committed
2736
#ifndef EMBEDDED_LIBRARY
2737
  if (active_vio)
unknown's avatar
unknown committed
2738
  {
2739 2740
    vio_close(active_vio);
    active_vio = 0;
unknown's avatar
unknown committed
2741
  }
unknown's avatar
unknown committed
2742
#endif
2743
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2744
}
2745
#endif
unknown's avatar
unknown committed
2746

2747

2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 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
/*
  @brief MySQL parser used for recursive invocations

  @param old_lex  The LEX structure in the state when this parser
                  is called recursively
  @param lex      The LEX structure used to parse a new SQL fragment
  @param str      The SQL fragment to parse
  @param str_len  The length of the SQL fragment to parse
  @param stmt_prepare_mode true <=> when parsing a prepare statement

  @details
    This function is to be used when parsing of an SQL fragment is
    needed within one of the grammar rules.

  @notes
    Currently the function is used only when the specification of a CTE
    is parsed for the not first and not recursive references of the CTE.

  @retval false   On a successful parsing of the fragment
  @retval true    Otherwise
*/

bool THD::sql_parser(LEX *old_lex, LEX *lex,
                     char *str, uint str_len, bool stmt_prepare_mode)
{
  extern int MYSQLparse(THD * thd);

  bool parse_status= false;
  Parser_state parser_state;
  Parser_state *old_parser_state= m_parser_state;

  if (parser_state.init(this, str, str_len))
    return true;

  m_parser_state= &parser_state;
  parser_state.m_lip.stmt_prepare_mode= stmt_prepare_mode;
  parser_state.m_lip.multi_statements= false;
  parser_state.m_lip.m_digest= NULL;

  lex->param_list= old_lex->param_list;
  lex->sphead= old_lex->sphead;
  lex->spname= old_lex->spname;
  lex->spcont= old_lex->spcont;
  lex->sp_chistics= old_lex->sp_chistics;
  lex->trg_chistics= old_lex->trg_chistics;

  parse_status= MYSQLparse(this) != 0;

  m_parser_state= old_parser_state;

  return parse_status;
}


2802 2803 2804 2805 2806
struct Item_change_record: public ilink
{
  Item **place;
  Item *old_value;
  /* Placement new was hidden by `new' in ilink (TODO: check): */
2807
  static void *operator new(size_t size, void *mem) { return mem; }
2808 2809
  static void operator delete(void *ptr, size_t size) {}
  static void operator delete(void *ptr, void *mem) { /* never called */ }
2810 2811 2812 2813 2814 2815
};


/*
  Register an item tree tree transformation, performed by the query
  optimizer. We need a pointer to runtime_memroot because it may be !=
unknown's avatar
unknown committed
2816
  thd->mem_root (due to possible set_n_backup_active_arena called for thd).
2817 2818
*/

2819 2820 2821 2822
void
Item_change_list::nocheck_register_item_tree_change(Item **place,
                                                    Item *old_value,
                                                    MEM_ROOT *runtime_memroot)
2823 2824
{
  Item_change_record *change;
2825 2826
  DBUG_ENTER("THD::nocheck_register_item_tree_change");
  DBUG_PRINT("enter", ("Register %p <- %p", old_value, (*place)));
2827 2828 2829 2830 2831 2832 2833 2834
  /*
    Now we use one node per change, which adds some memory overhead,
    but still is rather fast as we use alloc_root for allocations.
    A list of item tree changes of an average query should be short.
  */
  void *change_mem= alloc_root(runtime_memroot, sizeof(*change));
  if (change_mem == 0)
  {
2835 2836 2837 2838
    /*
      OOM, thd->fatal_error() is called by the error handler of the
      memroot. Just return.
    */
2839
    DBUG_VOID_RETURN;
2840 2841 2842 2843
  }
  change= new (change_mem) Item_change_record;
  change->place= place;
  change->old_value= old_value;
2844
  change_list.append(change);
2845
  DBUG_VOID_RETURN;
2846 2847
}

unknown's avatar
unknown committed
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
/**
  Check and register item change if needed

  @param place           place where we should assign new value
  @param new_value       place of the new value

  @details
    Let C be a reference to an item that changed the reference A
    at the location (occurrence) L1 and this change has been registered.
    If C is substituted for reference A another location (occurrence) L2
    that is to be registered as well than this change has to be
    consistent with the first change in order the procedure that rollback
    changes to substitute the same reference at both locations L1 and L2.
*/

2863 2864 2865 2866
void
Item_change_list::check_and_register_item_tree_change(Item **place,
                                                      Item **new_value,
                                                      MEM_ROOT *runtime_memroot)
unknown's avatar
unknown committed
2867 2868
{
  Item_change_record *change;
2869 2870 2871
  DBUG_ENTER("THD::check_and_register_item_tree_change");
  DBUG_PRINT("enter", ("Register: %p (%p) <- %p (%p)",
                       *place, place, *new_value, new_value));
unknown's avatar
unknown committed
2872 2873 2874 2875 2876 2877 2878 2879 2880
  I_List_iterator<Item_change_record> it(change_list);
  while ((change= it++))
  {
    if (change->place == new_value)
      break; // we need only very first value
  }
  if (change)
    nocheck_register_item_tree_change(place, change->old_value,
                                      runtime_memroot);
2881
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
2882 2883
}

2884

2885
void Item_change_list::rollback_item_tree_changes()
2886
{
2887
  DBUG_ENTER("THD::rollback_item_tree_changes");
2888 2889
  I_List_iterator<Item_change_record> it(change_list);
  Item_change_record *change;
unknown's avatar
unknown committed
2890

2891
  while ((change= it++))
2892
  {
2893 2894
    DBUG_PRINT("info", ("Rollback: %p (%p) <- %p",
                        *change->place, change->place, change->old_value));
2895
    *change->place= change->old_value;
2896
  }
2897 2898
  /* We can forget about changes memory: it's allocated in runtime memroot */
  change_list.empty();
2899
  DBUG_VOID_RETURN;
2900 2901 2902
}


unknown's avatar
unknown committed
2903 2904 2905 2906
/*****************************************************************************
** Functions to provide a interface to select results
*****************************************************************************/

2907 2908 2909 2910 2911
void select_result::cleanup()
{
  /* do nothing */
}

2912 2913 2914 2915 2916 2917 2918
bool select_result::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0));
  return TRUE;
}


2919 2920 2921
static String default_line_term("\n",default_charset_info);
static String default_escaped("\\",default_charset_info);
static String default_field_term("\t",default_charset_info);
2922
static String default_enclosed_and_line_start("", default_charset_info);
2923
static String default_xml_row_term("<row>", default_charset_info);
unknown's avatar
unknown committed
2924

2925
sql_exchange::sql_exchange(const char *name, bool flag,
2926
                           enum enum_filetype filetype_arg)
unknown's avatar
unknown committed
2927 2928
  :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0)
{
2929
  filetype= filetype_arg;
unknown's avatar
unknown committed
2930
  field_term= &default_field_term;
2931
  enclosed=   line_start= &default_enclosed_and_line_start;
2932 2933
  line_term=  filetype == FILETYPE_CSV ?
              &default_line_term : &default_xml_row_term;
unknown's avatar
unknown committed
2934
  escaped=    &default_escaped;
2935
  cs= NULL;
unknown's avatar
unknown committed
2936 2937
}

2938
bool sql_exchange::escaped_given(void) const
2939 2940 2941 2942 2943
{
  return escaped != &default_escaped;
}


2944
bool select_send::send_result_set_metadata(List<Item> &list, uint flags)
unknown's avatar
unknown committed
2945
{
2946
  bool res;
2947 2948 2949 2950 2951 2952 2953
#ifdef WITH_WSREP
  if (WSREP(thd) && thd->wsrep_retry_query)
  {
    WSREP_DEBUG("skipping select metadata");
    return FALSE;
  }
#endif /* WITH_WSREP */
2954
  if (!(res= thd->protocol->send_result_set_metadata(&list, flags)))
2955
    is_result_set_started= 1;
2956
  return res;
unknown's avatar
unknown committed
2957 2958
}

2959
void select_send::abort_result_set()
2960
{
2961
  DBUG_ENTER("select_send::abort_result_set");
Marc Alff's avatar
Marc Alff committed
2962 2963

  if (is_result_set_started && thd->spcont)
2964 2965
  {
    /*
2966
      We're executing a stored procedure, have an open result
Marc Alff's avatar
Marc Alff committed
2967 2968 2969
      set and an SQL exception condition. In this situation we
      must abort the current statement, silence the error and
      start executing the continue/exit handler if one is found.
2970 2971 2972
      Before aborting the statement, let's end the open result set, as
      otherwise the client will hang due to the violation of the
      client/server protocol.
2973
    */
Marc Alff's avatar
Marc Alff committed
2974
    thd->spcont->end_partial_result_set= TRUE;
2975 2976 2977 2978 2979
  }
  DBUG_VOID_RETURN;
}


2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
/** 
  Cleanup an instance of this class for re-use
  at next execution of a prepared statement/
  stored procedure statement.
*/

void select_send::cleanup()
{
  is_result_set_started= FALSE;
}

unknown's avatar
unknown committed
2991 2992
/* Send data to client. Returns 0 if ok */

2993
int select_send::send_data(List<Item> &items)
unknown's avatar
unknown committed
2994
{
2995 2996 2997
  Protocol *protocol= thd->protocol;
  DBUG_ENTER("select_send::send_data");

2998 2999
  /* unit is not set when using 'delete ... returning' */
  if (unit && unit->offset_limit_cnt)
unknown's avatar
unknown committed
3000
  {						// using limit offset,count
3001
    unit->offset_limit_cnt--;
3002
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
3003
  }
3004
  if (thd->killed == ABORT_QUERY)
3005
    DBUG_RETURN(FALSE);
3006 3007

  protocol->prepare_for_resend();
3008
  if (protocol->send_result_set_row(&items))
3009 3010
  {
    protocol->remove_last_row();
3011
    DBUG_RETURN(TRUE);
3012
  }
3013

Sergei Golubchik's avatar
Sergei Golubchik committed
3014
  thd->inc_sent_row_count(1);
3015

3016
  if (thd->vio_ok())
3017
    DBUG_RETURN(protocol->write());
3018

3019
  DBUG_RETURN(0);
unknown's avatar
unknown committed
3020 3021
}

3022

unknown's avatar
unknown committed
3023 3024
bool select_send::send_eof()
{
3025 3026 3027 3028
  /* 
    Don't send EOF if we're in error condition (which implies we've already
    sent or are sending an error)
  */
3029
  if (unlikely(thd->is_error()))
3030
    return TRUE;
3031
  ::my_eof(thd);
3032 3033
  is_result_set_started= 0;
  return FALSE;
unknown's avatar
unknown committed
3034 3035 3036
}


3037 3038 3039
/************************************************************************
  Handling writing to file
************************************************************************/
unknown's avatar
unknown committed
3040

3041 3042
bool select_to_file::send_eof()
{
3043
  int error= MY_TEST(end_io_cache(&cache));
3044 3045
  if (unlikely(mysql_file_close(file, MYF(MY_WME))) ||
      unlikely(thd->is_error()))
3046 3047
    error= true;

3048
  if (likely(!error) && !suppress_my_ok)
3049
  {
3050
    ::my_ok(thd,row_count);
3051
  }
3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
  file= -1;
  return error;
}


void select_to_file::cleanup()
{
  /* In case of error send_eof() may be not called: close the file here. */
  if (file >= 0)
  {
    (void) end_io_cache(&cache);
Marc Alff's avatar
Marc Alff committed
3063
    mysql_file_close(file, MYF(0));
3064 3065 3066 3067 3068 3069 3070
    file= -1;
  }
  path[0]= '\0';
  row_count= 0;
}


3071
select_to_file::~select_to_file()
unknown's avatar
unknown committed
3072 3073 3074 3075
{
  if (file >= 0)
  {					// This only happens in case of error
    (void) end_io_cache(&cache);
Marc Alff's avatar
Marc Alff committed
3076
    mysql_file_close(file, MYF(0));
unknown's avatar
unknown committed
3077 3078
    file= -1;
  }
3079 3080 3081 3082 3083 3084 3085 3086
}

/***************************************************************************
** Export of select to textfile
***************************************************************************/

select_export::~select_export()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
3087
  thd->set_sent_row_count(row_count);
unknown's avatar
unknown committed
3088 3089
}

3090

3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
/*
  Create file with IO cache

  SYNOPSIS
    create_file()
    thd			Thread handle
    path		File name
    exchange		Excange class
    cache		IO cache

  RETURN
    >= 0 	File handle
   -1		Error
*/


static File create_file(THD *thd, char *path, sql_exchange *exchange,
			IO_CACHE *cache)
unknown's avatar
unknown committed
3109
{
3110
  File file;
3111
  uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH;
3112

unknown's avatar
unknown committed
3113
#ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS
3114
  option|= MY_REPLACE_DIR;			// Force use of db directory
unknown's avatar
unknown committed
3115
#endif
3116

unknown's avatar
unknown committed
3117
  if (!dirname_length(exchange->file_name))
3118
  {
3119
    strxnmov(path, FN_REFLEN-1, mysql_real_data_home, thd->get_db(), NullS);
3120 3121 3122 3123
    (void) fn_format(path, exchange->file_name, path, "", option);
  }
  else
    (void) fn_format(path, exchange->file_name, mysql_real_data_home, "", option);
3124

3125
  if (!is_secure_file_path(path))
3126 3127 3128 3129 3130 3131
  {
    /* Write only allowed to dir or subdir specified by secure_file_priv */
    my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
    return -1;
  }

3132
  if (!access(path, F_OK))
unknown's avatar
unknown committed
3133
  {
3134
    my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
unknown's avatar
unknown committed
3135
    return -1;
unknown's avatar
unknown committed
3136 3137
  }
  /* Create the file world readable */
Marc Alff's avatar
Marc Alff committed
3138
  if ((file= mysql_file_create(key_select_to_file,
3139
                               path, 0644, O_WRONLY|O_EXCL, MYF(MY_WME))) < 0)
3140
    return file;
unknown's avatar
unknown committed
3141
#ifdef HAVE_FCHMOD
3142
  (void) fchmod(file, 0644);			// Because of umask()
unknown's avatar
unknown committed
3143
#else
3144
  (void) chmod(path, 0644);
unknown's avatar
unknown committed
3145
#endif
3146
  if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME)))
unknown's avatar
unknown committed
3147
  {
Marc Alff's avatar
Marc Alff committed
3148 3149 3150
    mysql_file_close(file, MYF(0));
    /* Delete file on error, it was just created */
    mysql_file_delete(key_select_to_file, path, MYF(0));
3151
    return -1;
unknown's avatar
unknown committed
3152
  }
3153
  return file;
3154 3155 3156 3157 3158 3159 3160
}


int
select_export::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
{
  bool blob_flag=0;
3161
  bool string_results= FALSE, non_string_results= FALSE;
3162 3163
  unit= u;
  if ((uint) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
3164
    strmake_buf(path,exchange->file_name);
3165

3166 3167
  write_cs= exchange->cs ? exchange->cs : &my_charset_bin;

3168
  if ((file= create_file(thd, path, exchange, &cache)) < 0)
3169
    return 1;
unknown's avatar
unknown committed
3170 3171
  /* Check if there is any blobs in data */
  {
unknown's avatar
unknown committed
3172
    List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
3173 3174 3175 3176 3177 3178 3179 3180
    Item *item;
    while ((item=li++))
    {
      if (item->max_length >= MAX_BLOB_WIDTH)
      {
	blob_flag=1;
	break;
      }
3181 3182 3183 3184
      if (item->result_type() == STRING_RESULT)
        string_results= TRUE;
      else
        non_string_results= TRUE;
unknown's avatar
unknown committed
3185 3186
    }
  }
3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
  if (exchange->escaped->numchars() > 1 || exchange->enclosed->numchars() > 1)
  {
    my_error(ER_WRONG_FIELD_TERMINATORS, MYF(0));
    return TRUE;
  }
  if (exchange->escaped->length() > 1 || exchange->enclosed->length() > 1 ||
      !my_isascii(exchange->escaped->ptr()[0]) ||
      !my_isascii(exchange->enclosed->ptr()[0]) ||
      !exchange->field_term->is_ascii() || !exchange->line_term->is_ascii() ||
      !exchange->line_start->is_ascii())
  {
    /*
      Current LOAD DATA INFILE recognizes field/line separators "as is" without
      converting from client charset to data file charset. So, it is supposed,
      that input file of LOAD DATA INFILE consists of data in one charset and
      separators in other charset. For the compatibility with that [buggy]
      behaviour SELECT INTO OUTFILE implementation has been saved "as is" too,
      but the new warning message has been added:

        Non-ASCII separator arguments are not fully supported
    */
3208
    push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
3209
                 WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED,
3210
                 ER_THD(thd, WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED));
3211
  }
unknown's avatar
unknown committed
3212
  field_term_length=exchange->field_term->length();
unknown's avatar
unknown committed
3213 3214
  field_term_char= field_term_length ?
                   (int) (uchar) (*exchange->field_term)[0] : INT_MAX;
unknown's avatar
unknown committed
3215 3216
  if (!exchange->line_term->length())
    exchange->line_term=exchange->field_term;	// Use this if it exists
unknown's avatar
unknown committed
3217 3218
  field_sep_char= (exchange->enclosed->length() ?
                  (int) (uchar) (*exchange->enclosed)[0] : field_term_char);
3219 3220 3221 3222 3223
  if (exchange->escaped->length() && (exchange->escaped_given() ||
      !(thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)))
    escape_char= (int) (uchar) (*exchange->escaped)[0];
  else
    escape_char= -1;
3224 3225
  is_ambiguous_field_sep= MY_TEST(strchr(ESCAPE_CHARS, field_sep_char));
  is_unsafe_field_sep= MY_TEST(strchr(NUMERIC_CHARS, field_sep_char));
unknown's avatar
unknown committed
3226
  line_sep_char= (exchange->line_term->length() ?
unknown's avatar
unknown committed
3227
                 (int) (uchar) (*exchange->line_term)[0] : INT_MAX);
unknown's avatar
unknown committed
3228 3229 3230 3231 3232 3233
  if (!field_term_length)
    exchange->opt_enclosed=0;
  if (!exchange->enclosed->length())
    exchange->opt_enclosed=1;			// A little quicker loop
  fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
		   !blob_flag);
3234 3235 3236 3237 3238
  if ((is_ambiguous_field_sep && exchange->enclosed->is_empty() &&
       (string_results || is_unsafe_field_sep)) ||
      (exchange->opt_enclosed && non_string_results &&
       field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
  {
3239
    push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
3240 3241
                 ER_AMBIGUOUS_FIELD_TERM,
                 ER_THD(thd, ER_AMBIGUOUS_FIELD_TERM));
3242 3243 3244 3245 3246
    is_ambiguous_field_term= TRUE;
  }
  else
    is_ambiguous_field_term= FALSE;

unknown's avatar
unknown committed
3247 3248 3249 3250
  return 0;
}


3251
#define NEED_ESCAPING(x) ((int) (uchar) (x) == escape_char    || \
3252 3253
                          (enclosed ? (int) (uchar) (x) == field_sep_char      \
                                    : (int) (uchar) (x) == field_term_char) || \
3254 3255 3256
                          (int) (uchar) (x) == line_sep_char  || \
                          !(x))

3257
int select_export::send_data(List<Item> &items)
unknown's avatar
unknown committed
3258 3259
{

3260
  DBUG_ENTER("select_export::send_data");
unknown's avatar
unknown committed
3261
  char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
3262 3263
  char cvt_buff[MAX_FIELD_WIDTH];
  String cvt_str(cvt_buff, sizeof(cvt_buff), write_cs);
unknown's avatar
unknown committed
3264
  bool space_inited=0;
unknown's avatar
unknown committed
3265
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
unknown's avatar
unknown committed
3266 3267
  tmp.length(0);

3268
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
3269
  {						// using limit offset,count
3270
    unit->offset_limit_cnt--;
unknown's avatar
unknown committed
3271 3272
    DBUG_RETURN(0);
  }
3273 3274
  if (thd->killed == ABORT_QUERY)
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3275 3276 3277
  row_count++;
  Item *item;
  uint used_length=0,items_left=items.elements;
unknown's avatar
unknown committed
3278
  List_iterator_fast<Item> li(items);
unknown's avatar
unknown committed
3279

3280
  if (my_b_write(&cache,(uchar*) exchange->line_start->ptr(),
unknown's avatar
unknown committed
3281 3282 3283 3284 3285
		 exchange->line_start->length()))
    goto err;
  while ((item=li++))
  {
    Item_result result_type=item->result_type();
3286 3287
    bool enclosed = (exchange->enclosed->length() &&
                     (!exchange->opt_enclosed || result_type == STRING_RESULT));
unknown's avatar
unknown committed
3288
    res=item->str_result(&tmp);
3289 3290 3291
    if (res && !my_charset_same(write_cs, res->charset()) &&
        !my_charset_same(write_cs, &my_charset_bin))
    {
3292
      String_copier copier;
3293 3294
      const char *error_pos;
      uint32 bytes;
3295 3296 3297 3298 3299 3300
      uint64 estimated_bytes=
        ((uint64) res->length() / res->charset()->mbminlen + 1) *
        write_cs->mbmaxlen + 1;
      set_if_smaller(estimated_bytes, UINT_MAX32);
      if (cvt_str.realloc((uint32) estimated_bytes))
      {
3301
        my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), (uint32) estimated_bytes);
3302 3303 3304
        goto err;
      }

3305
      bytes= copier.well_formed_copy(write_cs, (char *) cvt_str.ptr(),
3306
                                     cvt_str.alloced_length(),
3307 3308 3309
                                     res->charset(),
                                     res->ptr(), res->length());
      error_pos= copier.most_important_error_pos();
3310
      if (unlikely(error_pos))
3311
      {
3312 3313 3314 3315
        /*
          TODO: 
             add new error message that will show user this printable_buff

3316 3317 3318 3319
        char printable_buff[32];
        convert_to_printable(printable_buff, sizeof(printable_buff),
                             error_pos, res->ptr() + res->length() - error_pos,
                             res->charset(), 6);
3320
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3321
                            ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
3322
                            ER_THD(thd, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
3323
                            "string", printable_buff,
3324
                            item->name.str, static_cast<long>(row_count));
3325 3326 3327 3328
        */
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
                            ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
                            ER_THD(thd, WARN_DATA_TRUNCATED),
Marko Mäkelä's avatar
Marko Mäkelä committed
3329
                            item->name.str, static_cast<long>(row_count));
3330
      }
3331
      else if (copier.source_end_pos() < res->ptr() + res->length())
3332 3333 3334 3335
      { 
        /*
          result is longer than UINT_MAX32 and doesn't fit into String
        */
3336
        push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3337 3338
                            WARN_DATA_TRUNCATED,
                            ER_THD(thd, WARN_DATA_TRUNCATED),
3339
                            item->full_name(), static_cast<long>(row_count));
3340
      }
3341 3342 3343
      cvt_str.length(bytes);
      res= &cvt_str;
    }
3344
    if (res && enclosed)
unknown's avatar
unknown committed
3345
    {
3346
      if (my_b_write(&cache,(uchar*) exchange->enclosed->ptr(),
unknown's avatar
unknown committed
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
		     exchange->enclosed->length()))
	goto err;
    }
    if (!res)
    {						// NULL
      if (!fixed_row_size)
      {
	if (escape_char != -1)			// Use \N syntax
	{
	  null_buff[0]=escape_char;
	  null_buff[1]='N';
3358
	  if (my_b_write(&cache,(uchar*) null_buff,2))
unknown's avatar
unknown committed
3359 3360
	    goto err;
	}
3361
	else if (my_b_write(&cache,(uchar*) "NULL",4))
unknown's avatar
unknown committed
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371
	  goto err;
      }
      else
      {
	used_length=0;				// Fill with space
      }
    }
    else
    {
      if (fixed_row_size)
3372
	used_length=MY_MIN(res->length(),item->max_length);
unknown's avatar
unknown committed
3373 3374
      else
	used_length=res->length();
unknown's avatar
unknown committed
3375 3376
      if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
           escape_char != -1)
unknown's avatar
unknown committed
3377
      {
3378 3379 3380 3381 3382 3383 3384 3385 3386
        char *pos, *start, *end;
        CHARSET_INFO *res_charset= res->charset();
        CHARSET_INFO *character_set_client= thd->variables.
                                            character_set_client;
        bool check_second_byte= (res_charset == &my_charset_bin) &&
                                 character_set_client->
                                 escape_with_backslash_is_dangerous;
        DBUG_ASSERT(character_set_client->mbmaxlen == 2 ||
                    !character_set_client->escape_with_backslash_is_dangerous);
unknown's avatar
unknown committed
3387 3388 3389 3390 3391
	for (start=pos=(char*) res->ptr(),end=pos+used_length ;
	     pos != end ;
	     pos++)
	{
#ifdef USE_MB
unknown's avatar
unknown committed
3392
	  if (use_mb(res_charset))
unknown's avatar
unknown committed
3393 3394
	  {
	    int l;
unknown's avatar
unknown committed
3395
	    if ((l=my_ismbchar(res_charset, pos, end)))
unknown's avatar
unknown committed
3396 3397 3398 3399 3400 3401
	    {
	      pos += l-1;
	      continue;
	    }
	  }
#endif
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

          /*
            Special case when dumping BINARY/VARBINARY/BLOB values
            for the clients with character sets big5, cp932, gbk and sjis,
            which can have the escape character (0x5C "\" by default)
            as the second byte of a multi-byte sequence.
            
            If
            - pos[0] is a valid multi-byte head (e.g 0xEE) and
            - pos[1] is 0x00, which will be escaped as "\0",
            
            then we'll get "0xEE + 0x5C + 0x30" in the output file.
            
            If this file is later loaded using this sequence of commands:
            
            mysql> create table t1 (a varchar(128)) character set big5;
            mysql> LOAD DATA INFILE 'dump.txt' INTO TABLE t1;
            
            then 0x5C will be misinterpreted as the second byte
            of a multi-byte character "0xEE + 0x5C", instead of
            escape character for 0x00.
            
            To avoid this confusion, we'll escape the multi-byte
            head character too, so the sequence "0xEE + 0x00" will be
            dumped as "0x5C + 0xEE + 0x5C + 0x30".
            
            Note, in the condition below we only check if
            mbcharlen is equal to 2, because there are no
            character sets with mbmaxlen longer than 2
            and with escape_with_backslash_is_dangerous set.
            DBUG_ASSERT before the loop makes that sure.
          */

3435 3436
          if ((NEED_ESCAPING(*pos) ||
               (check_second_byte &&
3437
                ((uchar) *pos) > 0x7F /* a potential MB2HEAD */ &&
3438 3439 3440 3441 3442 3443
                pos + 1 < end &&
                NEED_ESCAPING(pos[1]))) &&
              /*
               Don't escape field_term_char by doubling - doubling is only
               valid for ENCLOSED BY characters:
              */
unknown's avatar
unknown committed
3444 3445
              (enclosed || !is_ambiguous_field_term ||
               (int) (uchar) *pos != field_term_char))
3446
          {
unknown's avatar
unknown committed
3447
	    char tmp_buff[2];
unknown's avatar
unknown committed
3448
            tmp_buff[0]= ((int) (uchar) *pos == field_sep_char &&
unknown's avatar
unknown committed
3449 3450
                          is_ambiguous_field_sep) ?
                          field_sep_char : escape_char;
unknown's avatar
unknown committed
3451
	    tmp_buff[1]= *pos ? *pos : '0';
3452 3453
	    if (my_b_write(&cache,(uchar*) start,(uint) (pos-start)) ||
		my_b_write(&cache,(uchar*) tmp_buff,2))
unknown's avatar
unknown committed
3454 3455 3456 3457
	      goto err;
	    start=pos+1;
	  }
	}
3458
	if (my_b_write(&cache,(uchar*) start,(uint) (pos-start)))
unknown's avatar
unknown committed
3459 3460
	  goto err;
      }
3461
      else if (my_b_write(&cache,(uchar*) res->ptr(),used_length))
unknown's avatar
unknown committed
3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473
	goto err;
    }
    if (fixed_row_size)
    {						// Fill with space
      if (item->max_length > used_length)
      {
	if (!space_inited)
	{
	  space_inited=1;
	  bfill(space,sizeof(space),' ');
	}
	uint length=item->max_length-used_length;
3474
	for (; length > sizeof(space) ; length-=sizeof(space))
unknown's avatar
unknown committed
3475
	{
3476
	  if (my_b_write(&cache,(uchar*) space,sizeof(space)))
unknown's avatar
unknown committed
3477 3478
	    goto err;
	}
3479
	if (my_b_write(&cache,(uchar*) space,length))
unknown's avatar
unknown committed
3480 3481 3482
	  goto err;
      }
    }
3483
    if (res && enclosed)
unknown's avatar
unknown committed
3484
    {
3485
      if (my_b_write(&cache, (uchar*) exchange->enclosed->ptr(),
3486 3487
                     exchange->enclosed->length()))
        goto err;
unknown's avatar
unknown committed
3488 3489 3490
    }
    if (--items_left)
    {
3491
      if (my_b_write(&cache, (uchar*) exchange->field_term->ptr(),
3492 3493
                     field_term_length))
        goto err;
unknown's avatar
unknown committed
3494 3495
    }
  }
3496
  if (my_b_write(&cache,(uchar*) exchange->line_term->ptr(),
unknown's avatar
unknown committed
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
		 exchange->line_term->length()))
    goto err;
  DBUG_RETURN(0);
err:
  DBUG_RETURN(1);
}


/***************************************************************************
** Dump  of select to a binary file
***************************************************************************/


int
3511 3512
select_dump::prepare(List<Item> &list __attribute__((unused)),
		     SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
3513
{
3514
  unit= u;
3515
  return (int) ((file= create_file(thd, path, exchange, &cache)) < 0);
unknown's avatar
unknown committed
3516 3517 3518
}


3519
int select_dump::send_data(List<Item> &items)
unknown's avatar
unknown committed
3520
{
unknown's avatar
unknown committed
3521
  List_iterator_fast<Item> li(items);
unknown's avatar
unknown committed
3522
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
3523
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
unknown's avatar
unknown committed
3524 3525
  tmp.length(0);
  Item *item;
3526
  DBUG_ENTER("select_dump::send_data");
unknown's avatar
unknown committed
3527

3528
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
3529
  {						// using limit offset,count
3530
    unit->offset_limit_cnt--;
unknown's avatar
unknown committed
3531 3532
    DBUG_RETURN(0);
  }
3533 3534 3535
  if (thd->killed == ABORT_QUERY)
    DBUG_RETURN(0);

unknown's avatar
unknown committed
3536 3537
  if (row_count++ > 1) 
  {
3538
    my_message(ER_TOO_MANY_ROWS, ER_THD(thd, ER_TOO_MANY_ROWS), MYF(0));
unknown's avatar
unknown committed
3539 3540 3541 3542 3543
    goto err;
  }
  while ((item=li++))
  {
    res=item->str_result(&tmp);
3544
    if (!res)					// If NULL
unknown's avatar
unknown committed
3545
    {
3546
      if (my_b_write(&cache,(uchar*) "",1))
3547
	goto err;
unknown's avatar
unknown committed
3548
    }
3549
    else if (my_b_write(&cache,(uchar*) res->ptr(),res->length()))
unknown's avatar
unknown committed
3550
    {
3551
      my_error(ER_ERROR_ON_WRITE, MYF(0), path, my_errno);
unknown's avatar
unknown committed
3552 3553 3554 3555 3556 3557 3558 3559 3560
      goto err;
    }
  }
  DBUG_RETURN(0);
err:
  DBUG_RETURN(1);
}


3561
int select_singlerow_subselect::send_data(List<Item> &items)
3562
{
unknown's avatar
unknown committed
3563 3564
  DBUG_ENTER("select_singlerow_subselect::send_data");
  Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
unknown's avatar
unknown committed
3565 3566
  if (it->assigned())
  {
3567
    my_message(ER_SUBQUERY_NO_1_ROW, ER_THD(thd, ER_SUBQUERY_NO_1_ROW),
Michael Widenius's avatar
Michael Widenius committed
3568
               MYF(current_thd->lex->ignore ? ME_JUST_WARNING : 0));
unknown's avatar
unknown committed
3569 3570 3571
    DBUG_RETURN(1);
  }
  if (unit->offset_limit_cnt)
unknown's avatar
unknown committed
3572
  {				          // Using limit offset,count
unknown's avatar
unknown committed
3573 3574
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
3575
  }
3576 3577
  if (thd->killed == ABORT_QUERY)
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3578
  List_iterator_fast<Item> li(items);
3579 3580 3581
  Item *val_item;
  for (uint i= 0; (val_item= li++); i++)
    it->store(i, val_item);
unknown's avatar
unknown committed
3582
  it->assigned(1);
unknown's avatar
unknown committed
3583
  DBUG_RETURN(0);
3584
}
unknown's avatar
unknown committed
3585

3586

3587 3588 3589 3590 3591 3592 3593 3594
void select_max_min_finder_subselect::cleanup()
{
  DBUG_ENTER("select_max_min_finder_subselect::cleanup");
  cache= 0;
  DBUG_VOID_RETURN;
}


3595
int select_max_min_finder_subselect::send_data(List<Item> &items)
3596 3597
{
  DBUG_ENTER("select_max_min_finder_subselect::send_data");
3598
  Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
3599 3600
  List_iterator_fast<Item> li(items);
  Item *val_item= li++;
3601
  it->register_value();
3602 3603 3604 3605 3606 3607 3608 3609 3610 3611
  if (it->assigned())
  {
    cache->store(val_item);
    if ((this->*op)())
      it->store(0, cache);
  }
  else
  {
    if (!cache)
    {
3612
      cache= val_item->get_cache(thd);
3613
      switch (val_item->cmp_type()) {
3614 3615 3616 3617 3618 3619 3620 3621 3622
      case REAL_RESULT:
	op= &select_max_min_finder_subselect::cmp_real;
	break;
      case INT_RESULT:
	op= &select_max_min_finder_subselect::cmp_int;
	break;
      case STRING_RESULT:
	op= &select_max_min_finder_subselect::cmp_str;
	break;
unknown's avatar
unknown committed
3623 3624 3625
      case DECIMAL_RESULT:
        op= &select_max_min_finder_subselect::cmp_decimal;
        break;
Sergei Golubchik's avatar
Sergei Golubchik committed
3626
      case TIME_RESULT:
3627 3628 3629 3630 3631 3632
        if (val_item->field_type() == MYSQL_TYPE_TIME)
          op= &select_max_min_finder_subselect::cmp_time;
        else
          op= &select_max_min_finder_subselect::cmp_str;
        break;
      case ROW_RESULT:
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646
        // This case should never be choosen
	DBUG_ASSERT(0);
	op= 0;
      }
    }
    cache->store(val_item);
    it->store(0, cache);
  }
  it->assigned(1);
  DBUG_RETURN(0);
}

bool select_max_min_finder_subselect::cmp_real()
{
3647
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3648
  double val1= cache->val_real(), val2= maxmin->val_real();
unknown's avatar
unknown committed
3649 3650 3651 3652 3653 3654 3655

  /* Ignore NULLs for ANY and keep them for ALL subqueries */
  if (cache->null_value)
    return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
  if (maxmin->null_value)
    return !is_all;

3656
  if (fmax)
unknown's avatar
unknown committed
3657 3658
    return(val1 > val2);
  return (val1 < val2);
3659 3660 3661 3662
}

bool select_max_min_finder_subselect::cmp_int()
{
3663
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3664
  longlong val1= cache->val_int(), val2= maxmin->val_int();
unknown's avatar
unknown committed
3665 3666 3667 3668 3669 3670 3671

  /* Ignore NULLs for ANY and keep them for ALL subqueries */
  if (cache->null_value)
    return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
  if (maxmin->null_value)
    return !is_all;

3672
  if (fmax)
unknown's avatar
unknown committed
3673 3674
    return(val1 > val2);
  return (val1 < val2);
3675 3676
}

3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692
bool select_max_min_finder_subselect::cmp_time()
{
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
  longlong val1= cache->val_time_packed(), val2= maxmin->val_time_packed();

  /* Ignore NULLs for ANY and keep them for ALL subqueries */
  if (cache->null_value)
    return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
  if (maxmin->null_value)
    return !is_all;

  if (fmax)
    return(val1 > val2);
  return (val1 < val2);
}

unknown's avatar
unknown committed
3693 3694
bool select_max_min_finder_subselect::cmp_decimal()
{
3695
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
unknown's avatar
unknown committed
3696 3697
  my_decimal cval, *cvalue= cache->val_decimal(&cval);
  my_decimal mval, *mvalue= maxmin->val_decimal(&mval);
unknown's avatar
unknown committed
3698 3699 3700 3701 3702 3703 3704

  /* Ignore NULLs for ANY and keep them for ALL subqueries */
  if (cache->null_value)
    return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
  if (maxmin->null_value)
    return !is_all;

unknown's avatar
unknown committed
3705
  if (fmax)
unknown's avatar
unknown committed
3706 3707
    return (my_decimal_cmp(cvalue, mvalue) > 0) ;
  return (my_decimal_cmp(cvalue,mvalue) < 0);
unknown's avatar
unknown committed
3708 3709
}

3710 3711 3712
bool select_max_min_finder_subselect::cmp_str()
{
  String *val1, *val2, buf1, buf2;
3713
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3714 3715 3716 3717 3718
  /*
    as far as both operand is Item_cache buf1 & buf2 will not be used,
    but added for safety
  */
  val1= cache->val_str(&buf1);
3719
  val2= maxmin->val_str(&buf2);
unknown's avatar
unknown committed
3720 3721 3722 3723 3724 3725 3726

  /* Ignore NULLs for ANY and keep them for ALL subqueries */
  if (cache->null_value)
    return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
  if (maxmin->null_value)
    return !is_all;

3727
  if (fmax)
unknown's avatar
unknown committed
3728 3729
    return (sortcmp(val1, val2, cache->collation.collation) > 0) ;
  return (sortcmp(val1, val2, cache->collation.collation) < 0);
3730 3731
}

3732
int select_exists_subselect::send_data(List<Item> &items)
unknown's avatar
unknown committed
3733 3734 3735 3736 3737 3738 3739 3740
{
  DBUG_ENTER("select_exists_subselect::send_data");
  Item_exists_subselect *it= (Item_exists_subselect *)item;
  if (unit->offset_limit_cnt)
  {				          // Using limit offset,count
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
  }
3741 3742
  if (thd->killed == ABORT_QUERY)
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3743
  it->value= 1;
unknown's avatar
unknown committed
3744
  it->assigned(1);
unknown's avatar
unknown committed
3745 3746 3747
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
3748 3749

/***************************************************************************
3750
  Dump of select to variables
unknown's avatar
unknown committed
3751
***************************************************************************/
3752

3753
int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
unknown's avatar
unknown committed
3754
{
3755
  my_var_sp *mvsp;
3756
  unit= u;
3757 3758 3759 3760 3761
  m_var_sp_row= NULL;

  if (var_list.elements == 1 &&
      (mvsp= var_list.head()->get_my_var_sp()) &&
      mvsp->type_handler() == &type_handler_row)
unknown's avatar
unknown committed
3762
  {
3763
    // SELECT INTO row_type_sp_variable
3764 3765
    if (mvsp->get_rcontext(thd->spcont)->get_variable(mvsp->offset)->cols() !=
        list.elements)
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778
      goto error;
    m_var_sp_row= mvsp;
    return 0;
  }

  // SELECT INTO variable list
  if (var_list.elements == list.elements)
    return 0;

error:
  my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
             ER_THD(thd, ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0));
  return 1;
3779
}
3780

3781

3782 3783 3784 3785 3786 3787 3788
bool select_dumpvar::check_simple_select() const
{
  my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0));
  return TRUE;
}


3789 3790
void select_dumpvar::cleanup()
{
3791
  row_count= 0;
3792 3793 3794
}


unknown's avatar
unknown committed
3795
Query_arena::Type Query_arena::type() const
3796 3797
{
  return STATEMENT;
3798 3799 3800
}


3801 3802 3803 3804
void Query_arena::free_items()
{
  Item *next;
  DBUG_ENTER("Query_arena::free_items");
3805
  /* This works because items are allocated on THD::mem_root */
3806 3807 3808
  for (; free_list; free_list= next)
  {
    next= free_list->next;
3809
    DBUG_ASSERT(free_list != next);
3810
    DBUG_PRINT("info", ("free item: %p", free_list));
3811 3812 3813 3814 3815 3816 3817
    free_list->delete_self();
  }
  /* Postcondition: free_list is 0 */
  DBUG_VOID_RETURN;
}


3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
void Query_arena::set_query_arena(Query_arena *set)
{
  mem_root=  set->mem_root;
  free_list= set->free_list;
  state= set->state;
}


void Query_arena::cleanup_stmt()
{
3828
  DBUG_ASSERT(! "Query_arena::cleanup_stmt() not implemented");
3829 3830
}

3831
/*
unknown's avatar
unknown committed
3832
  Statement functions
3833 3834
*/

3835 3836 3837
Statement::Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
                     enum enum_state state_arg, ulong id_arg)
  :Query_arena(mem_root_arg, state_arg),
unknown's avatar
unknown committed
3838
  id(id_arg),
Sergei Golubchik's avatar
Sergei Golubchik committed
3839
  column_usage(MARK_COLUMNS_READ),
3840
  lex(lex_arg),
3841
  db(null_clex_str)
3842
{
3843
  name= null_clex_str;
3844 3845 3846
}


unknown's avatar
unknown committed
3847
Query_arena::Type Statement::type() const
3848 3849 3850 3851 3852 3853 3854 3855
{
  return STATEMENT;
}


void Statement::set_statement(Statement *stmt)
{
  id=             stmt->id;
Sergei Golubchik's avatar
Sergei Golubchik committed
3856
  column_usage=   stmt->column_usage;
3857
  lex=            stmt->lex;
3858
  query_string=   stmt->query_string;
3859 3860 3861
}


3862 3863 3864
void
Statement::set_n_backup_statement(Statement *stmt, Statement *backup)
{
3865
  DBUG_ENTER("Statement::set_n_backup_statement");
3866 3867
  backup->set_statement(this);
  set_statement(stmt);
3868
  DBUG_VOID_RETURN;
3869 3870 3871 3872 3873
}


void Statement::restore_backup_statement(Statement *stmt, Statement *backup)
{
3874
  DBUG_ENTER("Statement::restore_backup_statement");
3875 3876
  stmt->set_statement(this);
  set_statement(backup);
3877
  DBUG_VOID_RETURN;
3878 3879 3880
}


3881
void THD::end_statement()
3882
{
3883
  DBUG_ENTER("THD::end_statement");
3884
  /* Cleanup SQL processing state to reuse this statement in next query. */
3885 3886 3887
  lex_end(lex);
  delete lex->result;
  lex->result= 0;
3888 3889
  /* Note that free_list is freed in cleanup_after_query() */

3890 3891 3892 3893
  /*
    Don't free mem_root, as mem_root is freed in the end of dispatch_command
    (once for any command).
  */
3894
  DBUG_VOID_RETURN;
3895 3896 3897
}


3898 3899 3900 3901
/*
  Start using arena specified by @set. Current arena data will be saved to
  *backup.
*/
unknown's avatar
unknown committed
3902
void THD::set_n_backup_active_arena(Query_arena *set, Query_arena *backup)
unknown's avatar
unknown committed
3903
{
unknown's avatar
unknown committed
3904
  DBUG_ENTER("THD::set_n_backup_active_arena");
3905
  DBUG_ASSERT(backup->is_backup_arena == FALSE);
3906

unknown's avatar
unknown committed
3907 3908
  backup->set_query_arena(this);
  set_query_arena(set);
3909
#ifdef DBUG_ASSERT_EXISTS
3910
  backup->is_backup_arena= TRUE;
unknown's avatar
unknown committed
3911
#endif
3912
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
3913 3914 3915
}


3916 3917 3918 3919 3920 3921
/*
  Stop using the temporary arena, and start again using the arena that is 
  specified in *backup.
  The temporary arena is returned back into *set.
*/

unknown's avatar
unknown committed
3922
void THD::restore_active_arena(Query_arena *set, Query_arena *backup)
3923
{
unknown's avatar
unknown committed
3924
  DBUG_ENTER("THD::restore_active_arena");
3925
  DBUG_ASSERT(backup->is_backup_arena);
unknown's avatar
unknown committed
3926 3927
  set->set_query_arena(this);
  set_query_arena(backup);
3928
#ifdef DBUG_ASSERT_EXISTS
3929
  backup->is_backup_arena= FALSE;
3930
#endif
unknown's avatar
unknown committed
3931
  DBUG_VOID_RETURN;
3932 3933
}

3934 3935 3936 3937 3938 3939
Statement::~Statement()
{
}

C_MODE_START

3940 3941
static uchar *
get_statement_id_as_hash_key(const uchar *record, size_t *key_length,
3942 3943 3944 3945
                             my_bool not_used __attribute__((unused)))
{
  const Statement *statement= (const Statement *) record; 
  *key_length= sizeof(statement->id);
3946
  return (uchar *) &((const Statement *) statement)->id;
3947 3948 3949 3950 3951 3952 3953
}

static void delete_statement_as_hash_key(void *key)
{
  delete (Statement *) key;
}

3954
static uchar *get_stmt_name_hash_key(Statement *entry, size_t *length,
3955
                                    my_bool not_used __attribute__((unused)))
3956
{
3957 3958
  *length= entry->name.length;
  return (uchar*) entry->name.str;
3959 3960
}

3961 3962 3963 3964 3965
C_MODE_END

Statement_map::Statement_map() :
  last_found_statement(0)
{
3966 3967 3968 3969 3970
  enum
  {
    START_STMT_HASH_SIZE = 16,
    START_NAME_HASH_SIZE = 16
  };
Konstantin Osipov's avatar
Konstantin Osipov committed
3971 3972 3973 3974 3975 3976
  my_hash_init(&st_hash, &my_charset_bin, START_STMT_HASH_SIZE, 0, 0,
               get_statement_id_as_hash_key,
               delete_statement_as_hash_key, MYF(0));
  my_hash_init(&names_hash, system_charset_info, START_NAME_HASH_SIZE, 0, 0,
               (my_hash_get_key) get_stmt_name_hash_key,
               NULL,MYF(0));
3977 3978
}

3979

3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
/*
  Insert a new statement to the thread-local statement map.

  DESCRIPTION
    If there was an old statement with the same name, replace it with the
    new one. Otherwise, check if max_prepared_stmt_count is not reached yet,
    increase prepared_stmt_count, and insert the new statement. It's okay
    to delete an old statement and fail to insert the new one.

  POSTCONDITIONS
    All named prepared statements are also present in names_hash.
    Statement names in names_hash are unique.
    The statement is added only if prepared_stmt_count < max_prepard_stmt_count
    last_found_statement always points to a valid statement or is 0

  RETURN VALUE
    0  success
    1  error: out of resources or max_prepared_stmt_count limit has been
       reached. An error is sent to the client, the statement is deleted.
*/

int Statement_map::insert(THD *thd, Statement *statement)
4002
{
4003
  if (my_hash_insert(&st_hash, (uchar*) statement))
4004
  {
4005 4006 4007 4008 4009 4010 4011 4012
    /*
      Delete is needed only in case of an insert failure. In all other
      cases hash_delete will also delete the statement.
    */
    delete statement;
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    goto err_st_hash;
  }
4013
  if (statement->name.str && my_hash_insert(&names_hash, (uchar*) statement))
4014
  {
4015 4016
    my_error(ER_OUT_OF_RESOURCES, MYF(0));
    goto err_names_hash;
4017
  }
Marc Alff's avatar
Marc Alff committed
4018
  mysql_mutex_lock(&LOCK_prepared_stmt_count);
4019 4020 4021 4022 4023 4024 4025 4026 4027
  /*
    We don't check that prepared_stmt_count is <= max_prepared_stmt_count
    because we would like to allow to lower the total limit
    of prepared statements below the current count. In that case
    no new statements can be added until prepared_stmt_count drops below
    the limit.
  */
  if (prepared_stmt_count >= max_prepared_stmt_count)
  {
Marc Alff's avatar
Marc Alff committed
4028
    mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4029 4030
    my_error(ER_MAX_PREPARED_STMT_COUNT_REACHED, MYF(0),
             max_prepared_stmt_count);
4031 4032 4033
    goto err_max;
  }
  prepared_stmt_count++;
Marc Alff's avatar
Marc Alff committed
4034
  mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4035

4036
  last_found_statement= statement;
4037 4038 4039 4040
  return 0;

err_max:
  if (statement->name.str)
Konstantin Osipov's avatar
Konstantin Osipov committed
4041
    my_hash_delete(&names_hash, (uchar*) statement);
4042
err_names_hash:
Konstantin Osipov's avatar
Konstantin Osipov committed
4043
  my_hash_delete(&st_hash, (uchar*) statement);
4044 4045
err_st_hash:
  return 1;
4046 4047
}

4048

4049 4050
void Statement_map::close_transient_cursors()
{
4051
#ifdef TO_BE_IMPLEMENTED
4052 4053 4054
  Statement *stmt;
  while ((stmt= transient_cursor_list.head()))
    stmt->close_cursor();                 /* deletes itself from the list */
4055
#endif
4056 4057 4058
}


4059 4060 4061 4062 4063
void Statement_map::erase(Statement *statement)
{
  if (statement == last_found_statement)
    last_found_statement= 0;
  if (statement->name.str)
Konstantin Osipov's avatar
Konstantin Osipov committed
4064
    my_hash_delete(&names_hash, (uchar *) statement);
4065

Konstantin Osipov's avatar
Konstantin Osipov committed
4066
  my_hash_delete(&st_hash, (uchar *) statement);
Marc Alff's avatar
Marc Alff committed
4067
  mysql_mutex_lock(&LOCK_prepared_stmt_count);
4068 4069
  DBUG_ASSERT(prepared_stmt_count > 0);
  prepared_stmt_count--;
Marc Alff's avatar
Marc Alff committed
4070
  mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4071 4072 4073 4074 4075 4076
}


void Statement_map::reset()
{
  /* Must be first, hash_free will reset st_hash.records */
4077 4078 4079 4080 4081 4082 4083
  if (st_hash.records)
  {
    mysql_mutex_lock(&LOCK_prepared_stmt_count);
    DBUG_ASSERT(prepared_stmt_count >= st_hash.records);
    prepared_stmt_count-= st_hash.records;
    mysql_mutex_unlock(&LOCK_prepared_stmt_count);
  }
4084 4085 4086
  my_hash_reset(&names_hash);
  my_hash_reset(&st_hash);
  last_found_statement= 0;
4087 4088
}

4089

4090 4091
Statement_map::~Statement_map()
{
4092 4093
  /* Statement_map::reset() should be called prior to destructor. */
  DBUG_ASSERT(!st_hash.records);
Konstantin Osipov's avatar
Konstantin Osipov committed
4094 4095
  my_hash_free(&names_hash);
  my_hash_free(&st_hash);
4096 4097
}

Sergei Golubchik's avatar
Sergei Golubchik committed
4098 4099
bool my_var_user::set(THD *thd, Item *item)
{
4100
  Item_func_set_user_var *suv= new (thd->mem_root) Item_func_set_user_var(thd, &name, item);
Sergei Golubchik's avatar
Sergei Golubchik committed
4101 4102 4103 4104
  suv->save_item_result(item);
  return suv->fix_fields(thd, 0) || suv->update();
}

4105 4106 4107 4108 4109 4110 4111

sp_rcontext *my_var_sp::get_rcontext(sp_rcontext *local_ctx) const
{
  return m_rcontext_handler->get_rcontext(local_ctx);
}


Sergei Golubchik's avatar
Sergei Golubchik committed
4112 4113
bool my_var_sp::set(THD *thd, Item *item)
{
4114
  return get_rcontext(thd->spcont)->set_variable(thd, offset, &item);
Sergei Golubchik's avatar
Sergei Golubchik committed
4115 4116
}

4117 4118
bool my_var_sp_row_field::set(THD *thd, Item *item)
{
4119 4120
  return get_rcontext(thd->spcont)->
           set_variable_row_field(thd, offset, m_field_offset, &item);
4121 4122
}

4123 4124

bool select_dumpvar::send_data_to_var_list(List<Item> &items)
4125
{
4126
  DBUG_ENTER("select_dumpvar::send_data_to_var_list");
4127
  List_iterator_fast<my_var> var_li(var_list);
4128
  List_iterator<Item> it(items);
4129
  Item *item;
4130
  my_var *mv;
4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141
  while ((mv= var_li++) && (item= it++))
  {
    if (mv->set(thd, item))
      DBUG_RETURN(true);
  }
  DBUG_RETURN(false);
}


int select_dumpvar::send_data(List<Item> &items)
{
4142
  DBUG_ENTER("select_dumpvar::send_data");
4143

4144
  if (unit->offset_limit_cnt)
4145
  {						// using limit offset,count
4146 4147 4148
    unit->offset_limit_cnt--;
    DBUG_RETURN(0);
  }
4149 4150
  if (row_count++) 
  {
4151
    my_message(ER_TOO_MANY_ROWS, ER_THD(thd, ER_TOO_MANY_ROWS), MYF(0));
4152 4153
    DBUG_RETURN(1);
  }
4154
  if (m_var_sp_row ?
4155 4156
      m_var_sp_row->get_rcontext(thd->spcont)->
        set_variable_row(thd, m_var_sp_row->offset, items) :
4157 4158 4159
      send_data_to_var_list(items))
    DBUG_RETURN(1);

4160
  DBUG_RETURN(thd->is_error());
unknown's avatar
unknown committed
4161 4162 4163 4164
}

bool select_dumpvar::send_eof()
{
4165
  if (! row_count)
4166
    push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
4167
                 ER_SP_FETCH_NO_DATA, ER_THD(thd, ER_SP_FETCH_NO_DATA));
4168 4169 4170 4171
  /*
    Don't send EOF if we're in error condition (which implies we've already
    sent or are sending an error)
  */
4172
  if (unlikely(thd->is_error()))
4173 4174
    return true;

4175 4176 4177
  if (!suppress_my_ok)
    ::my_ok(thd,row_count);

4178
  return 0;
unknown's avatar
unknown committed
4179
}
4180

4181

4182

4183 4184 4185 4186
bool
select_materialize_with_stats::
create_result_table(THD *thd_arg, List<Item> *column_types,
                    bool is_union_distinct, ulonglong options,
4187
                    const LEX_CSTRING *table_alias, bool bit_fields_as_long,
4188
                    bool create_table,
4189 4190
                    bool keep_row_order,
                    uint hidden)
4191 4192 4193 4194 4195 4196 4197
{
  DBUG_ASSERT(table == 0);
  tmp_table_param.field_count= column_types->elements;
  tmp_table_param.bit_fields_as_long= bit_fields_as_long;

  if (! (table= create_tmp_table(thd_arg, &tmp_table_param, *column_types,
                                 (ORDER*) 0, is_union_distinct, 1,
4198
                                 options, HA_POS_ERROR, table_alias,
4199
                                 !create_table, keep_row_order)))
4200 4201 4202 4203
    return TRUE;

  col_stat= (Column_statistics*) table->in_use->alloc(table->s->fields *
                                                      sizeof(Column_statistics));
4204
  if (!col_stat)
4205 4206
    return TRUE;

4207
  reset();
4208 4209 4210 4211 4212 4213
  table->file->extra(HA_EXTRA_WRITE_CACHE);
  table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
  return FALSE;
}


4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224
void select_materialize_with_stats::reset()
{
  memset(col_stat, 0, table->s->fields * sizeof(Column_statistics));
  max_nulls_in_row= 0;
  count_rows= 0;
}


void select_materialize_with_stats::cleanup()
{
  reset();
4225
  select_unit::cleanup();
4226 4227 4228
}


4229
/**
4230
  Override select_unit::send_data to analyze each row for NULLs and to
4231 4232 4233 4234 4235 4236
  update null_statistics before sending data to the client.

  @return TRUE if fatal error when sending data to the client
  @return FALSE on success
*/

Michael Widenius's avatar
Michael Widenius committed
4237
int select_materialize_with_stats::send_data(List<Item> &items)
4238 4239 4240 4241 4242
{
  List_iterator_fast<Item> item_it(items);
  Item *cur_item;
  Column_statistics *cur_col_stat= col_stat;
  uint nulls_in_row= 0;
Michael Widenius's avatar
Michael Widenius committed
4243
  int res;
4244

4245
  if ((res= select_unit::send_data(items)))
Michael Widenius's avatar
Michael Widenius committed
4246
    return res;
Igor Babaev's avatar
Igor Babaev committed
4247 4248 4249 4250 4251
  if (table->null_catch_flags & REJECT_ROW_DUE_TO_NULL_FIELDS)
  {
    table->null_catch_flags&= ~REJECT_ROW_DUE_TO_NULL_FIELDS;
    return 0;
  }
unknown's avatar
unknown committed
4252 4253 4254 4255
  /* Skip duplicate rows. */
  if (write_err == HA_ERR_FOUND_DUPP_KEY ||
      write_err == HA_ERR_FOUND_DUPP_UNIQUE)
    return 0;
4256 4257 4258 4259 4260

  ++count_rows;

  while ((cur_item= item_it++))
  {
unknown's avatar
unknown committed
4261
    if (cur_item->is_null_result())
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
    {
      ++cur_col_stat->null_count;
      cur_col_stat->max_null_row= count_rows;
      if (!cur_col_stat->min_null_row)
        cur_col_stat->min_null_row= count_rows;
      ++nulls_in_row;
    }
    ++cur_col_stat;
  }
  if (nulls_in_row > max_nulls_in_row)
    max_nulls_in_row= nulls_in_row;

unknown's avatar
unknown committed
4274
  return 0;
4275 4276 4277
}


4278 4279 4280 4281 4282 4283
/****************************************************************************
  TMP_TABLE_PARAM
****************************************************************************/

void TMP_TABLE_PARAM::init()
{
4284
  DBUG_ENTER("TMP_TABLE_PARAM::init");
4285
  DBUG_PRINT("enter", ("this: %p", this));
4286 4287 4288
  field_count= sum_func_count= func_count= hidden_field_count= 0;
  group_parts= group_length= group_null_parts= 0;
  quick_group= 1;
unknown's avatar
unknown committed
4289
  table_charset= 0;
4290
  precomputed_group_by= 0;
4291
  bit_fields_as_long= 0;
4292
  materialized_subquery= 0;
Igor Babaev's avatar
Igor Babaev committed
4293
  force_not_null_cols= 0;
unknown's avatar
unknown committed
4294
  skip_create_table= 0;
4295
  DBUG_VOID_RETURN;
4296
}
4297 4298


4299
void thd_increment_bytes_sent(void *thd, size_t length)
4300
{
4301
  /* thd == 0 when close_connection() calls net_send_error() */
unknown's avatar
unknown committed
4302
  if (likely(thd != 0))
4303
  {
4304
    ((THD*) thd)->status_var.bytes_sent+= length;
unknown's avatar
unknown committed
4305
  }
4306 4307
}

4308
my_bool thd_net_is_killed(THD *thd)
Monty's avatar
Monty committed
4309 4310 4311 4312
{
  return thd && thd->killed ? 1 : 0;
}

4313

4314
void thd_increment_bytes_received(void *thd, size_t length)
4315
{
4316 4317
  if (thd != NULL) // MDEV-13073 Ack collector having NULL
    ((THD*) thd)->status_var.bytes_received+= length;
4318 4319 4320 4321 4322
}


void THD::set_status_var_init()
{
4323 4324
  bzero((char*) &status_var, offsetof(STATUS_VAR,
                                      last_cleared_system_status_var));
4325 4326 4327 4328 4329 4330
  /*
    Session status for Threads_running is always 1. It can only be queried
    by thread itself via INFORMATION_SCHEMA.SESSION_STATUS or SHOW [SESSION]
    STATUS. And at this point thread is guaranteed to be running.
  */
  status_var.threads_running= 1;
4331
}
4332

4333

4334
void Security_context::init()
4335
{
4336
  host= user= ip= external_user= 0;
4337
  host_or_ip= "connecting host";
4338
  priv_user[0]= priv_host[0]= proxy_user[0]= priv_role[0]= '\0';
4339
  master_access= 0;
4340 4341 4342 4343 4344 4345
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  db_access= NO_ACCESS;
#endif
}


4346
void Security_context::destroy()
4347
{
4348
  DBUG_PRINT("info", ("freeing security context"));
4349 4350
  // If not pointer to constant
  if (host != my_localhost)
4351
  {
4352
    my_free((char*) host);
4353 4354
    host= NULL;
  }
4355
  if (user != delayed_user)
4356
  {
4357
    my_free((char*) user);
4358 4359 4360
    user= NULL;
  }

4361 4362 4363
  if (external_user)
  {
    my_free(external_user);
4364
    external_user= NULL;
4365 4366
  }

4367
  my_free((char*) ip);
4368
  ip= NULL;
4369 4370 4371
}


4372
void Security_context::skip_grants()
4373 4374 4375 4376
{
  /* privileges for the user are unknown everything is allowed */
  host_or_ip= (char *)"";
  master_access= ~NO_ACCESS;
4377
  *priv_user= *priv_host= '\0';
4378 4379 4380
}


4381 4382
bool Security_context::set_user(char *user_arg)
{
4383
  my_free((char*) user);
4384 4385 4386 4387
  user= my_strdup(user_arg, MYF(0));
  return user == 0;
}

4388 4389 4390 4391 4392
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/**
  Initialize this security context from the passed in credentials
  and activate it in the current thread.

unknown's avatar
unknown committed
4393 4394 4395 4396
  @param       thd
  @param       definer_user
  @param       definer_host
  @param       db
4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418
  @param[out]  backup  Save a pointer to the current security context
                       in the thread. In case of success it points to the
                       saved old context, otherwise it points to NULL.


  During execution of a statement, multiple security contexts may
  be needed:
  - the security context of the authenticated user, used as the
    default security context for all top-level statements
  - in case of a view or a stored program, possibly the security
    context of the definer of the routine, if the object is
    defined with SQL SECURITY DEFINER option.

  The currently "active" security context is parameterized in THD
  member security_ctx. By default, after a connection is
  established, this member points at the "main" security context
  - the credentials of the authenticated user.

  Later, if we would like to execute some sub-statement or a part
  of a statement under credentials of a different user, e.g.
  definer of a procedure, we authenticate this user in a local
  instance of Security_context by means of this method (and
4419
  ultimately by means of acl_getroot), and make the
4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440
  local instance active in the thread by re-setting
  thd->security_ctx pointer.

  Note, that the life cycle and memory management of the "main" and
  temporary security contexts are different.
  For the main security context, the memory for user/host/ip is
  allocated on system heap, and the THD class frees this memory in
  its destructor. The only case when contents of the main security
  context may change during its life time is when someone issued
  CHANGE USER command.
  Memory management of a "temporary" security context is
  responsibility of the module that creates it.

  @retval TRUE  there is no user with the given credentials. The erro
                is reported in the thread.
  @retval FALSE success
*/

bool
Security_context::
change_security_context(THD *thd,
4441 4442 4443
                        LEX_CSTRING *definer_user,
                        LEX_CSTRING *definer_host,
                        LEX_CSTRING *db,
4444 4445 4446 4447 4448 4449 4450 4451 4452
                        Security_context **backup)
{
  bool needs_change;

  DBUG_ENTER("Security_context::change_security_context");

  DBUG_ASSERT(definer_user->str && definer_host->str);

  *backup= NULL;
4453
  needs_change= (strcmp(definer_user->str, thd->security_ctx->priv_user) ||
4454 4455 4456 4457
                 my_strcasecmp(system_charset_info, definer_host->str,
                               thd->security_ctx->priv_host));
  if (needs_change)
  {
4458
    if (acl_getroot(this, definer_user->str, definer_host->str,
4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
                                definer_host->str, db->str))
    {
      my_error(ER_NO_SUCH_USER, MYF(0), definer_user->str,
               definer_host->str);
      DBUG_RETURN(TRUE);
    }
    *backup= thd->security_ctx;
    thd->security_ctx= this;
  }

  DBUG_RETURN(FALSE);
}


void
Security_context::restore_security_context(THD *thd,
                                           Security_context *backup)
{
  if (backup)
    thd->security_ctx= backup;
}
#endif
unknown's avatar
unknown committed
4481

4482

4483 4484 4485 4486 4487 4488 4489
bool Security_context::user_matches(Security_context *them)
{
  return ((user != NULL) && (them->user != NULL) &&
          !strcmp(user, them->user));
}


4490 4491 4492 4493 4494 4495 4496 4497
/****************************************************************************
  Handling of open and locked tables states.

  This is used when we want to open/lock (and then close) some tables when
  we already have a set of tables open and locked. We use these methods for
  access to mysql.proc table to find definitions of stored routines.
****************************************************************************/

4498
void THD::reset_n_backup_open_tables_state(Open_tables_backup *backup)
4499
{
4500 4501
  DBUG_ENTER("reset_n_backup_open_tables_state");
  backup->set_open_tables_state(this);
4502
  backup->mdl_system_tables_svp= mdl_context.mdl_savepoint();
4503
  reset_open_tables_state(this);
4504
  state_flags|= Open_tables_state::BACKUPS_AVAIL;
4505
  DBUG_VOID_RETURN;
4506 4507 4508
}


4509
void THD::restore_backup_open_tables_state(Open_tables_backup *backup)
4510 4511
{
  DBUG_ENTER("restore_backup_open_tables_state");
4512
  mdl_context.rollback_to_savepoint(backup->mdl_system_tables_svp);
4513 4514 4515 4516
  /*
    Before we will throw away current open tables state we want
    to be sure that it was properly cleaned up.
  */
4517 4518
  DBUG_ASSERT(open_tables == 0 &&
              temporary_tables == 0 &&
4519
              derived_tables == 0 &&
Konstantin Osipov's avatar
Konstantin Osipov committed
4520 4521
              lock == 0 &&
              locked_tables_mode == LTM_NONE &&
4522
              m_reprepare_observer == NULL);
4523

4524
  set_open_tables_state(backup);
4525 4526
  DBUG_VOID_RETURN;
}
4527

4528
#if MARIA_PLUGIN_INTERFACE_VERSION < 0x0200
4529
/**
4530 4531 4532
  This is a backward compatibility method, made obsolete
  by the thd_kill_statement service. Keep it here to avoid breaking the
  ABI in case some binary plugins still use it.
4533
*/
4534
#undef thd_killed
4535 4536
extern "C" int thd_killed(const MYSQL_THD thd)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
4537
  return thd_kill_level(thd) > THD_ABORT_SOFTLY;
4538
}
4539 4540 4541 4542 4543 4544 4545
#else
#error now thd_killed() function can go away
#endif

/*
  return thd->killed status to the client,
  mapped to the API enum thd_kill_levels values.
4546 4547 4548 4549 4550 4551 4552 4553 4554

  @note Since this function is called quite frequently thd_kill_level(NULL) is
  forbidden for performance reasons (saves one conditional branch). If your ever
  need to call thd_kill_level() when THD is not available, you options are (most
  to least preferred):
  - try to pass THD through to thd_kill_level()
  - add current_thd to some service and use thd_killed(current_thd)
  - add thd_killed_current() function to kill statement service
  - add if (!thd) thd= current_thd here
4555 4556
*/
extern "C" enum thd_kill_levels thd_kill_level(const MYSQL_THD thd)
4557
{
4558
  DBUG_ASSERT(thd);
4559

4560
  if (likely(thd->killed == NOT_KILLED))
4561 4562 4563 4564 4565 4566 4567
  {
    Apc_target *apc_target= (Apc_target*) &thd->apc_target;
    if (unlikely(apc_target->have_apc_requests()))
    {
      if (thd == current_thd)
        apc_target->process_apc_requests();
    }
4568
    return THD_IS_NOT_KILLED;
4569
  }
4570

4571
  return thd->killed & KILL_HARD_BIT ? THD_ABORT_ASAP : THD_ABORT_SOFTLY;
4572
}
4573

4574 4575 4576 4577 4578 4579 4580 4581

/**
   Send an out-of-band progress report to the client

   The report is sent every 'thd->...progress_report_time' second,
   however not more often than global.progress_report_time.
   If global.progress_report_time is 0, then don't send progress reports, but
   check every second if the value has changed
4582 4583 4584 4585

  We clear any errors that we get from sending the progress packet to
  the client as we don't want to set an error without the caller knowing
  about it.
4586 4587 4588 4589 4590 4591 4592 4593
*/

static void thd_send_progress(THD *thd)
{
  /* Check if we should send the client a progress report */
  ulonglong report_time= my_interval_timer();
  if (report_time > thd->progress.next_report_time)
  {
4594
    uint seconds_to_next= MY_MAX(thd->variables.progress_report_time,
4595 4596 4597 4598 4599 4600 4601
                              global_system_variables.progress_report_time);
    if (seconds_to_next == 0)             // Turned off
      seconds_to_next= 1;                 // Check again after 1 second

    thd->progress.next_report_time= (report_time +
                                     seconds_to_next * 1000000000ULL);
    if (global_system_variables.progress_report_time &&
4602 4603
        thd->variables.progress_report_time && !thd->is_error())
    {
4604
      net_send_progress_packet(thd);
4605 4606 4607
      if (thd->is_error())
        thd->clear_error();
    }
4608 4609 4610 4611 4612 4613 4614 4615
  }
}


/** Initialize progress report handling **/

extern "C" void thd_progress_init(MYSQL_THD thd, uint max_stage)
{
4616 4617 4618
  DBUG_ASSERT(thd->stmt_arena != thd->progress.arena);
  if (thd->progress.arena)
    return; // already initialized
4619 4620 4621 4622 4623
  /*
    Send progress reports to clients that supports it, if the command
    is a high level command (like ALTER TABLE) and we are not in a
    stored procedure
  */
4624
  thd->progress.report= ((thd->client_capabilities & MARIADB_CLIENT_PROGRESS) &&
4625 4626 4627 4628 4629 4630
                         thd->progress.report_to_client &&
                         !thd->in_sub_stmt);
  thd->progress.next_report_time= 0;
  thd->progress.stage= 0;
  thd->progress.counter= thd->progress.max_counter= 0;
  thd->progress.max_stage= max_stage;
4631
  thd->progress.arena= thd->stmt_arena;
4632 4633 4634 4635 4636 4637 4638 4639
}


/* Inform processlist and the client that some progress has been made */

extern "C" void thd_progress_report(MYSQL_THD thd,
                                    ulonglong progress, ulonglong max_progress)
{
4640 4641
  if (thd->stmt_arena != thd->progress.arena)
    return;
4642 4643
  if (thd->progress.max_counter != max_progress)        // Simple optimization
  {
Sergei Golubchik's avatar
Sergei Golubchik committed
4644
    mysql_mutex_lock(&thd->LOCK_thd_data);
4645 4646
    thd->progress.counter= progress;
    thd->progress.max_counter= max_progress;
Sergei Golubchik's avatar
Sergei Golubchik committed
4647
    mysql_mutex_unlock(&thd->LOCK_thd_data);
4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664
  }
  else
    thd->progress.counter= progress;

  if (thd->progress.report)
    thd_send_progress(thd);
}

/**
  Move to next stage in process list handling

  This will reset the timer to ensure the progress is sent to the client
  if client progress reports are activated.
*/

extern "C" void thd_progress_next_stage(MYSQL_THD thd)
{
4665 4666
  if (thd->stmt_arena != thd->progress.arena)
    return;
Sergei Golubchik's avatar
Sergei Golubchik committed
4667
  mysql_mutex_lock(&thd->LOCK_thd_data);
4668 4669 4670
  thd->progress.stage++;
  thd->progress.counter= 0;
  DBUG_ASSERT(thd->progress.stage < thd->progress.max_stage);
Sergei Golubchik's avatar
Sergei Golubchik committed
4671
  mysql_mutex_unlock(&thd->LOCK_thd_data);
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692
  if (thd->progress.report)
  {
    thd->progress.next_report_time= 0;          // Send new stage info
    thd_send_progress(thd);
  }
}

/**
  Disable reporting of progress in process list.

  @note
  This function is safe to call even if one has not called thd_progress_init.

  This function should be called by all parts that does progress
  reporting to ensure that progress list doesn't contain 100 % done
  forever.
*/


extern "C" void thd_progress_end(MYSQL_THD thd)
{
4693 4694
  if (thd->stmt_arena != thd->progress.arena)
    return;
4695 4696 4697 4698 4699
  /*
    It's enough to reset max_counter to set disable progress indicator
    in processlist.
  */
  thd->progress.max_counter= 0;
4700
  thd->progress.arena= 0;
4701 4702 4703
}


4704 4705 4706 4707 4708 4709 4710 4711 4712 4713
/**
  Return the thread id of a user thread
  @param thd user thread
  @return thread id
*/
extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd)
{
  return((unsigned long)thd->thread_id);
}

4714 4715 4716 4717 4718 4719 4720 4721 4722
/**
  Check if THD socket is still connected.
 */
extern "C" int thd_is_connected(MYSQL_THD thd)
{
  return thd->is_connected();
}


Sergei Golubchik's avatar
Sergei Golubchik committed
4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
extern "C" double thd_rnd(MYSQL_THD thd)
{
  return my_rnd(&thd->rand);
}


/**
  Generate string of printable random characters of requested length.

  @param to[out]      Buffer for generation; must be at least length+1 bytes
                      long; result string is always null-terminated
  @param length[in]   How many random characters to put in buffer
*/
extern "C" void thd_create_random_password(MYSQL_THD thd,
                                           char *to, size_t length)
{
  for (char *end= to + length; to < end; to++)
    *to= (char) (my_rnd(&thd->rand)*94 + 33);
  *to= '\0';
}


4745
#ifdef INNODB_COMPATIBILITY_HOOKS
4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763

/** open a table and add it to thd->open_tables

  @note At the moment this is used in innodb background purge threads
  *only*.There should be no table locks, because the background purge does not
  change the table as far as LOCK TABLES is concerned. MDL locks are
  still needed, though.

  To make sure no table stays open for long, this helper allows the thread to
  have only one table open at any given time.
*/
TABLE *open_purge_table(THD *thd, const char *db, size_t dblen,
                        const char *tb, size_t tblen)
{
  DBUG_ENTER("open_purge_table");
  DBUG_ASSERT(thd->open_tables == NULL);
  DBUG_ASSERT(thd->locked_tables_mode < LTM_PRELOCKED);

4764
  Open_table_context ot_ctx(thd, MYSQL_OPEN_IGNORE_FLUSH);
4765
  TABLE_LIST *tl= (TABLE_LIST*)thd->alloc(sizeof(TABLE_LIST));
4766 4767
  LEX_CSTRING db_name= {db, dblen };
  LEX_CSTRING table_name= { tb, tblen };
4768

4769
  tl->init_one_table(&db_name, &table_name, 0, TL_READ);
4770 4771 4772 4773 4774 4775 4776
  tl->i_s_requested_object= OPEN_TABLE_ONLY;

  bool error= open_table(thd, tl, &ot_ctx);

  /* we don't recover here */
  DBUG_ASSERT(!error || !ot_ctx.can_recover_from_failed_open());

4777
  if (unlikely(error))
4778 4779 4780 4781 4782
    close_thread_tables(thd);

  DBUG_RETURN(error ? NULL : tl->table);
}

4783

4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798
/** Find an open table in the list of prelocked tabled

  Used for foreign key actions, for example, in UPDATE t1 SET a=1;
  where a child table t2 has a KB on t1.a.

  But only when virtual columns are involved, otherwise InnoDB
  does not need an open TABLE.
*/
TABLE *find_fk_open_table(THD *thd, const char *db, size_t db_len,
                       const char *table, size_t table_len)
{
  for (TABLE *t= thd->open_tables; t; t= t->next)
  {
    if (t->s->db.length == db_len && t->s->table_name.length == table_len &&
        !strcmp(t->s->db.str, db) && !strcmp(t->s->table_name.str, table) &&
4799
        t->pos_in_table_list->prelocking_placeholder == TABLE_LIST::PRELOCK_FK)
4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
      return t;
  }
  return NULL;
}

/* the following three functions are used in background purge threads */

MYSQL_THD create_thd()
{
  THD *thd= new THD(next_thread_id());
  thd->thread_stack= (char*) &thd;
  thd->store_globals();
  thd->set_command(COM_DAEMON);
  thd->system_thread= SYSTEM_THREAD_GENERIC;
4814
  thd->security_ctx->host_or_ip="";
4815 4816 4817 4818 4819 4820
  add_to_active_threads(thd);
  return thd;
}

void destroy_thd(MYSQL_THD thd)
{
4821 4822 4823
  thd->add_status_to_global();
  unlink_not_visible_thd(thd);
  delete thd;
4824 4825 4826 4827 4828
}

void reset_thd(MYSQL_THD thd)
{
  close_thread_tables(thd);
4829
  thd->release_transactional_locks();
4830 4831 4832 4833 4834 4835 4836 4837 4838
  thd->free_items();
  free_root(thd->mem_root, MYF(MY_KEEP_PREALLOC));
}

unsigned long long thd_get_query_id(const MYSQL_THD thd)
{
  return((unsigned long long)thd->query_id);
}

4839 4840 4841 4842 4843
void thd_clear_error(MYSQL_THD thd)
{
  thd->clear_error();
}

4844
extern "C" const struct charset_info_st *thd_charset(MYSQL_THD thd)
4845 4846 4847 4848
{
  return(thd->charset());
}

4849 4850 4851 4852

/**
  Get the current query string for the thread.

4853 4854
  This function is not thread safe and can be used only by thd owner thread.

4855 4856 4857 4858 4859
  @param The MySQL internal thread pointer
  @return query string and length. May be non-null-terminated.
*/
extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd)
{
4860
  DBUG_ASSERT(thd == current_thd);
4861
  return(&thd->query_string.string);
4862 4863
}

4864 4865 4866 4867 4868 4869 4870 4871 4872

/**
  Get the current query string for the thread.

  @param thd     The MySQL internal thread pointer
  @param buf     Buffer where the query string will be copied
  @param buflen  Length of the buffer

  @return Length of the query
4873
  @retval 0 if LOCK_thd_data cannot be acquired without waiting
4874 4875 4876 4877 4878 4879 4880 4881

  @note This function is thread safe as the query string is
        accessed under mutex protection and the string is copied
        into the provided buffer. @see thd_query_string().
*/

extern "C" size_t thd_query_safe(MYSQL_THD thd, char *buf, size_t buflen)
{
4882 4883 4884 4885 4886 4887 4888 4889 4890 4891
  size_t len= 0;
  /* InnoDB invokes this function while holding internal mutexes.
  THD::awake() will hold LOCK_thd_data while invoking an InnoDB
  function that would acquire the internal mutex. Because this
  function is a non-essential part of information_schema view output,
  we will break the deadlock by avoiding a mutex wait here
  and returning the empty string if a wait would be needed. */
  if (!mysql_mutex_trylock(&thd->LOCK_thd_data))
  {
    len= MY_MIN(buflen - 1, thd->query_length());
4892 4893
    if (len)
      memcpy(buf, thd->query(), len);
4894 4895
    mysql_mutex_unlock(&thd->LOCK_thd_data);
  }
4896 4897 4898 4899 4900
  buf[len]= '\0';
  return len;
}


4901 4902 4903 4904
extern "C" int thd_slave_thread(const MYSQL_THD thd)
{
  return(thd->slave_thread);
}
4905

4906

4907

Marko Mäkelä's avatar
Marko Mäkelä committed
4908

4909 4910 4911 4912
/* Returns high resolution timestamp for the start
  of the current query. */
extern "C" unsigned long long thd_start_utime(const MYSQL_THD thd)
{
4913
  return thd->start_time * 1000000 + thd->start_time_sec_part;
4914 4915 4916
}


4917
/*
4918
  This function can optionally be called to check if thd_rpl_deadlock_check()
4919 4920
  needs to be called for waits done by a given transaction.

4921 4922
  If this function returns false for a given thd, there is no need to do
  any calls to thd_rpl_deadlock_check() on that thd.
4923

4924 4925 4926 4927 4928
  This call is optional; it is safe to call thd_rpl_deadlock_check() in
  any case. This call can be used to save some redundant calls to
  thd_rpl_deadlock_check() if desired. (This is unlikely to matter much
  unless there are _lots_ of waits to report, as the overhead of
  thd_rpl_deadlock_check() is small).
4929
*/
4930
extern "C" int
4931
thd_need_wait_reports(const MYSQL_THD thd)
4932
{
4933 4934
  rpl_group_info *rgi;

4935 4936
  if (mysql_bin_log.is_open())
    return true;
4937 4938 4939 4940 4941 4942
  if (!thd)
    return false;
  rgi= thd->rgi_slave;
  if (!rgi)
    return false;
  return rgi->is_parallel_exec;
4943 4944
}

4945
/*
Marko Mäkelä's avatar
Marko Mäkelä committed
4946
  Used by storage engines (currently TokuDB and InnoDB) to report that
4947 4948
  one transaction THD is about to go to wait for a transactional lock held by
  another transactions OTHER_THD.
4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962

  This is used for parallel replication, where transactions are required to
  commit in the same order on the slave as they did on the master. If the
  transactions on the slave encounter lock conflicts on the slave that did not
  exist on the master, this can cause deadlocks. This is primarily used in
  optimistic (and aggressive) modes.

  Normally, such conflicts will not occur in conservative mode, because the
  same conflict would have prevented the two transactions from committing in
  parallel on the master, thus preventing them from running in parallel on the
  slave in the first place. However, it is possible in case when the optimizer
  chooses a different plan on the slave than on the master (eg. table scan
  instead of index scan).

4963 4964 4965
  Storage engines report lock waits using this call. If a lock wait causes a
  deadlock with the pre-determined commit order, we kill the later
  transaction, and later re-try it, to resolve the deadlock.
4966 4967

  This call need only receive reports about waits for locks that will remain
Marko Mäkelä's avatar
Marko Mäkelä committed
4968
  until the holding transaction commits. InnoDB auto-increment locks,
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 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019
  for example, are released earlier, and so need not be reported. (Such false
  positives are not harmful, but could lead to unnecessary kill and retry, so
  best avoided).

  Returns 1 if the OTHER_THD will be killed to resolve deadlock, 0 if not. The
  actual kill will happen later, asynchronously from another thread. The
  caller does not need to take any actions on the return value if the
  handlerton kill_query method is implemented to abort the to-be-killed
  transaction.
*/
extern "C" int
thd_rpl_deadlock_check(MYSQL_THD thd, MYSQL_THD other_thd)
{
  rpl_group_info *rgi;
  rpl_group_info *other_rgi;

  if (!thd)
    return 0;
  DEBUG_SYNC(thd, "thd_report_wait_for");
  thd->transaction.stmt.mark_trans_did_wait();
  if (!other_thd)
    return 0;
  binlog_report_wait_for(thd, other_thd);
  rgi= thd->rgi_slave;
  other_rgi= other_thd->rgi_slave;
  if (!rgi || !other_rgi)
    return 0;
  if (!rgi->is_parallel_exec)
    return 0;
  if (rgi->rli != other_rgi->rli)
    return 0;
  if (!rgi->gtid_sub_id || !other_rgi->gtid_sub_id)
    return 0;
  if (rgi->current_gtid.domain_id != other_rgi->current_gtid.domain_id)
    return 0;
  if (rgi->gtid_sub_id > other_rgi->gtid_sub_id)
    return 0;
  /*
    This transaction is about to wait for another transaction that is required
    by replication binlog order to commit after. This would cause a deadlock.

    So send a kill to the other transaction, with a temporary error; this will
    cause replication to rollback (and later re-try) the other transaction,
    releasing the lock for this transaction so replication can proceed.
  */
#ifdef HAVE_REPLICATION
  slave_background_kill_request(other_thd);
#endif
  return 1;
}

5020
/*
Marko Mäkelä's avatar
Marko Mäkelä committed
5021
  This function is called from InnoDB to check if the commit order of
5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
  two transactions has already been decided by the upper layer. This happens
  in parallel replication, where the commit order is forced to be the same on
  the slave as it was originally on the master.

  If this function returns false, it means that such commit order will be
  enforced. This allows the storage engine to optionally omit gap lock waits
  or similar measures that would otherwise be needed to ensure that
  transactions would be serialised in a way that would cause a commit order
  that is correct for binlogging for statement-based replication.

  Since transactions are only run in parallel on the slave if they ran without
  lock conflicts on the master, normally no lock conflicts on the slave happen
  during parallel replication. However, there are a couple of corner cases
  where it can happen, like these secondary-index operations:

    T1: INSERT INTO t1 VALUES (7, NULL);
    T2: DELETE FROM t1 WHERE b <= 3;

    T1: UPDATE t1 SET secondary=NULL WHERE primary=1
    T2: DELETE t1 WHERE secondary <= 3

  The DELETE takes a gap lock that can block the INSERT/UPDATE, but the row
  locks set by INSERT/UPDATE do not block the DELETE. Thus, the execution
  order of the transactions determine whether a lock conflict occurs or
  not. Thus a lock conflict can occur on the slave where it did not on the
  master.

  If this function returns true, normal locking should be done as required by
  the binlogging and transaction isolation level in effect. But if it returns
Marko Mäkelä's avatar
Marko Mäkelä committed
5051
  false, the correct order will be enforced anyway, and InnoDB can
5052 5053 5054 5055
  avoid taking the gap lock, preventing the lock conflict.

  Calling this function is just an optimisation to avoid unnecessary
  deadlocks. If it was not used, a gap lock would be set that could eventually
5056 5057
  cause a deadlock; the deadlock would be caught by thd_rpl_deadlock_check()
  and the transaction T2 killed and rolled back (and later re-tried).
5058
*/
5059 5060 5061
extern "C" int
thd_need_ordering_with(const MYSQL_THD thd, const MYSQL_THD other_thd)
{
5062 5063
  rpl_group_info *rgi, *other_rgi;

5064
  DBUG_EXECUTE_IF("disable_thd_need_ordering_with", return 1;);
5065 5066
  if (!thd || !other_thd)
    return 1;
5067 5068 5069
#ifdef WITH_WSREP
  /* wsrep applier, replayer and TOI processing threads are ordered
     by replication provider, relaxed GAP locking protocol can be used
5070 5071 5072
     between high priority wsrep threads. Note that this function
     is called while holding lock_sys mutex, therefore we can't
     use THD::LOCK_thd_data mutex below to follow mutex ordering rules.
5073 5074 5075
  */
  if (WSREP_ON &&
      wsrep_thd_is_BF(const_cast<THD *>(thd), false) &&
5076
      wsrep_thd_is_BF(const_cast<THD *>(other_thd), false))
5077 5078
    return 0;
#endif /* WITH_WSREP */
5079 5080
  rgi= thd->rgi_slave;
  other_rgi= other_thd->rgi_slave;
5081 5082 5083 5084 5085 5086 5087 5088
  if (!rgi || !other_rgi)
    return 1;
  if (!rgi->is_parallel_exec)
    return 1;
  if (rgi->rli != other_rgi->rli)
    return 1;
  if (rgi->current_gtid.domain_id != other_rgi->current_gtid.domain_id)
    return 1;
5089
  if (!rgi->commit_id || rgi->commit_id != other_rgi->commit_id)
5090
    return 1;
5091
  DBUG_EXECUTE_IF("thd_need_ordering_with_force", return 1;);
5092
  /*
5093
    Otherwise, these two threads are doing parallel replication within the same
5094 5095 5096 5097 5098 5099 5100
    replication domain. Their commit order is already fixed, so we do not need
    gap locks or similar to otherwise enforce ordering (and in fact such locks
    could lead to unnecessary deadlocks and transaction retry).
  */
  return 0;
}

5101 5102
extern "C" int thd_non_transactional_update(const MYSQL_THD thd)
{
5103
  return(thd->transaction.all.modified_non_trans_table);
5104 5105
}

5106
extern "C" int thd_binlog_format(const MYSQL_THD thd)
5107
{
sjaakola's avatar
sjaakola committed
5108 5109 5110
  if (WSREP(thd))
  {
    /* for wsrep binlog format is meaningful also when binlogging is off */
5111
    return (int) thd->wsrep_binlog_format();
sjaakola's avatar
sjaakola committed
5112 5113 5114
  }
  if (mysql_bin_log.is_open() && (thd->variables.option_bits & OPTION_BIN_LOG))
    return (int) thd->variables.binlog_format;
5115
  return BINLOG_FORMAT_UNSPEC;
5116
}
5117 5118 5119

extern "C" void thd_mark_transaction_to_rollback(MYSQL_THD thd, bool all)
{
5120 5121
  DBUG_ASSERT(thd);
  thd->mark_transaction_to_rollback(all);
5122
}
5123 5124 5125

extern "C" bool thd_binlog_filter_ok(const MYSQL_THD thd)
{
5126
  return binlog_filter->db_ok(thd->db.str);
5127
}
5128

5129 5130 5131 5132 5133 5134 5135 5136
/*
  This is similar to sqlcom_can_generate_row_events, with the expection
  that we only return 1 if we are going to generate row events in a
  transaction.
  CREATE OR REPLACE is always safe to do as this will run in it's own
  transaction.
*/

5137 5138
extern "C" bool thd_sqlcom_can_generate_row_events(const MYSQL_THD thd)
{
5139 5140
  return (sqlcom_can_generate_row_events(thd) && thd->lex->sql_command !=
          SQLCOM_CREATE_TABLE);
5141
}
Mats Kindahl's avatar
Mats Kindahl committed
5142

5143

5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
extern "C" enum durability_properties thd_get_durability_property(const MYSQL_THD thd)
{
  enum durability_properties ret= HA_REGULAR_DURABILITY;
  
  if (thd != NULL)
    ret= thd->durability_property;

  return ret;
}

/** Get the auto_increment_offset auto_increment_increment.
5155
Exposed by thd_autoinc_service.
5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179
Needed by InnoDB.
@param thd	Thread object
@param off	auto_increment_offset
@param inc	auto_increment_increment */
extern "C" void thd_get_autoinc(const MYSQL_THD thd, ulong* off, ulong* inc)
{
  *off = thd->variables.auto_increment_offset;
  *inc = thd->variables.auto_increment_increment;
}


/**
  Is strict sql_mode set.
  Needed by InnoDB.
  @param thd	Thread object
  @return True if sql_mode has strict mode (all or trans).
    @retval true  sql_mode has strict mode (all or trans).
    @retval false sql_mode has not strict mode (all or trans).
*/
extern "C" bool thd_is_strict_mode(const MYSQL_THD thd)
{
  return thd->is_strict_mode();
}

5180

5181 5182 5183 5184 5185 5186 5187 5188
/**
  Get query start time as SQL field data.
  Needed by InnoDB.
  @param thd	Thread object
  @param buf	Buffer to hold start time data
*/
void thd_get_query_start_data(THD *thd, char *buf)
{
5189 5190
  Field_timestampf f((uchar *)buf, NULL, 0, Field::NONE, &empty_clex_str,
                     NULL, 6);
5191 5192 5193 5194
  f.store_TIME(thd->query_start(), thd->query_start_sec_part());
}


5195 5196 5197 5198 5199 5200 5201
/*
  Interface for MySQL Server, plugins and storage engines to report
  when they are going to sleep/stall.
  
  SYNOPSIS
  thd_wait_begin()
  thd                     Thread object
5202
                          Can be NULL, in this case current THD is used.
5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216
  wait_type               Type of wait
                          1 -- short wait (e.g. for mutex)
                          2 -- medium wait (e.g. for disk io)
                          3 -- large wait (e.g. for locked row/table)
  NOTES
    This is used by the threadpool to have better knowledge of which
    threads that currently are actively running on CPUs. When a thread
    reports that it's going to sleep/stall, the threadpool scheduler is
    free to start another thread in the pool most likely. The expected wait
    time is simply an indication of how long the wait is expected to
    become, the real wait time could be very different.

  thd_wait_end MUST be called immediately after waking up again.
*/
Mikael Ronstrom's avatar
Mikael Ronstrom committed
5217
extern "C" void thd_wait_begin(MYSQL_THD thd, int wait_type)
5218
{
5219
  if (!thd)
5220
  {
5221 5222
    thd= current_thd;
    if (unlikely(!thd))
5223 5224 5225
      return;
  }
  MYSQL_CALLBACK(thd->scheduler, thd_wait_begin, (thd, wait_type));
5226 5227 5228 5229 5230 5231 5232
}

/**
  Interface for MySQL Server, plugins and storage engines to report
  when they waking up from a sleep/stall.

  @param  thd   Thread handle
5233
  Can be NULL, in this case current THD is used.
5234 5235 5236
*/
extern "C" void thd_wait_end(MYSQL_THD thd)
{
5237
  if (!thd)
5238
  {
5239 5240
    thd= current_thd;
    if (unlikely(!thd))
5241 5242
      return;
  }
5243
  MYSQL_CALLBACK(thd->scheduler, thd_wait_end, (thd));
5244 5245
}

5246
#endif // INNODB_COMPATIBILITY_HOOKS */
5247

5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260
/****************************************************************************
  Handling of statement states in functions and triggers.

  This is used to ensure that the function/trigger gets a clean state
  to work with and does not cause any side effects of the calling statement.

  It also allows most stored functions and triggers to replicate even
  if they are used items that would normally be stored in the binary
  replication (like last_insert_id() etc...)

  The following things is done
  - Disable binary logging for the duration of the statement
  - Disable multi-result-sets for the duration of the statement
5261
  - Value of last_insert_id() is saved and restored
5262 5263 5264 5265
  - Value set by 'SET INSERT_ID=#' is reset and restored
  - Value for found_rows() is reset and restored
  - examined_row_count is added to the total
  - cuted_fields is added to the total
5266
  - new savepoint level is created and destroyed
5267 5268 5269 5270 5271 5272

  NOTES:
    Seed for random() is saved for the first! usage of RAND()
    We reset examined_row_count and cuted_fields and add these to the
    result to ensure that if we have a bug that would reset these within
    a function, we are not loosing any rows from the main statement.
5273 5274

    We do not reset value of last_insert_id().
5275 5276 5277 5278 5279
****************************************************************************/

void THD::reset_sub_statement_state(Sub_statement_state *backup,
                                    uint new_state)
{
5280 5281 5282 5283 5284 5285 5286
#ifndef EMBEDDED_LIBRARY
  /* BUG#33029, if we are replicating from a buggy master, reset
     auto_inc_intervals_forced to prevent substatement
     (triggers/functions) from using erroneous INSERT_ID value
   */
  if (rpl_master_erroneous_autoinc(this))
  {
5287 5288
    DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0);
    auto_inc_intervals_forced.swap(&backup->auto_inc_intervals_forced);
5289 5290 5291
  }
#endif
  
5292
  backup->option_bits=     variables.option_bits;
5293
  backup->count_cuted_fields= count_cuted_fields;
5294 5295 5296 5297 5298
  backup->in_sub_stmt=     in_sub_stmt;
  backup->enable_slow_log= enable_slow_log;
  backup->limit_found_rows= limit_found_rows;
  backup->cuted_fields=     cuted_fields;
  backup->client_capabilities= client_capabilities;
5299
  backup->savepoints= transaction.savepoints;
5300 5301 5302 5303
  backup->first_successful_insert_id_in_prev_stmt= 
    first_successful_insert_id_in_prev_stmt;
  backup->first_successful_insert_id_in_cur_stmt= 
    first_successful_insert_id_in_cur_stmt;
5304
  store_slow_query_state(backup);
5305

5306
  if ((!lex->requires_prelocking() || is_update_query(lex->sql_command)) &&
5307
      !is_current_stmt_binlog_format_row())
5308
  {
5309
    variables.option_bits&= ~OPTION_BIN_LOG;
5310
  }
5311

unknown's avatar
unknown committed
5312 5313 5314
  if ((backup->option_bits & OPTION_BIN_LOG) &&
       is_update_query(lex->sql_command) &&
       !is_current_stmt_binlog_format_row())
5315 5316
    mysql_bin_log.start_union_events(this, this->query_id);

5317 5318 5319 5320
  /* Disable result sets */
  client_capabilities &= ~CLIENT_MULTI_RESULTS;
  in_sub_stmt|= new_state;
  cuted_fields= 0;
5321
  transaction.savepoints= 0;
5322
  first_successful_insert_id_in_cur_stmt= 0;
5323
  reset_slow_query_state();
5324 5325 5326 5327
}

void THD::restore_sub_statement_state(Sub_statement_state *backup)
{
5328
  DBUG_ENTER("THD::restore_sub_statement_state");
5329 5330 5331 5332 5333 5334 5335
#ifndef EMBEDDED_LIBRARY
  /* BUG#33029, if we are replicating from a buggy master, restore
     auto_inc_intervals_forced so that the top statement can use the
     INSERT_ID value set before this statement.
   */
  if (rpl_master_erroneous_autoinc(this))
  {
5336 5337
    backup->auto_inc_intervals_forced.swap(&auto_inc_intervals_forced);
    DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0);
5338 5339 5340
  }
#endif

5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354
  /*
    To save resources we want to release savepoints which were created
    during execution of function or trigger before leaving their savepoint
    level. It is enough to release first savepoint set on this level since
    all later savepoints will be released automatically.
  */
  if (transaction.savepoints)
  {
    SAVEPOINT *sv;
    for (sv= transaction.savepoints; sv->prev; sv= sv->prev)
    {}
    /* ha_release_savepoint() never returns error. */
    (void)ha_release_savepoint(this, sv);
  }
5355
  count_cuted_fields= backup->count_cuted_fields;
5356
  transaction.savepoints= backup->savepoints;
5357
  variables.option_bits= backup->option_bits;
5358 5359
  in_sub_stmt=      backup->in_sub_stmt;
  enable_slow_log=  backup->enable_slow_log;
5360 5361 5362 5363
  first_successful_insert_id_in_prev_stmt= 
    backup->first_successful_insert_id_in_prev_stmt;
  first_successful_insert_id_in_cur_stmt= 
    backup->first_successful_insert_id_in_cur_stmt;
5364
  limit_found_rows= backup->limit_found_rows;
Sergei Golubchik's avatar
Sergei Golubchik committed
5365
  set_sent_row_count(backup->sent_row_count);
5366
  client_capabilities= backup->client_capabilities;
5367 5368 5369 5370

  /* Restore statistic needed for slow log */
  add_slow_query_state(backup);

5371 5372 5373 5374
  /*
    If we've left sub-statement mode, reset the fatal error flag.
    Otherwise keep the current value, to propagate it up the sub-statement
    stack.
5375 5376 5377

    NOTE: is_fatal_sub_stmt_error can be set only if we've been in the
    sub-statement mode.
5378 5379
  */
  if (!in_sub_stmt)
5380
    is_fatal_sub_stmt_error= false;
5381

5382
  if ((variables.option_bits & OPTION_BIN_LOG) && is_update_query(lex->sql_command) &&
unknown's avatar
unknown committed
5383
       !is_current_stmt_binlog_format_row())
5384
    mysql_bin_log.stop_union_events(this);
5385

5386 5387 5388 5389
  /*
    The following is added to the old values as we are interested in the
    total complexity of the query
  */
Sergei Golubchik's avatar
Sergei Golubchik committed
5390
  inc_examined_row_count(backup->examined_row_count);
5391
  cuted_fields+=       backup->cuted_fields;
5392
  DBUG_VOID_RETURN;
5393
}
5394

5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444
/*
  Store slow query state at start of a stored procedure statment
*/

void THD::store_slow_query_state(Sub_statement_state *backup)
{
  backup->affected_rows=           affected_rows;
  backup->bytes_sent_old=          bytes_sent_old;
  backup->examined_row_count=      m_examined_row_count;
  backup->query_plan_flags=        query_plan_flags;
  backup->query_plan_fsort_passes= query_plan_fsort_passes;
  backup->sent_row_count=          m_sent_row_count;
  backup->tmp_tables_disk_used=    tmp_tables_disk_used;
  backup->tmp_tables_size=         tmp_tables_size;
  backup->tmp_tables_used=         tmp_tables_used;
}

/* Reset variables related to slow query log */

void THD::reset_slow_query_state()
{
  affected_rows=                0;
  bytes_sent_old=               status_var.bytes_sent;
  m_examined_row_count=         0;
  m_sent_row_count=             0;
  query_plan_flags=             QPLAN_INIT;
  query_plan_fsort_passes=      0;
  tmp_tables_disk_used=         0;
  tmp_tables_size=              0;
  tmp_tables_used=              0;
}

/*
  Add back the stored values to the current counters to be able to get
  right status for 'call procedure_name'
*/

void THD::add_slow_query_state(Sub_statement_state *backup)
{
  affected_rows+=                backup->affected_rows;
  bytes_sent_old=                backup->bytes_sent_old;
  m_examined_row_count+=         backup->examined_row_count;
  m_sent_row_count+=             backup->sent_row_count;
  query_plan_flags|=             backup->query_plan_flags;
  query_plan_fsort_passes+=      backup->query_plan_fsort_passes;
  tmp_tables_disk_used+=         backup->tmp_tables_disk_used;
  tmp_tables_size+=              backup->tmp_tables_size;
  tmp_tables_used+=              backup->tmp_tables_used;
}

5445

5446 5447
void THD::set_statement(Statement *stmt)
{
Marc Alff's avatar
Marc Alff committed
5448
  mysql_mutex_lock(&LOCK_thd_data);
5449
  Statement::set_statement(stmt);
Marc Alff's avatar
Marc Alff committed
5450
  mysql_mutex_unlock(&LOCK_thd_data);
5451 5452
}

5453 5454
void THD::set_sent_row_count(ha_rows count)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5455 5456
  m_sent_row_count= count;
  MYSQL_SET_STATEMENT_ROWS_SENT(m_statement_psi, m_sent_row_count);
5457 5458 5459 5460
}

void THD::set_examined_row_count(ha_rows count)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5461 5462
  m_examined_row_count= count;
  MYSQL_SET_STATEMENT_ROWS_EXAMINED(m_statement_psi, m_examined_row_count);
5463 5464 5465 5466
}

void THD::inc_sent_row_count(ha_rows count)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5467 5468
  m_sent_row_count+= count;
  MYSQL_SET_STATEMENT_ROWS_SENT(m_statement_psi, m_sent_row_count);
5469 5470 5471 5472
}

void THD::inc_examined_row_count(ha_rows count)
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5473 5474
  m_examined_row_count+= count;
  MYSQL_SET_STATEMENT_ROWS_EXAMINED(m_statement_psi, m_examined_row_count);
5475 5476 5477 5478
}

void THD::inc_status_created_tmp_disk_tables()
{
5479 5480
  tmp_tables_disk_used++;
  query_plan_flags|= QPLAN_TMP_DISK;
Sergei Golubchik's avatar
Sergei Golubchik committed
5481
  status_var_increment(status_var.created_tmp_disk_tables_);
5482
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5483
  PSI_STATEMENT_CALL(inc_statement_created_tmp_disk_tables)(m_statement_psi, 1);
5484 5485 5486 5487 5488
#endif
}

void THD::inc_status_created_tmp_tables()
{
5489 5490
  tmp_tables_used++;
  query_plan_flags|= QPLAN_TMP_TABLE;
Sergei Golubchik's avatar
Sergei Golubchik committed
5491
  status_var_increment(status_var.created_tmp_tables_);
5492
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5493
  PSI_STATEMENT_CALL(inc_statement_created_tmp_tables)(m_statement_psi, 1);
5494 5495 5496 5497 5498
#endif
}

void THD::inc_status_select_full_join()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5499
  status_var_increment(status_var.select_full_join_count_);
5500
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5501
  PSI_STATEMENT_CALL(inc_statement_select_full_join)(m_statement_psi, 1);
5502 5503 5504 5505 5506
#endif
}

void THD::inc_status_select_full_range_join()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5507
  status_var_increment(status_var.select_full_range_join_count_);
5508
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5509
  PSI_STATEMENT_CALL(inc_statement_select_full_range_join)(m_statement_psi, 1);
5510 5511 5512 5513 5514
#endif
}

void THD::inc_status_select_range()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5515
  status_var_increment(status_var.select_range_count_);
5516
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5517
  PSI_STATEMENT_CALL(inc_statement_select_range)(m_statement_psi, 1);
5518 5519 5520 5521 5522
#endif
}

void THD::inc_status_select_range_check()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5523
  status_var_increment(status_var.select_range_check_count_);
5524
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5525
  PSI_STATEMENT_CALL(inc_statement_select_range_check)(m_statement_psi, 1);
5526 5527 5528 5529 5530
#endif
}

void THD::inc_status_select_scan()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5531
  status_var_increment(status_var.select_scan_count_);
5532
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5533
  PSI_STATEMENT_CALL(inc_statement_select_scan)(m_statement_psi, 1);
5534 5535 5536 5537 5538
#endif
}

void THD::inc_status_sort_merge_passes()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5539
  status_var_increment(status_var.filesort_merge_passes_);
5540
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5541
  PSI_STATEMENT_CALL(inc_statement_sort_merge_passes)(m_statement_psi, 1);
5542 5543 5544 5545 5546
#endif
}

void THD::inc_status_sort_range()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5547
  status_var_increment(status_var.filesort_range_count_);
5548
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5549
  PSI_STATEMENT_CALL(inc_statement_sort_range)(m_statement_psi, 1);
5550 5551 5552 5553 5554
#endif
}

void THD::inc_status_sort_rows(ha_rows count)
{
5555
  statistic_add(status_var.filesort_rows_, (ulong)count, &LOCK_status);
5556
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5557
  PSI_STATEMENT_CALL(inc_statement_sort_rows)(m_statement_psi, (ulong)count);
5558 5559 5560 5561 5562
#endif
}

void THD::inc_status_sort_scan()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
5563
  status_var_increment(status_var.filesort_scan_count_);
5564
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5565
  PSI_STATEMENT_CALL(inc_statement_sort_scan)(m_statement_psi, 1);
5566 5567 5568 5569 5570 5571 5572
#endif
}

void THD::set_status_no_index_used()
{
  server_status|= SERVER_QUERY_NO_INDEX_USED;
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5573
  PSI_STATEMENT_CALL(set_statement_no_index_used)(m_statement_psi);
5574 5575 5576 5577 5578 5579 5580
#endif
}

void THD::set_status_no_good_index_used()
{
  server_status|= SERVER_QUERY_NO_GOOD_INDEX_USED;
#ifdef HAVE_PSI_STATEMENT_INTERFACE
5581
  PSI_STATEMENT_CALL(set_statement_no_good_index_used)(m_statement_psi);
5582 5583 5584
#endif
}

5585 5586 5587
/** Assign a new value to thd->query and thd->query_id.  */

void THD::set_query_and_id(char *query_arg, uint32 query_length_arg,
5588
                           CHARSET_INFO *cs,
5589 5590
                           query_id_t new_query_id)
{
Marc Alff's avatar
Marc Alff committed
5591
  mysql_mutex_lock(&LOCK_thd_data);
5592
  set_query_inner(query_arg, query_length_arg, cs);
Marc Alff's avatar
Marc Alff committed
5593
  mysql_mutex_unlock(&LOCK_thd_data);
5594 5595 5596
  query_id= new_query_id;
}

5597 5598 5599
/** Assign a new value to thd->mysys_var.  */
void THD::set_mysys_var(struct st_my_thread_var *new_mysys_var)
{
5600
  mysql_mutex_lock(&LOCK_thd_kill);
5601
  mysys_var= new_mysys_var;
5602
  mysql_mutex_unlock(&LOCK_thd_kill);
5603
}
5604

5605 5606 5607 5608 5609 5610 5611
/**
  Leave explicit LOCK TABLES or prelocked mode and restore value of
  transaction sentinel in MDL subsystem.
*/

void THD::leave_locked_tables_mode()
{
5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
  if (locked_tables_mode == LTM_LOCK_TABLES)
  {
    /*
      When leaving LOCK TABLES mode we have to change the duration of most
      of the metadata locks being held, except for HANDLER and GRL locks,
      to transactional for them to be properly released at UNLOCK TABLES.
    */
    mdl_context.set_transaction_duration_for_all_locks();
    /*
      Make sure we don't release the global read lock and commit blocker
      when leaving LTM.
    */
    global_read_lock.set_explicit_lock_duration(this);
    /* Also ensure that we don't release metadata locks for open HANDLERs. */
    if (handler_tables_hash.records)
      mysql_ha_set_explicit_lock_duration(this);
5628 5629
    if (ull_hash.records)
      mysql_ull_set_explicit_lock_duration(this);
5630
  }
5631 5632 5633
  locked_tables_mode= LTM_NONE;
}

5634
void THD::get_definer(LEX_USER *definer, bool role)
5635
{
5636
  binlog_invoker(role);
5637
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
5638 5639 5640
#ifdef WITH_WSREP
  if ((wsrep_applier || slave_thread) && has_invoker())
#else
5641
  if (slave_thread && has_invoker())
5642
#endif
5643
  {
5644 5645
    definer->user= invoker.user;
    definer->host= invoker.host;
5646
    definer->reset_auth();
5647 5648 5649
  }
  else
#endif
5650
    get_default_definer(this, definer, role);
5651 5652
}

5653

5654 5655 5656 5657 5658 5659
/**
  Mark transaction to rollback and mark error as fatal to a sub-statement.

  @param  all   TRUE <=> rollback main transaction.
*/

5660
void THD::mark_transaction_to_rollback(bool all)
5661
{
5662 5663 5664 5665 5666 5667 5668
  /*
    There is no point in setting is_fatal_sub_stmt_error unless
    we are actually in_sub_stmt.
  */
  if (in_sub_stmt)
    is_fatal_sub_stmt_error= true;
  transaction_rollback_request= all;
5669
}
5670 5671 5672
/***************************************************************************
  Handling of XA id cacheing
***************************************************************************/
5673 5674 5675
class XID_cache_element
{
  /*
5676 5677 5678 5679 5680 5681 5682
    m_state is used to prevent elements from being deleted while XA RECOVER
    iterates xid cache and to prevent recovered elments from being acquired by
    multiple threads.

    bits 1..29 are reference counter
    bit 30 is RECOVERED flag
    bit 31 is ACQUIRED flag (thread owns this xid)
5683
    bit 32 is unused
5684

5685
    Newly allocated and deleted elements have m_state set to 0.
5686

5687 5688
    On lock() m_state is atomically incremented. It also creates load-ACQUIRE
    memory barrier to make sure m_state is actually updated before furhter
5689 5690 5691
    memory accesses. Attempting to lock an element that has neither ACQUIRED
    nor RECOVERED flag set returns failure and further accesses to element
    memory are forbidden.
5692

5693 5694 5695
    On unlock() m_state is decremented. It also creates store-RELEASE memory
    barrier to make sure m_state is actually updated after preceding memory
    accesses.
5696

5697 5698
    ACQUIRED flag is set when thread registers it's xid or when thread acquires
    recovered xid.
5699

5700
    RECOVERED flag is set for elements found during crash recovery.
Marc Alff's avatar
Marc Alff committed
5701

5702 5703
    ACQUIRED and RECOVERED flags are cleared before element is deleted from
    hash in a spin loop, after last reference is released.
5704
  */
5705
  int32 m_state;
5706
public:
5707 5708
  static const int32 ACQUIRED= 1 << 30;
  static const int32 RECOVERED= 1 << 29;
5709
  XID_STATE *m_xid_state;
5710 5711 5712
  bool is_set(int32 flag)
  { return my_atomic_load32_explicit(&m_state, MY_MEMORY_ORDER_RELAXED) & flag; }
  void set(int32 flag)
5713
  {
5714 5715
    DBUG_ASSERT(!is_set(ACQUIRED | RECOVERED));
    my_atomic_add32_explicit(&m_state, flag, MY_MEMORY_ORDER_RELAXED);
5716
  }
5717
  bool lock()
5718
  {
5719 5720 5721 5722 5723
    int32 old= my_atomic_add32_explicit(&m_state, 1, MY_MEMORY_ORDER_ACQUIRE);
    if (old & (ACQUIRED | RECOVERED))
      return true;
    unlock();
    return false;
5724
  }
5725 5726
  void unlock()
  { my_atomic_add32_explicit(&m_state, -1, MY_MEMORY_ORDER_RELEASE); }
5727 5728
  void mark_uninitialized()
  {
5729 5730
    int32 old= ACQUIRED;
    while (!my_atomic_cas32_weak_explicit(&m_state, &old, 0,
5731 5732 5733
                                          MY_MEMORY_ORDER_RELAXED,
                                          MY_MEMORY_ORDER_RELAXED))
    {
5734
      old&= ACQUIRED | RECOVERED;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
5735
      (void) LF_BACKOFF();
5736 5737
    }
  }
5738
  bool acquire_recovered()
5739
  {
5740 5741 5742 5743 5744 5745 5746 5747
    int32 old= RECOVERED;
    while (!my_atomic_cas32_weak_explicit(&m_state, &old, ACQUIRED | RECOVERED,
                                          MY_MEMORY_ORDER_RELAXED,
                                          MY_MEMORY_ORDER_RELAXED))
    {
      if (!(old & RECOVERED) || (old & ACQUIRED))
        return false;
      old= RECOVERED;
Sergey Vojtovich's avatar
Sergey Vojtovich committed
5748
      (void) LF_BACKOFF();
5749 5750
    }
    return true;
5751 5752 5753 5754 5755
  }
  static void lf_hash_initializer(LF_HASH *hash __attribute__((unused)),
                                  XID_cache_element *element,
                                  XID_STATE *xid_state)
  {
5756
    DBUG_ASSERT(!element->is_set(ACQUIRED | RECOVERED));
5757 5758 5759 5760 5761 5762
    element->m_xid_state= xid_state;
    xid_state->xid_cache_element= element;
  }
  static void lf_alloc_constructor(uchar *ptr)
  {
    XID_cache_element *element= (XID_cache_element*) (ptr + LF_HASH_OVERHEAD);
5763
    element->m_state= 0;
5764 5765 5766 5767
  }
  static void lf_alloc_destructor(uchar *ptr)
  {
    XID_cache_element *element= (XID_cache_element*) (ptr + LF_HASH_OVERHEAD);
5768 5769
    DBUG_ASSERT(!element->is_set(ACQUIRED));
    if (element->is_set(RECOVERED))
5770 5771 5772 5773 5774 5775 5776 5777
      my_free(element->m_xid_state);
  }
  static uchar *key(const XID_cache_element *element, size_t *length,
                    my_bool not_used __attribute__((unused)))
  {
    *length= element->m_xid_state->xid.key_length();
    return element->m_xid_state->xid.key();
  }
Marc Alff's avatar
Marc Alff committed
5778 5779 5780
};


5781 5782
static LF_HASH xid_cache;
static bool xid_cache_inited;
Marc Alff's avatar
Marc Alff committed
5783 5784


5785
bool THD::fix_xid_hash_pins()
5786
{
5787 5788 5789 5790 5791
  if (!xid_hash_pins)
    xid_hash_pins= lf_hash_get_pins(&xid_cache);
  return !xid_hash_pins;
}

Marc Alff's avatar
Marc Alff committed
5792

5793 5794 5795 5796 5797 5798 5799 5800 5801
void xid_cache_init()
{
  xid_cache_inited= true;
  lf_hash_init(&xid_cache, sizeof(XID_cache_element), LF_HASH_UNIQUE, 0, 0,
               (my_hash_get_key) XID_cache_element::key, &my_charset_bin);
  xid_cache.alloc.constructor= XID_cache_element::lf_alloc_constructor;
  xid_cache.alloc.destructor= XID_cache_element::lf_alloc_destructor;
  xid_cache.initializer=
    (lf_hash_initializer) XID_cache_element::lf_hash_initializer;
5802 5803
}

5804

5805 5806
void xid_cache_free()
{
5807
  if (xid_cache_inited)
5808
  {
5809 5810
    lf_hash_destroy(&xid_cache);
    xid_cache_inited= false;
5811 5812 5813
  }
}

5814

5815 5816 5817 5818
/**
  Find recovered XA transaction by XID.
*/

5819
XID_STATE *xid_cache_search(THD *thd, XID *xid)
5820
{
5821
  XID_STATE *xs= 0;
5822 5823 5824 5825 5826 5827
  DBUG_ASSERT(thd->xid_hash_pins);
  XID_cache_element *element=
    (XID_cache_element*) lf_hash_search(&xid_cache, thd->xid_hash_pins,
                                        xid->key(), xid->key_length());
  if (element)
  {
5828 5829
    if (element->acquire_recovered())
      xs= element->m_xid_state;
5830
    lf_hash_search_unpin(thd->xid_hash_pins);
5831
    DEBUG_SYNC(thd, "xa_after_search");
5832
  }
5833
  return xs;
5834 5835
}

5836

5837 5838 5839
bool xid_cache_insert(XID *xid, enum xa_states xa_state)
{
  XID_STATE *xs;
5840 5841 5842 5843 5844 5845 5846
  LF_PINS *pins;
  int res= 1;

  if (!(pins= lf_hash_get_pins(&xid_cache)))
    return true;

  if ((xs= (XID_STATE*) my_malloc(sizeof(*xs), MYF(MY_WME))))
5847 5848 5849
  {
    xs->xa_state=xa_state;
    xs->xid.set(xid);
5850
    xs->rm_error=0;
5851 5852 5853 5854

    if ((res= lf_hash_insert(&xid_cache, pins, xs)))
      my_free(xs);
    else
5855
      xs->xid_cache_element->set(XID_cache_element::RECOVERED);
5856 5857
    if (res == 1)
      res= 0;
5858
  }
5859
  lf_hash_put_pins(pins);
5860 5861 5862
  return res;
}

5863

5864
bool xid_cache_insert(THD *thd, XID_STATE *xid_state)
5865
{
5866 5867 5868 5869 5870
  if (thd->fix_xid_hash_pins())
    return true;

  int res= lf_hash_insert(&xid_cache, thd->xid_hash_pins, xid_state);
  switch (res)
5871
  {
5872
  case 0:
5873
    xid_state->xid_cache_element->set(XID_cache_element::ACQUIRED);
5874 5875
    break;
  case 1:
5876
    my_error(ER_XAER_DUPID, MYF(0));
5877
    /* fall through */
5878 5879
  default:
    xid_state->xid_cache_element= 0;
5880
  }
5881 5882 5883
  return res;
}

5884

5885 5886 5887 5888
void xid_cache_delete(THD *thd, XID_STATE *xid_state)
{
  if (xid_state->xid_cache_element)
  {
5889
    bool recovered= xid_state->xid_cache_element->is_set(XID_cache_element::RECOVERED);
5890 5891 5892 5893 5894
    DBUG_ASSERT(thd->xid_hash_pins);
    xid_state->xid_cache_element->mark_uninitialized();
    lf_hash_delete(&xid_cache, thd->xid_hash_pins,
                   xid_state->xid.key(), xid_state->xid.key_length());
    xid_state->xid_cache_element= 0;
5895
    if (recovered)
5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919
      my_free(xid_state);
  }
}


struct xid_cache_iterate_arg
{
  my_hash_walk_action action;
  void *argument;
};

static my_bool xid_cache_iterate_callback(XID_cache_element *element,
                                          xid_cache_iterate_arg *arg)
{
  my_bool res= FALSE;
  if (element->lock())
  {
    res= arg->action(element->m_xid_state, arg->argument);
    element->unlock();
  }
  return res;
}

int xid_cache_iterate(THD *thd, my_hash_walk_action action, void *arg)
5920
{
5921 5922 5923 5924 5925
  xid_cache_iterate_arg argument= { action, arg };
  return thd->fix_xid_hash_pins() ? -1 :
         lf_hash_iterate(&xid_cache, thd->xid_hash_pins,
                         (my_hash_walk_action) xid_cache_iterate_callback,
                         &argument);
5926 5927
}

Sven Sandberg's avatar
Sven Sandberg committed
5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966

/**
  Decide on logging format to use for the statement and issue errors
  or warnings as needed.  The decision depends on the following
  parameters:

  - The logging mode, i.e., the value of binlog_format.  Can be
    statement, mixed, or row.

  - The type of statement.  There are three types of statements:
    "normal" safe statements; unsafe statements; and row injections.
    An unsafe statement is one that, if logged in statement format,
    might produce different results when replayed on the slave (e.g.,
    INSERT DELAYED).  A row injection is either a BINLOG statement, or
    a row event executed by the slave's SQL thread.

  - The capabilities of tables modified by the statement.  The
    *capabilities vector* for a table is a set of flags associated
    with the table.  Currently, it only includes two flags: *row
    capability flag* and *statement capability flag*.

    The row capability flag is set if and only if the engine can
    handle row-based logging. The statement capability flag is set if
    and only if the table can handle statement-based logging.

  Decision table for logging format
  ---------------------------------

  The following table summarizes how the format and generated
  warning/error depends on the tables' capabilities, the statement
  type, and the current binlog_format.

     Row capable        N NNNNNNNNN YYYYYYYYY YYYYYYYYY
     Statement capable  N YYYYYYYYY NNNNNNNNN YYYYYYYYY

     Statement type     * SSSUUUIII SSSUUUIII SSSUUUIII

     binlog_format      * SMRSMRSMR SMRSMRSMR SMRSMRSMR

5967 5968
     Logged format      - SS-S----- -RR-RR-RR SRRSRR-RR
     Warning/Error      1 --2732444 5--5--6-- ---7--6--
Sven Sandberg's avatar
Sven Sandberg committed
5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987

  Legend
  ------

  Row capable:    N - Some table not row-capable, Y - All tables row-capable
  Stmt capable:   N - Some table not stmt-capable, Y - All tables stmt-capable
  Statement type: (S)afe, (U)nsafe, or Row (I)njection
  binlog_format:  (S)TATEMENT, (M)IXED, or (R)OW
  Logged format:  (S)tatement or (R)ow
  Warning/Error:  Warnings and error messages are as follows:

  1. Error: Cannot execute statement: binlogging impossible since both
     row-incapable engines and statement-incapable engines are
     involved.

  2. Error: Cannot execute statement: binlogging impossible since
     BINLOG_FORMAT = ROW and at least one table uses a storage engine
     limited to statement-logging.

5988 5989 5990
  3. Error: Cannot execute statement: binlogging of unsafe statement
     is impossible when storage engine is limited to statement-logging
     and BINLOG_FORMAT = MIXED.
Sven Sandberg's avatar
Sven Sandberg committed
5991 5992 5993 5994 5995 5996 5997 5998 5999

  4. Error: Cannot execute row injection: binlogging impossible since
     at least one table uses a storage engine limited to
     statement-logging.

  5. Error: Cannot execute statement: binlogging impossible since
     BINLOG_FORMAT = STATEMENT and at least one table uses a storage
     engine limited to row-logging.

6000
  6. Warning: Unsafe statement binlogged in statement format since
Sven Sandberg's avatar
Sven Sandberg committed
6001 6002 6003 6004 6005
     BINLOG_FORMAT = STATEMENT.

  In addition, we can produce the following error (not depending on
  the variables of the decision diagram):

6006
  7. Error: Cannot execute statement: binlogging impossible since more
Sven Sandberg's avatar
Sven Sandberg committed
6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026
     than one engine is involved and at least one engine is
     self-logging.

  For each error case above, the statement is prevented from being
  logged, we report an error, and roll back the statement.  For
  warnings, we set the thd->binlog_flags variable: the warning will be
  printed only if the statement is successfully logged.

  @see THD::binlog_query

  @param[in] thd    Client thread
  @param[in] tables Tables involved in the query

  @retval 0 No error; statement can be logged.
  @retval -1 One of the error conditions above applies (1, 2, 4, 5, or 6).
*/

int THD::decide_logging_format(TABLE_LIST *tables)
{
  DBUG_ENTER("THD::decide_logging_format");
6027
  DBUG_PRINT("info", ("Query: %.*s", (uint) query_length(), query()));
Georgi Kodinov's avatar
merge  
Georgi Kodinov committed
6028
  DBUG_PRINT("info", ("variables.binlog_format: %lu",
Sven Sandberg's avatar
Sven Sandberg committed
6029 6030 6031
                      variables.binlog_format));
  DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags(): 0x%x",
                      lex->get_stmt_unsafe_flags()));
6032

6033 6034
  reset_binlog_local_stmt_filter();

6035 6036 6037 6038 6039
  /*
    We should not decide logging format if the binlog is closed or
    binlogging is off, or if the statement is filtered out from the
    binlog by filtering rules.
  */
unknown's avatar
unknown committed
6040
  if (mysql_bin_log.is_open() && (variables.option_bits & OPTION_BIN_LOG) &&
6041
      !(wsrep_binlog_format() == BINLOG_FORMAT_STMT &&
6042
        !binlog_filter->db_ok(db.str)))
Sven Sandberg's avatar
Sven Sandberg committed
6043
  {
6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054

    if (is_bulk_op())
    {
      if (wsrep_binlog_format() == BINLOG_FORMAT_STMT)
      {
        my_error(ER_BINLOG_NON_SUPPORTED_BULK, MYF(0));
        DBUG_PRINT("info",
                   ("decision: no logging since an error was generated"));
        DBUG_RETURN(-1);
      }
    }
Sven Sandberg's avatar
Sven Sandberg committed
6055 6056 6057 6058 6059
    /*
      Compute one bit field with the union of all the engine
      capabilities, and one with the intersection of all the engine
      capabilities.
    */
6060
    handler::Table_flags flags_write_some_set= 0;
6061
    handler::Table_flags flags_access_some_set= 0;
6062
    handler::Table_flags flags_write_all_set=
Sven Sandberg's avatar
Sven Sandberg committed
6063 6064
      HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE;

6065 6066 6067 6068
    /* 
       If different types of engines are about to be updated.
       For example: Innodb and Falcon; Innodb and MyIsam.
    */
6069
    bool multi_write_engine= FALSE;
6070 6071 6072 6073 6074
    /*
       If different types of engines are about to be accessed 
       and any of them is about to be updated. For example:
       Innodb and Falcon; Innodb and MyIsam.
    */
6075
    bool multi_access_engine= FALSE;
6076 6077 6078
    /*
      Identifies if a table is changed.
    */
6079 6080 6081
    bool is_write= FALSE;                        // If any write tables
    bool has_read_tables= FALSE;                 // If any read only tables
    bool has_auto_increment_write_tables= FALSE; // Write with auto-increment
6082 6083 6084 6085
    /* true if it's necessary to switch current statement log format from
    STATEMENT to ROW if binary log format is MIXED and autoincrement values
    are changed in the statement */
    bool has_unsafe_stmt_autoinc_lock_mode= false;
6086 6087 6088 6089
    /* If a write table that doesn't have auto increment part first */
    bool has_write_table_auto_increment_not_first_in_pk= FALSE;
    bool has_auto_increment_write_tables_not_first= FALSE;
    bool found_first_not_own_table= FALSE;
6090
    bool has_write_tables_with_unsafe_statements= FALSE;
6091

6092 6093 6094
    /*
      A pointer to a previous table that was changed.
    */
6095
    TABLE* prev_write_table= NULL;
6096 6097 6098
    /*
      A pointer to a previous table that was accessed.
    */
6099
    TABLE* prev_access_table= NULL;
6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121
    /**
      The number of tables used in the current statement,
      that should be replicated.
    */
    uint replicated_tables_count= 0;
    /**
      The number of tables written to in the current statement,
      that should not be replicated.
      A table should not be replicated when it is considered
      'local' to a MySQL instance.
      Currently, these tables are:
      - mysql.slow_log
      - mysql.general_log
      - mysql.slave_relay_log_info
      - mysql.slave_master_info
      - mysql.slave_worker_info
      - performance_schema.*
      - TODO: information_schema.*
      In practice, from this list, only performance_schema.* tables
      are written to by user queries.
    */
    uint non_replicated_tables_count= 0;
Sven Sandberg's avatar
Sven Sandberg committed
6122 6123 6124 6125 6126

#ifndef DBUG_OFF
    {
      static const char *prelocked_mode_name[] = {
        "NON_PRELOCKED",
6127
        "LOCK_TABLES",
Sven Sandberg's avatar
Sven Sandberg committed
6128 6129 6130
        "PRELOCKED",
        "PRELOCKED_UNDER_LOCK_TABLES",
      };
6131
      compile_time_assert(array_elements(prelocked_mode_name) == LTM_always_last);
Sven Sandberg's avatar
Sven Sandberg committed
6132
      DBUG_PRINT("debug", ("prelocked_mode: %s",
6133
                           prelocked_mode_name[locked_tables_mode]));
Sven Sandberg's avatar
Sven Sandberg committed
6134 6135 6136 6137 6138 6139 6140
    }
#endif

    /*
      Get the capabilities vector for all involved storage engines and
      mask out the flags for the binary log.
    */
6141
    for (TABLE_LIST *tbl= tables; tbl; tbl= tbl->next_global)
Sven Sandberg's avatar
Sven Sandberg committed
6142
    {
6143 6144 6145 6146
      TABLE *table;
      TABLE_SHARE *share;
      handler::Table_flags flags;
      if (tbl->placeholder())
Sven Sandberg's avatar
Sven Sandberg committed
6147
        continue;
6148

6149 6150 6151 6152
      table= tbl->table;
      share= table->s;
      flags= table->file->ha_table_flags();
      if (!share->table_creation_was_logged)
6153 6154 6155 6156 6157
      {
        /*
          This is a temporary table which was not logged in the binary log.
          Disable statement logging to enforce row level logging.
        */
6158
        DBUG_ASSERT(share->tmp_table);
6159
        flags&= ~HA_BINLOG_STMT_CAPABLE;
6160 6161
        /* We can only use row logging */
        set_current_stmt_binlog_format_row();
6162
      }
6163

6164
      DBUG_PRINT("info", ("table: %s; ha_table_flags: 0x%llx",
6165
                          tbl->table_name.str, flags));
6166

6167
      if (share->no_replicate)
6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184
      {
        /*
          The statement uses a table that is not replicated.
          The following properties about the table:
          - persistent / transient
          - transactional / non transactional
          - temporary / permanent
          - read or write
          - multiple engines involved because of this table
          are not relevant, as this table is completely ignored.
          Because the statement uses a non replicated table,
          using STATEMENT format in the binlog is impossible.
          Either this statement will be discarded entirely,
          or it will be logged (possibly partially) in ROW format.
        */
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_TABLE);

6185
        if (tbl->lock_type >= TL_WRITE_ALLOW_WRITE)
6186 6187 6188 6189 6190
        {
          non_replicated_tables_count++;
          continue;
        }
      }
6191
      if (tbl == lex->first_not_own_table())
6192
        found_first_not_own_table= true;
6193 6194 6195

      replicated_tables_count++;

6196
      if (tbl->prelocking_placeholder != TABLE_LIST::PRELOCK_FK)
6197
      {
6198
        if (tbl->lock_type <= TL_READ_NO_INSERT)
6199
          has_read_tables= true;
6200 6201
        else if (table->found_next_number_field &&
                 (tbl->lock_type >= TL_WRITE_ALLOW_WRITE))
6202 6203 6204
        {
          has_auto_increment_write_tables= true;
          has_auto_increment_write_tables_not_first= found_first_not_own_table;
6205
          if (share->next_number_keypart != 0)
6206
            has_write_table_auto_increment_not_first_in_pk= true;
6207 6208
          has_unsafe_stmt_autoinc_lock_mode=
            table->file->autoinc_lock_mode_stmt_unsafe();
6209
        }
6210 6211
      }

6212
      if (tbl->lock_type >= TL_WRITE_ALLOW_WRITE)
Sven Sandberg's avatar
Sven Sandberg committed
6213
      {
6214
        bool trans;
6215
        if (prev_write_table && prev_write_table->file->ht !=
6216
            table->file->ht)
6217
          multi_write_engine= TRUE;
6218
        if (share->non_determinstic_insert &&
6219 6220
            (sql_command_flags[lex->sql_command] & CF_CAN_GENERATE_ROW_EVENTS
             && !(sql_command_flags[lex->sql_command] & CF_SCHEMA_CHANGE)))
6221
          has_write_tables_with_unsafe_statements= true;
6222

6223
        trans= table->file->has_transactions();
6224

6225
        if (share->tmp_table)
6226 6227
          lex->set_stmt_accessed_table(trans ? LEX::STMT_WRITES_TEMP_TRANS_TABLE :
                                               LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE);
6228
        else
6229 6230
          lex->set_stmt_accessed_table(trans ? LEX::STMT_WRITES_TRANS_TABLE :
                                               LEX::STMT_WRITES_NON_TRANS_TABLE);
6231

6232 6233
        flags_write_all_set &= flags;
        flags_write_some_set |= flags;
6234
        is_write= TRUE;
6235

6236
        prev_write_table= table;
6237

6238 6239
      }
      flags_access_some_set |= flags;
6240

6241
      if (lex->sql_command != SQLCOM_CREATE_TABLE || lex->tmp_table())
6242
      {
6243
        my_bool trans= table->file->has_transactions();
6244

6245
        if (share->tmp_table)
6246 6247
          lex->set_stmt_accessed_table(trans ? LEX::STMT_READS_TEMP_TRANS_TABLE :
                                               LEX::STMT_READS_TEMP_NON_TRANS_TABLE);
6248
        else
6249 6250
          lex->set_stmt_accessed_table(trans ? LEX::STMT_READS_TRANS_TABLE :
                                               LEX::STMT_READS_NON_TRANS_TABLE);
6251
      }
6252 6253

      if (prev_access_table && prev_access_table->file->ht !=
6254
          table->file->ht)
6255 6256
        multi_access_engine= TRUE;

6257
      prev_access_table= table;
Sven Sandberg's avatar
Sven Sandberg committed
6258 6259
    }

6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272
    if (wsrep_binlog_format() != BINLOG_FORMAT_ROW)
    {
      /*
        DML statements that modify a table with an auto_increment
        column based on rows selected from a table are unsafe as the
        order in which the rows are fetched fron the select tables
        cannot be determined and may differ on master and slave.
      */
      if (has_auto_increment_write_tables && has_read_tables)
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT);

      if (has_write_table_auto_increment_not_first_in_pk)
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST);
6273 6274 6275 6276

      if (has_write_tables_with_unsafe_statements)
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);

6277 6278 6279
      if (has_unsafe_stmt_autoinc_lock_mode)
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_LOCK_MODE);

6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290
      /*
        A query that modifies autoinc column in sub-statement can make the
        master and slave inconsistent.
        We can solve these problems in mixed mode by switching to binlogging
        if at least one updated table is used by sub-statement
      */
      if (lex->requires_prelocking() &&
          has_auto_increment_write_tables_not_first)
        lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS);
    }

6291 6292
    DBUG_PRINT("info", ("flags_write_all_set: 0x%llx", flags_write_all_set));
    DBUG_PRINT("info", ("flags_write_some_set: 0x%llx", flags_write_some_set));
6293
    DBUG_PRINT("info", ("flags_access_some_set: 0x%llx", flags_access_some_set));
6294
    DBUG_PRINT("info", ("multi_write_engine: %d", multi_write_engine));
6295
    DBUG_PRINT("info", ("multi_access_engine: %d", multi_access_engine));
6296 6297 6298 6299

    int error= 0;
    int unsafe_flags;

6300 6301 6302
    bool multi_stmt_trans= in_multi_stmt_transaction_mode();
    bool trans_table= trans_has_updated_trans_table(this);
    bool binlog_direct= variables.binlog_direct_non_trans_update;
6303

6304 6305 6306 6307 6308 6309
    if (lex->is_mixed_stmt_unsafe(multi_stmt_trans, binlog_direct,
                                  trans_table, tx_isolation))
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_MIXED_STATEMENT);
    else if (multi_stmt_trans && trans_table && !binlog_direct &&
             lex->stmt_accessed_table(LEX::STMT_WRITES_NON_TRANS_TABLE))
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS);
6310

Sven Sandberg's avatar
Sven Sandberg committed
6311 6312 6313 6314 6315 6316
    /*
      If more than one engine is involved in the statement and at
      least one is doing it's own logging (is *self-logging*), the
      statement cannot be logged atomically, so we generate an error
      rather than allowing the binlog to become corrupt.
    */
6317 6318
    if (multi_write_engine &&
        (flags_write_some_set & HA_HAS_OWN_BINLOGGING))
Sven Sandberg's avatar
Sven Sandberg committed
6319 6320
      my_error((error= ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE),
               MYF(0));
6321
    else if (multi_access_engine && flags_access_some_set & HA_HAS_OWN_BINLOGGING)
6322
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE);
Sven Sandberg's avatar
Sven Sandberg committed
6323 6324

    /* both statement-only and row-only engines involved */
6325
    if ((flags_write_all_set & (HA_BINLOG_STMT_CAPABLE | HA_BINLOG_ROW_CAPABLE)) == 0)
Sven Sandberg's avatar
Sven Sandberg committed
6326 6327 6328 6329 6330 6331 6332 6333
    {
      /*
        1. Error: Binary logging impossible since both row-incapable
           engines and statement-incapable engines are involved
      */
      my_error((error= ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE), MYF(0));
    }
    /* statement-only engines involved */
6334
    else if ((flags_write_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
Sven Sandberg's avatar
Sven Sandberg committed
6335 6336 6337 6338 6339 6340 6341 6342 6343
    {
      if (lex->is_stmt_row_injection())
      {
        /*
          4. Error: Cannot execute row injection since table uses
             storage engine limited to statement-logging
        */
        my_error((error= ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE), MYF(0));
      }
6344
      else if ((wsrep_binlog_format() == BINLOG_FORMAT_ROW || is_bulk_op()) &&
6345
               sqlcom_can_generate_row_events(this))
Sven Sandberg's avatar
Sven Sandberg committed
6346 6347 6348 6349 6350 6351 6352 6353 6354 6355
      {
        /*
          2. Error: Cannot modify table that uses a storage engine
             limited to statement-logging when BINLOG_FORMAT = ROW
        */
        my_error((error= ER_BINLOG_ROW_MODE_AND_STMT_ENGINE), MYF(0));
      }
      else if ((unsafe_flags= lex->get_stmt_unsafe_flags()) != 0)
      {
        /*
6356 6357 6358
          3. Error: Cannot execute statement: binlogging of unsafe
             statement is impossible when storage engine is limited to
             statement-logging and BINLOG_FORMAT = MIXED.
Sven Sandberg's avatar
Sven Sandberg committed
6359
        */
6360 6361 6362 6363 6364
        for (int unsafe_type= 0;
             unsafe_type < LEX::BINLOG_STMT_UNSAFE_COUNT;
             unsafe_type++)
          if (unsafe_flags & (1 << unsafe_type))
            my_error((error= ER_BINLOG_UNSAFE_AND_STMT_ENGINE), MYF(0),
6365 6366
                     ER_THD(this,
                            LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
Sven Sandberg's avatar
Sven Sandberg committed
6367 6368 6369 6370 6371 6372 6373
      }
      /* log in statement format! */
    }
    /* no statement-only engines */
    else
    {
      /* binlog_format = STATEMENT */
6374
      if (wsrep_binlog_format() == BINLOG_FORMAT_STMT)
Sven Sandberg's avatar
Sven Sandberg committed
6375 6376 6377 6378
      {
        if (lex->is_stmt_row_injection())
        {
          /*
6379 6380
            We have to log the statement as row or give an error.
            Better to accept what master gives us than stopping replication.
Sven Sandberg's avatar
Sven Sandberg committed
6381
          */
6382
          set_current_stmt_binlog_format_row();
Sven Sandberg's avatar
Sven Sandberg committed
6383
        }
6384 6385
        else if ((flags_write_all_set & HA_BINLOG_STMT_CAPABLE) == 0 &&
                 sqlcom_can_generate_row_events(this))
Sven Sandberg's avatar
Sven Sandberg committed
6386 6387 6388
        {
          /*
            5. Error: Cannot modify table that uses a storage engine
6389 6390
               limited to row-logging when binlog_format = STATEMENT, except
               if all tables that are updated are temporary tables
Sven Sandberg's avatar
Sven Sandberg committed
6391
          */
6392 6393 6394 6395 6396 6397 6398
          if (!lex->stmt_writes_to_non_temp_table())
          {
            /* As all updated tables are temporary, nothing will be logged */
            set_current_stmt_binlog_format_row();
          }
          else if (IF_WSREP((!WSREP(this) ||
                             wsrep_exec_mode == LOCAL_STATE),1))
6399 6400 6401
	  {
            my_error((error= ER_BINLOG_STMT_MODE_AND_ROW_ENGINE), MYF(0), "");
	  }
Sven Sandberg's avatar
Sven Sandberg committed
6402
        }
6403
        else if (is_write && (unsafe_flags= lex->get_stmt_unsafe_flags()) != 0)
Sven Sandberg's avatar
Sven Sandberg committed
6404 6405 6406 6407 6408
        {
          /*
            7. Warning: Unsafe statement logged as statement due to
               binlog_format = STATEMENT
          */
6409
          binlog_unsafe_warning_flags|= unsafe_flags;
6410

Sven Sandberg's avatar
Sven Sandberg committed
6411 6412
          DBUG_PRINT("info", ("Scheduling warning to be issued by "
                              "binlog_query: '%s'",
6413
                              ER_THD(this, ER_BINLOG_UNSAFE_STATEMENT)));
6414
          DBUG_PRINT("info", ("binlog_unsafe_warning_flags: 0x%x",
Sven Sandberg's avatar
Sven Sandberg committed
6415 6416
                              binlog_unsafe_warning_flags));
        }
6417
        /* log in statement format (or row if row event)! */
Sven Sandberg's avatar
Sven Sandberg committed
6418 6419 6420 6421 6422 6423
      }
      /* No statement-only engines and binlog_format != STATEMENT.
         I.e., nothing prevents us from row logging if needed. */
      else
      {
        if (lex->is_stmt_unsafe() || lex->is_stmt_row_injection()
6424 6425
            || (flags_write_all_set & HA_BINLOG_STMT_CAPABLE) == 0 ||
            is_bulk_op())
Sven Sandberg's avatar
Sven Sandberg committed
6426 6427
        {
          /* log in row format! */
6428
          set_current_stmt_binlog_format_row_if_mixed();
Sven Sandberg's avatar
Sven Sandberg committed
6429 6430 6431 6432
        }
      }
    }

6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456
    if (non_replicated_tables_count > 0)
    {
      if ((replicated_tables_count == 0) || ! is_write)
      {
        DBUG_PRINT("info", ("decision: no logging, no replicated table affected"));
        set_binlog_local_stmt_filter();
      }
      else
      {
        if (! is_current_stmt_binlog_format_row())
        {
          my_error((error= ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES), MYF(0));
        }
        else
        {
          clear_binlog_local_stmt_filter();
        }
      }
    }
    else
    {
      clear_binlog_local_stmt_filter();
    }

6457 6458
    if (unlikely(error))
    {
Sven Sandberg's avatar
Sven Sandberg committed
6459 6460 6461 6462 6463 6464
      DBUG_PRINT("info", ("decision: no logging since an error was generated"));
      DBUG_RETURN(-1);
    }
    DBUG_PRINT("info", ("decision: logging in %s format",
                        is_current_stmt_binlog_format_row() ?
                        "ROW" : "STATEMENT"));
6465 6466

    if (variables.binlog_format == BINLOG_FORMAT_ROW &&
6467 6468
        (sql_command_flags[lex->sql_command] &
         (CF_UPDATES_DATA | CF_DELETES_DATA)))
6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481
    {
      String table_names;
      /*
        Generate a warning for UPDATE/DELETE statements that modify a
        BLACKHOLE table, as row events are not logged in row format.
      */
      for (TABLE_LIST *table= tables; table; table= table->next_global)
      {
        if (table->placeholder())
          continue;
        if (table->table->file->ht->db_type == DB_TYPE_BLACKHOLE_DB &&
            table->lock_type >= TL_WRITE_ALLOW_WRITE)
        {
6482
            table_names.append(&table->table_name);
6483 6484 6485 6486 6487
            table_names.append(",");
        }
      }
      if (!table_names.is_empty())
      {
6488 6489
        bool is_update= MY_TEST(sql_command_flags[lex->sql_command] &
                                CF_UPDATES_DATA);
6490 6491 6492 6493
        /*
          Replace the last ',' with '.' for table_names
        */
        table_names.replace(table_names.length()-1, 1, ".", 1);
Sergei Golubchik's avatar
Sergei Golubchik committed
6494
        push_warning_printf(this, Sql_condition::WARN_LEVEL_WARN,
6495 6496 6497 6498
                            ER_UNKNOWN_ERROR,
                            "Row events are not logged for %s statements "
                            "that modify BLACKHOLE tables in row format. "
                            "Table(s): '%-.192s'",
6499 6500 6501 6502
                            is_update ? "UPDATE" : "DELETE",
                            table_names.c_ptr());
      }
    }
Sven Sandberg's avatar
Sven Sandberg committed
6503 6504 6505 6506 6507
  }
#ifndef DBUG_OFF
  else
    DBUG_PRINT("info", ("decision: no logging since "
                        "mysql_bin_log.is_open() = %d "
6508
                        "and (options & OPTION_BIN_LOG) = 0x%llx "
6509
                        "and binlog_format = %u "
6510 6511
                        "and binlog_filter->db_ok(db) = %d",
                        mysql_bin_log.is_open(),
unknown's avatar
unknown committed
6512
                        (variables.option_bits & OPTION_BIN_LOG),
6513
                        (uint) wsrep_binlog_format(),
6514
                        binlog_filter->db_ok(db.str)));
Sven Sandberg's avatar
Sven Sandberg committed
6515 6516 6517 6518 6519
#endif

  DBUG_RETURN(0);
}

6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561
int THD::decide_logging_format_low(TABLE *table)
{
  /*
   INSERT...ON DUPLICATE KEY UPDATE on a table with more than one unique keys
   can be unsafe.
   */
  if(wsrep_binlog_format() <= BINLOG_FORMAT_STMT &&
       !is_current_stmt_binlog_format_row() &&
       !lex->is_stmt_unsafe() &&
       lex->sql_command == SQLCOM_INSERT &&
       lex->duplicates == DUP_UPDATE)
  {
    uint unique_keys= 0;
    uint keys= table->s->keys, i= 0;
    Field *field;
    for (KEY* keyinfo= table->s->key_info;
             i < keys && unique_keys <= 1; i++, keyinfo++)
      if (keyinfo->flags & HA_NOSAME &&
         !(keyinfo->key_part->field->flags & AUTO_INCREMENT_FLAG &&
             //User given auto inc can be unsafe
             !keyinfo->key_part->field->val_int()))
      {
        for (uint j= 0; j < keyinfo->user_defined_key_parts; j++)
        {
          field= keyinfo->key_part[j].field;
          if(!bitmap_is_set(table->write_set,field->field_index))
            goto exit;
        }
        unique_keys++;
exit:;
      }

    if (unique_keys > 1)
    {
      lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS);
      binlog_unsafe_warning_flags|= lex->get_stmt_unsafe_flags();
      set_current_stmt_binlog_format_row_if_mixed();
      return 1;
    }
  }
  return 0;
}
Sven Sandberg's avatar
Sven Sandberg committed
6562

6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591
/*
  Implementation of interface to write rows to the binary log through the
  thread.  The thread is responsible for writing the rows it has
  inserted/updated/deleted.
*/

#ifndef MYSQL_CLIENT

/*
  Template member function for ensuring that there is an rows log
  event of the apropriate type before proceeding.

  PRE CONDITION:
    - Events of type 'RowEventT' have the type code 'type_code'.
    
  POST CONDITION:
    If a non-NULL pointer is returned, the pending event for thread 'thd' will
    be an event of type 'RowEventT' (which have the type code 'type_code')
    will either empty or have enough space to hold 'needed' bytes.  In
    addition, the columns bitmap will be correct for the row, meaning that
    the pending event will be flushed if the columns in the event differ from
    the columns suppled to the function.

  RETURNS
    If no error, a non-NULL pending event (either one which already existed or
    the newly created one).
    If error, NULL.
 */

6592
template <class RowsEventT> Rows_log_event*
6593
THD::binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
6594
                                       size_t needed,
unknown's avatar
unknown committed
6595
                                       bool is_transactional,
6596
                                       RowsEventT *hint __attribute__((unused)))
6597
{
6598
  DBUG_ENTER("binlog_prepare_pending_rows_event");
6599
  /* Pre-conditions */
6600
  DBUG_ASSERT(table->s->table_map_id != ~0UL);
6601 6602

  /* Fetch the type code for the RowsEventT template parameter */
6603
  int const general_type_code= RowsEventT::TYPE_CODE;
6604

6605 6606 6607 6608
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_transactional= 1;

6609 6610 6611 6612
  /*
    There is no good place to set up the transactional data, so we
    have to do it here.
  */
6613
  if (binlog_setup_trx_data() == NULL)
6614
    DBUG_RETURN(NULL);
6615

6616
  Rows_log_event* pending= binlog_get_pending_rows_event(is_transactional);
6617 6618

  if (unlikely(pending && !pending->is_valid()))
6619
    DBUG_RETURN(NULL);
6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631

  /*
    Check if the current event is non-NULL and a write-rows
    event. Also check if the table provided is mapped: if it is not,
    then we have switched to writing to a new table.
    If there is no pending event, we need to create one. If there is a pending
    event, but it's not about the same table id, or not of the same type
    (between Write, Update and Delete), or not the same affected columns, or
    going to be too big, flush this event to disk and create a new pending
    event.
  */
  if (!pending ||
6632
      pending->server_id != serv_id ||
6633
      pending->get_table_id() != table->s->table_map_id ||
6634 6635 6636
      pending->get_general_type_code() != general_type_code ||
      pending->get_data_size() + needed > opt_binlog_rows_event_max_size ||
      pending->read_write_bitmaps_cmp(table) == FALSE)
6637 6638 6639
  {
    /* Create a new RowsEventT... */
    Rows_log_event* const
6640
        ev= new RowsEventT(this, table, table->s->table_map_id,
6641 6642
                           is_transactional);
    if (unlikely(!ev))
6643
      DBUG_RETURN(NULL);
6644 6645 6646 6647 6648
    ev->server_id= serv_id; // I don't like this, it's too easy to forget.
    /*
      flush the pending event and replace it with the newly created
      event...
    */
6649 6650 6651
    if (unlikely(
        mysql_bin_log.flush_and_set_pending_rows_event(this, ev,
                                                       is_transactional)))
6652 6653
    {
      delete ev;
6654
      DBUG_RETURN(NULL);
6655 6656
    }

6657
    DBUG_RETURN(ev);               /* This is the new pending event */
6658
  }
6659
  DBUG_RETURN(pending);        /* This is the current pending event */
6660 6661
}

6662 6663
/* Declare in unnamed namespace. */
CPP_UNNAMED_NS_START
6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690
  /**
     Class to handle temporary allocation of memory for row data.

     The responsibilities of the class is to provide memory for
     packing one or two rows of packed data (depending on what
     constructor is called).

     In order to make the allocation more efficient for "simple" rows,
     i.e., rows that do not contain any blobs, a pointer to the
     allocated memory is of memory is stored in the table structure
     for simple rows.  If memory for a table containing a blob field
     is requested, only memory for that is allocated, and subsequently
     released when the object is destroyed.

   */
  class Row_data_memory {
  public:
    /**
      Build an object to keep track of a block-local piece of memory
      for storing a row of data.

      @param table
      Table where the pre-allocated memory is stored.

      @param length
      Length of data that is needed, if the record contain blobs.
     */
6691
    Row_data_memory(TABLE *table, size_t const len1)
6692 6693 6694
      : m_memory(0)
    {
#ifndef DBUG_OFF
6695
      m_alloc_checked= FALSE;
6696 6697 6698 6699 6700 6701
#endif
      allocate_memory(table, len1);
      m_ptr[0]= has_memory() ? m_memory : 0;
      m_ptr[1]= 0;
    }

6702
    Row_data_memory(TABLE *table, size_t const len1, size_t const len2)
6703 6704 6705
      : m_memory(0)
    {
#ifndef DBUG_OFF
6706
      m_alloc_checked= FALSE;
6707 6708 6709 6710 6711 6712 6713 6714 6715
#endif
      allocate_memory(table, len1 + len2);
      m_ptr[0]= has_memory() ? m_memory        : 0;
      m_ptr[1]= has_memory() ? m_memory + len1 : 0;
    }

    ~Row_data_memory()
    {
      if (m_memory != 0 && m_release_memory_on_destruction)
6716
        my_free(m_memory);
6717 6718 6719 6720 6721 6722 6723 6724 6725 6726
    }

    /**
       Is there memory allocated?

       @retval true There is memory allocated
       @retval false Memory allocation failed
     */
    bool has_memory() const {
#ifndef DBUG_OFF
6727
      m_alloc_checked= TRUE;
6728 6729 6730 6731
#endif
      return m_memory != 0;
    }

6732
    uchar *slot(uint s)
6733
    {
unknown's avatar
unknown committed
6734
      DBUG_ASSERT(s < sizeof(m_ptr)/sizeof(*m_ptr));
6735
      DBUG_ASSERT(m_ptr[s] != 0);
6736
      DBUG_SLOW_ASSERT(m_alloc_checked == TRUE);
6737 6738 6739 6740
      return m_ptr[s];
    }

  private:
6741
    void allocate_memory(TABLE *const table, size_t const total_length)
6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754
    {
      if (table->s->blob_fields == 0)
      {
        /*
          The maximum length of a packed record is less than this
          length. We use this value instead of the supplied length
          when allocating memory for records, since we don't know how
          the memory will be used in future allocations.

          Since table->s->reclength is for unpacked records, we have
          to add two bytes for each field, which can potentially be
          added to hold the length of a packed field.
        */
6755
        size_t const maxlen= table->s->reclength + 2 * table->s->fields;
6756 6757 6758 6759 6760 6761 6762 6763

        /*
          Allocate memory for two records if memory hasn't been
          allocated. We allocate memory for two records so that it can
          be used when processing update rows as well.
        */
        if (table->write_row_record == 0)
          table->write_row_record=
6764
            (uchar *) alloc_root(&table->mem_root, 2 * maxlen);
6765
        m_memory= table->write_row_record;
6766
        m_release_memory_on_destruction= FALSE;
6767 6768 6769
      }
      else
      {
6770
        m_memory= (uchar *) my_malloc(total_length, MYF(MY_WME));
6771
        m_release_memory_on_destruction= TRUE;
6772 6773 6774 6775 6776 6777 6778
      }
    }

#ifndef DBUG_OFF
    mutable bool m_alloc_checked;
#endif
    bool m_release_memory_on_destruction;
6779 6780
    uchar *m_memory;
    uchar *m_ptr[2];
6781 6782
  };

6783
CPP_UNNAMED_NS_END
6784

6785 6786
int THD::binlog_write_row(TABLE* table, bool is_trans,
                          uchar const *record)
6787
{
6788

6789
  DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6790
           ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6791 6792 6793
  /*
    Pack records into format for transfer. We are allocating more
    memory than needed, but that doesn't matter.
6794
  */
6795 6796
  Row_data_memory memory(table, max_row_length(table, table->rpl_write_set,
                                               record));
6797 6798
  if (!memory.has_memory())
    return HA_ERR_OUT_OF_MEM;
6799

6800
  uchar *row_data= memory.slot(0);
6801

6802
  size_t const len= pack_row(table, table->rpl_write_set, row_data, record);
6803

6804 6805 6806 6807
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_trans= 1;

vinchen's avatar
vinchen committed
6808 6809 6810 6811 6812 6813 6814 6815
  Rows_log_event* ev;
  if (binlog_should_compress(len))
    ev =
    binlog_prepare_pending_rows_event(table, variables.server_id,
                                      len, is_trans,
                                      static_cast<Write_rows_compressed_log_event*>(0));
  else
    ev =
6816
    binlog_prepare_pending_rows_event(table, variables.server_id,
6817 6818 6819 6820 6821 6822 6823
                                      len, is_trans,
                                      static_cast<Write_rows_log_event*>(0));

  if (unlikely(ev == 0))
    return HA_ERR_OUT_OF_MEM;

  return ev->add_row_data(row_data, len);
6824 6825 6826
}

int THD::binlog_update_row(TABLE* table, bool is_trans,
6827 6828
                           const uchar *before_record,
                           const uchar *after_record)
6829 6830
{
  DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6831
            ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6832

6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848
  /**
    Save a reference to the original read bitmaps
    We will need this to restore the bitmaps at the end as
    binlog_prepare_row_images() may change table->read_set.
    table->read_set is used by pack_row and deep in
    binlog_prepare_pending_events().
  */
  MY_BITMAP *old_read_set= table->read_set;

  /**
     This will remove spurious fields required during execution but
     not needed for binlogging. This is done according to the:
     binlog-row-image option.
   */
  binlog_prepare_row_images(table);

6849 6850 6851 6852
  size_t const before_maxlen= max_row_length(table, table->read_set,
                                             before_record);
  size_t const after_maxlen=  max_row_length(table, table->rpl_write_set,
                                             after_record);
6853

6854 6855 6856 6857
  Row_data_memory row_data(table, before_maxlen, after_maxlen);
  if (!row_data.has_memory())
    return HA_ERR_OUT_OF_MEM;

6858 6859
  uchar *before_row= row_data.slot(0);
  uchar *after_row= row_data.slot(1);
6860

6861
  size_t const before_size= pack_row(table, table->read_set, before_row,
6862
                                     before_record);
6863
  size_t const after_size= pack_row(table, table->rpl_write_set, after_row,
6864
                                    after_record);
6865

6866 6867 6868 6869
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_trans= 1;

6870 6871 6872 6873
  /*
    Don't print debug messages when running valgrind since they can
    trigger false warnings.
   */
6874
#ifndef HAVE_valgrind
6875 6876 6877 6878
  DBUG_DUMP("before_record", before_record, table->s->reclength);
  DBUG_DUMP("after_record",  after_record, table->s->reclength);
  DBUG_DUMP("before_row",    before_row, before_size);
  DBUG_DUMP("after_row",     after_row, after_size);
6879
#endif
6880

vinchen's avatar
vinchen committed
6881 6882 6883 6884 6885 6886 6887 6888 6889
  Rows_log_event* ev;
  if(binlog_should_compress(before_size + after_size))
    ev =
      binlog_prepare_pending_rows_event(table, variables.server_id,
                                      before_size + after_size, is_trans,
                                      static_cast<Update_rows_compressed_log_event*>(0));
  else
    ev =
      binlog_prepare_pending_rows_event(table, variables.server_id,
6890 6891
                                      before_size + after_size, is_trans,
                                      static_cast<Update_rows_log_event*>(0));
6892

6893 6894 6895
  if (unlikely(ev == 0))
    return HA_ERR_OUT_OF_MEM;

6896 6897 6898
  int error=  ev->add_row_data(before_row, before_size) ||
              ev->add_row_data(after_row, after_size);

6899 6900 6901
  /* restore read set for the rest of execution */
  table->column_bitmaps_set_no_signal(old_read_set,
                                      table->write_set);
6902 6903
  return error;

6904 6905 6906
}

int THD::binlog_delete_row(TABLE* table, bool is_trans, 
6907
                           uchar const *record)
6908 6909
{
  DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6910
            ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6911
  /**
6912 6913 6914 6915 6916 6917
    Save a reference to the original read bitmaps
    We will need this to restore the bitmaps at the end as
    binlog_prepare_row_images() may change table->read_set.
    table->read_set is used by pack_row and deep in
    binlog_prepare_pending_events().
  */
6918
  MY_BITMAP *old_read_set= table->read_set;
6919

6920 6921 6922 6923 6924 6925 6926 6927
  /** 
     This will remove spurious fields required during execution but
     not needed for binlogging. This is done according to the:
     binlog-row-image option.
   */
  binlog_prepare_row_images(table);

  /*
6928 6929 6930
     Pack records into format for transfer. We are allocating more
     memory than needed, but that doesn't matter.
  */
6931 6932
  Row_data_memory memory(table, max_row_length(table, table->read_set,
                                               record));
6933
  if (unlikely(!memory.has_memory()))
6934
    return HA_ERR_OUT_OF_MEM;
6935

6936
  uchar *row_data= memory.slot(0);
6937

6938 6939
  DBUG_DUMP("table->read_set", (uchar*) table->read_set->bitmap, (table->s->fields + 7) / 8);
  size_t const len= pack_row(table, table->read_set, row_data, record);
6940

6941 6942 6943 6944
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_trans= 1;

vinchen's avatar
vinchen committed
6945 6946 6947 6948 6949 6950 6951 6952 6953
  Rows_log_event* ev;
  if(binlog_should_compress(len))
    ev =
      binlog_prepare_pending_rows_event(table, variables.server_id,
                                      len, is_trans,
                                      static_cast<Delete_rows_compressed_log_event*>(0));
  else
    ev =
      binlog_prepare_pending_rows_event(table, variables.server_id,
6954 6955
                                      len, is_trans,
                                      static_cast<Delete_rows_log_event*>(0));
6956

6957 6958
  if (unlikely(ev == 0))
    return HA_ERR_OUT_OF_MEM;
6959

6960 6961 6962

  int error= ev->add_row_data(row_data, len);

6963
  /* restore read set for the rest of execution */
6964
  table->column_bitmaps_set_no_signal(old_read_set,
6965
                                      table->write_set);
6966 6967

  return error;
6968 6969 6970
}


6971 6972 6973 6974 6975
/**
   Remove from read_set spurious columns. The write_set has been
   handled before in table->mark_columns_needed_for_update.
*/

6976 6977 6978 6979
void THD::binlog_prepare_row_images(TABLE *table)
{
  DBUG_ENTER("THD::binlog_prepare_row_images");

6980 6981
  DBUG_PRINT_BITSET("debug", "table->read_set (before preparing): %s",
                    table->read_set);
6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998
  THD *thd= table->in_use;

  /**
    if there is a primary key in the table (ie, user declared PK or a
    non-null unique index) and we dont want to ship the entire image,
    and the handler involved supports this.
   */
  if (table->s->primary_key < MAX_KEY &&
      (thd->variables.binlog_row_image < BINLOG_ROW_IMAGE_FULL) &&
      !ha_check_storage_engine_flag(table->s->db_type(), HTON_NO_BINLOG_ROW_OPT))
  {
    /**
      Just to be sure that tmp_set is currently not in use as
      the read_set already.
    */
    DBUG_ASSERT(table->read_set != &table->tmp_set);

6999
    switch (thd->variables.binlog_row_image)
7000 7001 7002
    {
      case BINLOG_ROW_IMAGE_MINIMAL:
        /* MINIMAL: Mark only PK */
7003 7004
        table->mark_index_columns(table->s->primary_key,
                                  &table->tmp_set);
7005 7006 7007 7008 7009 7010
        break;
      case BINLOG_ROW_IMAGE_NOBLOB:
        /**
          NOBLOB: Remove unnecessary BLOB fields from read_set
                  (the ones that are not part of PK).
         */
7011
        bitmap_copy(&table->tmp_set, table->read_set);
7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028
        for (Field **ptr=table->field ; *ptr ; ptr++)
        {
          Field *field= (*ptr);
          if ((field->type() == MYSQL_TYPE_BLOB) &&
              !(field->flags & PRI_KEY_FLAG))
            bitmap_clear_bit(&table->tmp_set, field->field_index);
        }
        break;
      default:
        DBUG_ASSERT(0); // impossible.
    }

    /* set the temporary read_set */
    table->column_bitmaps_set_no_signal(&table->tmp_set,
                                        table->write_set);
  }

7029 7030
  DBUG_PRINT_BITSET("debug", "table->read_set (after preparing): %s",
                    table->read_set);
7031
  DBUG_VOID_RETURN;
7032 7033 7034
}


7035

7036 7037
int THD::binlog_remove_pending_rows_event(bool clear_maps,
                                          bool is_transactional)
7038
{
7039
  DBUG_ENTER("THD::binlog_remove_pending_rows_event");
7040

7041
  if(!WSREP_EMULATE_BINLOG(this) && !mysql_bin_log.is_open())
7042 7043
    DBUG_RETURN(0);

7044 7045 7046 7047
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_transactional= 1;

7048
  mysql_bin_log.remove_pending_rows_event(this, is_transactional);
7049 7050 7051 7052 7053 7054 7055

  if (clear_maps)
    binlog_table_maps= 0;

  DBUG_RETURN(0);
}

7056
int THD::binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional)
7057 7058
{
  DBUG_ENTER("THD::binlog_flush_pending_rows_event");
7059 7060 7061 7062 7063
  /*
    We shall flush the pending event even if we are not in row-based
    mode: it might be the case that we left row-based mode before
    flushing anything (e.g., if we have explicitly locked tables).
   */
7064
  if(!WSREP_EMULATE_BINLOG(this) && !mysql_bin_log.is_open())
7065 7066
    DBUG_RETURN(0);

7067 7068 7069 7070
  /* Ensure that all events in a GTID group are in the same cache */
  if (variables.option_bits & OPTION_GTID_BEGIN)
    is_transactional= 1;

7071 7072 7073 7074 7075
  /*
    Mark the event as the last event of a statement if the stmt_end
    flag is set.
  */
  int error= 0;
7076
  if (Rows_log_event *pending= binlog_get_pending_rows_event(is_transactional))
7077 7078 7079 7080
  {
    if (stmt_end)
    {
      pending->set_flags(Rows_log_event::STMT_END_F);
7081
      binlog_table_maps= 0;
7082 7083
    }

7084 7085
    error= mysql_bin_log.flush_and_set_pending_rows_event(this, 0,
                                                          is_transactional);
7086
  }
7087 7088 7089 7090 7091

  DBUG_RETURN(error);
}


7092
#if !defined(DBUG_OFF) && !defined(_lint)
7093 7094 7095 7096 7097 7098 7099 7100
static const char *
show_query_type(THD::enum_binlog_query_type qtype)
{
  switch (qtype) {
  case THD::ROW_QUERY_TYPE:
    return "ROW";
  case THD::STMT_QUERY_TYPE:
    return "STMT";
7101
  case THD::QUERY_TYPE_COUNT:
7102
  default:
7103
    DBUG_ASSERT(0 <= qtype && qtype < THD::QUERY_TYPE_COUNT);
7104
  }
7105 7106 7107
  static char buf[64];
  sprintf(buf, "UNKNOWN#%d", qtype);
  return buf;
7108
}
7109
#endif
7110

7111 7112 7113 7114
/*
  Constants required for the limit unsafe warnings suppression
*/
//seconds after which the limit unsafe warnings suppression will be activated
7115
#define LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT 5*60
7116
//number of limit unsafe warnings after which the suppression will be activated
7117
#define LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT 10
7118

7119 7120 7121 7122
static ulonglong unsafe_suppression_start_time= 0;
static bool unsafe_warning_suppression_active[LEX::BINLOG_STMT_UNSAFE_COUNT];
static ulong unsafe_warnings_count[LEX::BINLOG_STMT_UNSAFE_COUNT];
static ulong total_unsafe_warnings_count;
7123 7124 7125

/**
  Auxiliary function to reset the limit unsafety warning suppression.
7126 7127 7128
  This is done without mutex protection, but this should be good
  enough as it doesn't matter if we loose a couple of suppressed
  messages or if this is called multiple times.
7129
*/
7130 7131

static void reset_binlog_unsafe_suppression(ulonglong now)
7132
{
7133
  uint i;
7134
  DBUG_ENTER("reset_binlog_unsafe_suppression");
7135 7136 7137 7138 7139 7140 7141 7142

  unsafe_suppression_start_time= now;
  total_unsafe_warnings_count= 0;

  for (i= 0 ; i < LEX::BINLOG_STMT_UNSAFE_COUNT ; i++)
  {
    unsafe_warnings_count[i]= 0;
    unsafe_warning_suppression_active[i]= 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
7143
  }
7144 7145 7146 7147 7148 7149
  DBUG_VOID_RETURN;
}

/**
  Auxiliary function to print warning in the error log.
*/
7150 7151
static void print_unsafe_warning_to_log(THD *thd, int unsafe_type, char* buf,
                                        char* query)
7152 7153
{
  DBUG_ENTER("print_unsafe_warning_in_log");
7154 7155 7156
  sprintf(buf, ER_THD(thd, ER_BINLOG_UNSAFE_STATEMENT),
          ER_THD(thd, LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
  sql_print_warning(ER_THD(thd, ER_MESSAGE_AND_STATEMENT), buf, query);
7157 7158 7159 7160
  DBUG_VOID_RETURN;
}

/**
7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173
  Auxiliary function to check if the warning for unsafe repliction statements
  should be thrown or suppressed.

  Logic is:
  - If we get more than LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT errors
    of one type, that type of errors will be suppressed for
    LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT.
  - When the time limit has been reached, all suppression is reset.

  This means that if one gets many different types of errors, some of them
  may be reset less than LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT. However at
  least one error is disable for this time.

7174 7175 7176 7177
  SYNOPSIS:
  @params
   unsafe_type - The type of unsafety.

7178 7179 7180
  RETURN:
    0   0k to log
    1   Message suppressed
7181
*/
7182 7183

static bool protect_against_unsafe_warning_flood(int unsafe_type)
7184
{
7185 7186 7187 7188 7189 7190 7191
  ulong count;
  ulonglong now= my_interval_timer()/1000000000ULL;
  DBUG_ENTER("protect_against_unsafe_warning_flood");

  count= ++unsafe_warnings_count[unsafe_type];
  total_unsafe_warnings_count++;

7192 7193 7194 7195 7196
  /*
    INITIALIZING:
    If this is the first time this function is called with log warning
    enabled, the monitoring the unsafe warnings should start.
  */
7197
  if (unsafe_suppression_start_time == 0)
7198
  {
7199 7200
    reset_binlog_unsafe_suppression(now);
    DBUG_RETURN(0);
7201
  }
7202 7203 7204 7205 7206 7207

  /*
    The following is true if we got too many errors or if the error was
    already suppressed
  */
  if (count >= LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT)
7208
  {
7209
    ulonglong diff_time= (now - unsafe_suppression_start_time);
7210

7211
    if (!unsafe_warning_suppression_active[unsafe_type])
7212
    {
7213 7214 7215 7216 7217 7218 7219
      /*
        ACTIVATION:
        We got LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT warnings in
        less than LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT we activate the
        suppression.
      */
      if (diff_time <= LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT)
7220
      {
7221 7222 7223 7224
        unsafe_warning_suppression_active[unsafe_type]= 1;
        sql_print_information("Suppressing warnings of type '%s' for up to %d seconds because of flooding",
                              ER(LEX::binlog_stmt_unsafe_errcode[unsafe_type]),
                              LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT);
7225 7226 7227 7228
      }
      else
      {
        /*
7229
          There is no flooding till now, therefore we restart the monitoring
7230
        */
7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244
        reset_binlog_unsafe_suppression(now);
      }
    }
    else
    {
      /* This type of warnings was suppressed */
      if (diff_time > LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT)
      {
        ulong save_count= total_unsafe_warnings_count;
        /* Print a suppression note and remove the suppression */
        reset_binlog_unsafe_suppression(now);
        sql_print_information("Suppressed %lu unsafe warnings during "
                              "the last %d seconds",
                              save_count, (int) diff_time);
7245 7246 7247
      }
    }
  }
7248
  DBUG_RETURN(unsafe_warning_suppression_active[unsafe_type]);
7249
}
7250

7251 7252 7253 7254 7255 7256 7257 7258 7259
MYSQL_TIME THD::query_start_TIME()
{
  MYSQL_TIME res;
  variables.time_zone->gmt_sec_to_TIME(&res, query_start());
  res.second_part= query_start_sec_part();
  time_zone_used= 1;
  return res;
}

7260 7261
/**
  Auxiliary method used by @c binlog_query() to raise warnings.
7262

7263 7264
  The type of warning and the type of unsafeness is stored in
  THD::binlog_unsafe_warning_flags.
7265 7266 7267
*/
void THD::issue_unsafe_warnings()
{
7268
  char buf[MYSQL_ERRMSG_SIZE * 2];
7269
  uint32 unsafe_type_flags;
7270 7271 7272 7273 7274
  DBUG_ENTER("issue_unsafe_warnings");
  /*
    Ensure that binlog_unsafe_warning_flags is big enough to hold all
    bits.  This is actually a constant expression.
  */
7275
  DBUG_ASSERT(LEX::BINLOG_STMT_UNSAFE_COUNT <=
7276
              sizeof(binlog_unsafe_warning_flags) * CHAR_BIT);
7277 7278 7279
  
  if (!(unsafe_type_flags= binlog_unsafe_warning_flags))
    DBUG_VOID_RETURN;                           // Nothing to do
7280

7281 7282 7283 7284 7285 7286 7287 7288 7289 7290
  /*
    For each unsafe_type, check if the statement is unsafe in this way
    and issue a warning.
  */
  for (int unsafe_type=0;
       unsafe_type < LEX::BINLOG_STMT_UNSAFE_COUNT;
       unsafe_type++)
  {
    if ((unsafe_type_flags & (1 << unsafe_type)) != 0)
    {
7291
      push_warning_printf(this, Sql_condition::WARN_LEVEL_NOTE,
7292
                          ER_BINLOG_UNSAFE_STATEMENT,
7293 7294
                          ER_THD(this, ER_BINLOG_UNSAFE_STATEMENT),
                          ER_THD(this, LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
7295
      if (global_system_variables.log_warnings > 0 &&
7296
          !protect_against_unsafe_warning_flood(unsafe_type))
7297
        print_unsafe_warning_to_log(this, unsafe_type, buf, query());
7298 7299 7300 7301 7302
    }
  }
  DBUG_VOID_RETURN;
}

7303 7304
/**
  Log the current query.
7305

7306
  The query will be logged in either row format or statement format
7307
  depending on the value of @c current_stmt_binlog_format_row field and
7308
  the value of the @c qtype parameter.
7309

7310
  This function must be called:
7311

7312
  - After the all calls to ha_*_row() functions have been issued.
7313

7314 7315 7316 7317 7318 7319 7320 7321 7322
  - After any writes to system tables. Rationale: if system tables
    were written after a call to this function, and the master crashes
    after the call to this function and before writing the system
    tables, then the master and slave get out of sync.

  - Before tables are unlocked and closed.

  @see decide_logging_format

7323
  @retval < 0 No logging of query (ok)
7324
  @retval 0 Success
7325 7326
  @retval > 0  If there is a failure when writing the query (e.g.,
               write failure), then the error code is returned.
7327
*/
7328

7329
int THD::binlog_query(THD::enum_binlog_query_type qtype, char const *query_arg,
7330 7331
                      ulong query_len, bool is_trans, bool direct, 
                      bool suppress_use, int errcode)
7332 7333
{
  DBUG_ENTER("THD::binlog_query");
7334 7335
  DBUG_PRINT("enter", ("qtype: %s  query: '%-.*s'",
                       show_query_type(qtype), (int) query_len, query_arg));
7336

Sergei Golubchik's avatar
Sergei Golubchik committed
7337 7338
  DBUG_ASSERT(query_arg);
  DBUG_ASSERT(WSREP_EMULATE_BINLOG(this) || mysql_bin_log.is_open());
7339

7340 7341 7342 7343 7344 7345 7346 7347
  /* If this is withing a BEGIN ... COMMIT group, don't log it */
  if (variables.option_bits & OPTION_GTID_BEGIN)
  {
    direct= 0;
    is_trans= 1;
  }
  DBUG_PRINT("info", ("is_trans: %d  direct: %d", is_trans, direct));

7348 7349 7350 7351 7352 7353
  if (get_binlog_local_stmt_filter() == BINLOG_FILTER_SET)
  {
    /*
      The current statement is to be ignored, and not written to
      the binlog. Do not call issue_unsafe_warnings().
    */
7354
    DBUG_RETURN(-1);
7355 7356
  }

7357 7358 7359 7360 7361 7362 7363 7364 7365
  /*
    If we are not in prelocked mode, mysql_unlock_tables() will be
    called after this binlog_query(), so we have to flush the pending
    rows event with the STMT_END_F set to unlock all tables at the
    slave side as well.

    If we are in prelocked mode, the flushing will be done inside the
    top-most close_thread_tables().
  */
Konstantin Osipov's avatar
Konstantin Osipov committed
7366
  if (this->locked_tables_mode <= LTM_LOCK_TABLES)
7367 7368 7369
  {
    int error;
    if (unlikely(error= binlog_flush_pending_rows_event(TRUE, is_trans)))
7370 7371
    {
      DBUG_ASSERT(error > 0);
7372
      DBUG_RETURN(error);
7373
    }
7374
  }
7375

7376
  /*
7377
    Warnings for unsafe statements logged in statement format are
7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391
    printed in three places instead of in decide_logging_format().
    This is because the warnings should be printed only if the statement
    is actually logged. When executing decide_logging_format(), we cannot
    know for sure if the statement will be logged:

    1 - sp_head::execute_procedure which prints out warnings for calls to
    stored procedures.

    2 - sp_head::execute_function which prints out warnings for calls
    involving functions.

    3 - THD::binlog_query (here) which prints warning for top level
    statements not covered by the two cases above: i.e., if not insided a
    procedure and a function.
7392 7393 7394 7395 7396

    Besides, we should not try to print these warnings if it is not
    possible to write statements to the binary log as it happens when
    the execution is inside a function, or generaly speaking, when
    the variables.option_bits & OPTION_BIN_LOG is false.
7397
    
7398
  */
7399 7400
  if ((variables.option_bits & OPTION_BIN_LOG) &&
      spcont == NULL && !binlog_evt_union.do_union)
7401
    issue_unsafe_warnings();
7402

7403
  switch (qtype) {
7404 7405 7406
    /*
      ROW_QUERY_TYPE means that the statement may be logged either in
      row format or in statement format.  If
7407
      current_stmt_binlog_format is row, it means that the
7408 7409 7410
      statement has already been logged in row format and hence shall
      not be logged again.
    */
7411
  case THD::ROW_QUERY_TYPE:
7412
    DBUG_PRINT("debug",
7413
               ("is_current_stmt_binlog_format_row: %d",
7414 7415
                is_current_stmt_binlog_format_row()));
    if (is_current_stmt_binlog_format_row())
7416
      DBUG_RETURN(-1);
7417
    /* Fall through */
7418

7419 7420 7421 7422
    /*
      STMT_QUERY_TYPE means that the query must be logged in statement
      format; it cannot be logged in row format.  This is typically
      used by DDL statements.  It is an error to use this query type
7423
      if current_stmt_binlog_format_row is row.
7424 7425

      @todo Currently there are places that call this method with
7426
      STMT_QUERY_TYPE and current_stmt_binlog_format is row.  Fix those
7427
      places and add assert to ensure correct behavior. /Sven
7428 7429 7430
    */
  case THD::STMT_QUERY_TYPE:
    /*
7431 7432
      The MYSQL_LOG::write() function will set the STMT_END_F flag and
      flush the pending rows event if necessary.
7433
    */
7434
    {
vinchen's avatar
vinchen committed
7435 7436
      int error = 0;

7437 7438 7439 7440 7441
      /*
        Binlog table maps will be irrelevant after a Query_log_event
        (they are just removed on the slave side) so after the query
        log event is written to the binary log, we pretend that no
        table maps were written.
vinchen's avatar
vinchen committed
7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455
      */
      if(binlog_should_compress(query_len))
      {
        Query_compressed_log_event qinfo(this, query_arg, query_len, is_trans, direct,
                            suppress_use, errcode);
        error= mysql_bin_log.write(&qinfo);
      }
      else
      {
        Query_log_event qinfo(this, query_arg, query_len, is_trans, direct,
          suppress_use, errcode);
        error= mysql_bin_log.write(&qinfo);
      }

7456
      binlog_table_maps= 0;
7457
      DBUG_RETURN(error >= 0 ? error : 1);
7458 7459 7460 7461
    }

  case THD::QUERY_TYPE_COUNT:
  default:
7462
    DBUG_ASSERT(qtype < QUERY_TYPE_COUNT);
7463 7464 7465 7466
  }
  DBUG_RETURN(0);
}

7467 7468 7469
void
THD::wait_for_wakeup_ready()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7470
  mysql_mutex_lock(&LOCK_wakeup_ready);
7471
  while (!wakeup_ready)
Sergei Golubchik's avatar
Sergei Golubchik committed
7472 7473
    mysql_cond_wait(&COND_wakeup_ready, &LOCK_wakeup_ready);
  mysql_mutex_unlock(&LOCK_wakeup_ready);
7474 7475 7476 7477 7478
}

void
THD::signal_wakeup_ready()
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7479
  mysql_mutex_lock(&LOCK_wakeup_ready);
7480
  wakeup_ready= true;
Sergei Golubchik's avatar
Sergei Golubchik committed
7481 7482
  mysql_mutex_unlock(&LOCK_wakeup_ready);
  mysql_cond_signal(&COND_wakeup_ready);
7483 7484
}

7485 7486 7487 7488 7489 7490 7491
void THD::set_last_commit_gtid(rpl_gtid &gtid)
{
#ifndef EMBEDDED_LIBRARY
  bool changed_gtid= (m_last_commit_gtid.seq_no != gtid.seq_no);
#endif
  m_last_commit_gtid= gtid;
#ifndef EMBEDDED_LIBRARY
7492
  if (changed_gtid && session_tracker.sysvars.is_enabled())
7493
  {
7494
    DBUG_ASSERT(current_thd == this);
7495
    session_tracker.sysvars.
7496
      mark_as_changed(this, (LEX_CSTRING*)Sys_last_gtid_ptr);
7497
  }
7498 7499
#endif
}
7500

unknown's avatar
unknown committed
7501 7502 7503 7504 7505 7506 7507 7508 7509
void
wait_for_commit::reinit()
{
  subsequent_commits_list= NULL;
  next_subsequent_commit= NULL;
  waitee= NULL;
  opaque_pointer= NULL;
  wakeup_error= 0;
  wakeup_subsequent_commits_running= false;
7510
  commit_started= false;
7511 7512 7513 7514 7515 7516 7517 7518
#ifdef SAFE_MUTEX
  /*
    When using SAFE_MUTEX, the ordering between taking the LOCK_wait_commit
    mutexes is checked. This causes a problem when we re-use a mutex, as then
    the expected locking order may change.

    So in this case, do a re-init of the mutex. In release builds, we want to
    avoid the overhead of a re-init though.
7519 7520 7521

    To ensure that no one is locking the mutex, we take a lock of it first.
    For full explanation, see wait_for_commit::~wait_for_commit()
7522
  */
7523 7524 7525
  mysql_mutex_lock(&LOCK_wait_commit);
  mysql_mutex_unlock(&LOCK_wait_commit);

7526 7527 7528
  mysql_mutex_destroy(&LOCK_wait_commit);
  mysql_mutex_init(key_LOCK_wait_commit, &LOCK_wait_commit, MY_MUTEX_INIT_FAST);
#endif
unknown's avatar
unknown committed
7529 7530 7531
}


7532 7533 7534 7535
wait_for_commit::wait_for_commit()
{
  mysql_mutex_init(key_LOCK_wait_commit, &LOCK_wait_commit, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_wait_commit, &COND_wait_commit, 0);
unknown's avatar
unknown committed
7536
  reinit();
7537 7538 7539
}


7540 7541
wait_for_commit::~wait_for_commit()
{
unknown's avatar
unknown committed
7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562
  /*
    Since we do a dirty read of the waiting_for_commit flag in
    wait_for_prior_commit() and in unregister_wait_for_prior_commit(), we need
    to take extra care before freeing the wait_for_commit object.

    It is possible for the waitee to be pre-empted inside wakeup(), just after
    it has cleared the waiting_for_commit flag and before it has released the
    LOCK_wait_commit mutex. And then it is possible for the waiter to find the
    flag cleared in wait_for_prior_commit() and go finish up things and
    de-allocate the LOCK_wait_commit and COND_wait_commit objects before the
    waitee has time to be re-scheduled and finish unlocking the mutex and
    signalling the condition. This would lead to the waitee accessing no
    longer valid memory.

    To prevent this, we do an extra lock/unlock of the mutex here before
    deallocation; this makes certain that any waitee has completed wakeup()
    first.
  */
  mysql_mutex_lock(&LOCK_wait_commit);
  mysql_mutex_unlock(&LOCK_wait_commit);

7563 7564 7565 7566 7567
  mysql_mutex_destroy(&LOCK_wait_commit);
  mysql_cond_destroy(&COND_wait_commit);
}


7568
void
7569
wait_for_commit::wakeup(int wakeup_error)
7570 7571 7572 7573 7574 7575 7576 7577
{
  /*
    We signal each waiter on their own condition and mutex (rather than using
    pthread_cond_broadcast() or something like that).

    Otherwise we would need to somehow ensure that they were done
    waking up before we could allow this THD to be destroyed, which would
    be annoying and unnecessary.
unknown's avatar
unknown committed
7578 7579 7580 7581

    Note that wakeup_subsequent_commits2() depends on this function being a
    full memory barrier (it is, because it takes a mutex lock).

7582 7583
  */
  mysql_mutex_lock(&LOCK_wait_commit);
unknown's avatar
unknown committed
7584
  waitee= NULL;
7585
  this->wakeup_error= wakeup_error;
unknown's avatar
unknown committed
7586 7587 7588 7589 7590
  /*
    Note that it is critical that the mysql_cond_signal() here is done while
    still holding the mutex. As soon as we release the mutex, the waiter might
    deallocate the condition object.
  */
7591
  mysql_cond_signal(&COND_wait_commit);
unknown's avatar
unknown committed
7592
  mysql_mutex_unlock(&LOCK_wait_commit);
7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616
}


/*
  Register that the next commit of this THD should wait to complete until
  commit in another THD (the waitee) has completed.

  The wait may occur explicitly, with the waiter sitting in
  wait_for_prior_commit() until the waitee calls wakeup_subsequent_commits().

  Alternatively, the TC (eg. binlog) may do the commits of both waitee and
  waiter at once during group commit, resolving both of them in the right
  order.

  Only one waitee can be registered for a waiter; it must be removed by
  wait_for_prior_commit() or unregister_wait_for_prior_commit() before a new
  one is registered. But it is ok for several waiters to register a wait for
  the same waitee. It is also permissible for one THD to be both a waiter and
  a waitee at the same time.
*/
void
wait_for_commit::register_wait_for_prior_commit(wait_for_commit *waitee)
{
  DBUG_ASSERT(!this->waitee /* No prior registration allowed */);
unknown's avatar
unknown committed
7617
  wakeup_error= 0;
7618 7619 7620 7621 7622 7623 7624 7625 7626
  this->waitee= waitee;

  mysql_mutex_lock(&waitee->LOCK_wait_commit);
  /*
    If waitee is in the middle of wakeup, then there is nothing to wait for,
    so we need not register. This is necessary to avoid a race in unregister,
    see comments on wakeup_subsequent_commits2() for details.
  */
  if (waitee->wakeup_subsequent_commits_running)
unknown's avatar
unknown committed
7627
    this->waitee= NULL;
7628 7629
  else
  {
unknown's avatar
unknown committed
7630 7631 7632 7633
    /*
      Put ourself at the head of the waitee's list of transactions that must
      wait for it to commit first.
     */
7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645
    this->next_subsequent_commit= waitee->subsequent_commits_list;
    waitee->subsequent_commits_list= this;
  }
  mysql_mutex_unlock(&waitee->LOCK_wait_commit);
}


/*
  Wait for commit of another transaction to complete, as already registered
  with register_wait_for_prior_commit(). If the commit already completed,
  returns immediately.
*/
7646
int
7647
wait_for_commit::wait_for_prior_commit2(THD *thd)
7648
{
Sergei Golubchik's avatar
Sergei Golubchik committed
7649
  PSI_stage_info old_stage;
7650
  wait_for_commit *loc_waitee;
7651

7652
  mysql_mutex_lock(&LOCK_wait_commit);
7653
  DEBUG_SYNC(thd, "wait_for_prior_commit_waiting");
Sergei Golubchik's avatar
Sergei Golubchik committed
7654 7655 7656
  thd->ENTER_COND(&COND_wait_commit, &LOCK_wait_commit,
                  &stage_waiting_for_prior_transaction_to_commit,
                  &old_stage);
7657
  while ((loc_waitee= this->waitee) && likely(!thd->check_killed(1)))
7658
    mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
unknown's avatar
unknown committed
7659
  if (!loc_waitee)
7660 7661 7662
  {
    if (wakeup_error)
      my_error(ER_PRIOR_COMMIT_FAILED, MYF(0));
7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679
    goto end;
  }
  /*
    Wait was interrupted by kill. We need to unregister our wait and give the
    error. But if a wakeup is already in progress, then we must ignore the
    kill and not give error, otherwise we get inconsistency between waitee and
    waiter as to whether we succeed or fail (eg. we may roll back but waitee
    might attempt to commit both us and any subsequent commits waiting for us).
  */
  mysql_mutex_lock(&loc_waitee->LOCK_wait_commit);
  if (loc_waitee->wakeup_subsequent_commits_running)
  {
    /* We are being woken up; ignore the kill and just wait. */
    mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
    do
    {
      mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
unknown's avatar
unknown committed
7680 7681 7682
    } while (this->waitee);
    if (wakeup_error)
      my_error(ER_PRIOR_COMMIT_FAILED, MYF(0));
7683
    goto end;
7684
  }
7685 7686
  remove_from_list(&loc_waitee->subsequent_commits_list);
  mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
unknown's avatar
unknown committed
7687
  this->waitee= NULL;
7688

7689 7690 7691
  wakeup_error= thd->killed_errno();
  if (!wakeup_error)
    wakeup_error= ER_QUERY_INTERRUPTED;
7692
  my_message(wakeup_error, ER_THD(thd, wakeup_error), MYF(0));
7693
  thd->EXIT_COND(&old_stage);
unknown's avatar
unknown committed
7694 7695 7696 7697 7698 7699
  /*
    Must do the DEBUG_SYNC() _after_ exit_cond(), as DEBUG_SYNC is not safe to
    use within enter_cond/exit_cond.
  */
  DEBUG_SYNC(thd, "wait_for_prior_commit_killed");
  return wakeup_error;
7700 7701

end:
Sergei Golubchik's avatar
Sergei Golubchik committed
7702
  thd->EXIT_COND(&old_stage);
7703
  return wakeup_error;
7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721
}


/*
  Wakeup anyone waiting for us to have committed.

  Note about locking:

  We have a potential race or deadlock between wakeup_subsequent_commits() in
  the waitee and unregister_wait_for_prior_commit() in the waiter.

  Both waiter and waitee needs to take their own lock before it is safe to take
  a lock on the other party - else the other party might disappear and invalid
  memory data could be accessed. But if we take the two locks in different
  order, we may end up in a deadlock.

  The waiter needs to lock the waitee to delete itself from the list in
  unregister_wait_for_prior_commit(). Thus wakeup_subsequent_commits() can not
unknown's avatar
unknown committed
7722
  hold its own lock while locking waiters, as this could lead to deadlock.
7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744

  So we need to prevent unregister_wait_for_prior_commit() running while wakeup
  is in progress - otherwise the unregister could complete before the wakeup,
  leading to incorrect spurious wakeup or accessing invalid memory.

  However, if we are in the middle of running wakeup_subsequent_commits(), then
  there is no need for unregister_wait_for_prior_commit() in the first place -
  the waiter can just do a normal wait_for_prior_commit(), as it will be
  immediately woken up.

  So the solution to the potential race/deadlock is to set a flag in the waitee
  that wakeup_subsequent_commits() is in progress. When this flag is set,
  unregister_wait_for_prior_commit() becomes just wait_for_prior_commit().

  Then also register_wait_for_prior_commit() needs to check if
  wakeup_subsequent_commits() is running, and skip the registration if
  so. This is needed in case a new waiter manages to register itself and
  immediately try to unregister while wakeup_subsequent_commits() is
  running. Else the new waiter would also wait rather than unregister, but it
  would not be woken up until next wakeup, which could be potentially much
  later than necessary.
*/
unknown's avatar
unknown committed
7745

7746
void
7747
wait_for_commit::wakeup_subsequent_commits2(int wakeup_error)
7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763
{
  wait_for_commit *waiter;

  mysql_mutex_lock(&LOCK_wait_commit);
  wakeup_subsequent_commits_running= true;
  waiter= subsequent_commits_list;
  subsequent_commits_list= NULL;
  mysql_mutex_unlock(&LOCK_wait_commit);

  while (waiter)
  {
    /*
      Important: we must grab the next pointer before waking up the waiter;
      once the wakeup is done, the field could be invalidated at any time.
    */
    wait_for_commit *next= waiter->next_subsequent_commit;
7764
    waiter->wakeup(wakeup_error);
7765 7766 7767
    waiter= next;
  }

unknown's avatar
unknown committed
7768
  /*
unknown's avatar
unknown committed
7769 7770 7771 7772 7773 7774 7775
    We need a full memory barrier between walking the list above, and clearing
    the flag wakeup_subsequent_commits_running below. This barrier is needed
    to ensure that no other thread will start to modify the list pointers
    before we are done traversing the list.

    But wait_for_commit::wakeup() does a full memory barrier already (it locks
    a mutex), so no extra explicit barrier is needed here.
unknown's avatar
unknown committed
7776
  */
7777
  wakeup_subsequent_commits_running= false;
7778
  DBUG_EXECUTE_IF("inject_wakeup_subsequent_commits_sleep", my_sleep(21000););
7779 7780 7781 7782 7783 7784 7785
}


/* Cancel a previously registered wait for another THD to commit before us. */
void
wait_for_commit::unregister_wait_for_prior_commit2()
{
unknown's avatar
unknown committed
7786 7787
  wait_for_commit *loc_waitee;

7788
  mysql_mutex_lock(&LOCK_wait_commit);
unknown's avatar
unknown committed
7789
  if ((loc_waitee= this->waitee))
7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801
  {
    mysql_mutex_lock(&loc_waitee->LOCK_wait_commit);
    if (loc_waitee->wakeup_subsequent_commits_running)
    {
      /*
        When a wakeup is running, we cannot safely remove ourselves from the
        list without corrupting it. Instead we can just wait, as wakeup is
        already in progress and will thus be immediate.

        See comments on wakeup_subsequent_commits2() for more details.
      */
      mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
unknown's avatar
unknown committed
7802
      while (this->waitee)
7803 7804 7805 7806 7807
        mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
    }
    else
    {
      /* Remove ourselves from the list in the waitee. */
7808
      remove_from_list(&loc_waitee->subsequent_commits_list);
7809
      mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
unknown's avatar
unknown committed
7810
      this->waitee= NULL;
7811 7812
    }
  }
7813
  wakeup_error= 0;
7814 7815 7816 7817
  mysql_mutex_unlock(&LOCK_wait_commit);
}


7818 7819 7820 7821 7822 7823 7824 7825 7826
bool Discrete_intervals_list::append(ulonglong start, ulonglong val,
                                 ulonglong incr)
{
  DBUG_ENTER("Discrete_intervals_list::append");
  /* first, see if this can be merged with previous */
  if ((head == NULL) || tail->merge_if_contiguous(start, val, incr))
  {
    /* it cannot, so need to add a new interval */
    Discrete_interval *new_interval= new Discrete_interval(start, val, incr);
7827
    DBUG_RETURN(append(new_interval));
7828 7829 7830 7831
  }
  DBUG_RETURN(0);
}

7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846
bool Discrete_intervals_list::append(Discrete_interval *new_interval)
{
  DBUG_ENTER("Discrete_intervals_list::append");
  if (unlikely(new_interval == NULL))
    DBUG_RETURN(1);
  DBUG_PRINT("info",("adding new auto_increment interval"));
  if (head == NULL)
    head= current= new_interval;
  else
    tail->next= new_interval;
  tail= new_interval;
  elements++;
  DBUG_RETURN(0);
}

7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858

void AUTHID::copy(MEM_ROOT *mem_root, const LEX_CSTRING *user_name,
                                      const LEX_CSTRING *host_name)
{
  user.str= strmake_root(mem_root, user_name->str, user_name->length);
  user.length= user_name->length;

  host.str= strmake_root(mem_root, host_name->str, host_name->length);
  host.length= host_name->length;
}


7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888
/*
  Set from a string in 'user@host' format.
  This method resebmles parse_user(),
  but does not need temporary buffers.
*/
void AUTHID::parse(const char *str, size_t length)
{
  const char *p= strrchr(str, '@');
  if (!p)
  {
    user.str= str;
    user.length= length;
    host= null_clex_str;
  }
  else
  {
    user.str= str;
    user.length= (size_t) (p - str);
    host.str= p + 1;
    host.length= (size_t) (length - user.length - 1);
    if (user.length && !host.length)
      host= host_not_specified; // 'user@' -> 'user@%'
  }
  if (user.length > USERNAME_LENGTH)
    user.length= USERNAME_LENGTH;
  if (host.length > HOSTNAME_LENGTH)
    host.length= HOSTNAME_LENGTH;
}


7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899
void Database_qualified_name::copy(MEM_ROOT *mem_root,
                                   const LEX_CSTRING &db,
                                   const LEX_CSTRING &name)
{
  m_db.length= db.length;
  m_db.str= strmake_root(mem_root, db.str, db.length);
  m_name.length= name.length;
  m_name.str= strmake_root(mem_root, name.str, name.length);
}


7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915
bool Table_ident::append_to(THD *thd, String *str) const
{
  return (db.length &&
          (append_identifier(thd, str, db.str, db.length) ||
           str->append('.'))) ||
         append_identifier(thd, str, table.str, table.length);
}


bool Qualified_column_ident::append_to(THD *thd, String *str) const
{
  return Table_ident::append_to(thd, str) || str->append('.') ||
         append_identifier(thd, str, m_column.str, m_column.length);
}


7916
#endif /* !defined(MYSQL_CLIENT) */
7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929


Query_arena_stmt::Query_arena_stmt(THD *_thd) :
  thd(_thd)
{
  arena= thd->activate_stmt_arena_if_needed(&backup);
}

Query_arena_stmt::~Query_arena_stmt()
{
  if (arena)
    thd->restore_active_arena(arena, &backup);
}
7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948


bool THD::timestamp_to_TIME(MYSQL_TIME *ltime, my_time_t ts,
                            ulong sec_part, ulonglong fuzzydate)
{
  time_zone_used= 1;
  if (ts == 0 && sec_part == 0)
  {
    if (fuzzydate & TIME_NO_ZERO_DATE)
      return 1;
    set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
  }
  else
  {
    variables.time_zone->gmt_sec_to_TIME(ltime, ts);
    ltime->second_part= sec_part;
  }
  return 0;
}