1/*
2 Copyright (c) 2000, 2015, Oracle and/or its affiliates.
3 Copyright (c) 2008, 2017, MariaDB Corporation.
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17*/
18
19
20/*****************************************************************************
21**
22** This file implements classes defined in sql_class.h
23** Especially the classes to handle a result from a select
24**
25*****************************************************************************/
26
27#ifdef USE_PRAGMA_IMPLEMENTATION
28#pragma implementation // gcc: Class implementation
29#endif
30
31#include "mariadb.h"
32#include "sql_priv.h"
33#include "sql_class.h"
34#include "sql_cache.h" // query_cache_abort
35#include "sql_base.h" // close_thread_tables
36#include "sql_time.h" // date_time_format_copy
37#include "tztime.h" // MYSQL_TIME <-> my_time_t
38#include "sql_acl.h" // NO_ACCESS,
39 // 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"
44#include "rpl_record.h"
45#include "slave.h"
46#include <my_bitmap.h>
47#include "log_event.h"
48#include "sql_audit.h"
49#include <m_ctype.h>
50#include <sys/stat.h>
51#include <thr_alarm.h>
52#ifdef __WIN__
53#include <io.h>
54#endif
55#include <mysys_err.h>
56#include <limits.h>
57
58#include "sp_head.h"
59#include "sp_rcontext.h"
60#include "sp_cache.h"
61#include "sql_show.h" // append_identifier
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"
67#include "lock.h"
68#include "wsrep_mysqld.h"
69#include "wsrep_thd.h"
70#include "sql_connect.h"
71#include "my_atomic.h"
72
73#ifdef HAVE_SYS_SYSCALL_H
74#include <sys/syscall.h>
75#endif
76
77/*
78 The following is used to initialise Table_ident with a internal
79 table name
80*/
81char internal_table_name[2]= "*";
82char empty_c_string[1]= {0}; /* used for not defined db */
83
84const char * const THD::DEFAULT_WHERE= "field list";
85
86/****************************************************************************
87** User variables
88****************************************************************************/
89
90extern "C" uchar *get_var_key(user_var_entry *entry, size_t *length,
91 my_bool not_used __attribute__((unused)))
92{
93 *length= entry->name.length;
94 return (uchar*) entry->name.str;
95}
96
97extern "C" void free_user_var(user_var_entry *entry)
98{
99 char *pos= (char*) entry+ALIGN_SIZE(sizeof(*entry));
100 if (entry->value && entry->value != pos)
101 my_free(entry->value);
102 my_free(entry);
103}
104
105/* Functions for last-value-from-sequence hash */
106
107extern "C" uchar *get_sequence_last_key(SEQUENCE_LAST_VALUE *entry,
108 size_t *length,
109 my_bool not_used
110 __attribute__((unused)))
111{
112 *length= entry->length;
113 return (uchar*) entry->key;
114}
115
116extern "C" void free_sequence_last(SEQUENCE_LAST_VALUE *entry)
117{
118 delete entry;
119}
120
121
122bool Key_part_spec::operator==(const Key_part_spec& other) const
123{
124 return length == other.length &&
125 !lex_string_cmp(system_charset_info, &field_name,
126 &other.field_name);
127}
128
129/**
130 Construct an (almost) deep copy of this key. Only those
131 elements that are known to never change are not copied.
132 If out of memory, a partial copy is returned and an error is set
133 in THD.
134*/
135
136Key::Key(const Key &rhs, MEM_ROOT *mem_root)
137 :DDL_options(rhs),type(rhs.type),
138 key_create_info(rhs.key_create_info),
139 columns(rhs.columns, mem_root),
140 name(rhs.name),
141 option_list(rhs.option_list),
142 generated(rhs.generated), invisible(false)
143{
144 list_copy_and_replace_each_value(columns, mem_root);
145}
146
147/**
148 Construct an (almost) deep copy of this foreign key. Only those
149 elements that are known to never change are not copied.
150 If out of memory, a partial copy is returned and an error is set
151 in THD.
152*/
153
154Foreign_key::Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root)
155 :Key(rhs,mem_root),
156 ref_db(rhs.ref_db),
157 ref_table(rhs.ref_table),
158 ref_columns(rhs.ref_columns,mem_root),
159 delete_opt(rhs.delete_opt),
160 update_opt(rhs.update_opt),
161 match_opt(rhs.match_opt)
162{
163 list_copy_and_replace_each_value(ref_columns, mem_root);
164}
165
166/*
167 Test if a foreign key (= generated key) is a prefix of the given key
168 (ignoring key name, key type and order of columns)
169
170 NOTES:
171 This is only used to test if an index for a FOREIGN KEY exists
172
173 IMPLEMENTATION
174 We only compare field names
175
176 RETURN
177 0 Generated key is a prefix of other key
178 1 Not equal
179*/
180
181bool foreign_key_prefix(Key *a, Key *b)
182{
183 /* Ensure that 'a' is the generated key */
184 if (a->generated)
185 {
186 if (b->generated && a->columns.elements > b->columns.elements)
187 swap_variables(Key*, a, b); // Put shorter key in 'a'
188 }
189 else
190 {
191 if (!b->generated)
192 return TRUE; // No foreign key
193 swap_variables(Key*, a, b); // Put generated key in 'a'
194 }
195
196 /* Test if 'a' is a prefix of 'b' */
197 if (a->columns.elements > b->columns.elements)
198 return TRUE; // Can't be prefix
199
200 List_iterator<Key_part_spec> col_it1(a->columns);
201 List_iterator<Key_part_spec> col_it2(b->columns);
202 const Key_part_spec *col1, *col2;
203
204#ifdef ENABLE_WHEN_INNODB_CAN_HANDLE_SWAPED_FOREIGN_KEY_COLUMNS
205 while ((col1= col_it1++))
206 {
207 bool found= 0;
208 col_it2.rewind();
209 while ((col2= col_it2++))
210 {
211 if (*col1 == *col2)
212 {
213 found= TRUE;
214 break;
215 }
216 }
217 if (!found)
218 return TRUE; // Error
219 }
220 return FALSE; // Is prefix
221#else
222 while ((col1= col_it1++))
223 {
224 col2= col_it2++;
225 if (!(*col1 == *col2))
226 return TRUE;
227 }
228 return FALSE; // Is prefix
229#endif
230}
231
232/*
233 @brief
234 Check if the foreign key options are compatible with the specification
235 of the columns on which the key is created
236
237 @retval
238 FALSE The foreign key options are compatible with key columns
239 @retval
240 TRUE Otherwise
241*/
242bool Foreign_key::validate(List<Create_field> &table_fields)
243{
244 Create_field *sql_field;
245 Key_part_spec *column;
246 List_iterator<Key_part_spec> cols(columns);
247 List_iterator<Create_field> it(table_fields);
248 DBUG_ENTER("Foreign_key::validate");
249 while ((column= cols++))
250 {
251 it.rewind();
252 while ((sql_field= it++) &&
253 lex_string_cmp(system_charset_info,
254 &column->field_name,
255 &sql_field->field_name)) {}
256 if (!sql_field)
257 {
258 my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.str);
259 DBUG_RETURN(TRUE);
260 }
261 if (type == Key::FOREIGN_KEY && sql_field->vcol_info)
262 {
263 if (delete_opt == FK_OPTION_SET_NULL)
264 {
265 my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0),
266 "ON DELETE SET NULL");
267 DBUG_RETURN(TRUE);
268 }
269 if (update_opt == FK_OPTION_SET_NULL)
270 {
271 my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0),
272 "ON UPDATE SET NULL");
273 DBUG_RETURN(TRUE);
274 }
275 if (update_opt == FK_OPTION_CASCADE)
276 {
277 my_error(ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN, MYF(0),
278 "ON UPDATE CASCADE");
279 DBUG_RETURN(TRUE);
280 }
281 }
282 }
283 DBUG_RETURN(FALSE);
284}
285
286/****************************************************************************
287** Thread specific functions
288****************************************************************************/
289
290/**
291 Get current THD object from thread local data
292
293 @retval The THD object for the thread, NULL if not connection thread
294*/
295THD *thd_get_current_thd()
296{
297 return current_thd;
298}
299
300/**
301 Clear errors from the previous THD
302
303 @param thd THD object
304*/
305void thd_clear_errors(THD *thd)
306{
307 my_errno= 0;
308 thd->mysys_var->abort= 0;
309}
310
311
312/**
313 Get thread attributes for connection threads
314
315 @retval Reference to thread attribute for connection threads
316*/
317pthread_attr_t *get_connection_attrib(void)
318{
319 return &connection_attrib;
320}
321
322/**
323 Get max number of connections
324
325 @retval Max number of connections for MySQL Server
326*/
327ulong get_max_connections(void)
328{
329 return max_connections;
330}
331
332/*
333 The following functions form part of the C plugin API
334*/
335
336extern "C" int mysql_tmpfile(const char *prefix)
337{
338 char filename[FN_REFLEN];
339 File fd= create_temp_file(filename, mysql_tmpdir, prefix,
340 O_BINARY | O_SEQUENTIAL,
341 MYF(MY_WME | MY_TEMPORARY));
342 return fd;
343}
344
345
346extern "C"
347int thd_in_lock_tables(const THD *thd)
348{
349 return MY_TEST(thd->in_lock_tables);
350}
351
352
353extern "C"
354int thd_tablespace_op(const THD *thd)
355{
356 return MY_TEST(thd->tablespace_op);
357}
358
359extern "C"
360const char *set_thd_proc_info(THD *thd_arg, const char *info,
361 const char *calling_function,
362 const char *calling_file,
363 const unsigned int calling_line)
364{
365 PSI_stage_info old_stage;
366 PSI_stage_info new_stage;
367
368 new_stage.m_key= 0;
369 new_stage.m_name= info;
370
371 set_thd_stage_info(thd_arg, & new_stage, & old_stage,
372 calling_function, calling_file, calling_line);
373
374 return old_stage.m_name;
375}
376
377extern "C"
378void set_thd_stage_info(void *thd_arg,
379 const PSI_stage_info *new_stage,
380 PSI_stage_info *old_stage,
381 const char *calling_func,
382 const char *calling_file,
383 const unsigned int calling_line)
384{
385 THD *thd= (THD*) thd_arg;
386 if (thd == NULL)
387 thd= current_thd;
388
389 if (old_stage)
390 thd->backup_stage(old_stage);
391
392 if (new_stage)
393 thd->enter_stage(new_stage, calling_func, calling_file, calling_line);
394}
395
396void thd_enter_cond(MYSQL_THD thd, mysql_cond_t *cond, mysql_mutex_t *mutex,
397 const PSI_stage_info *stage, PSI_stage_info *old_stage,
398 const char *src_function, const char *src_file,
399 int src_line)
400{
401 if (!thd)
402 thd= current_thd;
403
404 return thd->enter_cond(cond, mutex, stage, old_stage, src_function, src_file,
405 src_line);
406}
407
408void thd_exit_cond(MYSQL_THD thd, const PSI_stage_info *stage,
409 const char *src_function, const char *src_file,
410 int src_line)
411{
412 if (!thd)
413 thd= current_thd;
414
415 thd->exit_cond(stage, src_function, src_file, src_line);
416 return;
417}
418
419extern "C"
420void **thd_ha_data(const THD *thd, const struct handlerton *hton)
421{
422 return (void **) &thd->ha_data[hton->slot].ha_ptr;
423}
424
425extern "C"
426void thd_storage_lock_wait(THD *thd, long long value)
427{
428 thd->utime_after_lock+= value;
429}
430
431/**
432 Provide a handler data getter to simplify coding
433*/
434extern "C"
435void *thd_get_ha_data(const THD *thd, const struct handlerton *hton)
436{
437 return *thd_ha_data(thd, hton);
438}
439
440
441/**
442 Provide a handler data setter to simplify coding
443 @see thd_set_ha_data() definition in plugin.h
444*/
445extern "C"
446void thd_set_ha_data(THD *thd, const struct handlerton *hton,
447 const void *ha_data)
448{
449 plugin_ref *lock= &thd->ha_data[hton->slot].lock;
450 if (ha_data && !*lock)
451 *lock= ha_lock_engine(NULL, (handlerton*) hton);
452 else if (!ha_data && *lock)
453 {
454 plugin_unlock(NULL, *lock);
455 *lock= NULL;
456 }
457 *thd_ha_data(thd, hton)= (void*) ha_data;
458}
459
460
461/**
462 Allow storage engine to wakeup commits waiting in THD::wait_for_prior_commit.
463 @see thd_wakeup_subsequent_commits() definition in plugin.h
464*/
465extern "C"
466void thd_wakeup_subsequent_commits(THD *thd, int wakeup_error)
467{
468 thd->wakeup_subsequent_commits(wakeup_error);
469}
470
471
472extern "C"
473long long thd_test_options(const THD *thd, long long test_options)
474{
475 return thd->variables.option_bits & test_options;
476}
477
478extern "C"
479int thd_sql_command(const THD *thd)
480{
481 return (int) thd->lex->sql_command;
482}
483
484extern "C"
485int thd_tx_isolation(const THD *thd)
486{
487 return (int) thd->tx_isolation;
488}
489
490extern "C"
491int thd_tx_is_read_only(const THD *thd)
492{
493 return (int) thd->tx_read_only;
494}
495
496
497extern "C"
498{ /* Functions for thd_error_context_service */
499
500 const char *thd_get_error_message(const THD *thd)
501 {
502 return thd->get_stmt_da()->message();
503 }
504
505 uint thd_get_error_number(const THD *thd)
506 {
507 return thd->get_stmt_da()->sql_errno();
508 }
509
510 ulong thd_get_error_row(const THD *thd)
511 {
512 return thd->get_stmt_da()->current_row_for_warning();
513 }
514
515 void thd_inc_error_row(THD *thd)
516 {
517 thd->get_stmt_da()->inc_current_row_for_warning();
518 }
519}
520
521
522/**
523 Dumps a text description of a thread, its security context
524 (user, host) and the current query.
525
526 @param thd thread context
527 @param buffer pointer to preferred result buffer
528 @param length length of buffer
529 @param max_query_len how many chars of query to copy (0 for all)
530
531 @return Pointer to string
532*/
533
534extern "C"
535char *thd_get_error_context_description(THD *thd, char *buffer,
536 unsigned int length,
537 unsigned int max_query_len)
538{
539 String str(buffer, length, &my_charset_latin1);
540 const Security_context *sctx= &thd->main_security_ctx;
541 char header[256];
542 size_t len;
543
544 /*
545 The pointers thd->query and thd->proc_info might change since they are
546 being modified concurrently. This is acceptable for proc_info since its
547 values doesn't have to very accurate and the memory it points to is static,
548 but we need to attempt a snapshot on the pointer values to avoid using NULL
549 values. The pointer to thd->query however, doesn't point to static memory
550 and has to be protected by thd->LOCK_thd_data or risk pointing to
551 uninitialized memory.
552 */
553 const char *proc_info= thd->proc_info;
554
555 len= my_snprintf(header, sizeof(header),
556 "MySQL thread id %u, OS thread handle %lu, query id %llu",
557 (uint)thd->thread_id, (ulong) thd->real_id, (ulonglong) thd->query_id);
558 str.length(0);
559 str.append(header, len);
560
561 if (sctx->host)
562 {
563 str.append(' ');
564 str.append(sctx->host);
565 }
566
567 if (sctx->ip)
568 {
569 str.append(' ');
570 str.append(sctx->ip);
571 }
572
573 if (sctx->user)
574 {
575 str.append(' ');
576 str.append(sctx->user);
577 }
578
579 if (proc_info)
580 {
581 str.append(' ');
582 str.append(proc_info);
583 }
584
585 /* Don't wait if LOCK_thd_data is used as this could cause a deadlock */
586 if (!mysql_mutex_trylock(&thd->LOCK_thd_data))
587 {
588 if (thd->query())
589 {
590 if (max_query_len < 1)
591 len= thd->query_length();
592 else
593 len= MY_MIN(thd->query_length(), max_query_len);
594 str.append('\n');
595 str.append(thd->query(), len);
596 }
597 mysql_mutex_unlock(&thd->LOCK_thd_data);
598 }
599
600 if (str.c_ptr_safe() == buffer)
601 return buffer;
602
603 /*
604 We have to copy the new string to the destination buffer because the string
605 was reallocated to a larger buffer to be able to fit.
606 */
607 DBUG_ASSERT(buffer != NULL);
608 length= MY_MIN(str.length(), length-1);
609 memcpy(buffer, str.c_ptr_quick(), length);
610 /* Make sure that the new string is null terminated */
611 buffer[length]= '\0';
612 return buffer;
613}
614
615
616#if MARIA_PLUGIN_INTERFACE_VERSION < 0x0200
617/**
618 TODO: This function is for API compatibility, remove it eventually.
619 All engines should switch to use thd_get_error_context_description()
620 plugin service function.
621*/
622extern "C"
623char *thd_security_context(THD *thd,
624 char *buffer, unsigned int length,
625 unsigned int max_query_len)
626{
627 return thd_get_error_context_description(thd, buffer, length, max_query_len);
628}
629#endif
630
631/**
632 Implementation of Drop_table_error_handler::handle_condition().
633 The reason in having this implementation is to silence technical low-level
634 warnings during DROP TABLE operation. Currently we don't want to expose
635 the following warnings during DROP TABLE:
636 - Some of table files are missed or invalid (the table is going to be
637 deleted anyway, so why bother that something was missed);
638 - A trigger associated with the table does not have DEFINER (One of the
639 MySQL specifics now is that triggers are loaded for the table being
640 dropped. So, we may have a warning that trigger does not have DEFINER
641 attribute during DROP TABLE operation).
642
643 @return TRUE if the condition is handled.
644*/
645bool Drop_table_error_handler::handle_condition(THD *thd,
646 uint sql_errno,
647 const char* sqlstate,
648 Sql_condition::enum_warning_level *level,
649 const char* msg,
650 Sql_condition ** cond_hdl)
651{
652 *cond_hdl= NULL;
653 return ((sql_errno == EE_DELETE && my_errno == ENOENT) ||
654 sql_errno == ER_TRG_NO_DEFINER);
655}
656
657
658/**
659 Handle an error from MDL_context::upgrade_lock() and mysql_lock_tables().
660 Ignore ER_LOCK_ABORTED and ER_LOCK_DEADLOCK errors.
661*/
662
663bool
664MDL_deadlock_and_lock_abort_error_handler::
665handle_condition(THD *thd,
666 uint sql_errno,
667 const char *sqlstate,
668 Sql_condition::enum_warning_level *level,
669 const char* msg,
670 Sql_condition **cond_hdl)
671{
672 *cond_hdl= NULL;
673 if (sql_errno == ER_LOCK_ABORTED || sql_errno == ER_LOCK_DEADLOCK)
674 m_need_reopen= true;
675
676 return m_need_reopen;
677}
678
679
680/**
681 Send timeout to thread.
682
683 Note that this is always safe as the thread will always remove it's
684 timeouts at end of query (and thus before THD is destroyed)
685*/
686
687extern "C" void thd_kill_timeout(THD* thd)
688{
689 thd->status_var.max_statement_time_exceeded++;
690 /* Kill queries that can't cause data corruptions */
691 thd->awake(KILL_TIMEOUT);
692}
693
694THD::THD(my_thread_id id, bool is_wsrep_applier, bool skip_global_sys_var_lock)
695 :Statement(&main_lex, &main_mem_root, STMT_CONVENTIONAL_EXECUTION,
696 /* statement id */ 0),
697 rli_fake(0), rgi_fake(0), rgi_slave(NULL),
698 protocol_text(this), protocol_binary(this),
699 m_current_stage_key(0),
700 in_sub_stmt(0), log_all_errors(0),
701 binlog_unsafe_warning_flags(0),
702 binlog_table_maps(0),
703 bulk_param(0),
704 table_map_for_update(0),
705 m_examined_row_count(0),
706 accessed_rows_and_keys(0),
707 m_digest(NULL),
708 m_statement_psi(NULL),
709 m_idle_psi(NULL),
710 thread_id(id),
711 thread_dbug_id(id),
712 os_thread_id(0),
713 global_disable_checkpoint(0),
714 failed_com_change_user(0),
715 is_fatal_error(0),
716 transaction_rollback_request(0),
717 is_fatal_sub_stmt_error(false),
718 rand_used(0),
719 time_zone_used(0),
720 in_lock_tables(0),
721 bootstrap(0),
722 derived_tables_processing(FALSE),
723 waiting_on_group_commit(FALSE), has_waiter(FALSE),
724 spcont(NULL),
725 m_parser_state(NULL),
726#if defined(ENABLED_DEBUG_SYNC)
727 debug_sync_control(0),
728#endif /* defined(ENABLED_DEBUG_SYNC) */
729 wait_for_commit_ptr(0),
730 m_internal_handler(0),
731 main_da(0, false, false),
732 m_stmt_da(&main_da),
733 tdc_hash_pins(0),
734 xid_hash_pins(0),
735 m_tmp_tables_locked(false)
736#ifdef WITH_WSREP
737 ,
738 wsrep_applier(is_wsrep_applier),
739 wsrep_applier_closing(false),
740 wsrep_client_thread(false),
741 wsrep_apply_toi(false),
742 wsrep_po_handle(WSREP_PO_INITIALIZER),
743 wsrep_po_cnt(0),
744 wsrep_apply_format(0),
745 wsrep_ignore_table(false)
746#endif
747{
748 ulong tmp;
749 bzero(&variables, sizeof(variables));
750
751 /*
752 We set THR_THD to temporally point to this THD to register all the
753 variables that allocates memory for this THD
754 */
755 THD *old_THR_THD= current_thd;
756 set_current_thd(this);
757 status_var.local_memory_used= sizeof(THD);
758 status_var.max_local_memory_used= status_var.local_memory_used;
759 status_var.global_memory_used= 0;
760 variables.pseudo_thread_id= thread_id;
761 variables.max_mem_used= global_system_variables.max_mem_used;
762 main_da.init();
763
764 mdl_context.init(this);
765
766 /*
767 Pass nominal parameters to init_alloc_root only to ensure that
768 the destructor works OK in case of an error. The main_mem_root
769 will be re-initialized in init_for_queries().
770 */
771 init_sql_alloc(&main_mem_root, "THD::main_mem_root",
772 ALLOC_ROOT_MIN_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC));
773
774 /*
775 Allocation of user variables for binary logging is always done with main
776 mem root
777 */
778 user_var_events_alloc= mem_root;
779
780 stmt_arena= this;
781 thread_stack= 0;
782 scheduler= thread_scheduler; // Will be fixed later
783 event_scheduler.data= 0;
784 event_scheduler.m_psi= 0;
785 skip_wait_timeout= false;
786 extra_port= 0;
787 catalog= (char*)"std"; // the only catalog we have for now
788 main_security_ctx.init();
789 security_ctx= &main_security_ctx;
790 no_errors= 0;
791 password= 0;
792 query_start_sec_part_used= 0;
793 count_cuted_fields= CHECK_FIELD_IGNORE;
794 killed= NOT_KILLED;
795 killed_err= 0;
796 col_access=0;
797 is_slave_error= thread_specific_used= FALSE;
798 my_hash_clear(&handler_tables_hash);
799 my_hash_clear(&ull_hash);
800 tmp_table=0;
801 cuted_fields= 0L;
802 m_sent_row_count= 0L;
803 limit_found_rows= 0;
804 m_row_count_func= -1;
805 statement_id_counter= 0UL;
806 // Must be reset to handle error with THD's created for init of mysqld
807 lex->current_select= 0;
808 start_utime= utime_after_query= 0;
809 system_time.start.val= system_time.sec= system_time.sec_part= 0;
810 utime_after_lock= 0L;
811 progress.arena= 0;
812 progress.report_to_client= 0;
813 progress.max_counter= 0;
814 current_linfo = 0;
815 slave_thread = 0;
816 connection_name.str= 0;
817 connection_name.length= 0;
818
819 file_id = 0;
820 query_id= 0;
821 query_name_consts= 0;
822 semisync_info= 0;
823 db_charset= global_system_variables.collation_database;
824 bzero(ha_data, sizeof(ha_data));
825 mysys_var=0;
826 binlog_evt_union.do_union= FALSE;
827 enable_slow_log= 0;
828 durability_property= HA_REGULAR_DURABILITY;
829
830#ifdef DBUG_ASSERT_EXISTS
831 dbug_sentry=THD_SENTRY_MAGIC;
832#endif
833 mysql_audit_init_thd(this);
834 net.vio=0;
835 net.buff= 0;
836 net.reading_or_writing= 0;
837 client_capabilities= 0; // minimalistic client
838 system_thread= NON_SYSTEM_THREAD;
839 cleanup_done= free_connection_done= abort_on_warning= 0;
840 peer_port= 0; // For SHOW PROCESSLIST
841 transaction.m_pending_rows_event= 0;
842 transaction.on= 1;
843 wt_thd_lazy_init(&transaction.wt, &variables.wt_deadlock_search_depth_short,
844 &variables.wt_timeout_short,
845 &variables.wt_deadlock_search_depth_long,
846 &variables.wt_timeout_long);
847#ifdef SIGNAL_WITH_VIO_CLOSE
848 active_vio = 0;
849#endif
850 mysql_mutex_init(key_LOCK_thd_data, &LOCK_thd_data, MY_MUTEX_INIT_FAST);
851 mysql_mutex_init(key_LOCK_wakeup_ready, &LOCK_wakeup_ready, MY_MUTEX_INIT_FAST);
852 mysql_mutex_init(key_LOCK_thd_kill, &LOCK_thd_kill, MY_MUTEX_INIT_FAST);
853 mysql_cond_init(key_COND_wakeup_ready, &COND_wakeup_ready, 0);
854 /*
855 LOCK_thread_count goes before LOCK_thd_data - the former is called around
856 'delete thd', the latter - in THD::~THD
857 */
858 mysql_mutex_record_order(&LOCK_thread_count, &LOCK_thd_data);
859
860 /* Variables with default values */
861 proc_info="login";
862 where= THD::DEFAULT_WHERE;
863 slave_net = 0;
864 m_command=COM_CONNECT;
865 *scramble= '\0';
866
867#ifdef WITH_WSREP
868 wsrep_ws_handle.trx_id = WSREP_UNDEFINED_TRX_ID;
869 wsrep_ws_handle.opaque = NULL;
870 wsrep_retry_counter = 0;
871 wsrep_PA_safe = true;
872 wsrep_retry_query = NULL;
873 wsrep_retry_query_len = 0;
874 wsrep_retry_command = COM_CONNECT;
875 wsrep_consistency_check = NO_CONSISTENCY_CHECK;
876 wsrep_mysql_replicated = 0;
877 wsrep_TOI_pre_query = NULL;
878 wsrep_TOI_pre_query_len = 0;
879 wsrep_info[sizeof(wsrep_info) - 1] = '\0'; /* make sure it is 0-terminated */
880 wsrep_sync_wait_gtid = WSREP_GTID_UNDEFINED;
881 wsrep_affected_rows = 0;
882 wsrep_replicate_GTID = false;
883 wsrep_skip_wsrep_GTID = false;
884#endif
885 /* Call to init() below requires fully initialized Open_tables_state. */
886 reset_open_tables_state(this);
887
888 init(skip_global_sys_var_lock);
889#if defined(ENABLED_PROFILING)
890 profiling.set_thd(this);
891#endif
892 user_connect=(USER_CONN *)0;
893 my_hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
894 (my_hash_get_key) get_var_key,
895 (my_hash_free_key) free_user_var, HASH_THREAD_SPECIFIC);
896 my_hash_init(&sequences, system_charset_info, SEQUENCES_HASH_SIZE, 0, 0,
897 (my_hash_get_key) get_sequence_last_key,
898 (my_hash_free_key) free_sequence_last, HASH_THREAD_SPECIFIC);
899
900 sp_proc_cache= NULL;
901 sp_func_cache= NULL;
902 sp_package_spec_cache= NULL;
903 sp_package_body_cache= NULL;
904
905 /* For user vars replication*/
906 if (opt_bin_log)
907 my_init_dynamic_array(&user_var_events,
908 sizeof(BINLOG_USER_VAR_EVENT *), 16, 16, MYF(0));
909 else
910 bzero((char*) &user_var_events, sizeof(user_var_events));
911
912 /* Protocol */
913 protocol= &protocol_text; // Default protocol
914 protocol_text.init(this);
915 protocol_binary.init(this);
916
917 thr_timer_init(&query_timer, (void (*)(void*)) thd_kill_timeout, this);
918
919 tablespace_op=FALSE;
920
921 /*
922 Initialize the random generator. We call my_rnd() without a lock as
923 it's not really critical if two threads modifies the structure at the
924 same time. We ensure that we have an unique number foreach thread
925 by adding the address of the stack.
926 */
927 tmp= (ulong) (my_rnd(&sql_rand) * 0xffffffff);
928 my_rnd_init(&rand, tmp + (ulong)((size_t) &rand), tmp + (ulong) ::global_query_id);
929 substitute_null_with_insert_id = FALSE;
930 lock_info.mysql_thd= (void *)this;
931
932 m_token_array= NULL;
933 if (max_digest_length > 0)
934 {
935 m_token_array= (unsigned char*) my_malloc(max_digest_length,
936 MYF(MY_WME|MY_THREAD_SPECIFIC));
937 }
938
939 m_binlog_invoker= INVOKER_NONE;
940 invoker.init();
941 prepare_derived_at_open= FALSE;
942 create_tmp_table_for_derived= FALSE;
943 save_prep_leaf_list= FALSE;
944 /* Restore THR_THD */
945 set_current_thd(old_THR_THD);
946 inc_thread_count();
947}
948
949
950void THD::push_internal_handler(Internal_error_handler *handler)
951{
952 DBUG_ENTER("THD::push_internal_handler");
953 if (m_internal_handler)
954 {
955 handler->m_prev_internal_handler= m_internal_handler;
956 m_internal_handler= handler;
957 }
958 else
959 {
960 m_internal_handler= handler;
961 }
962 DBUG_VOID_RETURN;
963}
964
965bool THD::handle_condition(uint sql_errno,
966 const char* sqlstate,
967 Sql_condition::enum_warning_level *level,
968 const char* msg,
969 Sql_condition ** cond_hdl)
970{
971 if (!m_internal_handler)
972 {
973 *cond_hdl= NULL;
974 return FALSE;
975 }
976
977 for (Internal_error_handler *error_handler= m_internal_handler;
978 error_handler;
979 error_handler= error_handler->m_prev_internal_handler)
980 {
981 if (error_handler->handle_condition(this, sql_errno, sqlstate, level, msg,
982 cond_hdl))
983 {
984 return TRUE;
985 }
986 }
987 return FALSE;
988}
989
990
991Internal_error_handler *THD::pop_internal_handler()
992{
993 DBUG_ENTER("THD::pop_internal_handler");
994 DBUG_ASSERT(m_internal_handler != NULL);
995 Internal_error_handler *popped_handler= m_internal_handler;
996 m_internal_handler= m_internal_handler->m_prev_internal_handler;
997 DBUG_RETURN(popped_handler);
998}
999
1000
1001void THD::raise_error(uint sql_errno)
1002{
1003 const char* msg= ER_THD(this, sql_errno);
1004 (void) raise_condition(sql_errno,
1005 NULL,
1006 Sql_condition::WARN_LEVEL_ERROR,
1007 msg);
1008}
1009
1010void THD::raise_error_printf(uint sql_errno, ...)
1011{
1012 va_list args;
1013 char ebuff[MYSQL_ERRMSG_SIZE];
1014 DBUG_ENTER("THD::raise_error_printf");
1015 DBUG_PRINT("my", ("nr: %d errno: %d", sql_errno, errno));
1016 const char* format= ER_THD(this, sql_errno);
1017 va_start(args, sql_errno);
1018 my_vsnprintf(ebuff, sizeof(ebuff), format, args);
1019 va_end(args);
1020 (void) raise_condition(sql_errno,
1021 NULL,
1022 Sql_condition::WARN_LEVEL_ERROR,
1023 ebuff);
1024 DBUG_VOID_RETURN;
1025}
1026
1027void THD::raise_warning(uint sql_errno)
1028{
1029 const char* msg= ER_THD(this, sql_errno);
1030 (void) raise_condition(sql_errno,
1031 NULL,
1032 Sql_condition::WARN_LEVEL_WARN,
1033 msg);
1034}
1035
1036void THD::raise_warning_printf(uint sql_errno, ...)
1037{
1038 va_list args;
1039 char ebuff[MYSQL_ERRMSG_SIZE];
1040 DBUG_ENTER("THD::raise_warning_printf");
1041 DBUG_PRINT("enter", ("warning: %u", sql_errno));
1042 const char* format= ER_THD(this, sql_errno);
1043 va_start(args, sql_errno);
1044 my_vsnprintf(ebuff, sizeof(ebuff), format, args);
1045 va_end(args);
1046 (void) raise_condition(sql_errno,
1047 NULL,
1048 Sql_condition::WARN_LEVEL_WARN,
1049 ebuff);
1050 DBUG_VOID_RETURN;
1051}
1052
1053void THD::raise_note(uint sql_errno)
1054{
1055 DBUG_ENTER("THD::raise_note");
1056 DBUG_PRINT("enter", ("code: %d", sql_errno));
1057 if (!(variables.option_bits & OPTION_SQL_NOTES))
1058 DBUG_VOID_RETURN;
1059 const char* msg= ER_THD(this, sql_errno);
1060 (void) raise_condition(sql_errno,
1061 NULL,
1062 Sql_condition::WARN_LEVEL_NOTE,
1063 msg);
1064 DBUG_VOID_RETURN;
1065}
1066
1067void THD::raise_note_printf(uint sql_errno, ...)
1068{
1069 va_list args;
1070 char ebuff[MYSQL_ERRMSG_SIZE];
1071 DBUG_ENTER("THD::raise_note_printf");
1072 DBUG_PRINT("enter",("code: %u", sql_errno));
1073 if (!(variables.option_bits & OPTION_SQL_NOTES))
1074 DBUG_VOID_RETURN;
1075 const char* format= ER_THD(this, sql_errno);
1076 va_start(args, sql_errno);
1077 my_vsnprintf(ebuff, sizeof(ebuff), format, args);
1078 va_end(args);
1079 (void) raise_condition(sql_errno,
1080 NULL,
1081 Sql_condition::WARN_LEVEL_NOTE,
1082 ebuff);
1083 DBUG_VOID_RETURN;
1084}
1085
1086Sql_condition* THD::raise_condition(uint sql_errno,
1087 const char* sqlstate,
1088 Sql_condition::enum_warning_level level,
1089 const Sql_user_condition_identity &ucid,
1090 const char* msg)
1091{
1092 Diagnostics_area *da= get_stmt_da();
1093 Sql_condition *cond= NULL;
1094 DBUG_ENTER("THD::raise_condition");
1095 DBUG_ASSERT(level < Sql_condition::WARN_LEVEL_END);
1096
1097 if (!(variables.option_bits & OPTION_SQL_NOTES) &&
1098 (level == Sql_condition::WARN_LEVEL_NOTE))
1099 DBUG_RETURN(NULL);
1100
1101 da->opt_clear_warning_info(query_id);
1102
1103 /*
1104 TODO: replace by DBUG_ASSERT(sql_errno != 0) once all bugs similar to
1105 Bug#36768 are fixed: a SQL condition must have a real (!=0) error number
1106 so that it can be caught by handlers.
1107 */
1108 if (sql_errno == 0)
1109 sql_errno= ER_UNKNOWN_ERROR;
1110 if (msg == NULL)
1111 msg= ER_THD(this, sql_errno);
1112 if (sqlstate == NULL)
1113 sqlstate= mysql_errno_to_sqlstate(sql_errno);
1114
1115 if ((level == Sql_condition::WARN_LEVEL_WARN) &&
1116 really_abort_on_warning())
1117 {
1118 /*
1119 FIXME:
1120 push_warning and strict SQL_MODE case.
1121 */
1122 level= Sql_condition::WARN_LEVEL_ERROR;
1123 }
1124
1125 if (handle_condition(sql_errno, sqlstate, &level, msg, &cond))
1126 DBUG_RETURN(cond);
1127
1128 switch (level) {
1129 case Sql_condition::WARN_LEVEL_NOTE:
1130 case Sql_condition::WARN_LEVEL_WARN:
1131 got_warning= 1;
1132 break;
1133 case Sql_condition::WARN_LEVEL_ERROR:
1134 break;
1135 case Sql_condition::WARN_LEVEL_END:
1136 /* Impossible */
1137 break;
1138 }
1139
1140 if (level == Sql_condition::WARN_LEVEL_ERROR)
1141 {
1142 mysql_audit_general(this, MYSQL_AUDIT_GENERAL_ERROR, sql_errno, msg);
1143
1144 is_slave_error= 1; // needed to catch query errors during replication
1145
1146 if (!da->is_error())
1147 {
1148 set_row_count_func(-1);
1149 da->set_error_status(sql_errno, msg, sqlstate, ucid, cond);
1150 }
1151 }
1152
1153 query_cache_abort(this, &query_cache_tls);
1154
1155 /*
1156 Avoid pushing a condition for fatal out of memory errors as this will
1157 require memory allocation and therefore might fail. Non fatal out of
1158 memory errors can occur if raised by SIGNAL/RESIGNAL statement.
1159 */
1160 if (likely(!(is_fatal_error && (sql_errno == EE_OUTOFMEMORY ||
1161 sql_errno == ER_OUTOFMEMORY))))
1162 {
1163 cond= da->push_warning(this, sql_errno, sqlstate, level, ucid, msg);
1164 }
1165 DBUG_RETURN(cond);
1166}
1167
1168extern "C"
1169void *thd_alloc(MYSQL_THD thd, size_t size)
1170{
1171 return thd->alloc(size);
1172}
1173
1174extern "C"
1175void *thd_calloc(MYSQL_THD thd, size_t size)
1176{
1177 return thd->calloc(size);
1178}
1179
1180extern "C"
1181char *thd_strdup(MYSQL_THD thd, const char *str)
1182{
1183 return thd->strdup(str);
1184}
1185
1186extern "C"
1187char *thd_strmake(MYSQL_THD thd, const char *str, size_t size)
1188{
1189 return thd->strmake(str, size);
1190}
1191
1192extern "C"
1193LEX_CSTRING *thd_make_lex_string(THD *thd, LEX_CSTRING *lex_str,
1194 const char *str, size_t size,
1195 int allocate_lex_string)
1196{
1197 return allocate_lex_string ? thd->make_clex_string(str, size)
1198 : thd->make_lex_string(lex_str, str, size);
1199}
1200
1201extern "C"
1202void *thd_memdup(MYSQL_THD thd, const void* str, size_t size)
1203{
1204 return thd->memdup(str, size);
1205}
1206
1207extern "C"
1208void thd_get_xid(const MYSQL_THD thd, MYSQL_XID *xid)
1209{
1210 *xid = *(MYSQL_XID *) &thd->transaction.xid_state.xid;
1211}
1212
1213
1214extern "C"
1215my_time_t thd_TIME_to_gmt_sec(MYSQL_THD thd, const MYSQL_TIME *ltime,
1216 unsigned int *errcode)
1217{
1218 Time_zone *tz= thd ? thd->variables.time_zone :
1219 global_system_variables.time_zone;
1220 return tz->TIME_to_gmt_sec(ltime, errcode);
1221}
1222
1223
1224extern "C"
1225void thd_gmt_sec_to_TIME(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t)
1226{
1227 Time_zone *tz= thd ? thd->variables.time_zone :
1228 global_system_variables.time_zone;
1229 tz->gmt_sec_to_TIME(ltime, t);
1230}
1231
1232
1233#ifdef _WIN32
1234extern "C" THD *_current_thd_noinline(void)
1235{
1236 return my_pthread_getspecific_ptr(THD*,THR_THD);
1237}
1238
1239extern "C" my_thread_id next_thread_id_noinline()
1240{
1241#undef next_thread_id
1242 return next_thread_id();
1243}
1244#endif
1245
1246
1247const Type_handler *THD::type_handler_for_date() const
1248{
1249 if (!(variables.sql_mode & MODE_ORACLE))
1250 return &type_handler_newdate;
1251 if (opt_mysql56_temporal_format)
1252 return &type_handler_datetime2;
1253 return &type_handler_datetime;
1254}
1255
1256
1257/*
1258 Init common variables that has to be reset on start and on change_user
1259*/
1260
1261void THD::init(bool skip_lock)
1262{
1263 DBUG_ENTER("thd::init");
1264 if (!skip_lock)
1265 mysql_mutex_lock(&LOCK_global_system_variables);
1266 plugin_thdvar_init(this);
1267 /*
1268 plugin_thd_var_init() sets variables= global_system_variables, which
1269 has reset variables.pseudo_thread_id to 0. We need to correct it here to
1270 avoid temporary tables replication failure.
1271 */
1272 variables.pseudo_thread_id= thread_id;
1273
1274 variables.default_master_connection.str= default_master_connection_buff;
1275 ::strmake(default_master_connection_buff,
1276 global_system_variables.default_master_connection.str,
1277 variables.default_master_connection.length);
1278 if (!skip_lock)
1279 mysql_mutex_unlock(&LOCK_global_system_variables);
1280
1281 user_time.val= start_time= start_time_sec_part= 0;
1282
1283 server_status= SERVER_STATUS_AUTOCOMMIT;
1284 if (variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)
1285 server_status|= SERVER_STATUS_NO_BACKSLASH_ESCAPES;
1286 if (variables.sql_mode & MODE_ANSI_QUOTES)
1287 server_status|= SERVER_STATUS_ANSI_QUOTES;
1288
1289 transaction.all.modified_non_trans_table=
1290 transaction.stmt.modified_non_trans_table= FALSE;
1291 transaction.all.m_unsafe_rollback_flags=
1292 transaction.stmt.m_unsafe_rollback_flags= 0;
1293
1294 open_options=ha_open_options;
1295 update_lock_default= (variables.low_priority_updates ?
1296 TL_WRITE_LOW_PRIORITY :
1297 TL_WRITE);
1298 tx_isolation= (enum_tx_isolation) variables.tx_isolation;
1299 tx_read_only= variables.tx_read_only;
1300 update_charset(); // plugin_thd_var() changed character sets
1301 reset_current_stmt_binlog_format_row();
1302 reset_binlog_local_stmt_filter();
1303 set_status_var_init();
1304 status_var.max_local_memory_used= status_var.local_memory_used;
1305 bzero((char *) &org_status_var, sizeof(org_status_var));
1306 status_in_global= 0;
1307 start_bytes_received= 0;
1308 last_commit_gtid.seq_no= 0;
1309 last_stmt= NULL;
1310 /* Reset status of last insert id */
1311 arg_of_last_insert_id_function= FALSE;
1312 stmt_depends_on_first_successful_insert_id_in_prev_stmt= FALSE;
1313 first_successful_insert_id_in_prev_stmt= 0;
1314 first_successful_insert_id_in_prev_stmt_for_binlog= 0;
1315 first_successful_insert_id_in_cur_stmt= 0;
1316#ifdef WITH_WSREP
1317 wsrep_exec_mode= wsrep_applier ? REPL_RECV : LOCAL_STATE;
1318 wsrep_conflict_state= NO_CONFLICT;
1319 wsrep_query_state= QUERY_IDLE;
1320 wsrep_last_query_id= 0;
1321 wsrep_trx_meta.gtid= WSREP_GTID_UNDEFINED;
1322 wsrep_trx_meta.depends_on= WSREP_SEQNO_UNDEFINED;
1323 wsrep_converted_lock_session= false;
1324 wsrep_retry_counter= 0;
1325 wsrep_rgi= NULL;
1326 wsrep_PA_safe= true;
1327 wsrep_consistency_check = NO_CONSISTENCY_CHECK;
1328 wsrep_mysql_replicated = 0;
1329 wsrep_TOI_pre_query = NULL;
1330 wsrep_TOI_pre_query_len = 0;
1331 wsrep_sync_wait_gtid = WSREP_GTID_UNDEFINED;
1332 wsrep_affected_rows = 0;
1333 wsrep_replicate_GTID = false;
1334 wsrep_skip_wsrep_GTID = false;
1335#endif /* WITH_WSREP */
1336
1337 if (variables.sql_log_bin)
1338 variables.option_bits|= OPTION_BIN_LOG;
1339 else
1340 variables.option_bits&= ~OPTION_BIN_LOG;
1341
1342 variables.sql_log_bin_off= 0;
1343
1344 select_commands= update_commands= other_commands= 0;
1345 /* Set to handle counting of aborted connections */
1346 userstat_running= opt_userstat_running;
1347 last_global_update_time= current_connect_time= time(NULL);
1348#if defined(ENABLED_DEBUG_SYNC)
1349 /* Initialize the Debug Sync Facility. See debug_sync.cc. */
1350 debug_sync_init_thread(this);
1351#endif /* defined(ENABLED_DEBUG_SYNC) */
1352
1353#ifndef EMBEDDED_LIBRARY
1354 session_tracker.enable(this);
1355#endif //EMBEDDED_LIBRARY
1356
1357 apc_target.init(&LOCK_thd_kill);
1358 DBUG_VOID_RETURN;
1359}
1360
1361
1362bool THD::restore_from_local_lex_to_old_lex(LEX *oldlex)
1363{
1364 DBUG_ASSERT(lex->sphead);
1365 if (lex->sphead->merge_lex(this, oldlex, lex))
1366 return true;
1367 lex= oldlex;
1368 return false;
1369}
1370
1371
1372/* Updates some status variables to be used by update_global_user_stats */
1373
1374void THD::update_stats(void)
1375{
1376 /* sql_command == SQLCOM_END in case of parse errors or quit */
1377 if (lex->sql_command != SQLCOM_END)
1378 {
1379 /* A SQL query. */
1380 if (lex->sql_command == SQLCOM_SELECT)
1381 select_commands++;
1382 else if (sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND)
1383 {
1384 /* Ignore 'SHOW ' commands */
1385 }
1386 else if (is_update_query(lex->sql_command))
1387 update_commands++;
1388 else
1389 other_commands++;
1390 }
1391}
1392
1393
1394void THD::update_all_stats()
1395{
1396 ulonglong end_cpu_time, end_utime;
1397 double busy_time, cpu_time;
1398
1399 /* This is set at start of query if opt_userstat_running was set */
1400 if (!userstat_running)
1401 return;
1402
1403 end_cpu_time= my_getcputime();
1404 end_utime= microsecond_interval_timer();
1405 busy_time= (end_utime - start_utime) / 1000000.0;
1406 cpu_time= (end_cpu_time - start_cpu_time) / 10000000.0;
1407 /* In case there are bad values, 2629743 is the #seconds in a month. */
1408 if (cpu_time > 2629743.0)
1409 cpu_time= 0;
1410 status_var_add(status_var.cpu_time, cpu_time);
1411 status_var_add(status_var.busy_time, busy_time);
1412
1413 update_global_user_stats(this, TRUE, my_time(0));
1414 // Has to be updated after update_global_user_stats()
1415 userstat_running= 0;
1416}
1417
1418
1419/*
1420 Init THD for query processing.
1421 This has to be called once before we call mysql_parse.
1422 See also comments in sql_class.h.
1423*/
1424
1425void THD::init_for_queries()
1426{
1427 set_time();
1428 ha_enable_transaction(this,TRUE);
1429
1430 reset_root_defaults(mem_root, variables.query_alloc_block_size,
1431 variables.query_prealloc_size);
1432 reset_root_defaults(&transaction.mem_root,
1433 variables.trans_alloc_block_size,
1434 variables.trans_prealloc_size);
1435 transaction.xid_state.xid.null();
1436}
1437
1438
1439/*
1440 Do what's needed when one invokes change user
1441
1442 SYNOPSIS
1443 change_user()
1444
1445 IMPLEMENTATION
1446 Reset all resources that are connection specific
1447*/
1448
1449
1450void THD::change_user(void)
1451{
1452 if (!status_in_global) // Reset in init()
1453 add_status_to_global();
1454
1455 if (!cleanup_done)
1456 cleanup();
1457 cleanup_done= 0;
1458 reset_killed();
1459 thd_clear_errors(this);
1460 init();
1461 stmt_map.reset();
1462 my_hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0,
1463 (my_hash_get_key) get_var_key,
1464 (my_hash_free_key) free_user_var, 0);
1465 my_hash_init(&sequences, system_charset_info, SEQUENCES_HASH_SIZE, 0, 0,
1466 (my_hash_get_key) get_sequence_last_key,
1467 (my_hash_free_key) free_sequence_last, HASH_THREAD_SPECIFIC);
1468 sp_cache_clear(&sp_proc_cache);
1469 sp_cache_clear(&sp_func_cache);
1470 sp_cache_clear(&sp_package_spec_cache);
1471 sp_cache_clear(&sp_package_body_cache);
1472}
1473
1474/**
1475 Change default database
1476
1477 @note This is coded to have as few instructions as possible under
1478 LOCK_thd_data
1479*/
1480
1481bool THD::set_db(const LEX_CSTRING *new_db)
1482{
1483 bool result= 0;
1484 /*
1485 Acquiring mutex LOCK_thd_data as we either free the memory allocated
1486 for the database and reallocating the memory for the new db or memcpy
1487 the new_db to the db.
1488 */
1489 /* Do not reallocate memory if current chunk is big enough. */
1490 if (db.str && new_db->str && db.length >= new_db->length)
1491 {
1492 mysql_mutex_lock(&LOCK_thd_data);
1493 db.length= new_db->length;
1494 memcpy((char*) db.str, new_db->str, new_db->length+1);
1495 mysql_mutex_unlock(&LOCK_thd_data);
1496 }
1497 else
1498 {
1499 const char *org_db= db.str;
1500 const char *tmp= NULL;
1501 if (new_db->str)
1502 {
1503 if (!(tmp= my_strndup(new_db->str, new_db->length, MYF(MY_WME | ME_FATALERROR))))
1504 result= 1;
1505 }
1506
1507 mysql_mutex_lock(&LOCK_thd_data);
1508 db.str= tmp;
1509 db.length= tmp ? new_db->length : 0;
1510 mysql_mutex_unlock(&LOCK_thd_data);
1511 my_free((char*) org_db);
1512 }
1513 PSI_CALL_set_thread_db(db.str, (int) db.length);
1514 return result;
1515}
1516
1517
1518/**
1519 Set the current database
1520
1521 @param new_db a pointer to the new database name.
1522 @param new_db_len length of the new database name.
1523
1524 @note This operation just sets {db, db_length}. Switching the current
1525 database usually involves other actions, like switching other database
1526 attributes including security context. In the future, this operation
1527 will be made private and more convenient interface will be provided.
1528*/
1529
1530void THD::reset_db(const LEX_CSTRING *new_db)
1531{
1532 if (new_db->str != db.str || new_db->length != db.length)
1533 {
1534 if (db.str != 0)
1535 DBUG_PRINT("QQ", ("Overwriting: %p", db.str));
1536 mysql_mutex_lock(&LOCK_thd_data);
1537 db= *new_db;
1538 mysql_mutex_unlock(&LOCK_thd_data);
1539 PSI_CALL_set_thread_db(db.str, (int) db.length);
1540 }
1541}
1542
1543
1544/* Do operations that may take a long time */
1545
1546void THD::cleanup(void)
1547{
1548 DBUG_ENTER("THD::cleanup");
1549 DBUG_ASSERT(cleanup_done == 0);
1550
1551 set_killed(KILL_CONNECTION);
1552#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
1553 if (transaction.xid_state.xa_state == XA_PREPARED)
1554 {
1555#error xid_state in the cache should be replaced by the allocated value
1556 }
1557#endif
1558
1559 mysql_ha_cleanup(this);
1560 locked_tables_list.unlock_locked_tables(this);
1561
1562 delete_dynamic(&user_var_events);
1563 close_temporary_tables();
1564
1565 transaction.xid_state.xa_state= XA_NOTR;
1566 transaction.xid_state.rm_error= 0;
1567 trans_rollback(this);
1568 xid_cache_delete(this, &transaction.xid_state);
1569
1570 DBUG_ASSERT(open_tables == NULL);
1571 /*
1572 If the thread was in the middle of an ongoing transaction (rolled
1573 back a few lines above) or under LOCK TABLES (unlocked the tables
1574 and left the mode a few lines above), there will be outstanding
1575 metadata locks. Release them.
1576 */
1577 mdl_context.release_transactional_locks();
1578
1579 /* Release the global read lock, if acquired. */
1580 if (global_read_lock.is_acquired())
1581 global_read_lock.unlock_global_read_lock(this);
1582
1583 if (user_connect)
1584 {
1585 decrease_user_connections(user_connect);
1586 user_connect= 0; // Safety
1587 }
1588 wt_thd_destroy(&transaction.wt);
1589
1590#if defined(ENABLED_DEBUG_SYNC)
1591 /* End the Debug Sync Facility. See debug_sync.cc. */
1592 debug_sync_end_thread(this);
1593#endif /* defined(ENABLED_DEBUG_SYNC) */
1594
1595 my_hash_free(&user_vars);
1596 my_hash_free(&sequences);
1597 sp_cache_clear(&sp_proc_cache);
1598 sp_cache_clear(&sp_func_cache);
1599 sp_cache_clear(&sp_package_spec_cache);
1600 sp_cache_clear(&sp_package_body_cache);
1601 auto_inc_intervals_forced.empty();
1602 auto_inc_intervals_in_cur_stmt_for_binlog.empty();
1603
1604 mysql_ull_cleanup(this);
1605 /* All metadata locks must have been released by now. */
1606 DBUG_ASSERT(!mdl_context.has_locks());
1607
1608 apc_target.destroy();
1609 cleanup_done=1;
1610 DBUG_VOID_RETURN;
1611}
1612
1613
1614/*
1615 Free all connection related resources associated with a THD.
1616 This is used when we put a thread into the thread cache.
1617 After this call should either call ~THD or reset_for_reuse() depending on
1618 circumstances.
1619*/
1620
1621void THD::free_connection()
1622{
1623 DBUG_ASSERT(free_connection_done == 0);
1624 my_free((char*) db.str);
1625 db= null_clex_str;
1626#ifndef EMBEDDED_LIBRARY
1627 if (net.vio)
1628 vio_delete(net.vio);
1629 net.vio= 0;
1630 net_end(&net);
1631#endif
1632 if (!cleanup_done)
1633 cleanup();
1634 ha_close_connection(this);
1635 plugin_thdvar_cleanup(this);
1636 mysql_audit_free_thd(this);
1637 main_security_ctx.destroy();
1638 /* close all prepared statements, to save memory */
1639 stmt_map.reset();
1640 free_connection_done= 1;
1641#if defined(ENABLED_PROFILING)
1642 profiling.restart(); // Reset profiling
1643#endif
1644}
1645
1646/*
1647 Reset thd for reuse by another connection
1648 This is only used for user connections, so the following variables doesn't
1649 have to be reset:
1650 - Replication (slave) variables.
1651 - Variables not reset between each statements. See reset_for_next_command.
1652*/
1653
1654void THD::reset_for_reuse()
1655{
1656 mysql_audit_init_thd(this);
1657 change_user(); // Calls cleanup() & init()
1658 get_stmt_da()->reset_diagnostics_area();
1659 main_security_ctx.init();
1660 failed_com_change_user= 0;
1661 is_fatal_error= 0;
1662 client_capabilities= 0;
1663 peer_port= 0;
1664 query_name_consts= 0; // Safety
1665 abort_on_warning= 0;
1666 free_connection_done= 0;
1667 m_command= COM_CONNECT;
1668#if defined(ENABLED_PROFILING)
1669 profiling.reset();
1670#endif
1671#ifdef SIGNAL_WITH_VIO_CLOSE
1672 active_vio = 0;
1673#endif
1674}
1675
1676
1677THD::~THD()
1678{
1679 THD *orig_thd= current_thd;
1680 THD_CHECK_SENTRY(this);
1681 DBUG_ENTER("~THD()");
1682 /* Check that we have already called thd->unlink() */
1683 DBUG_ASSERT(prev == 0 && next == 0);
1684 /* This takes a long time so we should not do this under LOCK_thread_count */
1685 mysql_mutex_assert_not_owner(&LOCK_thread_count);
1686
1687 /*
1688 In error cases, thd may not be current thd. We have to fix this so
1689 that memory allocation counting is done correctly
1690 */
1691 set_current_thd(this);
1692 if (!status_in_global)
1693 add_status_to_global();
1694
1695 /*
1696 Other threads may have a lock on LOCK_thd_kill to ensure that this
1697 THD is not deleted while they access it. The following mutex_lock
1698 ensures that no one else is using this THD and it's now safe to delete
1699 */
1700 mysql_mutex_lock(&LOCK_thd_kill);
1701 mysql_mutex_unlock(&LOCK_thd_kill);
1702
1703#ifdef WITH_WSREP
1704 delete wsrep_rgi;
1705#endif
1706 if (!free_connection_done)
1707 free_connection();
1708
1709 mdl_context.destroy();
1710
1711 free_root(&transaction.mem_root,MYF(0));
1712 mysql_cond_destroy(&COND_wakeup_ready);
1713 mysql_mutex_destroy(&LOCK_wakeup_ready);
1714 mysql_mutex_destroy(&LOCK_thd_data);
1715 mysql_mutex_destroy(&LOCK_thd_kill);
1716#ifdef DBUG_ASSERT_EXISTS
1717 dbug_sentry= THD_SENTRY_GONE;
1718#endif
1719#ifndef EMBEDDED_LIBRARY
1720 if (rgi_fake)
1721 {
1722 delete rgi_fake;
1723 rgi_fake= NULL;
1724 }
1725 if (rli_fake)
1726 {
1727 delete rli_fake;
1728 rli_fake= NULL;
1729 }
1730
1731 if (rgi_slave)
1732 rgi_slave->cleanup_after_session();
1733 my_free(semisync_info);
1734#endif
1735 main_lex.free_set_stmt_mem_root();
1736 free_root(&main_mem_root, MYF(0));
1737 my_free(m_token_array);
1738 main_da.free_memory();
1739 if (tdc_hash_pins)
1740 lf_hash_put_pins(tdc_hash_pins);
1741 if (xid_hash_pins)
1742 lf_hash_put_pins(xid_hash_pins);
1743 /* Ensure everything is freed */
1744 status_var.local_memory_used-= sizeof(THD);
1745
1746 /* trick to make happy memory accounting system */
1747#ifndef EMBEDDED_LIBRARY
1748 session_tracker.deinit();
1749#endif //EMBEDDED_LIBRARY
1750
1751 if (status_var.local_memory_used != 0)
1752 {
1753 DBUG_PRINT("error", ("memory_used: %lld", status_var.local_memory_used));
1754 SAFEMALLOC_REPORT_MEMORY(thread_id);
1755 DBUG_ASSERT(status_var.local_memory_used == 0 ||
1756 !debug_assert_on_not_freed_memory);
1757 }
1758 update_global_memory_status(status_var.global_memory_used);
1759 set_current_thd(orig_thd == this ? 0 : orig_thd);
1760 dec_thread_count();
1761 DBUG_VOID_RETURN;
1762}
1763
1764
1765/*
1766 Add all status variables to another status variable array
1767
1768 SYNOPSIS
1769 add_to_status()
1770 to_var add to this array
1771 from_var from this array
1772
1773 NOTES
1774 This function assumes that all variables at start are long/ulong and
1775 other types are handled explicitly
1776*/
1777
1778void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var)
1779{
1780 ulong *end= (ulong*) ((uchar*) to_var +
1781 offsetof(STATUS_VAR, last_system_status_var) +
1782 sizeof(ulong));
1783 ulong *to= (ulong*) to_var, *from= (ulong*) from_var;
1784
1785 while (to != end)
1786 *(to++)+= *(from++);
1787
1788 /* Handle the not ulong variables. See end of system_status_var */
1789 to_var->bytes_received+= from_var->bytes_received;
1790 to_var->bytes_sent+= from_var->bytes_sent;
1791 to_var->rows_read+= from_var->rows_read;
1792 to_var->rows_sent+= from_var->rows_sent;
1793 to_var->rows_tmp_read+= from_var->rows_tmp_read;
1794 to_var->binlog_bytes_written+= from_var->binlog_bytes_written;
1795 to_var->cpu_time+= from_var->cpu_time;
1796 to_var->busy_time+= from_var->busy_time;
1797 to_var->table_open_cache_hits+= from_var->table_open_cache_hits;
1798 to_var->table_open_cache_misses+= from_var->table_open_cache_misses;
1799 to_var->table_open_cache_overflows+= from_var->table_open_cache_overflows;
1800
1801 /*
1802 Update global_memory_used. We have to do this with atomic_add as the
1803 global value can change outside of LOCK_status.
1804 */
1805 if (to_var == &global_status_var)
1806 {
1807 DBUG_PRINT("info", ("global memory_used: %lld size: %lld",
1808 (longlong) global_status_var.global_memory_used,
1809 (longlong) from_var->global_memory_used));
1810 update_global_memory_status(from_var->global_memory_used);
1811 }
1812 else
1813 to_var->global_memory_used+= from_var->global_memory_used;
1814}
1815
1816/*
1817 Add the difference between two status variable arrays to another one.
1818
1819 SYNOPSIS
1820 add_diff_to_status
1821 to_var add to this array
1822 from_var from this array
1823 dec_var minus this array
1824
1825 NOTE
1826 This function assumes that all variables at start are long/ulong and
1827 other types are handled explicitly
1828*/
1829
1830void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
1831 STATUS_VAR *dec_var)
1832{
1833 ulong *end= (ulong*) ((uchar*) to_var + offsetof(STATUS_VAR,
1834 last_system_status_var) +
1835 sizeof(ulong));
1836 ulong *to= (ulong*) to_var, *from= (ulong*) from_var, *dec= (ulong*) dec_var;
1837
1838 while (to != end)
1839 *(to++)+= *(from++) - *(dec++);
1840
1841 to_var->bytes_received+= from_var->bytes_received -
1842 dec_var->bytes_received;
1843 to_var->bytes_sent+= from_var->bytes_sent - dec_var->bytes_sent;
1844 to_var->rows_read+= from_var->rows_read - dec_var->rows_read;
1845 to_var->rows_sent+= from_var->rows_sent - dec_var->rows_sent;
1846 to_var->rows_tmp_read+= from_var->rows_tmp_read - dec_var->rows_tmp_read;
1847 to_var->binlog_bytes_written+= from_var->binlog_bytes_written -
1848 dec_var->binlog_bytes_written;
1849 to_var->cpu_time+= from_var->cpu_time - dec_var->cpu_time;
1850 to_var->busy_time+= from_var->busy_time - dec_var->busy_time;
1851 to_var->table_open_cache_hits+= from_var->table_open_cache_hits -
1852 dec_var->table_open_cache_hits;
1853 to_var->table_open_cache_misses+= from_var->table_open_cache_misses -
1854 dec_var->table_open_cache_misses;
1855 to_var->table_open_cache_overflows+= from_var->table_open_cache_overflows -
1856 dec_var->table_open_cache_overflows;
1857
1858 /*
1859 We don't need to accumulate memory_used as these are not reset or used by
1860 the calling functions. See execute_show_status().
1861 */
1862}
1863
1864#define SECONDS_TO_WAIT_FOR_KILL 2
1865#if !defined(__WIN__) && defined(HAVE_SELECT)
1866/* my_sleep() can wait for sub second times */
1867#define WAIT_FOR_KILL_TRY_TIMES 20
1868#else
1869#define WAIT_FOR_KILL_TRY_TIMES 2
1870#endif
1871
1872
1873/**
1874 Awake a thread.
1875
1876 @param[in] state_to_set value for THD::killed
1877
1878 This is normally called from another thread's THD object.
1879
1880 @note Do always call this while holding LOCK_thd_kill.
1881 NOT_KILLED is used to awake a thread for a slave
1882*/
1883
1884void THD::awake_no_mutex(killed_state state_to_set)
1885{
1886 DBUG_ENTER("THD::awake");
1887 DBUG_PRINT("enter", ("this: %p current_thd: %p state: %d",
1888 this, current_thd, (int) state_to_set));
1889 THD_CHECK_SENTRY(this);
1890 mysql_mutex_assert_owner(&LOCK_thd_kill);
1891
1892 print_aborted_warning(3, "KILLED");
1893
1894 /*
1895 Don't degrade killed state, for example from a KILL_CONNECTION to
1896 STATEMENT TIMEOUT
1897 */
1898 if (killed >= KILL_CONNECTION)
1899 state_to_set= killed;
1900
1901 set_killed_no_mutex(state_to_set);
1902
1903 if (state_to_set >= KILL_CONNECTION || state_to_set == NOT_KILLED)
1904 {
1905#ifdef SIGNAL_WITH_VIO_CLOSE
1906 if (this != current_thd)
1907 {
1908 if(active_vio)
1909 vio_shutdown(active_vio, SHUT_RDWR);
1910 }
1911#endif
1912
1913 /* Mark the target thread's alarm request expired, and signal alarm. */
1914 thr_alarm_kill(thread_id);
1915
1916 /* Send an event to the scheduler that a thread should be killed. */
1917 if (!slave_thread)
1918 MYSQL_CALLBACK(scheduler, post_kill_notification, (this));
1919 }
1920
1921 /* Interrupt target waiting inside a storage engine. */
1922 if (state_to_set != NOT_KILLED)
1923 ha_kill_query(this, thd_kill_level(this));
1924
1925 /* Broadcast a condition to kick the target if it is waiting on it. */
1926 if (mysys_var)
1927 {
1928 mysql_mutex_lock(&mysys_var->mutex);
1929 if (!system_thread) // Don't abort locks
1930 mysys_var->abort=1;
1931
1932 /*
1933 This broadcast could be up in the air if the victim thread
1934 exits the cond in the time between read and broadcast, but that is
1935 ok since all we want to do is to make the victim thread get out
1936 of waiting on current_cond.
1937 If we see a non-zero current_cond: it cannot be an old value (because
1938 then exit_cond() should have run and it can't because we have mutex); so
1939 it is the true value but maybe current_mutex is not yet non-zero (we're
1940 in the middle of enter_cond() and there is a "memory order
1941 inversion"). So we test the mutex too to not lock 0.
1942
1943 Note that there is a small chance we fail to kill. If victim has locked
1944 current_mutex, but hasn't yet entered enter_cond() (which means that
1945 current_cond and current_mutex are 0), then the victim will not get
1946 a signal and it may wait "forever" on the cond (until
1947 we issue a second KILL or the status it's waiting for happens).
1948 It's true that we have set its thd->killed but it may not
1949 see it immediately and so may have time to reach the cond_wait().
1950
1951 However, where possible, we test for killed once again after
1952 enter_cond(). This should make the signaling as safe as possible.
1953 However, there is still a small chance of failure on platforms with
1954 instruction or memory write reordering.
1955
1956 We have to do the loop with trylock, because if we would use
1957 pthread_mutex_lock(), we can cause a deadlock as we are here locking
1958 the mysys_var->mutex and mysys_var->current_mutex in a different order
1959 than in the thread we are trying to kill.
1960 We only sleep for 2 seconds as we don't want to have LOCK_thd_data
1961 locked too long time.
1962
1963 There is a small change we may not succeed in aborting a thread that
1964 is not yet waiting for a mutex, but as this happens only for a
1965 thread that was doing something else when the kill was issued and
1966 which should detect the kill flag before it starts to wait, this
1967 should be good enough.
1968 */
1969 if (mysys_var->current_cond && mysys_var->current_mutex)
1970 {
1971 uint i;
1972 for (i= 0; i < WAIT_FOR_KILL_TRY_TIMES * SECONDS_TO_WAIT_FOR_KILL; i++)
1973 {
1974 int ret= mysql_mutex_trylock(mysys_var->current_mutex);
1975 mysql_cond_broadcast(mysys_var->current_cond);
1976 if (!ret)
1977 {
1978 /* Signal is sure to get through */
1979 mysql_mutex_unlock(mysys_var->current_mutex);
1980 break;
1981 }
1982 my_sleep(1000000L / WAIT_FOR_KILL_TRY_TIMES);
1983 }
1984 }
1985 mysql_mutex_unlock(&mysys_var->mutex);
1986 }
1987 DBUG_VOID_RETURN;
1988}
1989
1990
1991/**
1992 Close the Vio associated this session.
1993
1994 @remark LOCK_thd_data is taken due to the fact that
1995 the Vio might be disassociated concurrently.
1996*/
1997
1998void THD::disconnect()
1999{
2000 Vio *vio= NULL;
2001
2002 set_killed(KILL_CONNECTION);
2003
2004 mysql_mutex_lock(&LOCK_thd_data);
2005
2006#ifdef SIGNAL_WITH_VIO_CLOSE
2007 /*
2008 Since a active vio might might have not been set yet, in
2009 any case save a reference to avoid closing a inexistent
2010 one or closing the vio twice if there is a active one.
2011 */
2012 vio= active_vio;
2013 close_active_vio();
2014#endif
2015
2016 /* Disconnect even if a active vio is not associated. */
2017 if (net.vio != vio)
2018 vio_close(net.vio);
2019 net.thd= 0; // Don't collect statistics
2020
2021 mysql_mutex_unlock(&LOCK_thd_data);
2022}
2023
2024
2025bool THD::notify_shared_lock(MDL_context_owner *ctx_in_use,
2026 bool needs_thr_lock_abort)
2027{
2028 THD *in_use= ctx_in_use->get_thd();
2029 bool signalled= FALSE;
2030 DBUG_ENTER("THD::notify_shared_lock");
2031 DBUG_PRINT("enter",("needs_thr_lock_abort: %d", needs_thr_lock_abort));
2032
2033 if ((in_use->system_thread & SYSTEM_THREAD_DELAYED_INSERT) &&
2034 !in_use->killed)
2035 {
2036 /* This code is similar to kill_delayed_threads() */
2037 DBUG_PRINT("info", ("kill delayed thread"));
2038 mysql_mutex_lock(&in_use->LOCK_thd_kill);
2039 if (in_use->killed < KILL_CONNECTION)
2040 in_use->set_killed_no_mutex(KILL_CONNECTION);
2041 if (in_use->mysys_var)
2042 {
2043 mysql_mutex_lock(&in_use->mysys_var->mutex);
2044 if (in_use->mysys_var->current_cond)
2045 mysql_cond_broadcast(in_use->mysys_var->current_cond);
2046
2047 /* Abort if about to wait in thr_upgrade_write_delay_lock */
2048 in_use->mysys_var->abort= 1;
2049 mysql_mutex_unlock(&in_use->mysys_var->mutex);
2050 }
2051 mysql_mutex_unlock(&in_use->LOCK_thd_kill);
2052 signalled= TRUE;
2053 }
2054
2055 if (needs_thr_lock_abort)
2056 {
2057 mysql_mutex_lock(&in_use->LOCK_thd_data);
2058 /* If not already dying */
2059 if (in_use->killed != KILL_CONNECTION_HARD)
2060 {
2061 for (TABLE *thd_table= in_use->open_tables;
2062 thd_table ;
2063 thd_table= thd_table->next)
2064 {
2065 /*
2066 Check for TABLE::needs_reopen() is needed since in some
2067 places we call handler::close() for table instance (and set
2068 TABLE::db_stat to 0) and do not remove such instances from
2069 the THD::open_tables for some time, during which other
2070 thread can see those instances (e.g. see partitioning code).
2071 */
2072 if (!thd_table->needs_reopen())
2073 {
2074 signalled|= mysql_lock_abort_for_thread(this, thd_table);
2075 if (WSREP(this) && wsrep_thd_is_BF(this, FALSE))
2076 {
2077 WSREP_DEBUG("remove_table_from_cache: %llu",
2078 (unsigned long long) this->real_id);
2079 wsrep_abort_thd((void *)this, (void *)in_use, FALSE);
2080 }
2081 }
2082 }
2083 }
2084 mysql_mutex_unlock(&in_use->LOCK_thd_data);
2085 }
2086 DBUG_RETURN(signalled);
2087}
2088
2089
2090/*
2091 Get error number for killed state
2092 Note that the error message can't have any parameters.
2093 If one needs parameters, one should use THD::killed_err_msg
2094 See thd::kill_message()
2095*/
2096
2097int THD::killed_errno()
2098{
2099 DBUG_ENTER("killed_errno");
2100 DBUG_PRINT("enter", ("killed: %d killed_errno: %d",
2101 killed, killed_err ? killed_err->no: 0));
2102
2103 /* Ensure that killed_err is not set if we are not killed */
2104 DBUG_ASSERT(!killed_err || killed != NOT_KILLED);
2105
2106 if (killed_err)
2107 DBUG_RETURN(killed_err->no);
2108
2109 switch (killed) {
2110 case NOT_KILLED:
2111 case KILL_HARD_BIT:
2112 DBUG_RETURN(0); // Probably wrong usage
2113 case KILL_BAD_DATA:
2114 case KILL_BAD_DATA_HARD:
2115 case ABORT_QUERY_HARD:
2116 case ABORT_QUERY:
2117 DBUG_RETURN(0); // Not a real error
2118 case KILL_CONNECTION:
2119 case KILL_CONNECTION_HARD:
2120 case KILL_SYSTEM_THREAD:
2121 case KILL_SYSTEM_THREAD_HARD:
2122 DBUG_RETURN(ER_CONNECTION_KILLED);
2123 case KILL_QUERY:
2124 case KILL_QUERY_HARD:
2125 DBUG_RETURN(ER_QUERY_INTERRUPTED);
2126 case KILL_TIMEOUT:
2127 case KILL_TIMEOUT_HARD:
2128 DBUG_RETURN(ER_STATEMENT_TIMEOUT);
2129 case KILL_SERVER:
2130 case KILL_SERVER_HARD:
2131 DBUG_RETURN(ER_SERVER_SHUTDOWN);
2132 case KILL_SLAVE_SAME_ID:
2133 DBUG_RETURN(ER_SLAVE_SAME_ID);
2134 case KILL_WAIT_TIMEOUT:
2135 case KILL_WAIT_TIMEOUT_HARD:
2136 DBUG_RETURN(ER_NET_READ_INTERRUPTED);
2137 }
2138 DBUG_RETURN(0); // Keep compiler happy
2139}
2140
2141
2142void THD::reset_killed()
2143{
2144 /*
2145 Resetting killed has to be done under a mutex to ensure
2146 its not done during an awake() call.
2147 */
2148 DBUG_ENTER("reset_killed");
2149 if (killed != NOT_KILLED)
2150 {
2151 mysql_mutex_lock(&LOCK_thd_kill);
2152 killed= NOT_KILLED;
2153 killed_err= 0;
2154 mysql_mutex_unlock(&LOCK_thd_kill);
2155 }
2156 DBUG_VOID_RETURN;
2157}
2158
2159/*
2160 Remember the location of thread info, the structure needed for
2161 the structure for the net buffer
2162*/
2163
2164bool THD::store_globals()
2165{
2166 /*
2167 Assert that thread_stack is initialized: it's necessary to be able
2168 to track stack overrun.
2169 */
2170 DBUG_ASSERT(thread_stack);
2171
2172 if (set_current_thd(this))
2173 return 1;
2174 /*
2175 mysys_var is concurrently readable by a killer thread.
2176 It is protected by LOCK_thd_kill, it is not needed to lock while the
2177 pointer is changing from NULL not non-NULL. If the kill thread reads
2178 NULL it doesn't refer to anything, but if it is non-NULL we need to
2179 ensure that the thread doesn't proceed to assign another thread to
2180 have the mysys_var reference (which in fact refers to the worker
2181 threads local storage with key THR_KEY_mysys.
2182 */
2183 mysys_var=my_thread_var;
2184 /*
2185 Let mysqld define the thread id (not mysys)
2186 This allows us to move THD to different threads if needed.
2187 */
2188 mysys_var->id= thread_id;
2189
2190 /* thread_dbug_id should not change for a THD */
2191 if (!thread_dbug_id)
2192 thread_dbug_id= mysys_var->dbug_id;
2193 else
2194 {
2195 /* This only changes if we are using pool-of-threads */
2196 mysys_var->dbug_id= thread_dbug_id;
2197 }
2198#ifdef __NR_gettid
2199 os_thread_id= (uint32)syscall(__NR_gettid);
2200#else
2201 os_thread_id= 0;
2202#endif
2203 real_id= pthread_self(); // For debugging
2204 mysys_var->stack_ends_here= thread_stack + // for consistency, see libevent_thread_proc
2205 STACK_DIRECTION * (long)my_thread_stack_size;
2206 if (net.vio)
2207 {
2208 net.thd= this;
2209 }
2210 /*
2211 We have to call thr_lock_info_init() again here as THD may have been
2212 created in another thread
2213 */
2214 thr_lock_info_init(&lock_info, mysys_var);
2215
2216 return 0;
2217}
2218
2219/**
2220 Untie THD from current thread
2221
2222 Used when using --thread-handling=pool-of-threads
2223*/
2224
2225void THD::reset_globals()
2226{
2227 mysql_mutex_lock(&LOCK_thd_kill);
2228 mysys_var= 0;
2229 mysql_mutex_unlock(&LOCK_thd_kill);
2230
2231 /* Undocking the thread specific data. */
2232 set_current_thd(0);
2233 net.thd= 0;
2234}
2235
2236/*
2237 Cleanup after query.
2238
2239 SYNOPSIS
2240 THD::cleanup_after_query()
2241
2242 DESCRIPTION
2243 This function is used to reset thread data to its default state.
2244
2245 NOTE
2246 This function is not suitable for setting thread data to some
2247 non-default values, as there is only one replication thread, so
2248 different master threads may overwrite data of each other on
2249 slave.
2250*/
2251
2252void THD::cleanup_after_query()
2253{
2254 DBUG_ENTER("THD::cleanup_after_query");
2255
2256 thd_progress_end(this);
2257
2258 /*
2259 Reset rand_used so that detection of calls to rand() will save random
2260 seeds if needed by the slave.
2261
2262 Do not reset rand_used if inside a stored function or trigger because
2263 only the call to these operations is logged. Thus only the calling
2264 statement needs to detect rand() calls made by its substatements. These
2265 substatements must not set rand_used to 0 because it would remove the
2266 detection of rand() by the calling statement.
2267 */
2268 if (!in_sub_stmt) /* stored functions and triggers are a special case */
2269 {
2270 /* Forget those values, for next binlogger: */
2271 stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
2272 auto_inc_intervals_in_cur_stmt_for_binlog.empty();
2273 rand_used= 0;
2274#ifndef EMBEDDED_LIBRARY
2275 /*
2276 Clean possible unused INSERT_ID events by current statement.
2277 is_update_query() is needed to ignore SET statements:
2278 Statements that don't update anything directly and don't
2279 used stored functions. This is mostly necessary to ignore
2280 statements in binlog between SET INSERT_ID and DML statement
2281 which is intended to consume its event (there can be other
2282 SET statements between them).
2283 */
2284 if ((rgi_slave || rli_fake) && is_update_query(lex->sql_command))
2285 auto_inc_intervals_forced.empty();
2286#endif
2287 }
2288 /*
2289 Forget the binlog stmt filter for the next query.
2290 There are some code paths that:
2291 - do not call THD::decide_logging_format()
2292 - do call THD::binlog_query(),
2293 making this reset necessary.
2294 */
2295 reset_binlog_local_stmt_filter();
2296 if (first_successful_insert_id_in_cur_stmt > 0)
2297 {
2298 /* set what LAST_INSERT_ID() will return */
2299 first_successful_insert_id_in_prev_stmt=
2300 first_successful_insert_id_in_cur_stmt;
2301 first_successful_insert_id_in_cur_stmt= 0;
2302 substitute_null_with_insert_id= TRUE;
2303 }
2304 arg_of_last_insert_id_function= 0;
2305 /* Free Items that were created during this execution */
2306 free_items();
2307 /* Reset where. */
2308 where= THD::DEFAULT_WHERE;
2309 /* reset table map for multi-table update */
2310 table_map_for_update= 0;
2311 m_binlog_invoker= INVOKER_NONE;
2312#ifdef WITH_WSREP
2313 if (TOTAL_ORDER == wsrep_exec_mode)
2314 {
2315 wsrep_exec_mode = LOCAL_STATE;
2316 }
2317#endif /* WITH_WSREP */
2318
2319#ifndef EMBEDDED_LIBRARY
2320 if (rgi_slave)
2321 rgi_slave->cleanup_after_query();
2322#endif
2323
2324#ifdef WITH_WSREP
2325 wsrep_sync_wait_gtid= WSREP_GTID_UNDEFINED;
2326 if (!in_active_multi_stmt_transaction())
2327 wsrep_affected_rows= 0;
2328#endif /* WITH_WSREP */
2329
2330 DBUG_VOID_RETURN;
2331}
2332
2333
2334/*
2335 Convert a string to another character set
2336
2337 SYNOPSIS
2338 convert_string()
2339 to Store new allocated string here
2340 to_cs New character set for allocated string
2341 from String to convert
2342 from_length Length of string to convert
2343 from_cs Original character set
2344
2345 NOTES
2346 to will be 0-terminated to make it easy to pass to system funcs
2347
2348 RETURN
2349 0 ok
2350 1 End of memory.
2351 In this case to->str will point to 0 and to->length will be 0.
2352*/
2353
2354bool THD::convert_string(LEX_STRING *to, CHARSET_INFO *to_cs,
2355 const char *from, size_t from_length,
2356 CHARSET_INFO *from_cs)
2357{
2358 DBUG_ENTER("THD::convert_string");
2359 size_t new_length= to_cs->mbmaxlen * from_length;
2360 uint errors;
2361 if (unlikely(alloc_lex_string(to, new_length + 1)))
2362 DBUG_RETURN(true); // EOM
2363 to->length= copy_and_convert((char*) to->str, new_length, to_cs,
2364 from, from_length, from_cs, &errors);
2365 to->str[to->length]= 0; // Safety
2366 if (unlikely(errors) && lex->parse_vcol_expr)
2367 {
2368 my_error(ER_BAD_DATA, MYF(0),
2369 ErrConvString(from, from_length, from_cs).ptr(),
2370 to_cs->csname);
2371 DBUG_RETURN(true);
2372 }
2373 DBUG_RETURN(false);
2374}
2375
2376
2377/*
2378 Convert a string between two character sets.
2379 dstcs and srccs cannot be &my_charset_bin.
2380*/
2381bool THD::convert_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
2382 CHARSET_INFO *srccs, const char *src, size_t src_length,
2383 String_copier *status)
2384{
2385 DBUG_ENTER("THD::convert_fix");
2386 size_t dst_length= dstcs->mbmaxlen * src_length;
2387 if (alloc_lex_string(dst, dst_length + 1))
2388 DBUG_RETURN(true); // EOM
2389 dst->length= status->convert_fix(dstcs, (char*) dst->str, dst_length,
2390 srccs, src, src_length, src_length);
2391 dst->str[dst->length]= 0; // Safety
2392 DBUG_RETURN(false);
2393}
2394
2395
2396/*
2397 Copy or convert a string.
2398*/
2399bool THD::copy_fix(CHARSET_INFO *dstcs, LEX_STRING *dst,
2400 CHARSET_INFO *srccs, const char *src, size_t src_length,
2401 String_copier *status)
2402{
2403 DBUG_ENTER("THD::copy_fix");
2404 size_t dst_length= dstcs->mbmaxlen * src_length;
2405 if (alloc_lex_string(dst, dst_length + 1))
2406 DBUG_RETURN(true); // EOM
2407 dst->length= status->well_formed_copy(dstcs, dst->str, dst_length,
2408 srccs, src, src_length, src_length);
2409 dst->str[dst->length]= '\0';
2410 DBUG_RETURN(false);
2411}
2412
2413
2414class String_copier_with_error: public String_copier
2415{
2416public:
2417 bool check_errors(CHARSET_INFO *srccs, const char *src, size_t src_length)
2418 {
2419 if (most_important_error_pos())
2420 {
2421 ErrConvString err(src, src_length, &my_charset_bin);
2422 my_error(ER_INVALID_CHARACTER_STRING, MYF(0), srccs->csname, err.ptr());
2423 return true;
2424 }
2425 return false;
2426 }
2427};
2428
2429
2430bool THD::convert_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
2431 CHARSET_INFO *srccs,
2432 const char *src, size_t src_length)
2433{
2434 String_copier_with_error status;
2435 return convert_fix(dstcs, dst, srccs, src, src_length, &status) ||
2436 status.check_errors(srccs, src, src_length);
2437}
2438
2439
2440bool THD::copy_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst,
2441 CHARSET_INFO *srccs,
2442 const char *src, size_t src_length)
2443{
2444 String_copier_with_error status;
2445 return copy_fix(dstcs, dst, srccs, src, src_length, &status) ||
2446 status.check_errors(srccs, src, src_length);
2447}
2448
2449
2450/*
2451 Convert string from source character set to target character set inplace.
2452
2453 SYNOPSIS
2454 THD::convert_string
2455
2456 DESCRIPTION
2457 Convert string using convert_buffer - buffer for character set
2458 conversion shared between all protocols.
2459
2460 RETURN
2461 0 ok
2462 !0 out of memory
2463*/
2464
2465bool THD::convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs)
2466{
2467 uint dummy_errors;
2468 if (unlikely(convert_buffer.copy(s->ptr(), s->length(), from_cs, to_cs,
2469 &dummy_errors)))
2470 return TRUE;
2471 /* If convert_buffer >> s copying is more efficient long term */
2472 if (convert_buffer.alloced_length() >= convert_buffer.length() * 2 ||
2473 !s->is_alloced())
2474 {
2475 return s->copy(convert_buffer);
2476 }
2477 s->swap(convert_buffer);
2478 return FALSE;
2479}
2480
2481
2482bool THD::check_string_for_wellformedness(const char *str,
2483 size_t length,
2484 CHARSET_INFO *cs) const
2485{
2486 DBUG_ASSERT(charset_is_system_charset);
2487 size_t wlen= Well_formed_prefix(cs, str, length).length();
2488 if (wlen < length)
2489 {
2490 ErrConvString err(str, length, &my_charset_bin);
2491 my_error(ER_INVALID_CHARACTER_STRING, MYF(0), cs->csname, err.ptr());
2492 return true;
2493 }
2494 return false;
2495}
2496
2497
2498bool THD::to_ident_sys_alloc(Lex_ident_sys_st *to, const Lex_ident_cli_st *ident)
2499{
2500 if (ident->is_quoted())
2501 {
2502 LEX_CSTRING unquoted;
2503 if (quote_unescape(&unquoted, ident, ident->quote()))
2504 return true;
2505 return charset_is_system_charset ?
2506 to->copy_sys(this, &unquoted) :
2507 to->convert(this, &unquoted, charset());
2508 }
2509 return charset_is_system_charset ?
2510 to->copy_sys(this, ident) :
2511 to->copy_or_convert(this, ident, charset());
2512}
2513
2514
2515Item_basic_constant *
2516THD::make_string_literal(const char *str, size_t length, uint repertoire)
2517{
2518 if (!length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
2519 return new (mem_root) Item_null(this, 0, variables.collation_connection);
2520 if (!charset_is_collation_connection &&
2521 (repertoire != MY_REPERTOIRE_ASCII ||
2522 !my_charset_is_ascii_based(variables.collation_connection)))
2523 {
2524 LEX_STRING to;
2525 if (convert_string(&to, variables.collation_connection,
2526 str, length, variables.character_set_client))
2527 return NULL;
2528 str= to.str;
2529 length= to.length;
2530 }
2531 return new (mem_root) Item_string(this, str, (uint)length,
2532 variables.collation_connection,
2533 DERIVATION_COERCIBLE, repertoire);
2534}
2535
2536
2537Item_basic_constant *
2538THD::make_string_literal_nchar(const Lex_string_with_metadata_st &str)
2539{
2540 DBUG_ASSERT(my_charset_is_ascii_based(national_charset_info));
2541 if (!str.length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
2542 return new (mem_root) Item_null(this, 0, national_charset_info);
2543
2544 return new (mem_root) Item_string(this, str.str, (uint)str.length,
2545 national_charset_info,
2546 DERIVATION_COERCIBLE,
2547 str.repertoire());
2548}
2549
2550
2551Item_basic_constant *
2552THD::make_string_literal_charset(const Lex_string_with_metadata_st &str,
2553 CHARSET_INFO *cs)
2554{
2555 if (!str.length && (variables.sql_mode & MODE_EMPTY_STRING_IS_NULL))
2556 return new (mem_root) Item_null(this, 0, cs);
2557 return new (mem_root) Item_string_with_introducer(this,
2558 str.str, (uint)str.length, cs);
2559}
2560
2561
2562/*
2563 Update some cache variables when character set changes
2564*/
2565
2566void THD::update_charset()
2567{
2568 uint32 not_used;
2569 charset_is_system_charset=
2570 !String::needs_conversion(0,
2571 variables.character_set_client,
2572 system_charset_info,
2573 &not_used);
2574 charset_is_collation_connection=
2575 !String::needs_conversion(0,
2576 variables.character_set_client,
2577 variables.collation_connection,
2578 &not_used);
2579 charset_is_character_set_filesystem=
2580 !String::needs_conversion(0,
2581 variables.character_set_client,
2582 variables.character_set_filesystem,
2583 &not_used);
2584}
2585
2586
2587/* routings to adding tables to list of changed in transaction tables */
2588
2589inline static void list_include(CHANGED_TABLE_LIST** prev,
2590 CHANGED_TABLE_LIST* curr,
2591 CHANGED_TABLE_LIST* new_table)
2592{
2593 if (new_table)
2594 {
2595 *prev = new_table;
2596 (*prev)->next = curr;
2597 }
2598}
2599
2600/* add table to list of changed in transaction tables */
2601
2602void THD::add_changed_table(TABLE *table)
2603{
2604 DBUG_ENTER("THD::add_changed_table(table)");
2605
2606 DBUG_ASSERT(in_multi_stmt_transaction_mode() && table->file->has_transactions());
2607 add_changed_table(table->s->table_cache_key.str,
2608 (long) table->s->table_cache_key.length);
2609 DBUG_VOID_RETURN;
2610}
2611
2612
2613void THD::add_changed_table(const char *key, size_t key_length)
2614{
2615 DBUG_ENTER("THD::add_changed_table(key)");
2616 CHANGED_TABLE_LIST **prev_changed = &transaction.changed_tables;
2617 CHANGED_TABLE_LIST *curr = transaction.changed_tables;
2618
2619 for (; curr; prev_changed = &(curr->next), curr = curr->next)
2620 {
2621 int cmp = (long)curr->key_length - (long)key_length;
2622 if (cmp < 0)
2623 {
2624 list_include(prev_changed, curr, changed_table_dup(key, key_length));
2625 DBUG_PRINT("info",
2626 ("key_length: %zu %zu", key_length,
2627 (*prev_changed)->key_length));
2628 DBUG_VOID_RETURN;
2629 }
2630 else if (cmp == 0)
2631 {
2632 cmp = memcmp(curr->key, key, curr->key_length);
2633 if (cmp < 0)
2634 {
2635 list_include(prev_changed, curr, changed_table_dup(key, key_length));
2636 DBUG_PRINT("info",
2637 ("key_length: %zu %zu", key_length,
2638 (*prev_changed)->key_length));
2639 DBUG_VOID_RETURN;
2640 }
2641 else if (cmp == 0)
2642 {
2643 DBUG_PRINT("info", ("already in list"));
2644 DBUG_VOID_RETURN;
2645 }
2646 }
2647 }
2648 *prev_changed = changed_table_dup(key, key_length);
2649 DBUG_PRINT("info", ("key_length: %zu %zu", key_length,
2650 (*prev_changed)->key_length));
2651 DBUG_VOID_RETURN;
2652}
2653
2654
2655CHANGED_TABLE_LIST* THD::changed_table_dup(const char *key, size_t key_length)
2656{
2657 CHANGED_TABLE_LIST* new_table =
2658 (CHANGED_TABLE_LIST*) trans_alloc(ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST))+
2659 key_length + 1);
2660 if (!new_table)
2661 {
2662 my_error(EE_OUTOFMEMORY, MYF(ME_BELL+ME_FATALERROR),
2663 ALIGN_SIZE(sizeof(TABLE_LIST)) + key_length + 1);
2664 set_killed(KILL_CONNECTION);
2665 return 0;
2666 }
2667
2668 new_table->key= ((char*)new_table)+ ALIGN_SIZE(sizeof(CHANGED_TABLE_LIST));
2669 new_table->next = 0;
2670 new_table->key_length = key_length;
2671 ::memcpy(new_table->key, key, key_length);
2672 return new_table;
2673}
2674
2675
2676void THD::prepare_explain_fields(select_result *result,
2677 List<Item> *field_list,
2678 uint8 explain_flags,
2679 bool is_analyze)
2680{
2681 if (lex->explain_json)
2682 make_explain_json_field_list(*field_list, is_analyze);
2683 else
2684 make_explain_field_list(*field_list, explain_flags, is_analyze);
2685
2686 result->prepare(*field_list, NULL);
2687}
2688
2689
2690int THD::send_explain_fields(select_result *result,
2691 uint8 explain_flags,
2692 bool is_analyze)
2693{
2694 List<Item> field_list;
2695 int rc;
2696 prepare_explain_fields(result, &field_list, explain_flags, is_analyze);
2697 rc= result->send_result_set_metadata(field_list,
2698 Protocol::SEND_NUM_ROWS |
2699 Protocol::SEND_EOF);
2700 return(rc);
2701}
2702
2703
2704void THD::make_explain_json_field_list(List<Item> &field_list, bool is_analyze)
2705{
2706 Item *item= new (mem_root) Item_empty_string(this, (is_analyze ?
2707 "ANALYZE" :
2708 "EXPLAIN"),
2709 78, system_charset_info);
2710 field_list.push_back(item, mem_root);
2711}
2712
2713
2714/*
2715 Populate the provided field_list with EXPLAIN output columns.
2716 this->lex->describe has the EXPLAIN flags
2717
2718 The set/order of columns must be kept in sync with
2719 Explain_query::print_explain and co.
2720*/
2721
2722void THD::make_explain_field_list(List<Item> &field_list, uint8 explain_flags,
2723 bool is_analyze)
2724{
2725 Item *item;
2726 CHARSET_INFO *cs= system_charset_info;
2727 field_list.push_back(item= new (mem_root)
2728 Item_return_int(this, "id", 3,
2729 MYSQL_TYPE_LONGLONG), mem_root);
2730 item->maybe_null= 1;
2731 field_list.push_back(new (mem_root)
2732 Item_empty_string(this, "select_type", 19, cs),
2733 mem_root);
2734 field_list.push_back(item= new (mem_root)
2735 Item_empty_string(this, "table", NAME_CHAR_LEN, cs),
2736 mem_root);
2737 item->maybe_null= 1;
2738 if (explain_flags & DESCRIBE_PARTITIONS)
2739 {
2740 /* Maximum length of string that make_used_partitions_str() can produce */
2741 item= new (mem_root) Item_empty_string(this, "partitions",
2742 MAX_PARTITIONS * (1 + FN_LEN), cs);
2743 field_list.push_back(item, mem_root);
2744 item->maybe_null= 1;
2745 }
2746 field_list.push_back(item= new (mem_root)
2747 Item_empty_string(this, "type", 10, cs),
2748 mem_root);
2749 item->maybe_null= 1;
2750 field_list.push_back(item= new (mem_root)
2751 Item_empty_string(this, "possible_keys",
2752 NAME_CHAR_LEN*MAX_KEY, cs),
2753 mem_root);
2754 item->maybe_null=1;
2755 field_list.push_back(item=new (mem_root)
2756 Item_empty_string(this, "key", NAME_CHAR_LEN, cs),
2757 mem_root);
2758 item->maybe_null=1;
2759 field_list.push_back(item=new (mem_root)
2760 Item_empty_string(this, "key_len",
2761 NAME_CHAR_LEN*MAX_KEY),
2762 mem_root);
2763 item->maybe_null=1;
2764 field_list.push_back(item=new (mem_root)
2765 Item_empty_string(this, "ref",
2766 NAME_CHAR_LEN*MAX_REF_PARTS, cs),
2767 mem_root);
2768 item->maybe_null=1;
2769 field_list.push_back(item= new (mem_root)
2770 Item_return_int(this, "rows", 10, MYSQL_TYPE_LONGLONG),
2771 mem_root);
2772 if (is_analyze)
2773 {
2774 field_list.push_back(item= new (mem_root)
2775 Item_float(this, "r_rows", 0.1234, 10, 4),
2776 mem_root);
2777 item->maybe_null=1;
2778 }
2779
2780 if (is_analyze || (explain_flags & DESCRIBE_EXTENDED))
2781 {
2782 field_list.push_back(item= new (mem_root)
2783 Item_float(this, "filtered", 0.1234, 2, 4),
2784 mem_root);
2785 item->maybe_null=1;
2786 }
2787
2788 if (is_analyze)
2789 {
2790 field_list.push_back(item= new (mem_root)
2791 Item_float(this, "r_filtered", 0.1234, 2, 4),
2792 mem_root);
2793 item->maybe_null=1;
2794 }
2795
2796 item->maybe_null= 1;
2797 field_list.push_back(new (mem_root)
2798 Item_empty_string(this, "Extra", 255, cs),
2799 mem_root);
2800}
2801
2802
2803#ifdef SIGNAL_WITH_VIO_CLOSE
2804void THD::close_active_vio()
2805{
2806 DBUG_ENTER("close_active_vio");
2807 mysql_mutex_assert_owner(&LOCK_thd_data);
2808#ifndef EMBEDDED_LIBRARY
2809 if (active_vio)
2810 {
2811 vio_close(active_vio);
2812 active_vio = 0;
2813 }
2814#endif
2815 DBUG_VOID_RETURN;
2816}
2817#endif
2818
2819
2820struct Item_change_record: public ilink
2821{
2822 Item **place;
2823 Item *old_value;
2824 /* Placement new was hidden by `new' in ilink (TODO: check): */
2825 static void *operator new(size_t size, void *mem) { return mem; }
2826 static void operator delete(void *ptr, size_t size) {}
2827 static void operator delete(void *ptr, void *mem) { /* never called */ }
2828};
2829
2830
2831/*
2832 Register an item tree tree transformation, performed by the query
2833 optimizer. We need a pointer to runtime_memroot because it may be !=
2834 thd->mem_root (due to possible set_n_backup_active_arena called for thd).
2835*/
2836
2837void
2838Item_change_list::nocheck_register_item_tree_change(Item **place,
2839 Item *old_value,
2840 MEM_ROOT *runtime_memroot)
2841{
2842 Item_change_record *change;
2843 DBUG_ENTER("THD::nocheck_register_item_tree_change");
2844 DBUG_PRINT("enter", ("Register %p <- %p", old_value, (*place)));
2845 /*
2846 Now we use one node per change, which adds some memory overhead,
2847 but still is rather fast as we use alloc_root for allocations.
2848 A list of item tree changes of an average query should be short.
2849 */
2850 void *change_mem= alloc_root(runtime_memroot, sizeof(*change));
2851 if (change_mem == 0)
2852 {
2853 /*
2854 OOM, thd->fatal_error() is called by the error handler of the
2855 memroot. Just return.
2856 */
2857 DBUG_VOID_RETURN;
2858 }
2859 change= new (change_mem) Item_change_record;
2860 change->place= place;
2861 change->old_value= old_value;
2862 change_list.append(change);
2863 DBUG_VOID_RETURN;
2864}
2865
2866/**
2867 Check and register item change if needed
2868
2869 @param place place where we should assign new value
2870 @param new_value place of the new value
2871
2872 @details
2873 Let C be a reference to an item that changed the reference A
2874 at the location (occurrence) L1 and this change has been registered.
2875 If C is substituted for reference A another location (occurrence) L2
2876 that is to be registered as well than this change has to be
2877 consistent with the first change in order the procedure that rollback
2878 changes to substitute the same reference at both locations L1 and L2.
2879*/
2880
2881void
2882Item_change_list::check_and_register_item_tree_change(Item **place,
2883 Item **new_value,
2884 MEM_ROOT *runtime_memroot)
2885{
2886 Item_change_record *change;
2887 DBUG_ENTER("THD::check_and_register_item_tree_change");
2888 DBUG_PRINT("enter", ("Register: %p (%p) <- %p (%p)",
2889 *place, place, *new_value, new_value));
2890 I_List_iterator<Item_change_record> it(change_list);
2891 while ((change= it++))
2892 {
2893 if (change->place == new_value)
2894 break; // we need only very first value
2895 }
2896 if (change)
2897 nocheck_register_item_tree_change(place, change->old_value,
2898 runtime_memroot);
2899 DBUG_VOID_RETURN;
2900}
2901
2902
2903void Item_change_list::rollback_item_tree_changes()
2904{
2905 DBUG_ENTER("THD::rollback_item_tree_changes");
2906 I_List_iterator<Item_change_record> it(change_list);
2907 Item_change_record *change;
2908
2909 while ((change= it++))
2910 {
2911 DBUG_PRINT("info", ("Rollback: %p (%p) <- %p",
2912 *change->place, change->place, change->old_value));
2913 *change->place= change->old_value;
2914 }
2915 /* We can forget about changes memory: it's allocated in runtime memroot */
2916 change_list.empty();
2917 DBUG_VOID_RETURN;
2918}
2919
2920
2921/*****************************************************************************
2922** Functions to provide a interface to select results
2923*****************************************************************************/
2924
2925void select_result::cleanup()
2926{
2927 /* do nothing */
2928}
2929
2930bool select_result::check_simple_select() const
2931{
2932 my_error(ER_SP_BAD_CURSOR_QUERY, MYF(0));
2933 return TRUE;
2934}
2935
2936
2937static String default_line_term("\n",default_charset_info);
2938static String default_escaped("\\",default_charset_info);
2939static String default_field_term("\t",default_charset_info);
2940static String default_enclosed_and_line_start("", default_charset_info);
2941static String default_xml_row_term("<row>", default_charset_info);
2942
2943sql_exchange::sql_exchange(const char *name, bool flag,
2944 enum enum_filetype filetype_arg)
2945 :file_name(name), opt_enclosed(0), dumpfile(flag), skip_lines(0)
2946{
2947 filetype= filetype_arg;
2948 field_term= &default_field_term;
2949 enclosed= line_start= &default_enclosed_and_line_start;
2950 line_term= filetype == FILETYPE_CSV ?
2951 &default_line_term : &default_xml_row_term;
2952 escaped= &default_escaped;
2953 cs= NULL;
2954}
2955
2956bool sql_exchange::escaped_given(void) const
2957{
2958 return escaped != &default_escaped;
2959}
2960
2961
2962bool select_send::send_result_set_metadata(List<Item> &list, uint flags)
2963{
2964 bool res;
2965#ifdef WITH_WSREP
2966 if (WSREP(thd) && thd->wsrep_retry_query)
2967 {
2968 WSREP_DEBUG("skipping select metadata");
2969 return FALSE;
2970 }
2971#endif /* WITH_WSREP */
2972 if (!(res= thd->protocol->send_result_set_metadata(&list, flags)))
2973 is_result_set_started= 1;
2974 return res;
2975}
2976
2977void select_send::abort_result_set()
2978{
2979 DBUG_ENTER("select_send::abort_result_set");
2980
2981 if (is_result_set_started && thd->spcont)
2982 {
2983 /*
2984 We're executing a stored procedure, have an open result
2985 set and an SQL exception condition. In this situation we
2986 must abort the current statement, silence the error and
2987 start executing the continue/exit handler if one is found.
2988 Before aborting the statement, let's end the open result set, as
2989 otherwise the client will hang due to the violation of the
2990 client/server protocol.
2991 */
2992 thd->spcont->end_partial_result_set= TRUE;
2993 }
2994 DBUG_VOID_RETURN;
2995}
2996
2997
2998/**
2999 Cleanup an instance of this class for re-use
3000 at next execution of a prepared statement/
3001 stored procedure statement.
3002*/
3003
3004void select_send::cleanup()
3005{
3006 is_result_set_started= FALSE;
3007}
3008
3009/* Send data to client. Returns 0 if ok */
3010
3011int select_send::send_data(List<Item> &items)
3012{
3013 Protocol *protocol= thd->protocol;
3014 DBUG_ENTER("select_send::send_data");
3015
3016 /* unit is not set when using 'delete ... returning' */
3017 if (unit && unit->offset_limit_cnt)
3018 { // using limit offset,count
3019 unit->offset_limit_cnt--;
3020 DBUG_RETURN(FALSE);
3021 }
3022 if (thd->killed == ABORT_QUERY)
3023 DBUG_RETURN(FALSE);
3024
3025 protocol->prepare_for_resend();
3026 if (protocol->send_result_set_row(&items))
3027 {
3028 protocol->remove_last_row();
3029 DBUG_RETURN(TRUE);
3030 }
3031
3032 thd->inc_sent_row_count(1);
3033
3034 if (thd->vio_ok())
3035 DBUG_RETURN(protocol->write());
3036
3037 DBUG_RETURN(0);
3038}
3039
3040
3041bool select_send::send_eof()
3042{
3043 /*
3044 Don't send EOF if we're in error condition (which implies we've already
3045 sent or are sending an error)
3046 */
3047 if (unlikely(thd->is_error()))
3048 return TRUE;
3049 ::my_eof(thd);
3050 is_result_set_started= 0;
3051 return FALSE;
3052}
3053
3054
3055/************************************************************************
3056 Handling writing to file
3057************************************************************************/
3058
3059bool select_to_file::send_eof()
3060{
3061 int error= MY_TEST(end_io_cache(&cache));
3062 if (unlikely(mysql_file_close(file, MYF(MY_WME))) ||
3063 unlikely(thd->is_error()))
3064 error= true;
3065
3066 if (likely(!error) && !suppress_my_ok)
3067 {
3068 ::my_ok(thd,row_count);
3069 }
3070 file= -1;
3071 return error;
3072}
3073
3074
3075void select_to_file::cleanup()
3076{
3077 /* In case of error send_eof() may be not called: close the file here. */
3078 if (file >= 0)
3079 {
3080 (void) end_io_cache(&cache);
3081 mysql_file_close(file, MYF(0));
3082 file= -1;
3083 }
3084 path[0]= '\0';
3085 row_count= 0;
3086}
3087
3088
3089select_to_file::~select_to_file()
3090{
3091 if (file >= 0)
3092 { // This only happens in case of error
3093 (void) end_io_cache(&cache);
3094 mysql_file_close(file, MYF(0));
3095 file= -1;
3096 }
3097}
3098
3099/***************************************************************************
3100** Export of select to textfile
3101***************************************************************************/
3102
3103select_export::~select_export()
3104{
3105 thd->set_sent_row_count(row_count);
3106}
3107
3108
3109/*
3110 Create file with IO cache
3111
3112 SYNOPSIS
3113 create_file()
3114 thd Thread handle
3115 path File name
3116 exchange Excange class
3117 cache IO cache
3118
3119 RETURN
3120 >= 0 File handle
3121 -1 Error
3122*/
3123
3124
3125static File create_file(THD *thd, char *path, sql_exchange *exchange,
3126 IO_CACHE *cache)
3127{
3128 File file;
3129 uint option= MY_UNPACK_FILENAME | MY_RELATIVE_PATH;
3130
3131#ifdef DONT_ALLOW_FULL_LOAD_DATA_PATHS
3132 option|= MY_REPLACE_DIR; // Force use of db directory
3133#endif
3134
3135 if (!dirname_length(exchange->file_name))
3136 {
3137 strxnmov(path, FN_REFLEN-1, mysql_real_data_home, thd->get_db(), NullS);
3138 (void) fn_format(path, exchange->file_name, path, "", option);
3139 }
3140 else
3141 (void) fn_format(path, exchange->file_name, mysql_real_data_home, "", option);
3142
3143 if (!is_secure_file_path(path))
3144 {
3145 /* Write only allowed to dir or subdir specified by secure_file_priv */
3146 my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
3147 return -1;
3148 }
3149
3150 if (!access(path, F_OK))
3151 {
3152 my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
3153 return -1;
3154 }
3155 /* Create the file world readable */
3156 if ((file= mysql_file_create(key_select_to_file,
3157 path, 0666, O_WRONLY|O_EXCL, MYF(MY_WME))) < 0)
3158 return file;
3159#ifdef HAVE_FCHMOD
3160 (void) fchmod(file, 0666); // Because of umask()
3161#else
3162 (void) chmod(path, 0666);
3163#endif
3164 if (init_io_cache(cache, file, 0L, WRITE_CACHE, 0L, 1, MYF(MY_WME)))
3165 {
3166 mysql_file_close(file, MYF(0));
3167 /* Delete file on error, it was just created */
3168 mysql_file_delete(key_select_to_file, path, MYF(0));
3169 return -1;
3170 }
3171 return file;
3172}
3173
3174
3175int
3176select_export::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
3177{
3178 bool blob_flag=0;
3179 bool string_results= FALSE, non_string_results= FALSE;
3180 unit= u;
3181 if ((uint) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
3182 strmake_buf(path,exchange->file_name);
3183
3184 write_cs= exchange->cs ? exchange->cs : &my_charset_bin;
3185
3186 if ((file= create_file(thd, path, exchange, &cache)) < 0)
3187 return 1;
3188 /* Check if there is any blobs in data */
3189 {
3190 List_iterator_fast<Item> li(list);
3191 Item *item;
3192 while ((item=li++))
3193 {
3194 if (item->max_length >= MAX_BLOB_WIDTH)
3195 {
3196 blob_flag=1;
3197 break;
3198 }
3199 if (item->result_type() == STRING_RESULT)
3200 string_results= TRUE;
3201 else
3202 non_string_results= TRUE;
3203 }
3204 }
3205 if (exchange->escaped->numchars() > 1 || exchange->enclosed->numchars() > 1)
3206 {
3207 my_error(ER_WRONG_FIELD_TERMINATORS, MYF(0));
3208 return TRUE;
3209 }
3210 if (exchange->escaped->length() > 1 || exchange->enclosed->length() > 1 ||
3211 !my_isascii(exchange->escaped->ptr()[0]) ||
3212 !my_isascii(exchange->enclosed->ptr()[0]) ||
3213 !exchange->field_term->is_ascii() || !exchange->line_term->is_ascii() ||
3214 !exchange->line_start->is_ascii())
3215 {
3216 /*
3217 Current LOAD DATA INFILE recognizes field/line separators "as is" without
3218 converting from client charset to data file charset. So, it is supposed,
3219 that input file of LOAD DATA INFILE consists of data in one charset and
3220 separators in other charset. For the compatibility with that [buggy]
3221 behaviour SELECT INTO OUTFILE implementation has been saved "as is" too,
3222 but the new warning message has been added:
3223
3224 Non-ASCII separator arguments are not fully supported
3225 */
3226 push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
3227 WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED,
3228 ER_THD(thd, WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED));
3229 }
3230 field_term_length=exchange->field_term->length();
3231 field_term_char= field_term_length ?
3232 (int) (uchar) (*exchange->field_term)[0] : INT_MAX;
3233 if (!exchange->line_term->length())
3234 exchange->line_term=exchange->field_term; // Use this if it exists
3235 field_sep_char= (exchange->enclosed->length() ?
3236 (int) (uchar) (*exchange->enclosed)[0] : field_term_char);
3237 if (exchange->escaped->length() && (exchange->escaped_given() ||
3238 !(thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)))
3239 escape_char= (int) (uchar) (*exchange->escaped)[0];
3240 else
3241 escape_char= -1;
3242 is_ambiguous_field_sep= MY_TEST(strchr(ESCAPE_CHARS, field_sep_char));
3243 is_unsafe_field_sep= MY_TEST(strchr(NUMERIC_CHARS, field_sep_char));
3244 line_sep_char= (exchange->line_term->length() ?
3245 (int) (uchar) (*exchange->line_term)[0] : INT_MAX);
3246 if (!field_term_length)
3247 exchange->opt_enclosed=0;
3248 if (!exchange->enclosed->length())
3249 exchange->opt_enclosed=1; // A little quicker loop
3250 fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
3251 !blob_flag);
3252 if ((is_ambiguous_field_sep && exchange->enclosed->is_empty() &&
3253 (string_results || is_unsafe_field_sep)) ||
3254 (exchange->opt_enclosed && non_string_results &&
3255 field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
3256 {
3257 push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
3258 ER_AMBIGUOUS_FIELD_TERM,
3259 ER_THD(thd, ER_AMBIGUOUS_FIELD_TERM));
3260 is_ambiguous_field_term= TRUE;
3261 }
3262 else
3263 is_ambiguous_field_term= FALSE;
3264
3265 return 0;
3266}
3267
3268
3269#define NEED_ESCAPING(x) ((int) (uchar) (x) == escape_char || \
3270 (enclosed ? (int) (uchar) (x) == field_sep_char \
3271 : (int) (uchar) (x) == field_term_char) || \
3272 (int) (uchar) (x) == line_sep_char || \
3273 !(x))
3274
3275int select_export::send_data(List<Item> &items)
3276{
3277
3278 DBUG_ENTER("select_export::send_data");
3279 char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
3280 char cvt_buff[MAX_FIELD_WIDTH];
3281 String cvt_str(cvt_buff, sizeof(cvt_buff), write_cs);
3282 bool space_inited=0;
3283 String tmp(buff,sizeof(buff),&my_charset_bin),*res;
3284 tmp.length(0);
3285
3286 if (unit->offset_limit_cnt)
3287 { // using limit offset,count
3288 unit->offset_limit_cnt--;
3289 DBUG_RETURN(0);
3290 }
3291 if (thd->killed == ABORT_QUERY)
3292 DBUG_RETURN(0);
3293 row_count++;
3294 Item *item;
3295 uint used_length=0,items_left=items.elements;
3296 List_iterator_fast<Item> li(items);
3297
3298 if (my_b_write(&cache,(uchar*) exchange->line_start->ptr(),
3299 exchange->line_start->length()))
3300 goto err;
3301 while ((item=li++))
3302 {
3303 Item_result result_type=item->result_type();
3304 bool enclosed = (exchange->enclosed->length() &&
3305 (!exchange->opt_enclosed || result_type == STRING_RESULT));
3306 res=item->str_result(&tmp);
3307 if (res && !my_charset_same(write_cs, res->charset()) &&
3308 !my_charset_same(write_cs, &my_charset_bin))
3309 {
3310 String_copier copier;
3311 const char *error_pos;
3312 uint32 bytes;
3313 uint64 estimated_bytes=
3314 ((uint64) res->length() / res->charset()->mbminlen + 1) *
3315 write_cs->mbmaxlen + 1;
3316 set_if_smaller(estimated_bytes, UINT_MAX32);
3317 if (cvt_str.realloc((uint32) estimated_bytes))
3318 {
3319 my_error(ER_OUTOFMEMORY, MYF(ME_FATALERROR), (uint32) estimated_bytes);
3320 goto err;
3321 }
3322
3323 bytes= copier.well_formed_copy(write_cs, (char *) cvt_str.ptr(),
3324 cvt_str.alloced_length(),
3325 res->charset(),
3326 res->ptr(), res->length());
3327 error_pos= copier.most_important_error_pos();
3328 if (unlikely(error_pos))
3329 {
3330 char printable_buff[32];
3331 convert_to_printable(printable_buff, sizeof(printable_buff),
3332 error_pos, res->ptr() + res->length() - error_pos,
3333 res->charset(), 6);
3334 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3335 ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
3336 ER_THD(thd, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
3337 "string", printable_buff,
3338 item->name.str, static_cast<long>(row_count));
3339 }
3340 else if (copier.source_end_pos() < res->ptr() + res->length())
3341 {
3342 /*
3343 result is longer than UINT_MAX32 and doesn't fit into String
3344 */
3345 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3346 WARN_DATA_TRUNCATED,
3347 ER_THD(thd, WARN_DATA_TRUNCATED),
3348 item->full_name(), static_cast<long>(row_count));
3349 }
3350 cvt_str.length(bytes);
3351 res= &cvt_str;
3352 }
3353 if (res && enclosed)
3354 {
3355 if (my_b_write(&cache,(uchar*) exchange->enclosed->ptr(),
3356 exchange->enclosed->length()))
3357 goto err;
3358 }
3359 if (!res)
3360 { // NULL
3361 if (!fixed_row_size)
3362 {
3363 if (escape_char != -1) // Use \N syntax
3364 {
3365 null_buff[0]=escape_char;
3366 null_buff[1]='N';
3367 if (my_b_write(&cache,(uchar*) null_buff,2))
3368 goto err;
3369 }
3370 else if (my_b_write(&cache,(uchar*) "NULL",4))
3371 goto err;
3372 }
3373 else
3374 {
3375 used_length=0; // Fill with space
3376 }
3377 }
3378 else
3379 {
3380 if (fixed_row_size)
3381 used_length=MY_MIN(res->length(),item->max_length);
3382 else
3383 used_length=res->length();
3384 if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
3385 escape_char != -1)
3386 {
3387 char *pos, *start, *end;
3388 CHARSET_INFO *res_charset= res->charset();
3389 CHARSET_INFO *character_set_client= thd->variables.
3390 character_set_client;
3391 bool check_second_byte= (res_charset == &my_charset_bin) &&
3392 character_set_client->
3393 escape_with_backslash_is_dangerous;
3394 DBUG_ASSERT(character_set_client->mbmaxlen == 2 ||
3395 !character_set_client->escape_with_backslash_is_dangerous);
3396 for (start=pos=(char*) res->ptr(),end=pos+used_length ;
3397 pos != end ;
3398 pos++)
3399 {
3400#ifdef USE_MB
3401 if (use_mb(res_charset))
3402 {
3403 int l;
3404 if ((l=my_ismbchar(res_charset, pos, end)))
3405 {
3406 pos += l-1;
3407 continue;
3408 }
3409 }
3410#endif
3411
3412 /*
3413 Special case when dumping BINARY/VARBINARY/BLOB values
3414 for the clients with character sets big5, cp932, gbk and sjis,
3415 which can have the escape character (0x5C "\" by default)
3416 as the second byte of a multi-byte sequence.
3417
3418 If
3419 - pos[0] is a valid multi-byte head (e.g 0xEE) and
3420 - pos[1] is 0x00, which will be escaped as "\0",
3421
3422 then we'll get "0xEE + 0x5C + 0x30" in the output file.
3423
3424 If this file is later loaded using this sequence of commands:
3425
3426 mysql> create table t1 (a varchar(128)) character set big5;
3427 mysql> LOAD DATA INFILE 'dump.txt' INTO TABLE t1;
3428
3429 then 0x5C will be misinterpreted as the second byte
3430 of a multi-byte character "0xEE + 0x5C", instead of
3431 escape character for 0x00.
3432
3433 To avoid this confusion, we'll escape the multi-byte
3434 head character too, so the sequence "0xEE + 0x00" will be
3435 dumped as "0x5C + 0xEE + 0x5C + 0x30".
3436
3437 Note, in the condition below we only check if
3438 mbcharlen is equal to 2, because there are no
3439 character sets with mbmaxlen longer than 2
3440 and with escape_with_backslash_is_dangerous set.
3441 DBUG_ASSERT before the loop makes that sure.
3442 */
3443
3444 if ((NEED_ESCAPING(*pos) ||
3445 (check_second_byte &&
3446 ((uchar) *pos) > 0x7F /* a potential MB2HEAD */ &&
3447 pos + 1 < end &&
3448 NEED_ESCAPING(pos[1]))) &&
3449 /*
3450 Don't escape field_term_char by doubling - doubling is only
3451 valid for ENCLOSED BY characters:
3452 */
3453 (enclosed || !is_ambiguous_field_term ||
3454 (int) (uchar) *pos != field_term_char))
3455 {
3456 char tmp_buff[2];
3457 tmp_buff[0]= ((int) (uchar) *pos == field_sep_char &&
3458 is_ambiguous_field_sep) ?
3459 field_sep_char : escape_char;
3460 tmp_buff[1]= *pos ? *pos : '0';
3461 if (my_b_write(&cache,(uchar*) start,(uint) (pos-start)) ||
3462 my_b_write(&cache,(uchar*) tmp_buff,2))
3463 goto err;
3464 start=pos+1;
3465 }
3466 }
3467 if (my_b_write(&cache,(uchar*) start,(uint) (pos-start)))
3468 goto err;
3469 }
3470 else if (my_b_write(&cache,(uchar*) res->ptr(),used_length))
3471 goto err;
3472 }
3473 if (fixed_row_size)
3474 { // Fill with space
3475 if (item->max_length > used_length)
3476 {
3477 if (!space_inited)
3478 {
3479 space_inited=1;
3480 bfill(space,sizeof(space),' ');
3481 }
3482 uint length=item->max_length-used_length;
3483 for (; length > sizeof(space) ; length-=sizeof(space))
3484 {
3485 if (my_b_write(&cache,(uchar*) space,sizeof(space)))
3486 goto err;
3487 }
3488 if (my_b_write(&cache,(uchar*) space,length))
3489 goto err;
3490 }
3491 }
3492 if (res && enclosed)
3493 {
3494 if (my_b_write(&cache, (uchar*) exchange->enclosed->ptr(),
3495 exchange->enclosed->length()))
3496 goto err;
3497 }
3498 if (--items_left)
3499 {
3500 if (my_b_write(&cache, (uchar*) exchange->field_term->ptr(),
3501 field_term_length))
3502 goto err;
3503 }
3504 }
3505 if (my_b_write(&cache,(uchar*) exchange->line_term->ptr(),
3506 exchange->line_term->length()))
3507 goto err;
3508 DBUG_RETURN(0);
3509err:
3510 DBUG_RETURN(1);
3511}
3512
3513
3514/***************************************************************************
3515** Dump of select to a binary file
3516***************************************************************************/
3517
3518
3519int
3520select_dump::prepare(List<Item> &list __attribute__((unused)),
3521 SELECT_LEX_UNIT *u)
3522{
3523 unit= u;
3524 return (int) ((file= create_file(thd, path, exchange, &cache)) < 0);
3525}
3526
3527
3528int select_dump::send_data(List<Item> &items)
3529{
3530 List_iterator_fast<Item> li(items);
3531 char buff[MAX_FIELD_WIDTH];
3532 String tmp(buff,sizeof(buff),&my_charset_bin),*res;
3533 tmp.length(0);
3534 Item *item;
3535 DBUG_ENTER("select_dump::send_data");
3536
3537 if (unit->offset_limit_cnt)
3538 { // using limit offset,count
3539 unit->offset_limit_cnt--;
3540 DBUG_RETURN(0);
3541 }
3542 if (thd->killed == ABORT_QUERY)
3543 DBUG_RETURN(0);
3544
3545 if (row_count++ > 1)
3546 {
3547 my_message(ER_TOO_MANY_ROWS, ER_THD(thd, ER_TOO_MANY_ROWS), MYF(0));
3548 goto err;
3549 }
3550 while ((item=li++))
3551 {
3552 res=item->str_result(&tmp);
3553 if (!res) // If NULL
3554 {
3555 if (my_b_write(&cache,(uchar*) "",1))
3556 goto err;
3557 }
3558 else if (my_b_write(&cache,(uchar*) res->ptr(),res->length()))
3559 {
3560 my_error(ER_ERROR_ON_WRITE, MYF(0), path, my_errno);
3561 goto err;
3562 }
3563 }
3564 DBUG_RETURN(0);
3565err:
3566 DBUG_RETURN(1);
3567}
3568
3569
3570int select_singlerow_subselect::send_data(List<Item> &items)
3571{
3572 DBUG_ENTER("select_singlerow_subselect::send_data");
3573 Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
3574 if (it->assigned())
3575 {
3576 my_message(ER_SUBQUERY_NO_1_ROW, ER_THD(thd, ER_SUBQUERY_NO_1_ROW),
3577 MYF(current_thd->lex->ignore ? ME_JUST_WARNING : 0));
3578 DBUG_RETURN(1);
3579 }
3580 if (unit->offset_limit_cnt)
3581 { // Using limit offset,count
3582 unit->offset_limit_cnt--;
3583 DBUG_RETURN(0);
3584 }
3585 if (thd->killed == ABORT_QUERY)
3586 DBUG_RETURN(0);
3587 List_iterator_fast<Item> li(items);
3588 Item *val_item;
3589 for (uint i= 0; (val_item= li++); i++)
3590 it->store(i, val_item);
3591 it->assigned(1);
3592 DBUG_RETURN(0);
3593}
3594
3595
3596void select_max_min_finder_subselect::cleanup()
3597{
3598 DBUG_ENTER("select_max_min_finder_subselect::cleanup");
3599 cache= 0;
3600 DBUG_VOID_RETURN;
3601}
3602
3603
3604int select_max_min_finder_subselect::send_data(List<Item> &items)
3605{
3606 DBUG_ENTER("select_max_min_finder_subselect::send_data");
3607 Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
3608 List_iterator_fast<Item> li(items);
3609 Item *val_item= li++;
3610 it->register_value();
3611 if (it->assigned())
3612 {
3613 cache->store(val_item);
3614 if ((this->*op)())
3615 it->store(0, cache);
3616 }
3617 else
3618 {
3619 if (!cache)
3620 {
3621 cache= val_item->get_cache(thd);
3622 switch (val_item->result_type()) {
3623 case REAL_RESULT:
3624 op= &select_max_min_finder_subselect::cmp_real;
3625 break;
3626 case INT_RESULT:
3627 op= &select_max_min_finder_subselect::cmp_int;
3628 break;
3629 case STRING_RESULT:
3630 op= &select_max_min_finder_subselect::cmp_str;
3631 break;
3632 case DECIMAL_RESULT:
3633 op= &select_max_min_finder_subselect::cmp_decimal;
3634 break;
3635 case ROW_RESULT:
3636 case TIME_RESULT:
3637 // This case should never be choosen
3638 DBUG_ASSERT(0);
3639 op= 0;
3640 }
3641 }
3642 cache->store(val_item);
3643 it->store(0, cache);
3644 }
3645 it->assigned(1);
3646 DBUG_RETURN(0);
3647}
3648
3649bool select_max_min_finder_subselect::cmp_real()
3650{
3651 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3652 double val1= cache->val_real(), val2= maxmin->val_real();
3653
3654 /* Ignore NULLs for ANY and keep them for ALL subqueries */
3655 if (cache->null_value)
3656 return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
3657 if (maxmin->null_value)
3658 return !is_all;
3659
3660 if (fmax)
3661 return(val1 > val2);
3662 return (val1 < val2);
3663}
3664
3665bool select_max_min_finder_subselect::cmp_int()
3666{
3667 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3668 longlong val1= cache->val_int(), val2= maxmin->val_int();
3669
3670 /* Ignore NULLs for ANY and keep them for ALL subqueries */
3671 if (cache->null_value)
3672 return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
3673 if (maxmin->null_value)
3674 return !is_all;
3675
3676 if (fmax)
3677 return(val1 > val2);
3678 return (val1 < val2);
3679}
3680
3681bool select_max_min_finder_subselect::cmp_decimal()
3682{
3683 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3684 my_decimal cval, *cvalue= cache->val_decimal(&cval);
3685 my_decimal mval, *mvalue= maxmin->val_decimal(&mval);
3686
3687 /* Ignore NULLs for ANY and keep them for ALL subqueries */
3688 if (cache->null_value)
3689 return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
3690 if (maxmin->null_value)
3691 return !is_all;
3692
3693 if (fmax)
3694 return (my_decimal_cmp(cvalue, mvalue) > 0) ;
3695 return (my_decimal_cmp(cvalue,mvalue) < 0);
3696}
3697
3698bool select_max_min_finder_subselect::cmp_str()
3699{
3700 String *val1, *val2, buf1, buf2;
3701 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
3702 /*
3703 as far as both operand is Item_cache buf1 & buf2 will not be used,
3704 but added for safety
3705 */
3706 val1= cache->val_str(&buf1);
3707 val2= maxmin->val_str(&buf1);
3708
3709 /* Ignore NULLs for ANY and keep them for ALL subqueries */
3710 if (cache->null_value)
3711 return (is_all && !maxmin->null_value) || (!is_all && maxmin->null_value);
3712 if (maxmin->null_value)
3713 return !is_all;
3714
3715 if (fmax)
3716 return (sortcmp(val1, val2, cache->collation.collation) > 0) ;
3717 return (sortcmp(val1, val2, cache->collation.collation) < 0);
3718}
3719
3720int select_exists_subselect::send_data(List<Item> &items)
3721{
3722 DBUG_ENTER("select_exists_subselect::send_data");
3723 Item_exists_subselect *it= (Item_exists_subselect *)item;
3724 if (unit->offset_limit_cnt)
3725 { // Using limit offset,count
3726 unit->offset_limit_cnt--;
3727 DBUG_RETURN(0);
3728 }
3729 if (thd->killed == ABORT_QUERY)
3730 DBUG_RETURN(0);
3731 it->value= 1;
3732 it->assigned(1);
3733 DBUG_RETURN(0);
3734}
3735
3736
3737/***************************************************************************
3738 Dump of select to variables
3739***************************************************************************/
3740
3741int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
3742{
3743 my_var_sp *mvsp;
3744 unit= u;
3745 m_var_sp_row= NULL;
3746
3747 if (var_list.elements == 1 &&
3748 (mvsp= var_list.head()->get_my_var_sp()) &&
3749 mvsp->type_handler() == &type_handler_row)
3750 {
3751 // SELECT INTO row_type_sp_variable
3752 if (mvsp->get_rcontext(thd->spcont)->get_variable(mvsp->offset)->cols() !=
3753 list.elements)
3754 goto error;
3755 m_var_sp_row= mvsp;
3756 return 0;
3757 }
3758
3759 // SELECT INTO variable list
3760 if (var_list.elements == list.elements)
3761 return 0;
3762
3763error:
3764 my_message(ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT,
3765 ER_THD(thd, ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT), MYF(0));
3766 return 1;
3767}
3768
3769
3770bool select_dumpvar::check_simple_select() const
3771{
3772 my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0));
3773 return TRUE;
3774}
3775
3776
3777void select_dumpvar::cleanup()
3778{
3779 row_count= 0;
3780}
3781
3782
3783Query_arena::Type Query_arena::type() const
3784{
3785 DBUG_ASSERT(0); /* Should never be called */
3786 return STATEMENT;
3787}
3788
3789
3790void Query_arena::free_items()
3791{
3792 Item *next;
3793 DBUG_ENTER("Query_arena::free_items");
3794 /* This works because items are allocated on THD::mem_root */
3795 for (; free_list; free_list= next)
3796 {
3797 next= free_list->next;
3798 DBUG_ASSERT(free_list != next);
3799 DBUG_PRINT("info", ("free item: %p", free_list));
3800 free_list->delete_self();
3801 }
3802 /* Postcondition: free_list is 0 */
3803 DBUG_VOID_RETURN;
3804}
3805
3806
3807void Query_arena::set_query_arena(Query_arena *set)
3808{
3809 mem_root= set->mem_root;
3810 free_list= set->free_list;
3811 state= set->state;
3812 is_stored_procedure= set->is_stored_procedure;
3813}
3814
3815
3816void Query_arena::cleanup_stmt()
3817{
3818 DBUG_ASSERT(! "Query_arena::cleanup_stmt() not implemented");
3819}
3820
3821/*
3822 Statement functions
3823*/
3824
3825Statement::Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
3826 enum enum_state state_arg, ulong id_arg)
3827 :Query_arena(mem_root_arg, state_arg),
3828 id(id_arg),
3829 column_usage(MARK_COLUMNS_READ),
3830 lex(lex_arg),
3831 db(null_clex_str)
3832{
3833 name= null_clex_str;
3834}
3835
3836
3837Query_arena::Type Statement::type() const
3838{
3839 return STATEMENT;
3840}
3841
3842
3843void Statement::set_statement(Statement *stmt)
3844{
3845 id= stmt->id;
3846 column_usage= stmt->column_usage;
3847 lex= stmt->lex;
3848 query_string= stmt->query_string;
3849}
3850
3851
3852void
3853Statement::set_n_backup_statement(Statement *stmt, Statement *backup)
3854{
3855 DBUG_ENTER("Statement::set_n_backup_statement");
3856 backup->set_statement(this);
3857 set_statement(stmt);
3858 DBUG_VOID_RETURN;
3859}
3860
3861
3862void Statement::restore_backup_statement(Statement *stmt, Statement *backup)
3863{
3864 DBUG_ENTER("Statement::restore_backup_statement");
3865 stmt->set_statement(this);
3866 set_statement(backup);
3867 DBUG_VOID_RETURN;
3868}
3869
3870
3871void THD::end_statement()
3872{
3873 DBUG_ENTER("THD::end_statement");
3874 /* Cleanup SQL processing state to reuse this statement in next query. */
3875 lex_end(lex);
3876 delete lex->result;
3877 lex->result= 0;
3878 /* Note that free_list is freed in cleanup_after_query() */
3879
3880 /*
3881 Don't free mem_root, as mem_root is freed in the end of dispatch_command
3882 (once for any command).
3883 */
3884 DBUG_VOID_RETURN;
3885}
3886
3887
3888/*
3889 Start using arena specified by @set. Current arena data will be saved to
3890 *backup.
3891*/
3892void THD::set_n_backup_active_arena(Query_arena *set, Query_arena *backup)
3893{
3894 DBUG_ENTER("THD::set_n_backup_active_arena");
3895 DBUG_ASSERT(backup->is_backup_arena == FALSE);
3896
3897 backup->set_query_arena(this);
3898 set_query_arena(set);
3899#ifdef DBUG_ASSERT_EXISTS
3900 backup->is_backup_arena= TRUE;
3901#endif
3902 DBUG_VOID_RETURN;
3903}
3904
3905
3906/*
3907 Stop using the temporary arena, and start again using the arena that is
3908 specified in *backup.
3909 The temporary arena is returned back into *set.
3910*/
3911
3912void THD::restore_active_arena(Query_arena *set, Query_arena *backup)
3913{
3914 DBUG_ENTER("THD::restore_active_arena");
3915 DBUG_ASSERT(backup->is_backup_arena);
3916 set->set_query_arena(this);
3917 set_query_arena(backup);
3918#ifdef DBUG_ASSERT_EXISTS
3919 backup->is_backup_arena= FALSE;
3920#endif
3921 DBUG_VOID_RETURN;
3922}
3923
3924Statement::~Statement()
3925{
3926}
3927
3928C_MODE_START
3929
3930static uchar *
3931get_statement_id_as_hash_key(const uchar *record, size_t *key_length,
3932 my_bool not_used __attribute__((unused)))
3933{
3934 const Statement *statement= (const Statement *) record;
3935 *key_length= sizeof(statement->id);
3936 return (uchar *) &((const Statement *) statement)->id;
3937}
3938
3939static void delete_statement_as_hash_key(void *key)
3940{
3941 delete (Statement *) key;
3942}
3943
3944static uchar *get_stmt_name_hash_key(Statement *entry, size_t *length,
3945 my_bool not_used __attribute__((unused)))
3946{
3947 *length= entry->name.length;
3948 return (uchar*) entry->name.str;
3949}
3950
3951C_MODE_END
3952
3953Statement_map::Statement_map() :
3954 last_found_statement(0)
3955{
3956 enum
3957 {
3958 START_STMT_HASH_SIZE = 16,
3959 START_NAME_HASH_SIZE = 16
3960 };
3961 my_hash_init(&st_hash, &my_charset_bin, START_STMT_HASH_SIZE, 0, 0,
3962 get_statement_id_as_hash_key,
3963 delete_statement_as_hash_key, MYF(0));
3964 my_hash_init(&names_hash, system_charset_info, START_NAME_HASH_SIZE, 0, 0,
3965 (my_hash_get_key) get_stmt_name_hash_key,
3966 NULL,MYF(0));
3967}
3968
3969
3970/*
3971 Insert a new statement to the thread-local statement map.
3972
3973 DESCRIPTION
3974 If there was an old statement with the same name, replace it with the
3975 new one. Otherwise, check if max_prepared_stmt_count is not reached yet,
3976 increase prepared_stmt_count, and insert the new statement. It's okay
3977 to delete an old statement and fail to insert the new one.
3978
3979 POSTCONDITIONS
3980 All named prepared statements are also present in names_hash.
3981 Statement names in names_hash are unique.
3982 The statement is added only if prepared_stmt_count < max_prepard_stmt_count
3983 last_found_statement always points to a valid statement or is 0
3984
3985 RETURN VALUE
3986 0 success
3987 1 error: out of resources or max_prepared_stmt_count limit has been
3988 reached. An error is sent to the client, the statement is deleted.
3989*/
3990
3991int Statement_map::insert(THD *thd, Statement *statement)
3992{
3993 if (my_hash_insert(&st_hash, (uchar*) statement))
3994 {
3995 /*
3996 Delete is needed only in case of an insert failure. In all other
3997 cases hash_delete will also delete the statement.
3998 */
3999 delete statement;
4000 my_error(ER_OUT_OF_RESOURCES, MYF(0));
4001 goto err_st_hash;
4002 }
4003 if (statement->name.str && my_hash_insert(&names_hash, (uchar*) statement))
4004 {
4005 my_error(ER_OUT_OF_RESOURCES, MYF(0));
4006 goto err_names_hash;
4007 }
4008 mysql_mutex_lock(&LOCK_prepared_stmt_count);
4009 /*
4010 We don't check that prepared_stmt_count is <= max_prepared_stmt_count
4011 because we would like to allow to lower the total limit
4012 of prepared statements below the current count. In that case
4013 no new statements can be added until prepared_stmt_count drops below
4014 the limit.
4015 */
4016 if (prepared_stmt_count >= max_prepared_stmt_count)
4017 {
4018 mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4019 my_error(ER_MAX_PREPARED_STMT_COUNT_REACHED, MYF(0),
4020 max_prepared_stmt_count);
4021 goto err_max;
4022 }
4023 prepared_stmt_count++;
4024 mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4025
4026 last_found_statement= statement;
4027 return 0;
4028
4029err_max:
4030 if (statement->name.str)
4031 my_hash_delete(&names_hash, (uchar*) statement);
4032err_names_hash:
4033 my_hash_delete(&st_hash, (uchar*) statement);
4034err_st_hash:
4035 return 1;
4036}
4037
4038
4039void Statement_map::close_transient_cursors()
4040{
4041#ifdef TO_BE_IMPLEMENTED
4042 Statement *stmt;
4043 while ((stmt= transient_cursor_list.head()))
4044 stmt->close_cursor(); /* deletes itself from the list */
4045#endif
4046}
4047
4048
4049void Statement_map::erase(Statement *statement)
4050{
4051 if (statement == last_found_statement)
4052 last_found_statement= 0;
4053 if (statement->name.str)
4054 my_hash_delete(&names_hash, (uchar *) statement);
4055
4056 my_hash_delete(&st_hash, (uchar *) statement);
4057 mysql_mutex_lock(&LOCK_prepared_stmt_count);
4058 DBUG_ASSERT(prepared_stmt_count > 0);
4059 prepared_stmt_count--;
4060 mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4061}
4062
4063
4064void Statement_map::reset()
4065{
4066 /* Must be first, hash_free will reset st_hash.records */
4067 mysql_mutex_lock(&LOCK_prepared_stmt_count);
4068 DBUG_ASSERT(prepared_stmt_count >= st_hash.records);
4069 prepared_stmt_count-= st_hash.records;
4070 mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4071
4072 my_hash_reset(&names_hash);
4073 my_hash_reset(&st_hash);
4074 last_found_statement= 0;
4075}
4076
4077
4078Statement_map::~Statement_map()
4079{
4080 /* Must go first, hash_free will reset st_hash.records */
4081 mysql_mutex_lock(&LOCK_prepared_stmt_count);
4082 DBUG_ASSERT(prepared_stmt_count >= st_hash.records);
4083 prepared_stmt_count-= st_hash.records;
4084 mysql_mutex_unlock(&LOCK_prepared_stmt_count);
4085
4086 my_hash_free(&names_hash);
4087 my_hash_free(&st_hash);
4088}
4089
4090bool my_var_user::set(THD *thd, Item *item)
4091{
4092 Item_func_set_user_var *suv= new (thd->mem_root) Item_func_set_user_var(thd, &name, item);
4093 suv->save_item_result(item);
4094 return suv->fix_fields(thd, 0) || suv->update();
4095}
4096
4097
4098sp_rcontext *my_var_sp::get_rcontext(sp_rcontext *local_ctx) const
4099{
4100 return m_rcontext_handler->get_rcontext(local_ctx);
4101}
4102
4103
4104bool my_var_sp::set(THD *thd, Item *item)
4105{
4106 return get_rcontext(thd->spcont)->set_variable(thd, offset, &item);
4107}
4108
4109bool my_var_sp_row_field::set(THD *thd, Item *item)
4110{
4111 return get_rcontext(thd->spcont)->
4112 set_variable_row_field(thd, offset, m_field_offset, &item);
4113}
4114
4115
4116bool select_dumpvar::send_data_to_var_list(List<Item> &items)
4117{
4118 DBUG_ENTER("select_dumpvar::send_data_to_var_list");
4119 List_iterator_fast<my_var> var_li(var_list);
4120 List_iterator<Item> it(items);
4121 Item *item;
4122 my_var *mv;
4123 while ((mv= var_li++) && (item= it++))
4124 {
4125 if (mv->set(thd, item))
4126 DBUG_RETURN(true);
4127 }
4128 DBUG_RETURN(false);
4129}
4130
4131
4132int select_dumpvar::send_data(List<Item> &items)
4133{
4134 DBUG_ENTER("select_dumpvar::send_data");
4135
4136 if (unit->offset_limit_cnt)
4137 { // using limit offset,count
4138 unit->offset_limit_cnt--;
4139 DBUG_RETURN(0);
4140 }
4141 if (row_count++)
4142 {
4143 my_message(ER_TOO_MANY_ROWS, ER_THD(thd, ER_TOO_MANY_ROWS), MYF(0));
4144 DBUG_RETURN(1);
4145 }
4146 if (m_var_sp_row ?
4147 m_var_sp_row->get_rcontext(thd->spcont)->
4148 set_variable_row(thd, m_var_sp_row->offset, items) :
4149 send_data_to_var_list(items))
4150 DBUG_RETURN(1);
4151
4152 DBUG_RETURN(thd->is_error());
4153}
4154
4155bool select_dumpvar::send_eof()
4156{
4157 if (! row_count)
4158 push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
4159 ER_SP_FETCH_NO_DATA, ER_THD(thd, ER_SP_FETCH_NO_DATA));
4160 /*
4161 Don't send EOF if we're in error condition (which implies we've already
4162 sent or are sending an error)
4163 */
4164 if (unlikely(thd->is_error()))
4165 return true;
4166
4167 if (!suppress_my_ok)
4168 ::my_ok(thd,row_count);
4169
4170 return 0;
4171}
4172
4173
4174
4175bool
4176select_materialize_with_stats::
4177create_result_table(THD *thd_arg, List<Item> *column_types,
4178 bool is_union_distinct, ulonglong options,
4179 const LEX_CSTRING *table_alias, bool bit_fields_as_long,
4180 bool create_table,
4181 bool keep_row_order,
4182 uint hidden)
4183{
4184 DBUG_ASSERT(table == 0);
4185 tmp_table_param.field_count= column_types->elements;
4186 tmp_table_param.bit_fields_as_long= bit_fields_as_long;
4187
4188 if (! (table= create_tmp_table(thd_arg, &tmp_table_param, *column_types,
4189 (ORDER*) 0, is_union_distinct, 1,
4190 options, HA_POS_ERROR, table_alias,
4191 !create_table, keep_row_order)))
4192 return TRUE;
4193
4194 col_stat= (Column_statistics*) table->in_use->alloc(table->s->fields *
4195 sizeof(Column_statistics));
4196 if (!col_stat)
4197 return TRUE;
4198
4199 reset();
4200 table->file->extra(HA_EXTRA_WRITE_CACHE);
4201 table->file->extra(HA_EXTRA_IGNORE_DUP_KEY);
4202 return FALSE;
4203}
4204
4205
4206void select_materialize_with_stats::reset()
4207{
4208 memset(col_stat, 0, table->s->fields * sizeof(Column_statistics));
4209 max_nulls_in_row= 0;
4210 count_rows= 0;
4211}
4212
4213
4214void select_materialize_with_stats::cleanup()
4215{
4216 reset();
4217 select_unit::cleanup();
4218}
4219
4220
4221/**
4222 Override select_unit::send_data to analyze each row for NULLs and to
4223 update null_statistics before sending data to the client.
4224
4225 @return TRUE if fatal error when sending data to the client
4226 @return FALSE on success
4227*/
4228
4229int select_materialize_with_stats::send_data(List<Item> &items)
4230{
4231 List_iterator_fast<Item> item_it(items);
4232 Item *cur_item;
4233 Column_statistics *cur_col_stat= col_stat;
4234 uint nulls_in_row= 0;
4235 int res;
4236
4237 if ((res= select_unit::send_data(items)))
4238 return res;
4239 if (table->null_catch_flags & REJECT_ROW_DUE_TO_NULL_FIELDS)
4240 {
4241 table->null_catch_flags&= ~REJECT_ROW_DUE_TO_NULL_FIELDS;
4242 return 0;
4243 }
4244 /* Skip duplicate rows. */
4245 if (write_err == HA_ERR_FOUND_DUPP_KEY ||
4246 write_err == HA_ERR_FOUND_DUPP_UNIQUE)
4247 return 0;
4248
4249 ++count_rows;
4250
4251 while ((cur_item= item_it++))
4252 {
4253 if (cur_item->is_null_result())
4254 {
4255 ++cur_col_stat->null_count;
4256 cur_col_stat->max_null_row= count_rows;
4257 if (!cur_col_stat->min_null_row)
4258 cur_col_stat->min_null_row= count_rows;
4259 ++nulls_in_row;
4260 }
4261 ++cur_col_stat;
4262 }
4263 if (nulls_in_row > max_nulls_in_row)
4264 max_nulls_in_row= nulls_in_row;
4265
4266 return 0;
4267}
4268
4269
4270/****************************************************************************
4271 TMP_TABLE_PARAM
4272****************************************************************************/
4273
4274void TMP_TABLE_PARAM::init()
4275{
4276 DBUG_ENTER("TMP_TABLE_PARAM::init");
4277 DBUG_PRINT("enter", ("this: %p", this));
4278 field_count= sum_func_count= func_count= hidden_field_count= 0;
4279 group_parts= group_length= group_null_parts= 0;
4280 quick_group= 1;
4281 table_charset= 0;
4282 precomputed_group_by= 0;
4283 bit_fields_as_long= 0;
4284 materialized_subquery= 0;
4285 force_not_null_cols= 0;
4286 skip_create_table= 0;
4287 DBUG_VOID_RETURN;
4288}
4289
4290
4291void thd_increment_bytes_sent(void *thd, size_t length)
4292{
4293 /* thd == 0 when close_connection() calls net_send_error() */
4294 if (likely(thd != 0))
4295 {
4296 ((THD*) thd)->status_var.bytes_sent+= length;
4297 }
4298}
4299
4300my_bool thd_net_is_killed(THD *thd)
4301{
4302 return thd && thd->killed ? 1 : 0;
4303}
4304
4305
4306void thd_increment_bytes_received(void *thd, size_t length)
4307{
4308 if (thd != NULL) // MDEV-13073 Ack collector having NULL
4309 ((THD*) thd)->status_var.bytes_received+= length;
4310}
4311
4312
4313void THD::set_status_var_init()
4314{
4315 bzero((char*) &status_var, offsetof(STATUS_VAR,
4316 last_cleared_system_status_var));
4317 /*
4318 Session status for Threads_running is always 1. It can only be queried
4319 by thread itself via INFORMATION_SCHEMA.SESSION_STATUS or SHOW [SESSION]
4320 STATUS. And at this point thread is guaranteed to be running.
4321 */
4322 status_var.threads_running= 1;
4323}
4324
4325
4326void Security_context::init()
4327{
4328 host= user= ip= external_user= 0;
4329 host_or_ip= "connecting host";
4330 priv_user[0]= priv_host[0]= proxy_user[0]= priv_role[0]= '\0';
4331 master_access= 0;
4332#ifndef NO_EMBEDDED_ACCESS_CHECKS
4333 db_access= NO_ACCESS;
4334#endif
4335}
4336
4337
4338void Security_context::destroy()
4339{
4340 DBUG_PRINT("info", ("freeing security context"));
4341 // If not pointer to constant
4342 if (host != my_localhost)
4343 {
4344 my_free((char*) host);
4345 host= NULL;
4346 }
4347 if (user != delayed_user)
4348 {
4349 my_free((char*) user);
4350 user= NULL;
4351 }
4352
4353 if (external_user)
4354 {
4355 my_free(external_user);
4356 external_user= NULL;
4357 }
4358
4359 my_free((char*) ip);
4360 ip= NULL;
4361}
4362
4363
4364void Security_context::skip_grants()
4365{
4366 /* privileges for the user are unknown everything is allowed */
4367 host_or_ip= (char *)"";
4368 master_access= ~NO_ACCESS;
4369 *priv_user= *priv_host= '\0';
4370}
4371
4372
4373bool Security_context::set_user(char *user_arg)
4374{
4375 my_free((char*) user);
4376 user= my_strdup(user_arg, MYF(0));
4377 return user == 0;
4378}
4379
4380#ifndef NO_EMBEDDED_ACCESS_CHECKS
4381/**
4382 Initialize this security context from the passed in credentials
4383 and activate it in the current thread.
4384
4385 @param thd
4386 @param definer_user
4387 @param definer_host
4388 @param db
4389 @param[out] backup Save a pointer to the current security context
4390 in the thread. In case of success it points to the
4391 saved old context, otherwise it points to NULL.
4392
4393
4394 During execution of a statement, multiple security contexts may
4395 be needed:
4396 - the security context of the authenticated user, used as the
4397 default security context for all top-level statements
4398 - in case of a view or a stored program, possibly the security
4399 context of the definer of the routine, if the object is
4400 defined with SQL SECURITY DEFINER option.
4401
4402 The currently "active" security context is parameterized in THD
4403 member security_ctx. By default, after a connection is
4404 established, this member points at the "main" security context
4405 - the credentials of the authenticated user.
4406
4407 Later, if we would like to execute some sub-statement or a part
4408 of a statement under credentials of a different user, e.g.
4409 definer of a procedure, we authenticate this user in a local
4410 instance of Security_context by means of this method (and
4411 ultimately by means of acl_getroot), and make the
4412 local instance active in the thread by re-setting
4413 thd->security_ctx pointer.
4414
4415 Note, that the life cycle and memory management of the "main" and
4416 temporary security contexts are different.
4417 For the main security context, the memory for user/host/ip is
4418 allocated on system heap, and the THD class frees this memory in
4419 its destructor. The only case when contents of the main security
4420 context may change during its life time is when someone issued
4421 CHANGE USER command.
4422 Memory management of a "temporary" security context is
4423 responsibility of the module that creates it.
4424
4425 @retval TRUE there is no user with the given credentials. The erro
4426 is reported in the thread.
4427 @retval FALSE success
4428*/
4429
4430bool
4431Security_context::
4432change_security_context(THD *thd,
4433 LEX_CSTRING *definer_user,
4434 LEX_CSTRING *definer_host,
4435 LEX_CSTRING *db,
4436 Security_context **backup)
4437{
4438 bool needs_change;
4439
4440 DBUG_ENTER("Security_context::change_security_context");
4441
4442 DBUG_ASSERT(definer_user->str && definer_host->str);
4443
4444 *backup= NULL;
4445 needs_change= (strcmp(definer_user->str, thd->security_ctx->priv_user) ||
4446 my_strcasecmp(system_charset_info, definer_host->str,
4447 thd->security_ctx->priv_host));
4448 if (needs_change)
4449 {
4450 if (acl_getroot(this, definer_user->str, definer_host->str,
4451 definer_host->str, db->str))
4452 {
4453 my_error(ER_NO_SUCH_USER, MYF(0), definer_user->str,
4454 definer_host->str);
4455 DBUG_RETURN(TRUE);
4456 }
4457 *backup= thd->security_ctx;
4458 thd->security_ctx= this;
4459 }
4460
4461 DBUG_RETURN(FALSE);
4462}
4463
4464
4465void
4466Security_context::restore_security_context(THD *thd,
4467 Security_context *backup)
4468{
4469 if (backup)
4470 thd->security_ctx= backup;
4471}
4472#endif
4473
4474
4475bool Security_context::user_matches(Security_context *them)
4476{
4477 return ((user != NULL) && (them->user != NULL) &&
4478 !strcmp(user, them->user));
4479}
4480
4481
4482/****************************************************************************
4483 Handling of open and locked tables states.
4484
4485 This is used when we want to open/lock (and then close) some tables when
4486 we already have a set of tables open and locked. We use these methods for
4487 access to mysql.proc table to find definitions of stored routines.
4488****************************************************************************/
4489
4490void THD::reset_n_backup_open_tables_state(Open_tables_backup *backup)
4491{
4492 DBUG_ENTER("reset_n_backup_open_tables_state");
4493 backup->set_open_tables_state(this);
4494 backup->mdl_system_tables_svp= mdl_context.mdl_savepoint();
4495 reset_open_tables_state(this);
4496 state_flags|= Open_tables_state::BACKUPS_AVAIL;
4497 DBUG_VOID_RETURN;
4498}
4499
4500
4501void THD::restore_backup_open_tables_state(Open_tables_backup *backup)
4502{
4503 DBUG_ENTER("restore_backup_open_tables_state");
4504 mdl_context.rollback_to_savepoint(backup->mdl_system_tables_svp);
4505 /*
4506 Before we will throw away current open tables state we want
4507 to be sure that it was properly cleaned up.
4508 */
4509 DBUG_ASSERT(open_tables == 0 &&
4510 temporary_tables == 0 &&
4511 derived_tables == 0 &&
4512 lock == 0 &&
4513 locked_tables_mode == LTM_NONE &&
4514 m_reprepare_observer == NULL);
4515
4516 set_open_tables_state(backup);
4517 DBUG_VOID_RETURN;
4518}
4519
4520#if MARIA_PLUGIN_INTERFACE_VERSION < 0x0200
4521/**
4522 This is a backward compatibility method, made obsolete
4523 by the thd_kill_statement service. Keep it here to avoid breaking the
4524 ABI in case some binary plugins still use it.
4525*/
4526#undef thd_killed
4527extern "C" int thd_killed(const MYSQL_THD thd)
4528{
4529 return thd_kill_level(thd) > THD_ABORT_SOFTLY;
4530}
4531#else
4532#error now thd_killed() function can go away
4533#endif
4534
4535/*
4536 return thd->killed status to the client,
4537 mapped to the API enum thd_kill_levels values.
4538
4539 @note Since this function is called quite frequently thd_kill_level(NULL) is
4540 forbidden for performance reasons (saves one conditional branch). If your ever
4541 need to call thd_kill_level() when THD is not available, you options are (most
4542 to least preferred):
4543 - try to pass THD through to thd_kill_level()
4544 - add current_thd to some service and use thd_killed(current_thd)
4545 - add thd_killed_current() function to kill statement service
4546 - add if (!thd) thd= current_thd here
4547*/
4548extern "C" enum thd_kill_levels thd_kill_level(const MYSQL_THD thd)
4549{
4550 DBUG_ASSERT(thd);
4551
4552 if (likely(thd->killed == NOT_KILLED))
4553 {
4554 Apc_target *apc_target= (Apc_target*) &thd->apc_target;
4555 if (unlikely(apc_target->have_apc_requests()))
4556 {
4557 if (thd == current_thd)
4558 apc_target->process_apc_requests();
4559 }
4560 return THD_IS_NOT_KILLED;
4561 }
4562
4563 return thd->killed & KILL_HARD_BIT ? THD_ABORT_ASAP : THD_ABORT_SOFTLY;
4564}
4565
4566
4567/**
4568 Send an out-of-band progress report to the client
4569
4570 The report is sent every 'thd->...progress_report_time' second,
4571 however not more often than global.progress_report_time.
4572 If global.progress_report_time is 0, then don't send progress reports, but
4573 check every second if the value has changed
4574
4575 We clear any errors that we get from sending the progress packet to
4576 the client as we don't want to set an error without the caller knowing
4577 about it.
4578*/
4579
4580static void thd_send_progress(THD *thd)
4581{
4582 /* Check if we should send the client a progress report */
4583 ulonglong report_time= my_interval_timer();
4584 if (report_time > thd->progress.next_report_time)
4585 {
4586 uint seconds_to_next= MY_MAX(thd->variables.progress_report_time,
4587 global_system_variables.progress_report_time);
4588 if (seconds_to_next == 0) // Turned off
4589 seconds_to_next= 1; // Check again after 1 second
4590
4591 thd->progress.next_report_time= (report_time +
4592 seconds_to_next * 1000000000ULL);
4593 if (global_system_variables.progress_report_time &&
4594 thd->variables.progress_report_time && !thd->is_error())
4595 {
4596 net_send_progress_packet(thd);
4597 if (thd->is_error())
4598 thd->clear_error();
4599 }
4600 }
4601}
4602
4603
4604/** Initialize progress report handling **/
4605
4606extern "C" void thd_progress_init(MYSQL_THD thd, uint max_stage)
4607{
4608 DBUG_ASSERT(thd->stmt_arena != thd->progress.arena);
4609 if (thd->progress.arena)
4610 return; // already initialized
4611 /*
4612 Send progress reports to clients that supports it, if the command
4613 is a high level command (like ALTER TABLE) and we are not in a
4614 stored procedure
4615 */
4616 thd->progress.report= ((thd->client_capabilities & MARIADB_CLIENT_PROGRESS) &&
4617 thd->progress.report_to_client &&
4618 !thd->in_sub_stmt);
4619 thd->progress.next_report_time= 0;
4620 thd->progress.stage= 0;
4621 thd->progress.counter= thd->progress.max_counter= 0;
4622 thd->progress.max_stage= max_stage;
4623 thd->progress.arena= thd->stmt_arena;
4624}
4625
4626
4627/* Inform processlist and the client that some progress has been made */
4628
4629extern "C" void thd_progress_report(MYSQL_THD thd,
4630 ulonglong progress, ulonglong max_progress)
4631{
4632 if (thd->stmt_arena != thd->progress.arena)
4633 return;
4634 if (thd->progress.max_counter != max_progress) // Simple optimization
4635 {
4636 mysql_mutex_lock(&thd->LOCK_thd_data);
4637 thd->progress.counter= progress;
4638 thd->progress.max_counter= max_progress;
4639 mysql_mutex_unlock(&thd->LOCK_thd_data);
4640 }
4641 else
4642 thd->progress.counter= progress;
4643
4644 if (thd->progress.report)
4645 thd_send_progress(thd);
4646}
4647
4648/**
4649 Move to next stage in process list handling
4650
4651 This will reset the timer to ensure the progress is sent to the client
4652 if client progress reports are activated.
4653*/
4654
4655extern "C" void thd_progress_next_stage(MYSQL_THD thd)
4656{
4657 if (thd->stmt_arena != thd->progress.arena)
4658 return;
4659 mysql_mutex_lock(&thd->LOCK_thd_data);
4660 thd->progress.stage++;
4661 thd->progress.counter= 0;
4662 DBUG_ASSERT(thd->progress.stage < thd->progress.max_stage);
4663 mysql_mutex_unlock(&thd->LOCK_thd_data);
4664 if (thd->progress.report)
4665 {
4666 thd->progress.next_report_time= 0; // Send new stage info
4667 thd_send_progress(thd);
4668 }
4669}
4670
4671/**
4672 Disable reporting of progress in process list.
4673
4674 @note
4675 This function is safe to call even if one has not called thd_progress_init.
4676
4677 This function should be called by all parts that does progress
4678 reporting to ensure that progress list doesn't contain 100 % done
4679 forever.
4680*/
4681
4682
4683extern "C" void thd_progress_end(MYSQL_THD thd)
4684{
4685 if (thd->stmt_arena != thd->progress.arena)
4686 return;
4687 /*
4688 It's enough to reset max_counter to set disable progress indicator
4689 in processlist.
4690 */
4691 thd->progress.max_counter= 0;
4692 thd->progress.arena= 0;
4693}
4694
4695
4696/**
4697 Return the thread id of a user thread
4698 @param thd user thread
4699 @return thread id
4700*/
4701extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd)
4702{
4703 return((unsigned long)thd->thread_id);
4704}
4705
4706/**
4707 Check if THD socket is still connected.
4708 */
4709extern "C" int thd_is_connected(MYSQL_THD thd)
4710{
4711 return thd->is_connected();
4712}
4713
4714
4715extern "C" double thd_rnd(MYSQL_THD thd)
4716{
4717 return my_rnd(&thd->rand);
4718}
4719
4720
4721/**
4722 Generate string of printable random characters of requested length.
4723
4724 @param to[out] Buffer for generation; must be at least length+1 bytes
4725 long; result string is always null-terminated
4726 @param length[in] How many random characters to put in buffer
4727*/
4728extern "C" void thd_create_random_password(MYSQL_THD thd,
4729 char *to, size_t length)
4730{
4731 for (char *end= to + length; to < end; to++)
4732 *to= (char) (my_rnd(&thd->rand)*94 + 33);
4733 *to= '\0';
4734}
4735
4736
4737#ifdef INNODB_COMPATIBILITY_HOOKS
4738
4739/** open a table and add it to thd->open_tables
4740
4741 @note At the moment this is used in innodb background purge threads
4742 *only*.There should be no table locks, because the background purge does not
4743 change the table as far as LOCK TABLES is concerned. MDL locks are
4744 still needed, though.
4745
4746 To make sure no table stays open for long, this helper allows the thread to
4747 have only one table open at any given time.
4748*/
4749TABLE *open_purge_table(THD *thd, const char *db, size_t dblen,
4750 const char *tb, size_t tblen)
4751{
4752 DBUG_ENTER("open_purge_table");
4753 DBUG_ASSERT(thd->open_tables == NULL);
4754 DBUG_ASSERT(thd->locked_tables_mode < LTM_PRELOCKED);
4755
4756 Open_table_context ot_ctx(thd, 0);
4757 TABLE_LIST *tl= (TABLE_LIST*)thd->alloc(sizeof(TABLE_LIST));
4758 LEX_CSTRING db_name= {db, dblen };
4759 LEX_CSTRING table_name= { tb, tblen };
4760
4761 tl->init_one_table(&db_name, &table_name, 0, TL_READ);
4762 tl->i_s_requested_object= OPEN_TABLE_ONLY;
4763
4764 bool error= open_table(thd, tl, &ot_ctx);
4765
4766 /* we don't recover here */
4767 DBUG_ASSERT(!error || !ot_ctx.can_recover_from_failed_open());
4768
4769 if (unlikely(error))
4770 close_thread_tables(thd);
4771
4772 DBUG_RETURN(error ? NULL : tl->table);
4773}
4774
4775TABLE *get_purge_table(THD *thd)
4776{
4777 /* see above, at most one table can be opened */
4778 DBUG_ASSERT(thd->open_tables == NULL || thd->open_tables->next == NULL);
4779 return thd->open_tables;
4780}
4781
4782
4783/** Find an open table in the list of prelocked tabled
4784
4785 Used for foreign key actions, for example, in UPDATE t1 SET a=1;
4786 where a child table t2 has a KB on t1.a.
4787
4788 But only when virtual columns are involved, otherwise InnoDB
4789 does not need an open TABLE.
4790*/
4791TABLE *find_fk_open_table(THD *thd, const char *db, size_t db_len,
4792 const char *table, size_t table_len)
4793{
4794 for (TABLE *t= thd->open_tables; t; t= t->next)
4795 {
4796 if (t->s->db.length == db_len && t->s->table_name.length == table_len &&
4797 !strcmp(t->s->db.str, db) && !strcmp(t->s->table_name.str, table) &&
4798 t->pos_in_table_list->prelocking_placeholder == TABLE_LIST::PRELOCK_FK)
4799 return t;
4800 }
4801 return NULL;
4802}
4803
4804/* the following three functions are used in background purge threads */
4805
4806MYSQL_THD create_thd()
4807{
4808 THD *thd= new THD(next_thread_id());
4809 thd->thread_stack= (char*) &thd;
4810 thd->store_globals();
4811 thd->set_command(COM_DAEMON);
4812 thd->system_thread= SYSTEM_THREAD_GENERIC;
4813 thd->security_ctx->host_or_ip="";
4814 add_to_active_threads(thd);
4815 return thd;
4816}
4817
4818void destroy_thd(MYSQL_THD thd)
4819{
4820 thd->add_status_to_global();
4821 unlink_not_visible_thd(thd);
4822 delete thd;
4823}
4824
4825void reset_thd(MYSQL_THD thd)
4826{
4827 close_thread_tables(thd);
4828 thd->mdl_context.release_transactional_locks();
4829 thd->free_items();
4830 free_root(thd->mem_root, MYF(MY_KEEP_PREALLOC));
4831}
4832
4833unsigned long long thd_get_query_id(const MYSQL_THD thd)
4834{
4835 return((unsigned long long)thd->query_id);
4836}
4837
4838extern "C" const struct charset_info_st *thd_charset(MYSQL_THD thd)
4839{
4840 return(thd->charset());
4841}
4842
4843
4844/**
4845 Get the current query string for the thread.
4846
4847 This function is not thread safe and can be used only by thd owner thread.
4848
4849 @param The MySQL internal thread pointer
4850 @return query string and length. May be non-null-terminated.
4851*/
4852extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd)
4853{
4854 DBUG_ASSERT(thd == current_thd);
4855 return(&thd->query_string.string);
4856}
4857
4858
4859/**
4860 Get the current query string for the thread.
4861
4862 @param thd The MySQL internal thread pointer
4863 @param buf Buffer where the query string will be copied
4864 @param buflen Length of the buffer
4865
4866 @return Length of the query
4867
4868 @note This function is thread safe as the query string is
4869 accessed under mutex protection and the string is copied
4870 into the provided buffer. @see thd_query_string().
4871*/
4872
4873extern "C" size_t thd_query_safe(MYSQL_THD thd, char *buf, size_t buflen)
4874{
4875 mysql_mutex_lock(&thd->LOCK_thd_data);
4876 size_t len= MY_MIN(buflen - 1, thd->query_length());
4877 memcpy(buf, thd->query(), len);
4878 mysql_mutex_unlock(&thd->LOCK_thd_data);
4879 buf[len]= '\0';
4880 return len;
4881}
4882
4883
4884extern "C" int thd_slave_thread(const MYSQL_THD thd)
4885{
4886 return(thd->slave_thread);
4887}
4888
4889/* Returns high resolution timestamp for the start
4890 of the current query. */
4891extern "C" unsigned long long thd_start_utime(const MYSQL_THD thd)
4892{
4893 return thd->start_time * 1000000 + thd->start_time_sec_part;
4894}
4895
4896
4897/*
4898 This function can optionally be called to check if thd_rpl_deadlock_check()
4899 needs to be called for waits done by a given transaction.
4900
4901 If this function returns false for a given thd, there is no need to do
4902 any calls to thd_rpl_deadlock_check() on that thd.
4903
4904 This call is optional; it is safe to call thd_rpl_deadlock_check() in
4905 any case. This call can be used to save some redundant calls to
4906 thd_rpl_deadlock_check() if desired. (This is unlikely to matter much
4907 unless there are _lots_ of waits to report, as the overhead of
4908 thd_rpl_deadlock_check() is small).
4909*/
4910extern "C" int
4911thd_need_wait_reports(const MYSQL_THD thd)
4912{
4913 rpl_group_info *rgi;
4914
4915 if (mysql_bin_log.is_open())
4916 return true;
4917 if (!thd)
4918 return false;
4919 rgi= thd->rgi_slave;
4920 if (!rgi)
4921 return false;
4922 return rgi->is_parallel_exec;
4923}
4924
4925/*
4926 Used by storage engines (currently TokuDB and InnoDB) to report that
4927 one transaction THD is about to go to wait for a transactional lock held by
4928 another transactions OTHER_THD.
4929
4930 This is used for parallel replication, where transactions are required to
4931 commit in the same order on the slave as they did on the master. If the
4932 transactions on the slave encounter lock conflicts on the slave that did not
4933 exist on the master, this can cause deadlocks. This is primarily used in
4934 optimistic (and aggressive) modes.
4935
4936 Normally, such conflicts will not occur in conservative mode, because the
4937 same conflict would have prevented the two transactions from committing in
4938 parallel on the master, thus preventing them from running in parallel on the
4939 slave in the first place. However, it is possible in case when the optimizer
4940 chooses a different plan on the slave than on the master (eg. table scan
4941 instead of index scan).
4942
4943 Storage engines report lock waits using this call. If a lock wait causes a
4944 deadlock with the pre-determined commit order, we kill the later
4945 transaction, and later re-try it, to resolve the deadlock.
4946
4947 This call need only receive reports about waits for locks that will remain
4948 until the holding transaction commits. InnoDB auto-increment locks,
4949 for example, are released earlier, and so need not be reported. (Such false
4950 positives are not harmful, but could lead to unnecessary kill and retry, so
4951 best avoided).
4952
4953 Returns 1 if the OTHER_THD will be killed to resolve deadlock, 0 if not. The
4954 actual kill will happen later, asynchronously from another thread. The
4955 caller does not need to take any actions on the return value if the
4956 handlerton kill_query method is implemented to abort the to-be-killed
4957 transaction.
4958*/
4959extern "C" int
4960thd_rpl_deadlock_check(MYSQL_THD thd, MYSQL_THD other_thd)
4961{
4962 rpl_group_info *rgi;
4963 rpl_group_info *other_rgi;
4964
4965 if (!thd)
4966 return 0;
4967 DEBUG_SYNC(thd, "thd_report_wait_for");
4968 thd->transaction.stmt.mark_trans_did_wait();
4969 if (!other_thd)
4970 return 0;
4971 binlog_report_wait_for(thd, other_thd);
4972 rgi= thd->rgi_slave;
4973 other_rgi= other_thd->rgi_slave;
4974 if (!rgi || !other_rgi)
4975 return 0;
4976 if (!rgi->is_parallel_exec)
4977 return 0;
4978 if (rgi->rli != other_rgi->rli)
4979 return 0;
4980 if (!rgi->gtid_sub_id || !other_rgi->gtid_sub_id)
4981 return 0;
4982 if (rgi->current_gtid.domain_id != other_rgi->current_gtid.domain_id)
4983 return 0;
4984 if (rgi->gtid_sub_id > other_rgi->gtid_sub_id)
4985 return 0;
4986 /*
4987 This transaction is about to wait for another transaction that is required
4988 by replication binlog order to commit after. This would cause a deadlock.
4989
4990 So send a kill to the other transaction, with a temporary error; this will
4991 cause replication to rollback (and later re-try) the other transaction,
4992 releasing the lock for this transaction so replication can proceed.
4993 */
4994#ifdef HAVE_REPLICATION
4995 slave_background_kill_request(other_thd);
4996#endif
4997 return 1;
4998}
4999
5000/*
5001 This function is called from InnoDB to check if the commit order of
5002 two transactions has already been decided by the upper layer. This happens
5003 in parallel replication, where the commit order is forced to be the same on
5004 the slave as it was originally on the master.
5005
5006 If this function returns false, it means that such commit order will be
5007 enforced. This allows the storage engine to optionally omit gap lock waits
5008 or similar measures that would otherwise be needed to ensure that
5009 transactions would be serialised in a way that would cause a commit order
5010 that is correct for binlogging for statement-based replication.
5011
5012 Since transactions are only run in parallel on the slave if they ran without
5013 lock conflicts on the master, normally no lock conflicts on the slave happen
5014 during parallel replication. However, there are a couple of corner cases
5015 where it can happen, like these secondary-index operations:
5016
5017 T1: INSERT INTO t1 VALUES (7, NULL);
5018 T2: DELETE FROM t1 WHERE b <= 3;
5019
5020 T1: UPDATE t1 SET secondary=NULL WHERE primary=1
5021 T2: DELETE t1 WHERE secondary <= 3
5022
5023 The DELETE takes a gap lock that can block the INSERT/UPDATE, but the row
5024 locks set by INSERT/UPDATE do not block the DELETE. Thus, the execution
5025 order of the transactions determine whether a lock conflict occurs or
5026 not. Thus a lock conflict can occur on the slave where it did not on the
5027 master.
5028
5029 If this function returns true, normal locking should be done as required by
5030 the binlogging and transaction isolation level in effect. But if it returns
5031 false, the correct order will be enforced anyway, and InnoDB can
5032 avoid taking the gap lock, preventing the lock conflict.
5033
5034 Calling this function is just an optimisation to avoid unnecessary
5035 deadlocks. If it was not used, a gap lock would be set that could eventually
5036 cause a deadlock; the deadlock would be caught by thd_rpl_deadlock_check()
5037 and the transaction T2 killed and rolled back (and later re-tried).
5038*/
5039extern "C" int
5040thd_need_ordering_with(const MYSQL_THD thd, const MYSQL_THD other_thd)
5041{
5042 rpl_group_info *rgi, *other_rgi;
5043
5044 DBUG_EXECUTE_IF("disable_thd_need_ordering_with", return 1;);
5045 if (!thd || !other_thd)
5046 return 1;
5047 rgi= thd->rgi_slave;
5048 other_rgi= other_thd->rgi_slave;
5049 if (!rgi || !other_rgi)
5050 return 1;
5051 if (!rgi->is_parallel_exec)
5052 return 1;
5053 if (rgi->rli != other_rgi->rli)
5054 return 1;
5055 if (rgi->current_gtid.domain_id != other_rgi->current_gtid.domain_id)
5056 return 1;
5057 if (!rgi->commit_id || rgi->commit_id != other_rgi->commit_id)
5058 return 1;
5059 DBUG_EXECUTE_IF("thd_need_ordering_with_force", return 1;);
5060 /*
5061 Otherwise, these two threads are doing parallel replication within the same
5062 replication domain. Their commit order is already fixed, so we do not need
5063 gap locks or similar to otherwise enforce ordering (and in fact such locks
5064 could lead to unnecessary deadlocks and transaction retry).
5065 */
5066 return 0;
5067}
5068
5069extern "C" int thd_non_transactional_update(const MYSQL_THD thd)
5070{
5071 return(thd->transaction.all.modified_non_trans_table);
5072}
5073
5074extern "C" int thd_binlog_format(const MYSQL_THD thd)
5075{
5076 if (WSREP(thd))
5077 {
5078 /* for wsrep binlog format is meaningful also when binlogging is off */
5079 return (int) thd->wsrep_binlog_format();
5080 }
5081 if (mysql_bin_log.is_open() && (thd->variables.option_bits & OPTION_BIN_LOG))
5082 return (int) thd->variables.binlog_format;
5083 return BINLOG_FORMAT_UNSPEC;
5084}
5085
5086extern "C" void thd_mark_transaction_to_rollback(MYSQL_THD thd, bool all)
5087{
5088 DBUG_ASSERT(thd);
5089 thd->mark_transaction_to_rollback(all);
5090}
5091
5092extern "C" bool thd_binlog_filter_ok(const MYSQL_THD thd)
5093{
5094 return binlog_filter->db_ok(thd->db.str);
5095}
5096
5097/*
5098 This is similar to sqlcom_can_generate_row_events, with the expection
5099 that we only return 1 if we are going to generate row events in a
5100 transaction.
5101 CREATE OR REPLACE is always safe to do as this will run in it's own
5102 transaction.
5103*/
5104
5105extern "C" bool thd_sqlcom_can_generate_row_events(const MYSQL_THD thd)
5106{
5107 return (sqlcom_can_generate_row_events(thd) && thd->lex->sql_command !=
5108 SQLCOM_CREATE_TABLE);
5109}
5110
5111
5112extern "C" enum durability_properties thd_get_durability_property(const MYSQL_THD thd)
5113{
5114 enum durability_properties ret= HA_REGULAR_DURABILITY;
5115
5116 if (thd != NULL)
5117 ret= thd->durability_property;
5118
5119 return ret;
5120}
5121
5122/** Get the auto_increment_offset auto_increment_increment.
5123Exposed by thd_autoinc_service.
5124Needed by InnoDB.
5125@param thd Thread object
5126@param off auto_increment_offset
5127@param inc auto_increment_increment */
5128extern "C" void thd_get_autoinc(const MYSQL_THD thd, ulong* off, ulong* inc)
5129{
5130 *off = thd->variables.auto_increment_offset;
5131 *inc = thd->variables.auto_increment_increment;
5132}
5133
5134
5135/**
5136 Is strict sql_mode set.
5137 Needed by InnoDB.
5138 @param thd Thread object
5139 @return True if sql_mode has strict mode (all or trans).
5140 @retval true sql_mode has strict mode (all or trans).
5141 @retval false sql_mode has not strict mode (all or trans).
5142*/
5143extern "C" bool thd_is_strict_mode(const MYSQL_THD thd)
5144{
5145 return thd->is_strict_mode();
5146}
5147
5148
5149/**
5150 Get query start time as SQL field data.
5151 Needed by InnoDB.
5152 @param thd Thread object
5153 @param buf Buffer to hold start time data
5154*/
5155void thd_get_query_start_data(THD *thd, char *buf)
5156{
5157 LEX_CSTRING field_name;
5158 Field_timestampf f((uchar *)buf, NULL, 0, Field::NONE, &field_name, NULL, 6);
5159 f.store_TIME(thd->query_start(), thd->query_start_sec_part());
5160}
5161
5162
5163/*
5164 Interface for MySQL Server, plugins and storage engines to report
5165 when they are going to sleep/stall.
5166
5167 SYNOPSIS
5168 thd_wait_begin()
5169 thd Thread object
5170 Can be NULL, in this case current THD is used.
5171 wait_type Type of wait
5172 1 -- short wait (e.g. for mutex)
5173 2 -- medium wait (e.g. for disk io)
5174 3 -- large wait (e.g. for locked row/table)
5175 NOTES
5176 This is used by the threadpool to have better knowledge of which
5177 threads that currently are actively running on CPUs. When a thread
5178 reports that it's going to sleep/stall, the threadpool scheduler is
5179 free to start another thread in the pool most likely. The expected wait
5180 time is simply an indication of how long the wait is expected to
5181 become, the real wait time could be very different.
5182
5183 thd_wait_end MUST be called immediately after waking up again.
5184*/
5185extern "C" void thd_wait_begin(MYSQL_THD thd, int wait_type)
5186{
5187 if (!thd)
5188 {
5189 thd= current_thd;
5190 if (unlikely(!thd))
5191 return;
5192 }
5193 MYSQL_CALLBACK(thd->scheduler, thd_wait_begin, (thd, wait_type));
5194}
5195
5196/**
5197 Interface for MySQL Server, plugins and storage engines to report
5198 when they waking up from a sleep/stall.
5199
5200 @param thd Thread handle
5201 Can be NULL, in this case current THD is used.
5202*/
5203extern "C" void thd_wait_end(MYSQL_THD thd)
5204{
5205 if (!thd)
5206 {
5207 thd= current_thd;
5208 if (unlikely(!thd))
5209 return;
5210 }
5211 MYSQL_CALLBACK(thd->scheduler, thd_wait_end, (thd));
5212}
5213
5214#endif // INNODB_COMPATIBILITY_HOOKS */
5215
5216/****************************************************************************
5217 Handling of statement states in functions and triggers.
5218
5219 This is used to ensure that the function/trigger gets a clean state
5220 to work with and does not cause any side effects of the calling statement.
5221
5222 It also allows most stored functions and triggers to replicate even
5223 if they are used items that would normally be stored in the binary
5224 replication (like last_insert_id() etc...)
5225
5226 The following things is done
5227 - Disable binary logging for the duration of the statement
5228 - Disable multi-result-sets for the duration of the statement
5229 - Value of last_insert_id() is saved and restored
5230 - Value set by 'SET INSERT_ID=#' is reset and restored
5231 - Value for found_rows() is reset and restored
5232 - examined_row_count is added to the total
5233 - cuted_fields is added to the total
5234 - new savepoint level is created and destroyed
5235
5236 NOTES:
5237 Seed for random() is saved for the first! usage of RAND()
5238 We reset examined_row_count and cuted_fields and add these to the
5239 result to ensure that if we have a bug that would reset these within
5240 a function, we are not loosing any rows from the main statement.
5241
5242 We do not reset value of last_insert_id().
5243****************************************************************************/
5244
5245void THD::reset_sub_statement_state(Sub_statement_state *backup,
5246 uint new_state)
5247{
5248#ifndef EMBEDDED_LIBRARY
5249 /* BUG#33029, if we are replicating from a buggy master, reset
5250 auto_inc_intervals_forced to prevent substatement
5251 (triggers/functions) from using erroneous INSERT_ID value
5252 */
5253 if (rpl_master_erroneous_autoinc(this))
5254 {
5255 DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0);
5256 auto_inc_intervals_forced.swap(&backup->auto_inc_intervals_forced);
5257 }
5258#endif
5259
5260 backup->option_bits= variables.option_bits;
5261 backup->count_cuted_fields= count_cuted_fields;
5262 backup->in_sub_stmt= in_sub_stmt;
5263 backup->enable_slow_log= enable_slow_log;
5264 backup->limit_found_rows= limit_found_rows;
5265 backup->cuted_fields= cuted_fields;
5266 backup->client_capabilities= client_capabilities;
5267 backup->savepoints= transaction.savepoints;
5268 backup->first_successful_insert_id_in_prev_stmt=
5269 first_successful_insert_id_in_prev_stmt;
5270 backup->first_successful_insert_id_in_cur_stmt=
5271 first_successful_insert_id_in_cur_stmt;
5272 store_slow_query_state(backup);
5273
5274 if ((!lex->requires_prelocking() || is_update_query(lex->sql_command)) &&
5275 !is_current_stmt_binlog_format_row())
5276 {
5277 variables.option_bits&= ~OPTION_BIN_LOG;
5278 }
5279
5280 if ((backup->option_bits & OPTION_BIN_LOG) &&
5281 is_update_query(lex->sql_command) &&
5282 !is_current_stmt_binlog_format_row())
5283 mysql_bin_log.start_union_events(this, this->query_id);
5284
5285 /* Disable result sets */
5286 client_capabilities &= ~CLIENT_MULTI_RESULTS;
5287 in_sub_stmt|= new_state;
5288 cuted_fields= 0;
5289 transaction.savepoints= 0;
5290 first_successful_insert_id_in_cur_stmt= 0;
5291 reset_slow_query_state();
5292}
5293
5294void THD::restore_sub_statement_state(Sub_statement_state *backup)
5295{
5296 DBUG_ENTER("THD::restore_sub_statement_state");
5297#ifndef EMBEDDED_LIBRARY
5298 /* BUG#33029, if we are replicating from a buggy master, restore
5299 auto_inc_intervals_forced so that the top statement can use the
5300 INSERT_ID value set before this statement.
5301 */
5302 if (rpl_master_erroneous_autoinc(this))
5303 {
5304 backup->auto_inc_intervals_forced.swap(&auto_inc_intervals_forced);
5305 DBUG_ASSERT(backup->auto_inc_intervals_forced.nb_elements() == 0);
5306 }
5307#endif
5308
5309 /*
5310 To save resources we want to release savepoints which were created
5311 during execution of function or trigger before leaving their savepoint
5312 level. It is enough to release first savepoint set on this level since
5313 all later savepoints will be released automatically.
5314 */
5315 if (transaction.savepoints)
5316 {
5317 SAVEPOINT *sv;
5318 for (sv= transaction.savepoints; sv->prev; sv= sv->prev)
5319 {}
5320 /* ha_release_savepoint() never returns error. */
5321 (void)ha_release_savepoint(this, sv);
5322 }
5323 count_cuted_fields= backup->count_cuted_fields;
5324 transaction.savepoints= backup->savepoints;
5325 variables.option_bits= backup->option_bits;
5326 in_sub_stmt= backup->in_sub_stmt;
5327 enable_slow_log= backup->enable_slow_log;
5328 first_successful_insert_id_in_prev_stmt=
5329 backup->first_successful_insert_id_in_prev_stmt;
5330 first_successful_insert_id_in_cur_stmt=
5331 backup->first_successful_insert_id_in_cur_stmt;
5332 limit_found_rows= backup->limit_found_rows;
5333 set_sent_row_count(backup->sent_row_count);
5334 client_capabilities= backup->client_capabilities;
5335
5336 /* Restore statistic needed for slow log */
5337 add_slow_query_state(backup);
5338
5339 /*
5340 If we've left sub-statement mode, reset the fatal error flag.
5341 Otherwise keep the current value, to propagate it up the sub-statement
5342 stack.
5343
5344 NOTE: is_fatal_sub_stmt_error can be set only if we've been in the
5345 sub-statement mode.
5346 */
5347 if (!in_sub_stmt)
5348 is_fatal_sub_stmt_error= false;
5349
5350 if ((variables.option_bits & OPTION_BIN_LOG) && is_update_query(lex->sql_command) &&
5351 !is_current_stmt_binlog_format_row())
5352 mysql_bin_log.stop_union_events(this);
5353
5354 /*
5355 The following is added to the old values as we are interested in the
5356 total complexity of the query
5357 */
5358 inc_examined_row_count(backup->examined_row_count);
5359 cuted_fields+= backup->cuted_fields;
5360 DBUG_VOID_RETURN;
5361}
5362
5363/*
5364 Store slow query state at start of a stored procedure statment
5365*/
5366
5367void THD::store_slow_query_state(Sub_statement_state *backup)
5368{
5369 backup->affected_rows= affected_rows;
5370 backup->bytes_sent_old= bytes_sent_old;
5371 backup->examined_row_count= m_examined_row_count;
5372 backup->query_plan_flags= query_plan_flags;
5373 backup->query_plan_fsort_passes= query_plan_fsort_passes;
5374 backup->sent_row_count= m_sent_row_count;
5375 backup->tmp_tables_disk_used= tmp_tables_disk_used;
5376 backup->tmp_tables_size= tmp_tables_size;
5377 backup->tmp_tables_used= tmp_tables_used;
5378}
5379
5380/* Reset variables related to slow query log */
5381
5382void THD::reset_slow_query_state()
5383{
5384 affected_rows= 0;
5385 bytes_sent_old= status_var.bytes_sent;
5386 m_examined_row_count= 0;
5387 m_sent_row_count= 0;
5388 query_plan_flags= QPLAN_INIT;
5389 query_plan_fsort_passes= 0;
5390 tmp_tables_disk_used= 0;
5391 tmp_tables_size= 0;
5392 tmp_tables_used= 0;
5393}
5394
5395/*
5396 Add back the stored values to the current counters to be able to get
5397 right status for 'call procedure_name'
5398*/
5399
5400void THD::add_slow_query_state(Sub_statement_state *backup)
5401{
5402 affected_rows+= backup->affected_rows;
5403 bytes_sent_old= backup->bytes_sent_old;
5404 m_examined_row_count+= backup->examined_row_count;
5405 m_sent_row_count+= backup->sent_row_count;
5406 query_plan_flags|= backup->query_plan_flags;
5407 query_plan_fsort_passes+= backup->query_plan_fsort_passes;
5408 tmp_tables_disk_used+= backup->tmp_tables_disk_used;
5409 tmp_tables_size+= backup->tmp_tables_size;
5410 tmp_tables_used+= backup->tmp_tables_used;
5411}
5412
5413
5414void THD::set_statement(Statement *stmt)
5415{
5416 mysql_mutex_lock(&LOCK_thd_data);
5417 Statement::set_statement(stmt);
5418 mysql_mutex_unlock(&LOCK_thd_data);
5419}
5420
5421void THD::set_sent_row_count(ha_rows count)
5422{
5423 m_sent_row_count= count;
5424 MYSQL_SET_STATEMENT_ROWS_SENT(m_statement_psi, m_sent_row_count);
5425}
5426
5427void THD::set_examined_row_count(ha_rows count)
5428{
5429 m_examined_row_count= count;
5430 MYSQL_SET_STATEMENT_ROWS_EXAMINED(m_statement_psi, m_examined_row_count);
5431}
5432
5433void THD::inc_sent_row_count(ha_rows count)
5434{
5435 m_sent_row_count+= count;
5436 MYSQL_SET_STATEMENT_ROWS_SENT(m_statement_psi, m_sent_row_count);
5437}
5438
5439void THD::inc_examined_row_count(ha_rows count)
5440{
5441 m_examined_row_count+= count;
5442 MYSQL_SET_STATEMENT_ROWS_EXAMINED(m_statement_psi, m_examined_row_count);
5443}
5444
5445void THD::inc_status_created_tmp_disk_tables()
5446{
5447 tmp_tables_disk_used++;
5448 query_plan_flags|= QPLAN_TMP_DISK;
5449 status_var_increment(status_var.created_tmp_disk_tables_);
5450#ifdef HAVE_PSI_STATEMENT_INTERFACE
5451 PSI_STATEMENT_CALL(inc_statement_created_tmp_disk_tables)(m_statement_psi, 1);
5452#endif
5453}
5454
5455void THD::inc_status_created_tmp_tables()
5456{
5457 tmp_tables_used++;
5458 query_plan_flags|= QPLAN_TMP_TABLE;
5459 status_var_increment(status_var.created_tmp_tables_);
5460#ifdef HAVE_PSI_STATEMENT_INTERFACE
5461 PSI_STATEMENT_CALL(inc_statement_created_tmp_tables)(m_statement_psi, 1);
5462#endif
5463}
5464
5465void THD::inc_status_select_full_join()
5466{
5467 status_var_increment(status_var.select_full_join_count_);
5468#ifdef HAVE_PSI_STATEMENT_INTERFACE
5469 PSI_STATEMENT_CALL(inc_statement_select_full_join)(m_statement_psi, 1);
5470#endif
5471}
5472
5473void THD::inc_status_select_full_range_join()
5474{
5475 status_var_increment(status_var.select_full_range_join_count_);
5476#ifdef HAVE_PSI_STATEMENT_INTERFACE
5477 PSI_STATEMENT_CALL(inc_statement_select_full_range_join)(m_statement_psi, 1);
5478#endif
5479}
5480
5481void THD::inc_status_select_range()
5482{
5483 status_var_increment(status_var.select_range_count_);
5484#ifdef HAVE_PSI_STATEMENT_INTERFACE
5485 PSI_STATEMENT_CALL(inc_statement_select_range)(m_statement_psi, 1);
5486#endif
5487}
5488
5489void THD::inc_status_select_range_check()
5490{
5491 status_var_increment(status_var.select_range_check_count_);
5492#ifdef HAVE_PSI_STATEMENT_INTERFACE
5493 PSI_STATEMENT_CALL(inc_statement_select_range_check)(m_statement_psi, 1);
5494#endif
5495}
5496
5497void THD::inc_status_select_scan()
5498{
5499 status_var_increment(status_var.select_scan_count_);
5500#ifdef HAVE_PSI_STATEMENT_INTERFACE
5501 PSI_STATEMENT_CALL(inc_statement_select_scan)(m_statement_psi, 1);
5502#endif
5503}
5504
5505void THD::inc_status_sort_merge_passes()
5506{
5507 status_var_increment(status_var.filesort_merge_passes_);
5508#ifdef HAVE_PSI_STATEMENT_INTERFACE
5509 PSI_STATEMENT_CALL(inc_statement_sort_merge_passes)(m_statement_psi, 1);
5510#endif
5511}
5512
5513void THD::inc_status_sort_range()
5514{
5515 status_var_increment(status_var.filesort_range_count_);
5516#ifdef HAVE_PSI_STATEMENT_INTERFACE
5517 PSI_STATEMENT_CALL(inc_statement_sort_range)(m_statement_psi, 1);
5518#endif
5519}
5520
5521void THD::inc_status_sort_rows(ha_rows count)
5522{
5523 statistic_add(status_var.filesort_rows_, (ulong)count, &LOCK_status);
5524#ifdef HAVE_PSI_STATEMENT_INTERFACE
5525 PSI_STATEMENT_CALL(inc_statement_sort_rows)(m_statement_psi, (ulong)count);
5526#endif
5527}
5528
5529void THD::inc_status_sort_scan()
5530{
5531 status_var_increment(status_var.filesort_scan_count_);
5532#ifdef HAVE_PSI_STATEMENT_INTERFACE
5533 PSI_STATEMENT_CALL(inc_statement_sort_scan)(m_statement_psi, 1);
5534#endif
5535}
5536
5537void THD::set_status_no_index_used()
5538{
5539 server_status|= SERVER_QUERY_NO_INDEX_USED;
5540#ifdef HAVE_PSI_STATEMENT_INTERFACE
5541 PSI_STATEMENT_CALL(set_statement_no_index_used)(m_statement_psi);
5542#endif
5543}
5544
5545void THD::set_status_no_good_index_used()
5546{
5547 server_status|= SERVER_QUERY_NO_GOOD_INDEX_USED;
5548#ifdef HAVE_PSI_STATEMENT_INTERFACE
5549 PSI_STATEMENT_CALL(set_statement_no_good_index_used)(m_statement_psi);
5550#endif
5551}
5552
5553/** Assign a new value to thd->query and thd->query_id. */
5554
5555void THD::set_query_and_id(char *query_arg, uint32 query_length_arg,
5556 CHARSET_INFO *cs,
5557 query_id_t new_query_id)
5558{
5559 mysql_mutex_lock(&LOCK_thd_data);
5560 set_query_inner(query_arg, query_length_arg, cs);
5561 mysql_mutex_unlock(&LOCK_thd_data);
5562 query_id= new_query_id;
5563}
5564
5565/** Assign a new value to thd->mysys_var. */
5566void THD::set_mysys_var(struct st_my_thread_var *new_mysys_var)
5567{
5568 mysql_mutex_lock(&LOCK_thd_kill);
5569 mysys_var= new_mysys_var;
5570 mysql_mutex_unlock(&LOCK_thd_kill);
5571}
5572
5573/**
5574 Leave explicit LOCK TABLES or prelocked mode and restore value of
5575 transaction sentinel in MDL subsystem.
5576*/
5577
5578void THD::leave_locked_tables_mode()
5579{
5580 if (locked_tables_mode == LTM_LOCK_TABLES)
5581 {
5582 /*
5583 When leaving LOCK TABLES mode we have to change the duration of most
5584 of the metadata locks being held, except for HANDLER and GRL locks,
5585 to transactional for them to be properly released at UNLOCK TABLES.
5586 */
5587 mdl_context.set_transaction_duration_for_all_locks();
5588 /*
5589 Make sure we don't release the global read lock and commit blocker
5590 when leaving LTM.
5591 */
5592 global_read_lock.set_explicit_lock_duration(this);
5593 /* Also ensure that we don't release metadata locks for open HANDLERs. */
5594 if (handler_tables_hash.records)
5595 mysql_ha_set_explicit_lock_duration(this);
5596 if (ull_hash.records)
5597 mysql_ull_set_explicit_lock_duration(this);
5598 }
5599 locked_tables_mode= LTM_NONE;
5600}
5601
5602void THD::get_definer(LEX_USER *definer, bool role)
5603{
5604 binlog_invoker(role);
5605#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
5606#ifdef WITH_WSREP
5607 if ((wsrep_applier || slave_thread) && has_invoker())
5608#else
5609 if (slave_thread && has_invoker())
5610#endif
5611 {
5612 definer->user= invoker.user;
5613 definer->host= invoker.host;
5614 definer->reset_auth();
5615 }
5616 else
5617#endif
5618 get_default_definer(this, definer, role);
5619}
5620
5621
5622/**
5623 Mark transaction to rollback and mark error as fatal to a sub-statement.
5624
5625 @param all TRUE <=> rollback main transaction.
5626*/
5627
5628void THD::mark_transaction_to_rollback(bool all)
5629{
5630 /*
5631 There is no point in setting is_fatal_sub_stmt_error unless
5632 we are actually in_sub_stmt.
5633 */
5634 if (in_sub_stmt)
5635 is_fatal_sub_stmt_error= true;
5636 transaction_rollback_request= all;
5637}
5638/***************************************************************************
5639 Handling of XA id cacheing
5640***************************************************************************/
5641class XID_cache_element
5642{
5643 /*
5644 m_state is used to prevent elements from being deleted while XA RECOVER
5645 iterates xid cache and to prevent recovered elments from being acquired by
5646 multiple threads.
5647
5648 bits 1..29 are reference counter
5649 bit 30 is RECOVERED flag
5650 bit 31 is ACQUIRED flag (thread owns this xid)
5651 bit 32 is unused
5652
5653 Newly allocated and deleted elements have m_state set to 0.
5654
5655 On lock() m_state is atomically incremented. It also creates load-ACQUIRE
5656 memory barrier to make sure m_state is actually updated before furhter
5657 memory accesses. Attempting to lock an element that has neither ACQUIRED
5658 nor RECOVERED flag set returns failure and further accesses to element
5659 memory are forbidden.
5660
5661 On unlock() m_state is decremented. It also creates store-RELEASE memory
5662 barrier to make sure m_state is actually updated after preceding memory
5663 accesses.
5664
5665 ACQUIRED flag is set when thread registers it's xid or when thread acquires
5666 recovered xid.
5667
5668 RECOVERED flag is set for elements found during crash recovery.
5669
5670 ACQUIRED and RECOVERED flags are cleared before element is deleted from
5671 hash in a spin loop, after last reference is released.
5672 */
5673 int32 m_state;
5674public:
5675 static const int32 ACQUIRED= 1 << 30;
5676 static const int32 RECOVERED= 1 << 29;
5677 XID_STATE *m_xid_state;
5678 bool is_set(int32 flag)
5679 { return my_atomic_load32_explicit(&m_state, MY_MEMORY_ORDER_RELAXED) & flag; }
5680 void set(int32 flag)
5681 {
5682 DBUG_ASSERT(!is_set(ACQUIRED | RECOVERED));
5683 my_atomic_add32_explicit(&m_state, flag, MY_MEMORY_ORDER_RELAXED);
5684 }
5685 bool lock()
5686 {
5687 int32 old= my_atomic_add32_explicit(&m_state, 1, MY_MEMORY_ORDER_ACQUIRE);
5688 if (old & (ACQUIRED | RECOVERED))
5689 return true;
5690 unlock();
5691 return false;
5692 }
5693 void unlock()
5694 { my_atomic_add32_explicit(&m_state, -1, MY_MEMORY_ORDER_RELEASE); }
5695 void mark_uninitialized()
5696 {
5697 int32 old= ACQUIRED;
5698 while (!my_atomic_cas32_weak_explicit(&m_state, &old, 0,
5699 MY_MEMORY_ORDER_RELAXED,
5700 MY_MEMORY_ORDER_RELAXED))
5701 {
5702 old&= ACQUIRED | RECOVERED;
5703 (void) LF_BACKOFF();
5704 }
5705 }
5706 bool acquire_recovered()
5707 {
5708 int32 old= RECOVERED;
5709 while (!my_atomic_cas32_weak_explicit(&m_state, &old, ACQUIRED | RECOVERED,
5710 MY_MEMORY_ORDER_RELAXED,
5711 MY_MEMORY_ORDER_RELAXED))
5712 {
5713 if (!(old & RECOVERED) || (old & ACQUIRED))
5714 return false;
5715 old= RECOVERED;
5716 (void) LF_BACKOFF();
5717 }
5718 return true;
5719 }
5720 static void lf_hash_initializer(LF_HASH *hash __attribute__((unused)),
5721 XID_cache_element *element,
5722 XID_STATE *xid_state)
5723 {
5724 DBUG_ASSERT(!element->is_set(ACQUIRED | RECOVERED));
5725 element->m_xid_state= xid_state;
5726 xid_state->xid_cache_element= element;
5727 }
5728 static void lf_alloc_constructor(uchar *ptr)
5729 {
5730 XID_cache_element *element= (XID_cache_element*) (ptr + LF_HASH_OVERHEAD);
5731 element->m_state= 0;
5732 }
5733 static void lf_alloc_destructor(uchar *ptr)
5734 {
5735 XID_cache_element *element= (XID_cache_element*) (ptr + LF_HASH_OVERHEAD);
5736 DBUG_ASSERT(!element->is_set(ACQUIRED));
5737 if (element->is_set(RECOVERED))
5738 my_free(element->m_xid_state);
5739 }
5740 static uchar *key(const XID_cache_element *element, size_t *length,
5741 my_bool not_used __attribute__((unused)))
5742 {
5743 *length= element->m_xid_state->xid.key_length();
5744 return element->m_xid_state->xid.key();
5745 }
5746};
5747
5748
5749static LF_HASH xid_cache;
5750static bool xid_cache_inited;
5751
5752
5753bool THD::fix_xid_hash_pins()
5754{
5755 if (!xid_hash_pins)
5756 xid_hash_pins= lf_hash_get_pins(&xid_cache);
5757 return !xid_hash_pins;
5758}
5759
5760
5761void xid_cache_init()
5762{
5763 xid_cache_inited= true;
5764 lf_hash_init(&xid_cache, sizeof(XID_cache_element), LF_HASH_UNIQUE, 0, 0,
5765 (my_hash_get_key) XID_cache_element::key, &my_charset_bin);
5766 xid_cache.alloc.constructor= XID_cache_element::lf_alloc_constructor;
5767 xid_cache.alloc.destructor= XID_cache_element::lf_alloc_destructor;
5768 xid_cache.initializer=
5769 (lf_hash_initializer) XID_cache_element::lf_hash_initializer;
5770}
5771
5772
5773void xid_cache_free()
5774{
5775 if (xid_cache_inited)
5776 {
5777 lf_hash_destroy(&xid_cache);
5778 xid_cache_inited= false;
5779 }
5780}
5781
5782
5783/**
5784 Find recovered XA transaction by XID.
5785*/
5786
5787XID_STATE *xid_cache_search(THD *thd, XID *xid)
5788{
5789 XID_STATE *xs= 0;
5790 DBUG_ASSERT(thd->xid_hash_pins);
5791 XID_cache_element *element=
5792 (XID_cache_element*) lf_hash_search(&xid_cache, thd->xid_hash_pins,
5793 xid->key(), xid->key_length());
5794 if (element)
5795 {
5796 if (element->acquire_recovered())
5797 xs= element->m_xid_state;
5798 lf_hash_search_unpin(thd->xid_hash_pins);
5799 DEBUG_SYNC(thd, "xa_after_search");
5800 }
5801 return xs;
5802}
5803
5804
5805bool xid_cache_insert(XID *xid, enum xa_states xa_state)
5806{
5807 XID_STATE *xs;
5808 LF_PINS *pins;
5809 int res= 1;
5810
5811 if (!(pins= lf_hash_get_pins(&xid_cache)))
5812 return true;
5813
5814 if ((xs= (XID_STATE*) my_malloc(sizeof(*xs), MYF(MY_WME))))
5815 {
5816 xs->xa_state=xa_state;
5817 xs->xid.set(xid);
5818 xs->rm_error=0;
5819
5820 if ((res= lf_hash_insert(&xid_cache, pins, xs)))
5821 my_free(xs);
5822 else
5823 xs->xid_cache_element->set(XID_cache_element::RECOVERED);
5824 if (res == 1)
5825 res= 0;
5826 }
5827 lf_hash_put_pins(pins);
5828 return res;
5829}
5830
5831
5832bool xid_cache_insert(THD *thd, XID_STATE *xid_state)
5833{
5834 if (thd->fix_xid_hash_pins())
5835 return true;
5836
5837 int res= lf_hash_insert(&xid_cache, thd->xid_hash_pins, xid_state);
5838 switch (res)
5839 {
5840 case 0:
5841 xid_state->xid_cache_element->set(XID_cache_element::ACQUIRED);
5842 break;
5843 case 1:
5844 my_error(ER_XAER_DUPID, MYF(0));
5845 /* fall through */
5846 default:
5847 xid_state->xid_cache_element= 0;
5848 }
5849 return res;
5850}
5851
5852
5853void xid_cache_delete(THD *thd, XID_STATE *xid_state)
5854{
5855 if (xid_state->xid_cache_element)
5856 {
5857 bool recovered= xid_state->xid_cache_element->is_set(XID_cache_element::RECOVERED);
5858 DBUG_ASSERT(thd->xid_hash_pins);
5859 xid_state->xid_cache_element->mark_uninitialized();
5860 lf_hash_delete(&xid_cache, thd->xid_hash_pins,
5861 xid_state->xid.key(), xid_state->xid.key_length());
5862 xid_state->xid_cache_element= 0;
5863 if (recovered)
5864 my_free(xid_state);
5865 }
5866}
5867
5868
5869struct xid_cache_iterate_arg
5870{
5871 my_hash_walk_action action;
5872 void *argument;
5873};
5874
5875static my_bool xid_cache_iterate_callback(XID_cache_element *element,
5876 xid_cache_iterate_arg *arg)
5877{
5878 my_bool res= FALSE;
5879 if (element->lock())
5880 {
5881 res= arg->action(element->m_xid_state, arg->argument);
5882 element->unlock();
5883 }
5884 return res;
5885}
5886
5887int xid_cache_iterate(THD *thd, my_hash_walk_action action, void *arg)
5888{
5889 xid_cache_iterate_arg argument= { action, arg };
5890 return thd->fix_xid_hash_pins() ? -1 :
5891 lf_hash_iterate(&xid_cache, thd->xid_hash_pins,
5892 (my_hash_walk_action) xid_cache_iterate_callback,
5893 &argument);
5894}
5895
5896
5897/**
5898 Decide on logging format to use for the statement and issue errors
5899 or warnings as needed. The decision depends on the following
5900 parameters:
5901
5902 - The logging mode, i.e., the value of binlog_format. Can be
5903 statement, mixed, or row.
5904
5905 - The type of statement. There are three types of statements:
5906 "normal" safe statements; unsafe statements; and row injections.
5907 An unsafe statement is one that, if logged in statement format,
5908 might produce different results when replayed on the slave (e.g.,
5909 INSERT DELAYED). A row injection is either a BINLOG statement, or
5910 a row event executed by the slave's SQL thread.
5911
5912 - The capabilities of tables modified by the statement. The
5913 *capabilities vector* for a table is a set of flags associated
5914 with the table. Currently, it only includes two flags: *row
5915 capability flag* and *statement capability flag*.
5916
5917 The row capability flag is set if and only if the engine can
5918 handle row-based logging. The statement capability flag is set if
5919 and only if the table can handle statement-based logging.
5920
5921 Decision table for logging format
5922 ---------------------------------
5923
5924 The following table summarizes how the format and generated
5925 warning/error depends on the tables' capabilities, the statement
5926 type, and the current binlog_format.
5927
5928 Row capable N NNNNNNNNN YYYYYYYYY YYYYYYYYY
5929 Statement capable N YYYYYYYYY NNNNNNNNN YYYYYYYYY
5930
5931 Statement type * SSSUUUIII SSSUUUIII SSSUUUIII
5932
5933 binlog_format * SMRSMRSMR SMRSMRSMR SMRSMRSMR
5934
5935 Logged format - SS-S----- -RR-RR-RR SRRSRR-RR
5936 Warning/Error 1 --2732444 5--5--6-- ---7--6--
5937
5938 Legend
5939 ------
5940
5941 Row capable: N - Some table not row-capable, Y - All tables row-capable
5942 Stmt capable: N - Some table not stmt-capable, Y - All tables stmt-capable
5943 Statement type: (S)afe, (U)nsafe, or Row (I)njection
5944 binlog_format: (S)TATEMENT, (M)IXED, or (R)OW
5945 Logged format: (S)tatement or (R)ow
5946 Warning/Error: Warnings and error messages are as follows:
5947
5948 1. Error: Cannot execute statement: binlogging impossible since both
5949 row-incapable engines and statement-incapable engines are
5950 involved.
5951
5952 2. Error: Cannot execute statement: binlogging impossible since
5953 BINLOG_FORMAT = ROW and at least one table uses a storage engine
5954 limited to statement-logging.
5955
5956 3. Error: Cannot execute statement: binlogging of unsafe statement
5957 is impossible when storage engine is limited to statement-logging
5958 and BINLOG_FORMAT = MIXED.
5959
5960 4. Error: Cannot execute row injection: binlogging impossible since
5961 at least one table uses a storage engine limited to
5962 statement-logging.
5963
5964 5. Error: Cannot execute statement: binlogging impossible since
5965 BINLOG_FORMAT = STATEMENT and at least one table uses a storage
5966 engine limited to row-logging.
5967
5968 6. Warning: Unsafe statement binlogged in statement format since
5969 BINLOG_FORMAT = STATEMENT.
5970
5971 In addition, we can produce the following error (not depending on
5972 the variables of the decision diagram):
5973
5974 7. Error: Cannot execute statement: binlogging impossible since more
5975 than one engine is involved and at least one engine is
5976 self-logging.
5977
5978 For each error case above, the statement is prevented from being
5979 logged, we report an error, and roll back the statement. For
5980 warnings, we set the thd->binlog_flags variable: the warning will be
5981 printed only if the statement is successfully logged.
5982
5983 @see THD::binlog_query
5984
5985 @param[in] thd Client thread
5986 @param[in] tables Tables involved in the query
5987
5988 @retval 0 No error; statement can be logged.
5989 @retval -1 One of the error conditions above applies (1, 2, 4, 5, or 6).
5990*/
5991
5992int THD::decide_logging_format(TABLE_LIST *tables)
5993{
5994 DBUG_ENTER("THD::decide_logging_format");
5995 DBUG_PRINT("info", ("Query: %.*s", (uint) query_length(), query()));
5996 DBUG_PRINT("info", ("variables.binlog_format: %lu",
5997 variables.binlog_format));
5998 DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags(): 0x%x",
5999 lex->get_stmt_unsafe_flags()));
6000
6001 reset_binlog_local_stmt_filter();
6002
6003 /*
6004 We should not decide logging format if the binlog is closed or
6005 binlogging is off, or if the statement is filtered out from the
6006 binlog by filtering rules.
6007 */
6008 if (mysql_bin_log.is_open() && (variables.option_bits & OPTION_BIN_LOG) &&
6009 !(wsrep_binlog_format() == BINLOG_FORMAT_STMT &&
6010 !binlog_filter->db_ok(db.str)))
6011 {
6012
6013 if (is_bulk_op())
6014 {
6015 if (wsrep_binlog_format() == BINLOG_FORMAT_STMT)
6016 {
6017 my_error(ER_BINLOG_NON_SUPPORTED_BULK, MYF(0));
6018 DBUG_PRINT("info",
6019 ("decision: no logging since an error was generated"));
6020 DBUG_RETURN(-1);
6021 }
6022 }
6023 /*
6024 Compute one bit field with the union of all the engine
6025 capabilities, and one with the intersection of all the engine
6026 capabilities.
6027 */
6028 handler::Table_flags flags_write_some_set= 0;
6029 handler::Table_flags flags_access_some_set= 0;
6030 handler::Table_flags flags_write_all_set=
6031 HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE;
6032
6033 /*
6034 If different types of engines are about to be updated.
6035 For example: Innodb and Falcon; Innodb and MyIsam.
6036 */
6037 bool multi_write_engine= FALSE;
6038 /*
6039 If different types of engines are about to be accessed
6040 and any of them is about to be updated. For example:
6041 Innodb and Falcon; Innodb and MyIsam.
6042 */
6043 bool multi_access_engine= FALSE;
6044 /*
6045 Identifies if a table is changed.
6046 */
6047 bool is_write= FALSE; // If any write tables
6048 bool has_read_tables= FALSE; // If any read only tables
6049 bool has_auto_increment_write_tables= FALSE; // Write with auto-increment
6050 /* If a write table that doesn't have auto increment part first */
6051 bool has_write_table_auto_increment_not_first_in_pk= FALSE;
6052 bool has_auto_increment_write_tables_not_first= FALSE;
6053 bool found_first_not_own_table= FALSE;
6054 bool has_write_tables_with_unsafe_statements= FALSE;
6055
6056 /*
6057 A pointer to a previous table that was changed.
6058 */
6059 TABLE* prev_write_table= NULL;
6060 /*
6061 A pointer to a previous table that was accessed.
6062 */
6063 TABLE* prev_access_table= NULL;
6064 /**
6065 The number of tables used in the current statement,
6066 that should be replicated.
6067 */
6068 uint replicated_tables_count= 0;
6069 /**
6070 The number of tables written to in the current statement,
6071 that should not be replicated.
6072 A table should not be replicated when it is considered
6073 'local' to a MySQL instance.
6074 Currently, these tables are:
6075 - mysql.slow_log
6076 - mysql.general_log
6077 - mysql.slave_relay_log_info
6078 - mysql.slave_master_info
6079 - mysql.slave_worker_info
6080 - performance_schema.*
6081 - TODO: information_schema.*
6082 In practice, from this list, only performance_schema.* tables
6083 are written to by user queries.
6084 */
6085 uint non_replicated_tables_count= 0;
6086
6087#ifndef DBUG_OFF
6088 {
6089 static const char *prelocked_mode_name[] = {
6090 "NON_PRELOCKED",
6091 "LOCK_TABLES",
6092 "PRELOCKED",
6093 "PRELOCKED_UNDER_LOCK_TABLES",
6094 };
6095 compile_time_assert(array_elements(prelocked_mode_name) == LTM_always_last);
6096 DBUG_PRINT("debug", ("prelocked_mode: %s",
6097 prelocked_mode_name[locked_tables_mode]));
6098 }
6099#endif
6100
6101 /*
6102 Get the capabilities vector for all involved storage engines and
6103 mask out the flags for the binary log.
6104 */
6105 for (TABLE_LIST *table= tables; table; table= table->next_global)
6106 {
6107 if (table->placeholder())
6108 continue;
6109
6110 handler::Table_flags const flags= table->table->file->ha_table_flags();
6111
6112 DBUG_PRINT("info", ("table: %s; ha_table_flags: 0x%llx",
6113 table->table_name.str, flags));
6114
6115 if (table->table->s->no_replicate)
6116 {
6117 /*
6118 The statement uses a table that is not replicated.
6119 The following properties about the table:
6120 - persistent / transient
6121 - transactional / non transactional
6122 - temporary / permanent
6123 - read or write
6124 - multiple engines involved because of this table
6125 are not relevant, as this table is completely ignored.
6126 Because the statement uses a non replicated table,
6127 using STATEMENT format in the binlog is impossible.
6128 Either this statement will be discarded entirely,
6129 or it will be logged (possibly partially) in ROW format.
6130 */
6131 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_TABLE);
6132
6133 if (table->lock_type >= TL_WRITE_ALLOW_WRITE)
6134 {
6135 non_replicated_tables_count++;
6136 continue;
6137 }
6138 }
6139 if (table == lex->first_not_own_table())
6140 found_first_not_own_table= true;
6141
6142 replicated_tables_count++;
6143
6144 if (table->lock_type <= TL_READ_NO_INSERT &&
6145 table->prelocking_placeholder != TABLE_LIST::PRELOCK_FK)
6146 has_read_tables= true;
6147 else if (table->table->found_next_number_field &&
6148 (table->lock_type >= TL_WRITE_ALLOW_WRITE))
6149 {
6150 has_auto_increment_write_tables= true;
6151 has_auto_increment_write_tables_not_first= found_first_not_own_table;
6152 if (table->table->s->next_number_keypart != 0)
6153 has_write_table_auto_increment_not_first_in_pk= true;
6154 }
6155
6156 if (table->lock_type >= TL_WRITE_ALLOW_WRITE)
6157 {
6158 bool trans;
6159 if (prev_write_table && prev_write_table->file->ht !=
6160 table->table->file->ht)
6161 multi_write_engine= TRUE;
6162 if (table->table->s->non_determinstic_insert &&
6163 !(sql_command_flags[lex->sql_command] & CF_SCHEMA_CHANGE))
6164 has_write_tables_with_unsafe_statements= true;
6165
6166 trans= table->table->file->has_transactions();
6167
6168 if (table->table->s->tmp_table)
6169 lex->set_stmt_accessed_table(trans ? LEX::STMT_WRITES_TEMP_TRANS_TABLE :
6170 LEX::STMT_WRITES_TEMP_NON_TRANS_TABLE);
6171 else
6172 lex->set_stmt_accessed_table(trans ? LEX::STMT_WRITES_TRANS_TABLE :
6173 LEX::STMT_WRITES_NON_TRANS_TABLE);
6174
6175 flags_write_all_set &= flags;
6176 flags_write_some_set |= flags;
6177 is_write= TRUE;
6178
6179 prev_write_table= table->table;
6180
6181 }
6182 flags_access_some_set |= flags;
6183
6184 if (lex->sql_command != SQLCOM_CREATE_TABLE ||
6185 (lex->sql_command == SQLCOM_CREATE_TABLE && lex->tmp_table()))
6186 {
6187 my_bool trans= table->table->file->has_transactions();
6188
6189 if (table->table->s->tmp_table)
6190 lex->set_stmt_accessed_table(trans ? LEX::STMT_READS_TEMP_TRANS_TABLE :
6191 LEX::STMT_READS_TEMP_NON_TRANS_TABLE);
6192 else
6193 lex->set_stmt_accessed_table(trans ? LEX::STMT_READS_TRANS_TABLE :
6194 LEX::STMT_READS_NON_TRANS_TABLE);
6195 }
6196
6197 if (prev_access_table && prev_access_table->file->ht !=
6198 table->table->file->ht)
6199 multi_access_engine= TRUE;
6200
6201 prev_access_table= table->table;
6202 }
6203
6204 if (wsrep_binlog_format() != BINLOG_FORMAT_ROW)
6205 {
6206 /*
6207 DML statements that modify a table with an auto_increment
6208 column based on rows selected from a table are unsafe as the
6209 order in which the rows are fetched fron the select tables
6210 cannot be determined and may differ on master and slave.
6211 */
6212 if (has_auto_increment_write_tables && has_read_tables)
6213 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT);
6214
6215 if (has_write_table_auto_increment_not_first_in_pk)
6216 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST);
6217
6218 if (has_write_tables_with_unsafe_statements)
6219 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
6220
6221 /*
6222 A query that modifies autoinc column in sub-statement can make the
6223 master and slave inconsistent.
6224 We can solve these problems in mixed mode by switching to binlogging
6225 if at least one updated table is used by sub-statement
6226 */
6227 if (lex->requires_prelocking() &&
6228 has_auto_increment_write_tables_not_first)
6229 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS);
6230 }
6231
6232 DBUG_PRINT("info", ("flags_write_all_set: 0x%llx", flags_write_all_set));
6233 DBUG_PRINT("info", ("flags_write_some_set: 0x%llx", flags_write_some_set));
6234 DBUG_PRINT("info", ("flags_access_some_set: 0x%llx", flags_access_some_set));
6235 DBUG_PRINT("info", ("multi_write_engine: %d", multi_write_engine));
6236 DBUG_PRINT("info", ("multi_access_engine: %d", multi_access_engine));
6237
6238 int error= 0;
6239 int unsafe_flags;
6240
6241 bool multi_stmt_trans= in_multi_stmt_transaction_mode();
6242 bool trans_table= trans_has_updated_trans_table(this);
6243 bool binlog_direct= variables.binlog_direct_non_trans_update;
6244
6245 if (lex->is_mixed_stmt_unsafe(multi_stmt_trans, binlog_direct,
6246 trans_table, tx_isolation))
6247 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_MIXED_STATEMENT);
6248 else if (multi_stmt_trans && trans_table && !binlog_direct &&
6249 lex->stmt_accessed_table(LEX::STMT_WRITES_NON_TRANS_TABLE))
6250 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS);
6251
6252 /*
6253 If more than one engine is involved in the statement and at
6254 least one is doing it's own logging (is *self-logging*), the
6255 statement cannot be logged atomically, so we generate an error
6256 rather than allowing the binlog to become corrupt.
6257 */
6258 if (multi_write_engine &&
6259 (flags_write_some_set & HA_HAS_OWN_BINLOGGING))
6260 my_error((error= ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE),
6261 MYF(0));
6262 else if (multi_access_engine && flags_access_some_set & HA_HAS_OWN_BINLOGGING)
6263 lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE);
6264
6265 /* both statement-only and row-only engines involved */
6266 if ((flags_write_all_set & (HA_BINLOG_STMT_CAPABLE | HA_BINLOG_ROW_CAPABLE)) == 0)
6267 {
6268 /*
6269 1. Error: Binary logging impossible since both row-incapable
6270 engines and statement-incapable engines are involved
6271 */
6272 my_error((error= ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE), MYF(0));
6273 }
6274 /* statement-only engines involved */
6275 else if ((flags_write_all_set & HA_BINLOG_ROW_CAPABLE) == 0)
6276 {
6277 if (lex->is_stmt_row_injection())
6278 {
6279 /*
6280 4. Error: Cannot execute row injection since table uses
6281 storage engine limited to statement-logging
6282 */
6283 my_error((error= ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE), MYF(0));
6284 }
6285 else if ((wsrep_binlog_format() == BINLOG_FORMAT_ROW || is_bulk_op()) &&
6286 sqlcom_can_generate_row_events(this))
6287 {
6288 /*
6289 2. Error: Cannot modify table that uses a storage engine
6290 limited to statement-logging when BINLOG_FORMAT = ROW
6291 */
6292 my_error((error= ER_BINLOG_ROW_MODE_AND_STMT_ENGINE), MYF(0));
6293 }
6294 else if ((unsafe_flags= lex->get_stmt_unsafe_flags()) != 0)
6295 {
6296 /*
6297 3. Error: Cannot execute statement: binlogging of unsafe
6298 statement is impossible when storage engine is limited to
6299 statement-logging and BINLOG_FORMAT = MIXED.
6300 */
6301 for (int unsafe_type= 0;
6302 unsafe_type < LEX::BINLOG_STMT_UNSAFE_COUNT;
6303 unsafe_type++)
6304 if (unsafe_flags & (1 << unsafe_type))
6305 my_error((error= ER_BINLOG_UNSAFE_AND_STMT_ENGINE), MYF(0),
6306 ER_THD(this,
6307 LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
6308 }
6309 /* log in statement format! */
6310 }
6311 /* no statement-only engines */
6312 else
6313 {
6314 /* binlog_format = STATEMENT */
6315 if (wsrep_binlog_format() == BINLOG_FORMAT_STMT)
6316 {
6317 if (lex->is_stmt_row_injection())
6318 {
6319 /*
6320 We have to log the statement as row or give an error.
6321 Better to accept what master gives us than stopping replication.
6322 */
6323 set_current_stmt_binlog_format_row();
6324 }
6325 else if ((flags_write_all_set & HA_BINLOG_STMT_CAPABLE) == 0 &&
6326 sqlcom_can_generate_row_events(this))
6327 {
6328 /*
6329 5. Error: Cannot modify table that uses a storage engine
6330 limited to row-logging when binlog_format = STATEMENT
6331 */
6332 if (IF_WSREP((!WSREP(this) || wsrep_exec_mode == LOCAL_STATE),1))
6333 {
6334 my_error((error= ER_BINLOG_STMT_MODE_AND_ROW_ENGINE), MYF(0), "");
6335 }
6336 }
6337 else if (is_write && (unsafe_flags= lex->get_stmt_unsafe_flags()) != 0)
6338 {
6339 /*
6340 7. Warning: Unsafe statement logged as statement due to
6341 binlog_format = STATEMENT
6342 */
6343 binlog_unsafe_warning_flags|= unsafe_flags;
6344
6345 DBUG_PRINT("info", ("Scheduling warning to be issued by "
6346 "binlog_query: '%s'",
6347 ER_THD(this, ER_BINLOG_UNSAFE_STATEMENT)));
6348 DBUG_PRINT("info", ("binlog_unsafe_warning_flags: 0x%x",
6349 binlog_unsafe_warning_flags));
6350 }
6351 /* log in statement format (or row if row event)! */
6352 }
6353 /* No statement-only engines and binlog_format != STATEMENT.
6354 I.e., nothing prevents us from row logging if needed. */
6355 else
6356 {
6357 if (lex->is_stmt_unsafe() || lex->is_stmt_row_injection()
6358 || (flags_write_all_set & HA_BINLOG_STMT_CAPABLE) == 0 ||
6359 is_bulk_op())
6360 {
6361 /* log in row format! */
6362 set_current_stmt_binlog_format_row_if_mixed();
6363 }
6364 }
6365 }
6366
6367 if (non_replicated_tables_count > 0)
6368 {
6369 if ((replicated_tables_count == 0) || ! is_write)
6370 {
6371 DBUG_PRINT("info", ("decision: no logging, no replicated table affected"));
6372 set_binlog_local_stmt_filter();
6373 }
6374 else
6375 {
6376 if (! is_current_stmt_binlog_format_row())
6377 {
6378 my_error((error= ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES), MYF(0));
6379 }
6380 else
6381 {
6382 clear_binlog_local_stmt_filter();
6383 }
6384 }
6385 }
6386 else
6387 {
6388 clear_binlog_local_stmt_filter();
6389 }
6390
6391 if (unlikely(error))
6392 {
6393 DBUG_PRINT("info", ("decision: no logging since an error was generated"));
6394 DBUG_RETURN(-1);
6395 }
6396 DBUG_PRINT("info", ("decision: logging in %s format",
6397 is_current_stmt_binlog_format_row() ?
6398 "ROW" : "STATEMENT"));
6399
6400 if (variables.binlog_format == BINLOG_FORMAT_ROW &&
6401 (lex->sql_command == SQLCOM_UPDATE ||
6402 lex->sql_command == SQLCOM_UPDATE_MULTI ||
6403 lex->sql_command == SQLCOM_DELETE ||
6404 lex->sql_command == SQLCOM_DELETE_MULTI))
6405 {
6406 String table_names;
6407 /*
6408 Generate a warning for UPDATE/DELETE statements that modify a
6409 BLACKHOLE table, as row events are not logged in row format.
6410 */
6411 for (TABLE_LIST *table= tables; table; table= table->next_global)
6412 {
6413 if (table->placeholder())
6414 continue;
6415 if (table->table->file->ht->db_type == DB_TYPE_BLACKHOLE_DB &&
6416 table->lock_type >= TL_WRITE_ALLOW_WRITE)
6417 {
6418 table_names.append(&table->table_name);
6419 table_names.append(",");
6420 }
6421 }
6422 if (!table_names.is_empty())
6423 {
6424 bool is_update= (lex->sql_command == SQLCOM_UPDATE ||
6425 lex->sql_command == SQLCOM_UPDATE_MULTI);
6426 /*
6427 Replace the last ',' with '.' for table_names
6428 */
6429 table_names.replace(table_names.length()-1, 1, ".", 1);
6430 push_warning_printf(this, Sql_condition::WARN_LEVEL_WARN,
6431 ER_UNKNOWN_ERROR,
6432 "Row events are not logged for %s statements "
6433 "that modify BLACKHOLE tables in row format. "
6434 "Table(s): '%-.192s'",
6435 is_update ? "UPDATE" : "DELETE",
6436 table_names.c_ptr());
6437 }
6438 }
6439 }
6440#ifndef DBUG_OFF
6441 else
6442 DBUG_PRINT("info", ("decision: no logging since "
6443 "mysql_bin_log.is_open() = %d "
6444 "and (options & OPTION_BIN_LOG) = 0x%llx "
6445 "and binlog_format = %u "
6446 "and binlog_filter->db_ok(db) = %d",
6447 mysql_bin_log.is_open(),
6448 (variables.option_bits & OPTION_BIN_LOG),
6449 (uint) wsrep_binlog_format(),
6450 binlog_filter->db_ok(db.str)));
6451#endif
6452
6453 DBUG_RETURN(0);
6454}
6455
6456
6457/*
6458 Implementation of interface to write rows to the binary log through the
6459 thread. The thread is responsible for writing the rows it has
6460 inserted/updated/deleted.
6461*/
6462
6463#ifndef MYSQL_CLIENT
6464
6465/*
6466 Template member function for ensuring that there is an rows log
6467 event of the apropriate type before proceeding.
6468
6469 PRE CONDITION:
6470 - Events of type 'RowEventT' have the type code 'type_code'.
6471
6472 POST CONDITION:
6473 If a non-NULL pointer is returned, the pending event for thread 'thd' will
6474 be an event of type 'RowEventT' (which have the type code 'type_code')
6475 will either empty or have enough space to hold 'needed' bytes. In
6476 addition, the columns bitmap will be correct for the row, meaning that
6477 the pending event will be flushed if the columns in the event differ from
6478 the columns suppled to the function.
6479
6480 RETURNS
6481 If no error, a non-NULL pending event (either one which already existed or
6482 the newly created one).
6483 If error, NULL.
6484 */
6485
6486template <class RowsEventT> Rows_log_event*
6487THD::binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id,
6488 size_t needed,
6489 bool is_transactional,
6490 RowsEventT *hint __attribute__((unused)))
6491{
6492 DBUG_ENTER("binlog_prepare_pending_rows_event");
6493 /* Pre-conditions */
6494 DBUG_ASSERT(table->s->table_map_id != ~0UL);
6495
6496 /* Fetch the type code for the RowsEventT template parameter */
6497 int const general_type_code= RowsEventT::TYPE_CODE;
6498
6499 /* Ensure that all events in a GTID group are in the same cache */
6500 if (variables.option_bits & OPTION_GTID_BEGIN)
6501 is_transactional= 1;
6502
6503 /*
6504 There is no good place to set up the transactional data, so we
6505 have to do it here.
6506 */
6507 if (binlog_setup_trx_data() == NULL)
6508 DBUG_RETURN(NULL);
6509
6510 Rows_log_event* pending= binlog_get_pending_rows_event(is_transactional);
6511
6512 if (unlikely(pending && !pending->is_valid()))
6513 DBUG_RETURN(NULL);
6514
6515 /*
6516 Check if the current event is non-NULL and a write-rows
6517 event. Also check if the table provided is mapped: if it is not,
6518 then we have switched to writing to a new table.
6519 If there is no pending event, we need to create one. If there is a pending
6520 event, but it's not about the same table id, or not of the same type
6521 (between Write, Update and Delete), or not the same affected columns, or
6522 going to be too big, flush this event to disk and create a new pending
6523 event.
6524 */
6525 if (!pending ||
6526 pending->server_id != serv_id ||
6527 pending->get_table_id() != table->s->table_map_id ||
6528 pending->get_general_type_code() != general_type_code ||
6529 pending->get_data_size() + needed > opt_binlog_rows_event_max_size ||
6530 pending->read_write_bitmaps_cmp(table) == FALSE)
6531 {
6532 /* Create a new RowsEventT... */
6533 Rows_log_event* const
6534 ev= new RowsEventT(this, table, table->s->table_map_id,
6535 is_transactional);
6536 if (unlikely(!ev))
6537 DBUG_RETURN(NULL);
6538 ev->server_id= serv_id; // I don't like this, it's too easy to forget.
6539 /*
6540 flush the pending event and replace it with the newly created
6541 event...
6542 */
6543 if (unlikely(
6544 mysql_bin_log.flush_and_set_pending_rows_event(this, ev,
6545 is_transactional)))
6546 {
6547 delete ev;
6548 DBUG_RETURN(NULL);
6549 }
6550
6551 DBUG_RETURN(ev); /* This is the new pending event */
6552 }
6553 DBUG_RETURN(pending); /* This is the current pending event */
6554}
6555
6556/* Declare in unnamed namespace. */
6557CPP_UNNAMED_NS_START
6558 /**
6559 Class to handle temporary allocation of memory for row data.
6560
6561 The responsibilities of the class is to provide memory for
6562 packing one or two rows of packed data (depending on what
6563 constructor is called).
6564
6565 In order to make the allocation more efficient for "simple" rows,
6566 i.e., rows that do not contain any blobs, a pointer to the
6567 allocated memory is of memory is stored in the table structure
6568 for simple rows. If memory for a table containing a blob field
6569 is requested, only memory for that is allocated, and subsequently
6570 released when the object is destroyed.
6571
6572 */
6573 class Row_data_memory {
6574 public:
6575 /**
6576 Build an object to keep track of a block-local piece of memory
6577 for storing a row of data.
6578
6579 @param table
6580 Table where the pre-allocated memory is stored.
6581
6582 @param length
6583 Length of data that is needed, if the record contain blobs.
6584 */
6585 Row_data_memory(TABLE *table, size_t const len1)
6586 : m_memory(0)
6587 {
6588#ifndef DBUG_OFF
6589 m_alloc_checked= FALSE;
6590#endif
6591 allocate_memory(table, len1);
6592 m_ptr[0]= has_memory() ? m_memory : 0;
6593 m_ptr[1]= 0;
6594 }
6595
6596 Row_data_memory(TABLE *table, size_t const len1, size_t const len2)
6597 : m_memory(0)
6598 {
6599#ifndef DBUG_OFF
6600 m_alloc_checked= FALSE;
6601#endif
6602 allocate_memory(table, len1 + len2);
6603 m_ptr[0]= has_memory() ? m_memory : 0;
6604 m_ptr[1]= has_memory() ? m_memory + len1 : 0;
6605 }
6606
6607 ~Row_data_memory()
6608 {
6609 if (m_memory != 0 && m_release_memory_on_destruction)
6610 my_free(m_memory);
6611 }
6612
6613 /**
6614 Is there memory allocated?
6615
6616 @retval true There is memory allocated
6617 @retval false Memory allocation failed
6618 */
6619 bool has_memory() const {
6620#ifndef DBUG_OFF
6621 m_alloc_checked= TRUE;
6622#endif
6623 return m_memory != 0;
6624 }
6625
6626 uchar *slot(uint s)
6627 {
6628 DBUG_ASSERT(s < sizeof(m_ptr)/sizeof(*m_ptr));
6629 DBUG_ASSERT(m_ptr[s] != 0);
6630 DBUG_SLOW_ASSERT(m_alloc_checked == TRUE);
6631 return m_ptr[s];
6632 }
6633
6634 private:
6635 void allocate_memory(TABLE *const table, size_t const total_length)
6636 {
6637 if (table->s->blob_fields == 0)
6638 {
6639 /*
6640 The maximum length of a packed record is less than this
6641 length. We use this value instead of the supplied length
6642 when allocating memory for records, since we don't know how
6643 the memory will be used in future allocations.
6644
6645 Since table->s->reclength is for unpacked records, we have
6646 to add two bytes for each field, which can potentially be
6647 added to hold the length of a packed field.
6648 */
6649 size_t const maxlen= table->s->reclength + 2 * table->s->fields;
6650
6651 /*
6652 Allocate memory for two records if memory hasn't been
6653 allocated. We allocate memory for two records so that it can
6654 be used when processing update rows as well.
6655 */
6656 if (table->write_row_record == 0)
6657 table->write_row_record=
6658 (uchar *) alloc_root(&table->mem_root, 2 * maxlen);
6659 m_memory= table->write_row_record;
6660 m_release_memory_on_destruction= FALSE;
6661 }
6662 else
6663 {
6664 m_memory= (uchar *) my_malloc(total_length, MYF(MY_WME));
6665 m_release_memory_on_destruction= TRUE;
6666 }
6667 }
6668
6669#ifndef DBUG_OFF
6670 mutable bool m_alloc_checked;
6671#endif
6672 bool m_release_memory_on_destruction;
6673 uchar *m_memory;
6674 uchar *m_ptr[2];
6675 };
6676
6677CPP_UNNAMED_NS_END
6678
6679int THD::binlog_write_row(TABLE* table, bool is_trans,
6680 uchar const *record)
6681{
6682
6683 DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6684 ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6685 /*
6686 Pack records into format for transfer. We are allocating more
6687 memory than needed, but that doesn't matter.
6688 */
6689 Row_data_memory memory(table, max_row_length(table, record));
6690 if (!memory.has_memory())
6691 return HA_ERR_OUT_OF_MEM;
6692
6693 uchar *row_data= memory.slot(0);
6694
6695 size_t const len= pack_row(table, table->rpl_write_set, row_data, record);
6696
6697 /* Ensure that all events in a GTID group are in the same cache */
6698 if (variables.option_bits & OPTION_GTID_BEGIN)
6699 is_trans= 1;
6700
6701 Rows_log_event* ev;
6702 if (binlog_should_compress(len))
6703 ev =
6704 binlog_prepare_pending_rows_event(table, variables.server_id,
6705 len, is_trans,
6706 static_cast<Write_rows_compressed_log_event*>(0));
6707 else
6708 ev =
6709 binlog_prepare_pending_rows_event(table, variables.server_id,
6710 len, is_trans,
6711 static_cast<Write_rows_log_event*>(0));
6712
6713 if (unlikely(ev == 0))
6714 return HA_ERR_OUT_OF_MEM;
6715
6716 return ev->add_row_data(row_data, len);
6717}
6718
6719int THD::binlog_update_row(TABLE* table, bool is_trans,
6720 const uchar *before_record,
6721 const uchar *after_record)
6722{
6723 DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6724 ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6725
6726 size_t const before_maxlen = max_row_length(table, before_record);
6727 size_t const after_maxlen = max_row_length(table, after_record);
6728
6729 Row_data_memory row_data(table, before_maxlen, after_maxlen);
6730 if (!row_data.has_memory())
6731 return HA_ERR_OUT_OF_MEM;
6732
6733 uchar *before_row= row_data.slot(0);
6734 uchar *after_row= row_data.slot(1);
6735
6736 size_t const before_size= pack_row(table, table->read_set, before_row,
6737 before_record);
6738 size_t const after_size= pack_row(table, table->rpl_write_set, after_row,
6739 after_record);
6740
6741 /* Ensure that all events in a GTID group are in the same cache */
6742 if (variables.option_bits & OPTION_GTID_BEGIN)
6743 is_trans= 1;
6744
6745 /*
6746 Don't print debug messages when running valgrind since they can
6747 trigger false warnings.
6748 */
6749#ifndef HAVE_valgrind
6750 DBUG_DUMP("before_record", before_record, table->s->reclength);
6751 DBUG_DUMP("after_record", after_record, table->s->reclength);
6752 DBUG_DUMP("before_row", before_row, before_size);
6753 DBUG_DUMP("after_row", after_row, after_size);
6754#endif
6755
6756 Rows_log_event* ev;
6757 if(binlog_should_compress(before_size + after_size))
6758 ev =
6759 binlog_prepare_pending_rows_event(table, variables.server_id,
6760 before_size + after_size, is_trans,
6761 static_cast<Update_rows_compressed_log_event*>(0));
6762 else
6763 ev =
6764 binlog_prepare_pending_rows_event(table, variables.server_id,
6765 before_size + after_size, is_trans,
6766 static_cast<Update_rows_log_event*>(0));
6767
6768 if (unlikely(ev == 0))
6769 return HA_ERR_OUT_OF_MEM;
6770
6771 int error= ev->add_row_data(before_row, before_size) ||
6772 ev->add_row_data(after_row, after_size);
6773
6774 return error;
6775
6776}
6777
6778int THD::binlog_delete_row(TABLE* table, bool is_trans,
6779 uchar const *record)
6780{
6781 DBUG_ASSERT(is_current_stmt_binlog_format_row() &&
6782 ((WSREP(this) && wsrep_emulate_bin_log) || mysql_bin_log.is_open()));
6783 /**
6784 Save a reference to the original read bitmaps
6785 We will need this to restore the bitmaps at the end as
6786 binlog_prepare_row_images() may change table->read_set.
6787 table->read_set is used by pack_row and deep in
6788 binlog_prepare_pending_events().
6789 */
6790 MY_BITMAP *old_read_set= table->read_set;
6791
6792 /**
6793 This will remove spurious fields required during execution but
6794 not needed for binlogging. This is done according to the:
6795 binlog-row-image option.
6796 */
6797 binlog_prepare_row_images(table);
6798
6799 /*
6800 Pack records into format for transfer. We are allocating more
6801 memory than needed, but that doesn't matter.
6802 */
6803 Row_data_memory memory(table, max_row_length(table, record));
6804 if (unlikely(!memory.has_memory()))
6805 return HA_ERR_OUT_OF_MEM;
6806
6807 uchar *row_data= memory.slot(0);
6808
6809 DBUG_DUMP("table->read_set", (uchar*) table->read_set->bitmap, (table->s->fields + 7) / 8);
6810 size_t const len= pack_row(table, table->read_set, row_data, record);
6811
6812 /* Ensure that all events in a GTID group are in the same cache */
6813 if (variables.option_bits & OPTION_GTID_BEGIN)
6814 is_trans= 1;
6815
6816 Rows_log_event* ev;
6817 if(binlog_should_compress(len))
6818 ev =
6819 binlog_prepare_pending_rows_event(table, variables.server_id,
6820 len, is_trans,
6821 static_cast<Delete_rows_compressed_log_event*>(0));
6822 else
6823 ev =
6824 binlog_prepare_pending_rows_event(table, variables.server_id,
6825 len, is_trans,
6826 static_cast<Delete_rows_log_event*>(0));
6827
6828 if (unlikely(ev == 0))
6829 return HA_ERR_OUT_OF_MEM;
6830
6831
6832 int error= ev->add_row_data(row_data, len);
6833
6834 /* restore read set for the rest of execution */
6835 table->column_bitmaps_set_no_signal(old_read_set,
6836 table->write_set);
6837
6838 return error;
6839}
6840
6841
6842void THD::binlog_prepare_row_images(TABLE *table)
6843{
6844 DBUG_ENTER("THD::binlog_prepare_row_images");
6845 /**
6846 Remove from read_set spurious columns. The write_set has been
6847 handled before in table->mark_columns_needed_for_update.
6848 */
6849
6850 DBUG_PRINT_BITSET("debug", "table->read_set (before preparing): %s", table->read_set);
6851 THD *thd= table->in_use;
6852
6853 /**
6854 if there is a primary key in the table (ie, user declared PK or a
6855 non-null unique index) and we dont want to ship the entire image,
6856 and the handler involved supports this.
6857 */
6858 if (table->s->primary_key < MAX_KEY &&
6859 (thd->variables.binlog_row_image < BINLOG_ROW_IMAGE_FULL) &&
6860 !ha_check_storage_engine_flag(table->s->db_type(), HTON_NO_BINLOG_ROW_OPT))
6861 {
6862 /**
6863 Just to be sure that tmp_set is currently not in use as
6864 the read_set already.
6865 */
6866 DBUG_ASSERT(table->read_set != &table->tmp_set);
6867
6868 switch(thd->variables.binlog_row_image)
6869 {
6870 case BINLOG_ROW_IMAGE_MINIMAL:
6871 /* MINIMAL: Mark only PK */
6872 table->mark_columns_used_by_index(table->s->primary_key,
6873 &table->tmp_set);
6874 break;
6875 case BINLOG_ROW_IMAGE_NOBLOB:
6876 /**
6877 NOBLOB: Remove unnecessary BLOB fields from read_set
6878 (the ones that are not part of PK).
6879 */
6880 bitmap_copy(&table->tmp_set, table->read_set);
6881 for (Field **ptr=table->field ; *ptr ; ptr++)
6882 {
6883 Field *field= (*ptr);
6884 if ((field->type() == MYSQL_TYPE_BLOB) &&
6885 !(field->flags & PRI_KEY_FLAG))
6886 bitmap_clear_bit(&table->tmp_set, field->field_index);
6887 }
6888 break;
6889 default:
6890 DBUG_ASSERT(0); // impossible.
6891 }
6892
6893 /* set the temporary read_set */
6894 table->column_bitmaps_set_no_signal(&table->tmp_set,
6895 table->write_set);
6896 }
6897
6898 DBUG_PRINT_BITSET("debug", "table->read_set (after preparing): %s", table->read_set);
6899 DBUG_VOID_RETURN;
6900}
6901
6902
6903
6904int THD::binlog_remove_pending_rows_event(bool clear_maps,
6905 bool is_transactional)
6906{
6907 DBUG_ENTER("THD::binlog_remove_pending_rows_event");
6908
6909 if(!WSREP_EMULATE_BINLOG(this) && !mysql_bin_log.is_open())
6910 DBUG_RETURN(0);
6911
6912 /* Ensure that all events in a GTID group are in the same cache */
6913 if (variables.option_bits & OPTION_GTID_BEGIN)
6914 is_transactional= 1;
6915
6916 mysql_bin_log.remove_pending_rows_event(this, is_transactional);
6917
6918 if (clear_maps)
6919 binlog_table_maps= 0;
6920
6921 DBUG_RETURN(0);
6922}
6923
6924int THD::binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional)
6925{
6926 DBUG_ENTER("THD::binlog_flush_pending_rows_event");
6927 /*
6928 We shall flush the pending event even if we are not in row-based
6929 mode: it might be the case that we left row-based mode before
6930 flushing anything (e.g., if we have explicitly locked tables).
6931 */
6932 if(!WSREP_EMULATE_BINLOG(this) && !mysql_bin_log.is_open())
6933 DBUG_RETURN(0);
6934
6935 /* Ensure that all events in a GTID group are in the same cache */
6936 if (variables.option_bits & OPTION_GTID_BEGIN)
6937 is_transactional= 1;
6938
6939 /*
6940 Mark the event as the last event of a statement if the stmt_end
6941 flag is set.
6942 */
6943 int error= 0;
6944 if (Rows_log_event *pending= binlog_get_pending_rows_event(is_transactional))
6945 {
6946 if (stmt_end)
6947 {
6948 pending->set_flags(Rows_log_event::STMT_END_F);
6949 binlog_table_maps= 0;
6950 }
6951
6952 error= mysql_bin_log.flush_and_set_pending_rows_event(this, 0,
6953 is_transactional);
6954 }
6955
6956 DBUG_RETURN(error);
6957}
6958
6959
6960#if !defined(DBUG_OFF) && !defined(_lint)
6961static const char *
6962show_query_type(THD::enum_binlog_query_type qtype)
6963{
6964 switch (qtype) {
6965 case THD::ROW_QUERY_TYPE:
6966 return "ROW";
6967 case THD::STMT_QUERY_TYPE:
6968 return "STMT";
6969 case THD::QUERY_TYPE_COUNT:
6970 default:
6971 DBUG_ASSERT(0 <= qtype && qtype < THD::QUERY_TYPE_COUNT);
6972 }
6973 static char buf[64];
6974 sprintf(buf, "UNKNOWN#%d", qtype);
6975 return buf;
6976}
6977#endif
6978
6979/*
6980 Constants required for the limit unsafe warnings suppression
6981*/
6982//seconds after which the limit unsafe warnings suppression will be activated
6983#define LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT 5*60
6984//number of limit unsafe warnings after which the suppression will be activated
6985#define LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT 10
6986
6987static ulonglong unsafe_suppression_start_time= 0;
6988static bool unsafe_warning_suppression_active[LEX::BINLOG_STMT_UNSAFE_COUNT];
6989static ulong unsafe_warnings_count[LEX::BINLOG_STMT_UNSAFE_COUNT];
6990static ulong total_unsafe_warnings_count;
6991
6992/**
6993 Auxiliary function to reset the limit unsafety warning suppression.
6994 This is done without mutex protection, but this should be good
6995 enough as it doesn't matter if we loose a couple of suppressed
6996 messages or if this is called multiple times.
6997*/
6998
6999static void reset_binlog_unsafe_suppression(ulonglong now)
7000{
7001 uint i;
7002 DBUG_ENTER("reset_binlog_unsafe_suppression");
7003
7004 unsafe_suppression_start_time= now;
7005 total_unsafe_warnings_count= 0;
7006
7007 for (i= 0 ; i < LEX::BINLOG_STMT_UNSAFE_COUNT ; i++)
7008 {
7009 unsafe_warnings_count[i]= 0;
7010 unsafe_warning_suppression_active[i]= 0;
7011 }
7012 DBUG_VOID_RETURN;
7013}
7014
7015/**
7016 Auxiliary function to print warning in the error log.
7017*/
7018static void print_unsafe_warning_to_log(THD *thd, int unsafe_type, char* buf,
7019 char* query)
7020{
7021 DBUG_ENTER("print_unsafe_warning_in_log");
7022 sprintf(buf, ER_THD(thd, ER_BINLOG_UNSAFE_STATEMENT),
7023 ER_THD(thd, LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
7024 sql_print_warning(ER_THD(thd, ER_MESSAGE_AND_STATEMENT), buf, query);
7025 DBUG_VOID_RETURN;
7026}
7027
7028/**
7029 Auxiliary function to check if the warning for unsafe repliction statements
7030 should be thrown or suppressed.
7031
7032 Logic is:
7033 - If we get more than LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT errors
7034 of one type, that type of errors will be suppressed for
7035 LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT.
7036 - When the time limit has been reached, all suppression is reset.
7037
7038 This means that if one gets many different types of errors, some of them
7039 may be reset less than LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT. However at
7040 least one error is disable for this time.
7041
7042 SYNOPSIS:
7043 @params
7044 unsafe_type - The type of unsafety.
7045
7046 RETURN:
7047 0 0k to log
7048 1 Message suppressed
7049*/
7050
7051static bool protect_against_unsafe_warning_flood(int unsafe_type)
7052{
7053 ulong count;
7054 ulonglong now= my_interval_timer()/1000000000ULL;
7055 DBUG_ENTER("protect_against_unsafe_warning_flood");
7056
7057 count= ++unsafe_warnings_count[unsafe_type];
7058 total_unsafe_warnings_count++;
7059
7060 /*
7061 INITIALIZING:
7062 If this is the first time this function is called with log warning
7063 enabled, the monitoring the unsafe warnings should start.
7064 */
7065 if (unsafe_suppression_start_time == 0)
7066 {
7067 reset_binlog_unsafe_suppression(now);
7068 DBUG_RETURN(0);
7069 }
7070
7071 /*
7072 The following is true if we got too many errors or if the error was
7073 already suppressed
7074 */
7075 if (count >= LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT)
7076 {
7077 ulonglong diff_time= (now - unsafe_suppression_start_time);
7078
7079 if (!unsafe_warning_suppression_active[unsafe_type])
7080 {
7081 /*
7082 ACTIVATION:
7083 We got LIMIT_UNSAFE_WARNING_ACTIVATION_THRESHOLD_COUNT warnings in
7084 less than LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT we activate the
7085 suppression.
7086 */
7087 if (diff_time <= LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT)
7088 {
7089 unsafe_warning_suppression_active[unsafe_type]= 1;
7090 sql_print_information("Suppressing warnings of type '%s' for up to %d seconds because of flooding",
7091 ER(LEX::binlog_stmt_unsafe_errcode[unsafe_type]),
7092 LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT);
7093 }
7094 else
7095 {
7096 /*
7097 There is no flooding till now, therefore we restart the monitoring
7098 */
7099 reset_binlog_unsafe_suppression(now);
7100 }
7101 }
7102 else
7103 {
7104 /* This type of warnings was suppressed */
7105 if (diff_time > LIMIT_UNSAFE_WARNING_ACTIVATION_TIMEOUT)
7106 {
7107 ulong save_count= total_unsafe_warnings_count;
7108 /* Print a suppression note and remove the suppression */
7109 reset_binlog_unsafe_suppression(now);
7110 sql_print_information("Suppressed %lu unsafe warnings during "
7111 "the last %d seconds",
7112 save_count, (int) diff_time);
7113 }
7114 }
7115 }
7116 DBUG_RETURN(unsafe_warning_suppression_active[unsafe_type]);
7117}
7118
7119MYSQL_TIME THD::query_start_TIME()
7120{
7121 MYSQL_TIME res;
7122 variables.time_zone->gmt_sec_to_TIME(&res, query_start());
7123 res.second_part= query_start_sec_part();
7124 time_zone_used= 1;
7125 return res;
7126}
7127
7128/**
7129 Auxiliary method used by @c binlog_query() to raise warnings.
7130
7131 The type of warning and the type of unsafeness is stored in
7132 THD::binlog_unsafe_warning_flags.
7133*/
7134void THD::issue_unsafe_warnings()
7135{
7136 char buf[MYSQL_ERRMSG_SIZE * 2];
7137 uint32 unsafe_type_flags;
7138 DBUG_ENTER("issue_unsafe_warnings");
7139 /*
7140 Ensure that binlog_unsafe_warning_flags is big enough to hold all
7141 bits. This is actually a constant expression.
7142 */
7143 DBUG_ASSERT(LEX::BINLOG_STMT_UNSAFE_COUNT <=
7144 sizeof(binlog_unsafe_warning_flags) * CHAR_BIT);
7145
7146 if (!(unsafe_type_flags= binlog_unsafe_warning_flags))
7147 DBUG_VOID_RETURN; // Nothing to do
7148
7149 /*
7150 For each unsafe_type, check if the statement is unsafe in this way
7151 and issue a warning.
7152 */
7153 for (int unsafe_type=0;
7154 unsafe_type < LEX::BINLOG_STMT_UNSAFE_COUNT;
7155 unsafe_type++)
7156 {
7157 if ((unsafe_type_flags & (1 << unsafe_type)) != 0)
7158 {
7159 push_warning_printf(this, Sql_condition::WARN_LEVEL_NOTE,
7160 ER_BINLOG_UNSAFE_STATEMENT,
7161 ER_THD(this, ER_BINLOG_UNSAFE_STATEMENT),
7162 ER_THD(this, LEX::binlog_stmt_unsafe_errcode[unsafe_type]));
7163 if (global_system_variables.log_warnings > 0 &&
7164 !protect_against_unsafe_warning_flood(unsafe_type))
7165 print_unsafe_warning_to_log(this, unsafe_type, buf, query());
7166 }
7167 }
7168 DBUG_VOID_RETURN;
7169}
7170
7171/**
7172 Log the current query.
7173
7174 The query will be logged in either row format or statement format
7175 depending on the value of @c current_stmt_binlog_format_row field and
7176 the value of the @c qtype parameter.
7177
7178 This function must be called:
7179
7180 - After the all calls to ha_*_row() functions have been issued.
7181
7182 - After any writes to system tables. Rationale: if system tables
7183 were written after a call to this function, and the master crashes
7184 after the call to this function and before writing the system
7185 tables, then the master and slave get out of sync.
7186
7187 - Before tables are unlocked and closed.
7188
7189 @see decide_logging_format
7190
7191 @retval 0 Success
7192
7193 @retval nonzero If there is a failure when writing the query (e.g.,
7194 write failure), then the error code is returned.
7195*/
7196int THD::binlog_query(THD::enum_binlog_query_type qtype, char const *query_arg,
7197 ulong query_len, bool is_trans, bool direct,
7198 bool suppress_use, int errcode)
7199{
7200 DBUG_ENTER("THD::binlog_query");
7201 DBUG_PRINT("enter", ("qtype: %s query: '%-.*s'",
7202 show_query_type(qtype), (int) query_len, query_arg));
7203
7204 DBUG_ASSERT(query_arg);
7205 DBUG_ASSERT(WSREP_EMULATE_BINLOG(this) || mysql_bin_log.is_open());
7206
7207 /* If this is withing a BEGIN ... COMMIT group, don't log it */
7208 if (variables.option_bits & OPTION_GTID_BEGIN)
7209 {
7210 direct= 0;
7211 is_trans= 1;
7212 }
7213 DBUG_PRINT("info", ("is_trans: %d direct: %d", is_trans, direct));
7214
7215 if (get_binlog_local_stmt_filter() == BINLOG_FILTER_SET)
7216 {
7217 /*
7218 The current statement is to be ignored, and not written to
7219 the binlog. Do not call issue_unsafe_warnings().
7220 */
7221 DBUG_RETURN(0);
7222 }
7223
7224 /*
7225 If we are not in prelocked mode, mysql_unlock_tables() will be
7226 called after this binlog_query(), so we have to flush the pending
7227 rows event with the STMT_END_F set to unlock all tables at the
7228 slave side as well.
7229
7230 If we are in prelocked mode, the flushing will be done inside the
7231 top-most close_thread_tables().
7232 */
7233 if (this->locked_tables_mode <= LTM_LOCK_TABLES)
7234 {
7235 int error;
7236 if (unlikely(error= binlog_flush_pending_rows_event(TRUE, is_trans)))
7237 DBUG_RETURN(error);
7238 }
7239
7240 /*
7241 Warnings for unsafe statements logged in statement format are
7242 printed in three places instead of in decide_logging_format().
7243 This is because the warnings should be printed only if the statement
7244 is actually logged. When executing decide_logging_format(), we cannot
7245 know for sure if the statement will be logged:
7246
7247 1 - sp_head::execute_procedure which prints out warnings for calls to
7248 stored procedures.
7249
7250 2 - sp_head::execute_function which prints out warnings for calls
7251 involving functions.
7252
7253 3 - THD::binlog_query (here) which prints warning for top level
7254 statements not covered by the two cases above: i.e., if not insided a
7255 procedure and a function.
7256
7257 Besides, we should not try to print these warnings if it is not
7258 possible to write statements to the binary log as it happens when
7259 the execution is inside a function, or generaly speaking, when
7260 the variables.option_bits & OPTION_BIN_LOG is false.
7261
7262 */
7263 if ((variables.option_bits & OPTION_BIN_LOG) &&
7264 spcont == NULL && !binlog_evt_union.do_union)
7265 issue_unsafe_warnings();
7266
7267 switch (qtype) {
7268 /*
7269 ROW_QUERY_TYPE means that the statement may be logged either in
7270 row format or in statement format. If
7271 current_stmt_binlog_format is row, it means that the
7272 statement has already been logged in row format and hence shall
7273 not be logged again.
7274 */
7275 case THD::ROW_QUERY_TYPE:
7276 DBUG_PRINT("debug",
7277 ("is_current_stmt_binlog_format_row: %d",
7278 is_current_stmt_binlog_format_row()));
7279 if (is_current_stmt_binlog_format_row())
7280 DBUG_RETURN(0);
7281 /* Fall through */
7282
7283 /*
7284 STMT_QUERY_TYPE means that the query must be logged in statement
7285 format; it cannot be logged in row format. This is typically
7286 used by DDL statements. It is an error to use this query type
7287 if current_stmt_binlog_format_row is row.
7288
7289 @todo Currently there are places that call this method with
7290 STMT_QUERY_TYPE and current_stmt_binlog_format is row. Fix those
7291 places and add assert to ensure correct behavior. /Sven
7292 */
7293 case THD::STMT_QUERY_TYPE:
7294 /*
7295 The MYSQL_LOG::write() function will set the STMT_END_F flag and
7296 flush the pending rows event if necessary.
7297 */
7298 {
7299 int error = 0;
7300
7301 /*
7302 Binlog table maps will be irrelevant after a Query_log_event
7303 (they are just removed on the slave side) so after the query
7304 log event is written to the binary log, we pretend that no
7305 table maps were written.
7306 */
7307 if(binlog_should_compress(query_len))
7308 {
7309 Query_compressed_log_event qinfo(this, query_arg, query_len, is_trans, direct,
7310 suppress_use, errcode);
7311 error= mysql_bin_log.write(&qinfo);
7312 }
7313 else
7314 {
7315 Query_log_event qinfo(this, query_arg, query_len, is_trans, direct,
7316 suppress_use, errcode);
7317 error= mysql_bin_log.write(&qinfo);
7318 }
7319
7320 binlog_table_maps= 0;
7321 DBUG_RETURN(error);
7322 }
7323
7324 case THD::QUERY_TYPE_COUNT:
7325 default:
7326 DBUG_ASSERT(qtype < QUERY_TYPE_COUNT);
7327 }
7328 DBUG_RETURN(0);
7329}
7330
7331void
7332THD::wait_for_wakeup_ready()
7333{
7334 mysql_mutex_lock(&LOCK_wakeup_ready);
7335 while (!wakeup_ready)
7336 mysql_cond_wait(&COND_wakeup_ready, &LOCK_wakeup_ready);
7337 mysql_mutex_unlock(&LOCK_wakeup_ready);
7338}
7339
7340void
7341THD::signal_wakeup_ready()
7342{
7343 mysql_mutex_lock(&LOCK_wakeup_ready);
7344 wakeup_ready= true;
7345 mysql_mutex_unlock(&LOCK_wakeup_ready);
7346 mysql_cond_signal(&COND_wakeup_ready);
7347}
7348
7349
7350void
7351wait_for_commit::reinit()
7352{
7353 subsequent_commits_list= NULL;
7354 next_subsequent_commit= NULL;
7355 waitee= NULL;
7356 opaque_pointer= NULL;
7357 wakeup_error= 0;
7358 wakeup_subsequent_commits_running= false;
7359 commit_started= false;
7360#ifdef SAFE_MUTEX
7361 /*
7362 When using SAFE_MUTEX, the ordering between taking the LOCK_wait_commit
7363 mutexes is checked. This causes a problem when we re-use a mutex, as then
7364 the expected locking order may change.
7365
7366 So in this case, do a re-init of the mutex. In release builds, we want to
7367 avoid the overhead of a re-init though.
7368
7369 To ensure that no one is locking the mutex, we take a lock of it first.
7370 For full explanation, see wait_for_commit::~wait_for_commit()
7371 */
7372 mysql_mutex_lock(&LOCK_wait_commit);
7373 mysql_mutex_unlock(&LOCK_wait_commit);
7374
7375 mysql_mutex_destroy(&LOCK_wait_commit);
7376 mysql_mutex_init(key_LOCK_wait_commit, &LOCK_wait_commit, MY_MUTEX_INIT_FAST);
7377#endif
7378}
7379
7380
7381wait_for_commit::wait_for_commit()
7382{
7383 mysql_mutex_init(key_LOCK_wait_commit, &LOCK_wait_commit, MY_MUTEX_INIT_FAST);
7384 mysql_cond_init(key_COND_wait_commit, &COND_wait_commit, 0);
7385 reinit();
7386}
7387
7388
7389wait_for_commit::~wait_for_commit()
7390{
7391 /*
7392 Since we do a dirty read of the waiting_for_commit flag in
7393 wait_for_prior_commit() and in unregister_wait_for_prior_commit(), we need
7394 to take extra care before freeing the wait_for_commit object.
7395
7396 It is possible for the waitee to be pre-empted inside wakeup(), just after
7397 it has cleared the waiting_for_commit flag and before it has released the
7398 LOCK_wait_commit mutex. And then it is possible for the waiter to find the
7399 flag cleared in wait_for_prior_commit() and go finish up things and
7400 de-allocate the LOCK_wait_commit and COND_wait_commit objects before the
7401 waitee has time to be re-scheduled and finish unlocking the mutex and
7402 signalling the condition. This would lead to the waitee accessing no
7403 longer valid memory.
7404
7405 To prevent this, we do an extra lock/unlock of the mutex here before
7406 deallocation; this makes certain that any waitee has completed wakeup()
7407 first.
7408 */
7409 mysql_mutex_lock(&LOCK_wait_commit);
7410 mysql_mutex_unlock(&LOCK_wait_commit);
7411
7412 mysql_mutex_destroy(&LOCK_wait_commit);
7413 mysql_cond_destroy(&COND_wait_commit);
7414}
7415
7416
7417void
7418wait_for_commit::wakeup(int wakeup_error)
7419{
7420 /*
7421 We signal each waiter on their own condition and mutex (rather than using
7422 pthread_cond_broadcast() or something like that).
7423
7424 Otherwise we would need to somehow ensure that they were done
7425 waking up before we could allow this THD to be destroyed, which would
7426 be annoying and unnecessary.
7427
7428 Note that wakeup_subsequent_commits2() depends on this function being a
7429 full memory barrier (it is, because it takes a mutex lock).
7430
7431 */
7432 mysql_mutex_lock(&LOCK_wait_commit);
7433 waitee= NULL;
7434 this->wakeup_error= wakeup_error;
7435 /*
7436 Note that it is critical that the mysql_cond_signal() here is done while
7437 still holding the mutex. As soon as we release the mutex, the waiter might
7438 deallocate the condition object.
7439 */
7440 mysql_cond_signal(&COND_wait_commit);
7441 mysql_mutex_unlock(&LOCK_wait_commit);
7442}
7443
7444
7445/*
7446 Register that the next commit of this THD should wait to complete until
7447 commit in another THD (the waitee) has completed.
7448
7449 The wait may occur explicitly, with the waiter sitting in
7450 wait_for_prior_commit() until the waitee calls wakeup_subsequent_commits().
7451
7452 Alternatively, the TC (eg. binlog) may do the commits of both waitee and
7453 waiter at once during group commit, resolving both of them in the right
7454 order.
7455
7456 Only one waitee can be registered for a waiter; it must be removed by
7457 wait_for_prior_commit() or unregister_wait_for_prior_commit() before a new
7458 one is registered. But it is ok for several waiters to register a wait for
7459 the same waitee. It is also permissible for one THD to be both a waiter and
7460 a waitee at the same time.
7461*/
7462void
7463wait_for_commit::register_wait_for_prior_commit(wait_for_commit *waitee)
7464{
7465 DBUG_ASSERT(!this->waitee /* No prior registration allowed */);
7466 wakeup_error= 0;
7467 this->waitee= waitee;
7468
7469 mysql_mutex_lock(&waitee->LOCK_wait_commit);
7470 /*
7471 If waitee is in the middle of wakeup, then there is nothing to wait for,
7472 so we need not register. This is necessary to avoid a race in unregister,
7473 see comments on wakeup_subsequent_commits2() for details.
7474 */
7475 if (waitee->wakeup_subsequent_commits_running)
7476 this->waitee= NULL;
7477 else
7478 {
7479 /*
7480 Put ourself at the head of the waitee's list of transactions that must
7481 wait for it to commit first.
7482 */
7483 this->next_subsequent_commit= waitee->subsequent_commits_list;
7484 waitee->subsequent_commits_list= this;
7485 }
7486 mysql_mutex_unlock(&waitee->LOCK_wait_commit);
7487}
7488
7489
7490/*
7491 Wait for commit of another transaction to complete, as already registered
7492 with register_wait_for_prior_commit(). If the commit already completed,
7493 returns immediately.
7494*/
7495int
7496wait_for_commit::wait_for_prior_commit2(THD *thd)
7497{
7498 PSI_stage_info old_stage;
7499 wait_for_commit *loc_waitee;
7500
7501 mysql_mutex_lock(&LOCK_wait_commit);
7502 DEBUG_SYNC(thd, "wait_for_prior_commit_waiting");
7503 thd->ENTER_COND(&COND_wait_commit, &LOCK_wait_commit,
7504 &stage_waiting_for_prior_transaction_to_commit,
7505 &old_stage);
7506 while ((loc_waitee= this->waitee) && likely(!thd->check_killed()))
7507 mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
7508 if (!loc_waitee)
7509 {
7510 if (wakeup_error)
7511 my_error(ER_PRIOR_COMMIT_FAILED, MYF(0));
7512 goto end;
7513 }
7514 /*
7515 Wait was interrupted by kill. We need to unregister our wait and give the
7516 error. But if a wakeup is already in progress, then we must ignore the
7517 kill and not give error, otherwise we get inconsistency between waitee and
7518 waiter as to whether we succeed or fail (eg. we may roll back but waitee
7519 might attempt to commit both us and any subsequent commits waiting for us).
7520 */
7521 mysql_mutex_lock(&loc_waitee->LOCK_wait_commit);
7522 if (loc_waitee->wakeup_subsequent_commits_running)
7523 {
7524 /* We are being woken up; ignore the kill and just wait. */
7525 mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
7526 do
7527 {
7528 mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
7529 } while (this->waitee);
7530 if (wakeup_error)
7531 my_error(ER_PRIOR_COMMIT_FAILED, MYF(0));
7532 goto end;
7533 }
7534 remove_from_list(&loc_waitee->subsequent_commits_list);
7535 mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
7536 this->waitee= NULL;
7537
7538 wakeup_error= thd->killed_errno();
7539 if (!wakeup_error)
7540 wakeup_error= ER_QUERY_INTERRUPTED;
7541 my_message(wakeup_error, ER_THD(thd, wakeup_error), MYF(0));
7542 thd->EXIT_COND(&old_stage);
7543 /*
7544 Must do the DEBUG_SYNC() _after_ exit_cond(), as DEBUG_SYNC is not safe to
7545 use within enter_cond/exit_cond.
7546 */
7547 DEBUG_SYNC(thd, "wait_for_prior_commit_killed");
7548 return wakeup_error;
7549
7550end:
7551 thd->EXIT_COND(&old_stage);
7552 return wakeup_error;
7553}
7554
7555
7556/*
7557 Wakeup anyone waiting for us to have committed.
7558
7559 Note about locking:
7560
7561 We have a potential race or deadlock between wakeup_subsequent_commits() in
7562 the waitee and unregister_wait_for_prior_commit() in the waiter.
7563
7564 Both waiter and waitee needs to take their own lock before it is safe to take
7565 a lock on the other party - else the other party might disappear and invalid
7566 memory data could be accessed. But if we take the two locks in different
7567 order, we may end up in a deadlock.
7568
7569 The waiter needs to lock the waitee to delete itself from the list in
7570 unregister_wait_for_prior_commit(). Thus wakeup_subsequent_commits() can not
7571 hold its own lock while locking waiters, as this could lead to deadlock.
7572
7573 So we need to prevent unregister_wait_for_prior_commit() running while wakeup
7574 is in progress - otherwise the unregister could complete before the wakeup,
7575 leading to incorrect spurious wakeup or accessing invalid memory.
7576
7577 However, if we are in the middle of running wakeup_subsequent_commits(), then
7578 there is no need for unregister_wait_for_prior_commit() in the first place -
7579 the waiter can just do a normal wait_for_prior_commit(), as it will be
7580 immediately woken up.
7581
7582 So the solution to the potential race/deadlock is to set a flag in the waitee
7583 that wakeup_subsequent_commits() is in progress. When this flag is set,
7584 unregister_wait_for_prior_commit() becomes just wait_for_prior_commit().
7585
7586 Then also register_wait_for_prior_commit() needs to check if
7587 wakeup_subsequent_commits() is running, and skip the registration if
7588 so. This is needed in case a new waiter manages to register itself and
7589 immediately try to unregister while wakeup_subsequent_commits() is
7590 running. Else the new waiter would also wait rather than unregister, but it
7591 would not be woken up until next wakeup, which could be potentially much
7592 later than necessary.
7593*/
7594
7595void
7596wait_for_commit::wakeup_subsequent_commits2(int wakeup_error)
7597{
7598 wait_for_commit *waiter;
7599
7600 mysql_mutex_lock(&LOCK_wait_commit);
7601 wakeup_subsequent_commits_running= true;
7602 waiter= subsequent_commits_list;
7603 subsequent_commits_list= NULL;
7604 mysql_mutex_unlock(&LOCK_wait_commit);
7605
7606 while (waiter)
7607 {
7608 /*
7609 Important: we must grab the next pointer before waking up the waiter;
7610 once the wakeup is done, the field could be invalidated at any time.
7611 */
7612 wait_for_commit *next= waiter->next_subsequent_commit;
7613 waiter->wakeup(wakeup_error);
7614 waiter= next;
7615 }
7616
7617 /*
7618 We need a full memory barrier between walking the list above, and clearing
7619 the flag wakeup_subsequent_commits_running below. This barrier is needed
7620 to ensure that no other thread will start to modify the list pointers
7621 before we are done traversing the list.
7622
7623 But wait_for_commit::wakeup() does a full memory barrier already (it locks
7624 a mutex), so no extra explicit barrier is needed here.
7625 */
7626 wakeup_subsequent_commits_running= false;
7627 DBUG_EXECUTE_IF("inject_wakeup_subsequent_commits_sleep", my_sleep(21000););
7628}
7629
7630
7631/* Cancel a previously registered wait for another THD to commit before us. */
7632void
7633wait_for_commit::unregister_wait_for_prior_commit2()
7634{
7635 wait_for_commit *loc_waitee;
7636
7637 mysql_mutex_lock(&LOCK_wait_commit);
7638 if ((loc_waitee= this->waitee))
7639 {
7640 mysql_mutex_lock(&loc_waitee->LOCK_wait_commit);
7641 if (loc_waitee->wakeup_subsequent_commits_running)
7642 {
7643 /*
7644 When a wakeup is running, we cannot safely remove ourselves from the
7645 list without corrupting it. Instead we can just wait, as wakeup is
7646 already in progress and will thus be immediate.
7647
7648 See comments on wakeup_subsequent_commits2() for more details.
7649 */
7650 mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
7651 while (this->waitee)
7652 mysql_cond_wait(&COND_wait_commit, &LOCK_wait_commit);
7653 }
7654 else
7655 {
7656 /* Remove ourselves from the list in the waitee. */
7657 remove_from_list(&loc_waitee->subsequent_commits_list);
7658 mysql_mutex_unlock(&loc_waitee->LOCK_wait_commit);
7659 this->waitee= NULL;
7660 }
7661 }
7662 wakeup_error= 0;
7663 mysql_mutex_unlock(&LOCK_wait_commit);
7664}
7665
7666
7667bool Discrete_intervals_list::append(ulonglong start, ulonglong val,
7668 ulonglong incr)
7669{
7670 DBUG_ENTER("Discrete_intervals_list::append");
7671 /* first, see if this can be merged with previous */
7672 if ((head == NULL) || tail->merge_if_contiguous(start, val, incr))
7673 {
7674 /* it cannot, so need to add a new interval */
7675 Discrete_interval *new_interval= new Discrete_interval(start, val, incr);
7676 DBUG_RETURN(append(new_interval));
7677 }
7678 DBUG_RETURN(0);
7679}
7680
7681bool Discrete_intervals_list::append(Discrete_interval *new_interval)
7682{
7683 DBUG_ENTER("Discrete_intervals_list::append");
7684 if (unlikely(new_interval == NULL))
7685 DBUG_RETURN(1);
7686 DBUG_PRINT("info",("adding new auto_increment interval"));
7687 if (head == NULL)
7688 head= current= new_interval;
7689 else
7690 tail->next= new_interval;
7691 tail= new_interval;
7692 elements++;
7693 DBUG_RETURN(0);
7694}
7695
7696
7697void AUTHID::copy(MEM_ROOT *mem_root, const LEX_CSTRING *user_name,
7698 const LEX_CSTRING *host_name)
7699{
7700 user.str= strmake_root(mem_root, user_name->str, user_name->length);
7701 user.length= user_name->length;
7702
7703 host.str= strmake_root(mem_root, host_name->str, host_name->length);
7704 host.length= host_name->length;
7705}
7706
7707
7708/*
7709 Set from a string in 'user@host' format.
7710 This method resebmles parse_user(),
7711 but does not need temporary buffers.
7712*/
7713void AUTHID::parse(const char *str, size_t length)
7714{
7715 const char *p= strrchr(str, '@');
7716 if (!p)
7717 {
7718 user.str= str;
7719 user.length= length;
7720 host= null_clex_str;
7721 }
7722 else
7723 {
7724 user.str= str;
7725 user.length= (size_t) (p - str);
7726 host.str= p + 1;
7727 host.length= (size_t) (length - user.length - 1);
7728 if (user.length && !host.length)
7729 host= host_not_specified; // 'user@' -> 'user@%'
7730 }
7731 if (user.length > USERNAME_LENGTH)
7732 user.length= USERNAME_LENGTH;
7733 if (host.length > HOSTNAME_LENGTH)
7734 host.length= HOSTNAME_LENGTH;
7735}
7736
7737
7738void Database_qualified_name::copy(MEM_ROOT *mem_root,
7739 const LEX_CSTRING &db,
7740 const LEX_CSTRING &name)
7741{
7742 m_db.length= db.length;
7743 m_db.str= strmake_root(mem_root, db.str, db.length);
7744 m_name.length= name.length;
7745 m_name.str= strmake_root(mem_root, name.str, name.length);
7746}
7747
7748
7749bool Table_ident::append_to(THD *thd, String *str) const
7750{
7751 return (db.length &&
7752 (append_identifier(thd, str, db.str, db.length) ||
7753 str->append('.'))) ||
7754 append_identifier(thd, str, table.str, table.length);
7755}
7756
7757
7758bool Qualified_column_ident::append_to(THD *thd, String *str) const
7759{
7760 return Table_ident::append_to(thd, str) || str->append('.') ||
7761 append_identifier(thd, str, m_column.str, m_column.length);
7762}
7763
7764
7765#endif /* !defined(MYSQL_CLIENT) */
7766
7767
7768Query_arena_stmt::Query_arena_stmt(THD *_thd) :
7769 thd(_thd)
7770{
7771 arena= thd->activate_stmt_arena_if_needed(&backup);
7772}
7773
7774Query_arena_stmt::~Query_arena_stmt()
7775{
7776 if (arena)
7777 thd->restore_active_arena(arena, &backup);
7778}
7779
7780
7781bool THD::timestamp_to_TIME(MYSQL_TIME *ltime, my_time_t ts,
7782 ulong sec_part, ulonglong fuzzydate)
7783{
7784 time_zone_used= 1;
7785 if (ts == 0 && sec_part == 0)
7786 {
7787 if (fuzzydate & TIME_NO_ZERO_DATE)
7788 return 1;
7789 set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
7790 }
7791 else
7792 {
7793 variables.time_zone->gmt_sec_to_TIME(ltime, ts);
7794 ltime->second_part= sec_part;
7795 }
7796 return 0;
7797}
7798