From 8eb16159e19b38e67728fca7c7f316f921a2c7e0 Mon Sep 17 00:00:00 2001 From: Sergey Petrunya Date: Mon, 27 Aug 2012 08:44:58 +0400 Subject: Cassandra storage engine: BKA support - We use HA_MRR_NO_ASSOC ("optimizer_switch=join_cache_hashed") mode - Not able to use BKA's buffers yet. - There is a variable to control batch size - There are status counters. - Nedeed to make some fixes in BKA code (to be checked with Igor) --- sql/sql_join_cache.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_join_cache.cc b/sql/sql_join_cache.cc index f953cf4df57..d785366ae69 100644 --- a/sql/sql_join_cache.cc +++ b/sql/sql_join_cache.cc @@ -3876,8 +3876,11 @@ int JOIN_TAB_SCAN_MRR::next() If a record in in an incremental cache contains no fields then the association for the last record in cache will be equal to cache->end_pos */ + /* + psergey: this makes no sense where HA_MRR_NO_ASSOC is used. DBUG_ASSERT(cache->buff <= (uchar *) (*ptr) && (uchar *) (*ptr) <= cache->end_pos); + */ if (join_tab->table->vfield) update_virtual_fields(join->thd, join_tab->table); } @@ -4543,7 +4546,7 @@ bool JOIN_CACHE_BKAH::prepare_look_for_matches(bool skip_last) { last_matching_rec_ref_ptr= next_matching_rec_ref_ptr= 0; if (no_association && - (curr_matching_chain= get_matching_chain_by_join_key())) + !(curr_matching_chain= get_matching_chain_by_join_key())) //psergey: added '!' return 1; last_matching_rec_ref_ptr= get_next_rec_ref(curr_matching_chain); return 0; -- cgit v1.2.1 From 8c641484dc43571b16edeb9780a587472fc1f14b Mon Sep 17 00:00:00 2001 From: Jon Olav Hauglid Date: Tue, 11 Sep 2012 16:29:51 +0200 Subject: WL#6454: Deprecate SHOW AUTHORS and SHOW CONTRIBUTORS Added deprecation warning for SHOW AUTHORS and SHOW CONTRIBUTORS. This is the 5.5 version of the patch. --- sql/sql_yacc.yy | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'sql') diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index 45024faa03f..e93ed4e8853 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -11010,11 +11010,19 @@ show_param: { LEX *lex=Lex; lex->sql_command= SQLCOM_SHOW_AUTHORS; + push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT, + ER(ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT), + "SHOW AUTHORS"); } | CONTRIBUTORS_SYM { LEX *lex=Lex; lex->sql_command= SQLCOM_SHOW_CONTRIBUTORS; + push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN, + ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT, + ER(ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT), + "SHOW CONTRIBUTORS"); } | PRIVILEGES { -- cgit v1.2.1 From 88f2746a7a22734d2f2aaa2ac20cc40665e52f6c Mon Sep 17 00:00:00 2001 From: Tor Didriksen Date: Tue, 18 Sep 2012 17:32:02 +0200 Subject: Bug#14542543 FIX BUG #12694872 IN 5.5 Bug#14530242 CRASH / MEMORY CORRUPTION IN FILESORT_BUFFER::GET_RECORD_BUFFER WITH MYISAM This is a backport of Bug#12694872 - VALGRIND: 18,816 BYTES IN 196 BLOCKS ARE DEFINITELY LOST Bug#13340270: assertion table->sort.record_pointers == __null Bug#14536113 CRASH IN CLOSEFRM (TABLE.CC) OR UNPACK (FIELD.H) ON SUBQUERY WITH MYISAM TABLES Also: removed and re-added test files with file-ids from trunk. --- sql/filesort.cc | 3 +++ sql/opt_range.cc | 7 ++++++- sql/sql_select.cc | 12 ++++++------ sql/uniques.cc | 7 ++++++- 4 files changed, 21 insertions(+), 8 deletions(-) (limited to 'sql') diff --git a/sql/filesort.cc b/sql/filesort.cc index dba09c969e3..a11be501991 100644 --- a/sql/filesort.cc +++ b/sql/filesort.cc @@ -138,6 +138,7 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, */ memcpy(&table_sort, &table->sort, sizeof(FILESORT_INFO)); table->sort.io_cache= NULL; + DBUG_ASSERT(table_sort.record_pointers == NULL); outfile= table_sort.io_cache; my_b_clear(&tempfile); @@ -366,6 +367,7 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, void filesort_free_buffers(TABLE *table, bool full) { + DBUG_ENTER("filesort_free_buffers"); my_free(table->sort.record_pointers); table->sort.record_pointers= NULL; @@ -383,6 +385,7 @@ void filesort_free_buffers(TABLE *table, bool full) my_free(table->sort.addon_field); table->sort.addon_buf= NULL; table->sort.addon_field= NULL; + DBUG_VOID_RETURN; } /** Make a array of string pointers. */ diff --git a/sql/opt_range.cc b/sql/opt_range.cc index 8d221af392b..ce48a8da958 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -74,6 +74,7 @@ #include "records.h" // init_read_record, end_read_record #include #include "sql_select.h" +#include "filesort.h" // filesort_free_buffers #ifndef EXTRA_DEBUG #define test_rb_tree(A,B) {} @@ -1246,7 +1247,8 @@ int QUICK_INDEX_MERGE_SELECT::init() int QUICK_INDEX_MERGE_SELECT::reset() { DBUG_ENTER("QUICK_INDEX_MERGE_SELECT::reset"); - DBUG_RETURN(read_keys_and_merge()); + const int retval= read_keys_and_merge(); + DBUG_RETURN(retval); } bool @@ -8295,7 +8297,10 @@ int QUICK_INDEX_MERGE_SELECT::read_keys_and_merge() thd->variables.sortbuff_size); } else + { unique->reset(); + filesort_free_buffers(head, false); + } DBUG_ASSERT(file->ref_length == unique->get_size()); DBUG_ASSERT(thd->variables.sortbuff_size == unique->get_max_in_memory_size()); diff --git a/sql/sql_select.cc b/sql/sql_select.cc index fd6d0e44597..3bde5aa8f6a 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -7173,14 +7173,14 @@ void JOIN::cleanup(bool full) { JOIN_TAB *tab,*end; /* - Only a sorted table may be cached. This sorted table is always the - first non const table in join->all_tables + Free resources allocated by filesort() and Unique::get() */ if (tables > const_tables) // Test for not-const tables - { - free_io_cache(all_tables[const_tables]); - filesort_free_buffers(all_tables[const_tables],full); - } + for (uint ix= const_tables; ix < tables; ++ix) + { + free_io_cache(all_tables[ix]); + filesort_free_buffers(all_tables[ix], full); + } if (full) { diff --git a/sql/uniques.cc b/sql/uniques.cc index e7ce2197147..71e680682cd 100644 --- a/sql/uniques.cc +++ b/sql/uniques.cc @@ -57,7 +57,10 @@ int unique_write_to_ptrs(uchar* key, element_count count, Unique *unique) Unique::Unique(qsort_cmp2 comp_func, void * comp_func_fixed_arg, uint size_arg, ulonglong max_in_memory_size_arg) - :max_in_memory_size(max_in_memory_size_arg), size(size_arg), elements(0) + :max_in_memory_size(max_in_memory_size_arg), + record_pointers(NULL), + size(size_arg), + elements(0) { my_b_clear(&file); init_tree(&tree, (ulong) (max_in_memory_size / 16), 0, size, comp_func, 0, @@ -583,6 +586,7 @@ bool Unique::get(TABLE *table) if (my_b_tell(&file) == 0) { /* Whole tree is in memory; Don't use disk if you don't need to */ + DBUG_ASSERT(table->sort.record_pointers == NULL); if ((record_pointers=table->sort.record_pointers= (uchar*) my_malloc(size * tree.elements_in_tree, MYF(0)))) { @@ -603,6 +607,7 @@ bool Unique::get(TABLE *table) bool error=1; /* Open cached file if it isn't open */ + DBUG_ASSERT(table->sort.io_cache == NULL); outfile=table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), MYF(MY_ZEROFILL)); -- cgit v1.2.1 From 8ce6582c37be81281b7ada6797c456c661c214dd Mon Sep 17 00:00:00 2001 From: Mattias Jonsson Date: Mon, 10 Sep 2012 13:32:50 +0200 Subject: Bug#14495351: CRASH IN HA_PARTITION::HANDLE_UNORDERED_NEXT The partitioning engine does not implement index_next for partitions which return HA_ERR_KEY_NOT_FOUND in index_read_map. If HA_ERR_KEY_NOT_FOUND was returned by a partition during index_read_map, that partition would not be included in following calls to index_next. If no partition returned a row in index_read_map, then the subsequent call to index_next would try to use a non existing handler (index out of bound). Even after fixing the index out of bound if at least one partition returned. So it is really two connected bugs 1) crash due to index out of bound (-1 unsigned). 2) not including partitions that returned HA_ERR_KEY_NOT_FOUND. Fixed by recording the partitions that returned HA_ERR_KEY_NOT_FOUND, and include them too when doing handle_ordered_next the first time. --- sql/ha_partition.cc | 218 +++++++++++++++++++++++++++++++++++++++++----------- sql/ha_partition.h | 4 + 2 files changed, 176 insertions(+), 46 deletions(-) (limited to 'sql') diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index 14b89bf0dc8..e9ffc7abbac 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -2670,6 +2670,17 @@ int ha_partition::open(const char *name, int mode, uint test_if_locked) if (bitmap_init(&m_bulk_insert_started, NULL, m_tot_parts + 1, FALSE)) DBUG_RETURN(error); bitmap_clear_all(&m_bulk_insert_started); + /* + Initialize the bitmap we use to keep track of partitions which returned + HA_ERR_KEY_NOT_FOUND from index_read_map. + */ + if (bitmap_init(&m_key_not_found_partitions, NULL, m_tot_parts, FALSE)) + { + bitmap_free(&m_bulk_insert_started); + DBUG_RETURN(error); + } + bitmap_clear_all(&m_key_not_found_partitions); + m_key_not_found= false; /* Initialize the bitmap we use to determine what partitions are used */ if (!m_is_clone_of) { @@ -2810,6 +2821,7 @@ err_handler: (*file)->close(); err_alloc: bitmap_free(&m_bulk_insert_started); + bitmap_free(&m_key_not_found_partitions); if (!m_is_clone_of) bitmap_free(&(m_part_info->used_partitions)); @@ -2886,6 +2898,7 @@ int ha_partition::close(void) DBUG_ASSERT(table->s == table_share); destroy_record_priority_queue(); bitmap_free(&m_bulk_insert_started); + bitmap_free(&m_key_not_found_partitions); if (!m_is_clone_of) bitmap_free(&(m_part_info->used_partitions)); file= m_file; @@ -4419,21 +4432,24 @@ int ha_partition::index_read_map(uchar *buf, const uchar *key, } -/* +/** Common routine for a number of index_read variants - SYNOPSIS - ha_partition::common_index_read() - buf Buffer where the record should be returned - have_start_key TRUE <=> the left endpoint is available, i.e. - we're in index_read call or in read_range_first - call and the range has left endpoint - - FALSE <=> there is no left endpoint (we're in - read_range_first() call and the range has no left - endpoint) + @param buf Buffer where the record should be returned. + @param have_start_key TRUE <=> the left endpoint is available, i.e. + we're in index_read call or in read_range_first + call and the range has left endpoint. + FALSE <=> there is no left endpoint (we're in + read_range_first() call and the range has no left + endpoint). - DESCRIPTION + @return Operation status + @retval 0 OK + @retval HA_ERR_END_OF_FILE Whole index scanned, without finding the record. + @retval HA_ERR_KEY_NOT_FOUND Record not found, but index cursor positioned. + @retval other error code. + + @details Start scanning the range (when invoked from read_range_first()) or doing an index lookup (when invoked from index_read_XXX): - If possible, perform partition selection @@ -4443,10 +4459,6 @@ int ha_partition::index_read_map(uchar *buf, const uchar *key, handle_unordered_scan_next_partition) YES: Fill the priority queue and get the record that is the first in the ordering - - RETURN - 0 OK - other HA_ERR_END_OF_FILE or other error code. */ int ha_partition::common_index_read(uchar *buf, bool have_start_key) @@ -4456,14 +4468,16 @@ int ha_partition::common_index_read(uchar *buf, bool have_start_key) bool reverse_order= FALSE; DBUG_ENTER("ha_partition::common_index_read"); - DBUG_PRINT("info", ("m_ordered %u m_ordered_scan_ong %u have_start_key %u", - m_ordered, m_ordered_scan_ongoing, have_start_key)); + DBUG_PRINT("info", ("m_ordered %u m_ordered_scan_ong %u", + m_ordered, m_ordered_scan_ongoing)); if (have_start_key) { m_start_key.length= key_len= calculate_key_len(table, active_index, m_start_key.key, m_start_key.keypart_map); + DBUG_PRINT("info", ("have_start_key map %u find_flag %u len %u", + m_start_key.keypart_map, m_start_key.flag, key_len)); DBUG_ASSERT(key_len); } if ((error= partition_scan_set_up(buf, have_start_key))) @@ -4481,24 +4495,16 @@ int ha_partition::common_index_read(uchar *buf, bool have_start_key) } DBUG_PRINT("info", ("m_ordered %u m_o_scan_ong %u have_start_key %u", m_ordered, m_ordered_scan_ongoing, have_start_key)); - if (!m_ordered_scan_ongoing || - (have_start_key && m_start_key.flag == HA_READ_KEY_EXACT && - !m_pkey_is_clustered && - key_len >= m_curr_key_info[0]->key_length)) + if (!m_ordered_scan_ongoing) { /* - We use unordered index scan either when read_range is used and flag - is set to not use ordered or when an exact key is used and in this - case all records will be sorted equal and thus the sort order of the - resulting records doesn't matter. + We use unordered index scan when read_range is used and flag + is set to not use ordered. We also use an unordered index scan when the number of partitions to scan is only one. The unordered index scan will use the partition set created. - Need to set unordered scan ongoing since we can come here even when - it isn't set. */ DBUG_PRINT("info", ("doing unordered scan")); - m_ordered_scan_ongoing= FALSE; error= handle_unordered_scan_next_partition(buf); } else @@ -4616,7 +4622,7 @@ int ha_partition::common_first_last(uchar *buf) int ha_partition::index_read_last_map(uchar *buf, const uchar *key, key_part_map keypart_map) { - DBUG_ENTER("ha_partition::index_read_last"); + DBUG_ENTER("ha_partition::index_read_last_map"); m_ordered= TRUE; // Safety measure end_range= 0; @@ -4709,6 +4715,8 @@ int ha_partition::index_next(uchar * buf) TODO(low priority): If we want partition to work with the HANDLER commands, we must be able to do index_last() -> index_prev() -> index_next() + and if direction changes, we must step back those partitions in + the record queue so we don't return a value from the wrong direction. */ DBUG_ASSERT(m_index_scan_type != partition_index_last); if (!m_ordered_scan_ongoing) @@ -4960,10 +4968,18 @@ int ha_partition::partition_scan_set_up(uchar * buf, bool idx_read_flag) int ha_partition::handle_unordered_next(uchar *buf, bool is_next_same) { - handler *file= m_file[m_part_spec.start_part]; + handler *file; int error; DBUG_ENTER("ha_partition::handle_unordered_next"); + if (m_part_spec.start_part >= m_tot_parts) + { + /* Should never happen! */ + DBUG_ASSERT(0); + DBUG_RETURN(HA_ERR_END_OF_FILE); + } + file= m_file[m_part_spec.start_part]; + /* We should consider if this should be split into three functions as partition_read_range is_next_same are always local constants @@ -5024,6 +5040,7 @@ int ha_partition::handle_unordered_next(uchar *buf, bool is_next_same) int ha_partition::handle_unordered_scan_next_partition(uchar * buf) { uint i; + int saved_error= HA_ERR_END_OF_FILE; DBUG_ENTER("ha_partition::handle_unordered_scan_next_partition"); for (i= m_part_spec.start_part; i <= m_part_spec.end_part; i++) @@ -5074,26 +5091,33 @@ int ha_partition::handle_unordered_scan_next_partition(uchar * buf) } if ((error != HA_ERR_END_OF_FILE) && (error != HA_ERR_KEY_NOT_FOUND)) DBUG_RETURN(error); - DBUG_PRINT("info", ("HA_ERR_END_OF_FILE on partition %d", i)); + + /* + If HA_ERR_KEY_NOT_FOUND, we must return that error instead of + HA_ERR_END_OF_FILE, to be able to continue search. + */ + if (saved_error != HA_ERR_KEY_NOT_FOUND) + saved_error= error; + DBUG_PRINT("info", ("END_OF_FILE/KEY_NOT_FOUND on partition %d", i)); } - m_part_spec.start_part= NO_CURRENT_PART_ID; - DBUG_RETURN(HA_ERR_END_OF_FILE); + if (saved_error == HA_ERR_END_OF_FILE) + m_part_spec.start_part= NO_CURRENT_PART_ID; + DBUG_RETURN(saved_error); } -/* - Common routine to start index scan with ordered results +/** + Common routine to start index scan with ordered results. - SYNOPSIS - handle_ordered_index_scan() - out:buf Read row in MySQL Row Format + @param[out] buf Read row in MySQL Row Format - RETURN VALUE - HA_ERR_END_OF_FILE End of scan - 0 Success - other Error code + @return Operation status + @retval HA_ERR_END_OF_FILE End of scan + @retval HA_ERR_KEY_NOT_FOUNE End of scan + @retval 0 Success + @retval other Error code - DESCRIPTION + @details This part contains the logic to handle index scans that require ordered output. This includes all except those started by read_range_first with the flag ordered set to FALSE. Thus most direct index_read and all @@ -5115,8 +5139,14 @@ int ha_partition::handle_ordered_index_scan(uchar *buf, bool reverse_order) uint j= 0; bool found= FALSE; uchar *part_rec_buf_ptr= m_ordered_rec_buffer; + int saved_error= HA_ERR_END_OF_FILE; DBUG_ENTER("ha_partition::handle_ordered_index_scan"); + if (m_key_not_found) + { + m_key_not_found= false; + bitmap_clear_all(&m_key_not_found_partitions); + } m_top_entry= NO_CURRENT_PART_ID; queue_remove_all(&m_queue); @@ -5178,6 +5208,13 @@ int ha_partition::handle_ordered_index_scan(uchar *buf, bool reverse_order) { DBUG_RETURN(error); } + else if (error == HA_ERR_KEY_NOT_FOUND) + { + DBUG_PRINT("info", ("HA_ERR_KEY_NOT_FOUND from partition %u", i)); + bitmap_set_bit(&m_key_not_found_partitions, i); + m_key_not_found= true; + saved_error= error; + } part_rec_buf_ptr+= m_rec_length + PARTITION_BYTES_IN_POS; } if (found) @@ -5195,7 +5232,7 @@ int ha_partition::handle_ordered_index_scan(uchar *buf, bool reverse_order) DBUG_PRINT("info", ("Record returned from partition %d", m_top_entry)); DBUG_RETURN(0); } - DBUG_RETURN(HA_ERR_END_OF_FILE); + DBUG_RETURN(saved_error); } @@ -5223,6 +5260,59 @@ void ha_partition::return_top_record(uchar *buf) } +/** + Add index_next/prev from partitions without exact match. + + If there where any partitions that returned HA_ERR_KEY_NOT_FOUND when + ha_index_read_map was done, those partitions must be included in the + following index_next/prev call. +*/ + +int ha_partition::handle_ordered_index_scan_key_not_found() +{ + int error; + uint i; + uchar *part_buf= m_ordered_rec_buffer; + uchar *curr_rec_buf= NULL; + DBUG_ENTER("ha_partition::handle_ordered_index_scan_key_not_found"); + DBUG_ASSERT(m_key_not_found); + /* + Loop over all used partitions to get the correct offset + into m_ordered_rec_buffer. + */ + for (i= 0; i < m_tot_parts; i++) + { + if (!bitmap_is_set(&m_part_info->used_partitions, i)) + continue; + + if (bitmap_is_set(&m_key_not_found_partitions, i)) + { + /* + This partition is used and did return HA_ERR_KEY_NOT_FOUND + in index_read_map. + */ + curr_rec_buf= part_buf + PARTITION_BYTES_IN_POS; + error= m_file[i]->index_next(curr_rec_buf); + /* HA_ERR_KEY_NOT_FOUND is not allowed from index_next! */ + DBUG_ASSERT(error != HA_ERR_KEY_NOT_FOUND); + if (!error) + queue_insert(&m_queue, part_buf); + else if (error != HA_ERR_END_OF_FILE && error != HA_ERR_KEY_NOT_FOUND) + DBUG_RETURN(error); + } + part_buf+= m_rec_length + PARTITION_BYTES_IN_POS; + } + DBUG_ASSERT(curr_rec_buf); + bitmap_clear_all(&m_key_not_found_partitions); + m_key_not_found= false; + + /* Update m_top_entry, which may have changed. */ + uchar *key_buffer= queue_top(&m_queue); + m_top_entry= uint2korr(key_buffer); + DBUG_RETURN(0); +} + + /* Common routine to handle index_next with ordered results @@ -5242,9 +5332,45 @@ int ha_partition::handle_ordered_next(uchar *buf, bool is_next_same) int error; uint part_id= m_top_entry; uchar *rec_buf= queue_top(&m_queue) + PARTITION_BYTES_IN_POS; - handler *file= m_file[part_id]; + handler *file; DBUG_ENTER("ha_partition::handle_ordered_next"); + if (m_key_not_found) + { + if (is_next_same) + { + /* Only rows which match the key. */ + m_key_not_found= false; + bitmap_clear_all(&m_key_not_found_partitions); + } + else + { + /* There are partitions not included in the index record queue. */ + uint old_elements= m_queue.elements; + if ((error= handle_ordered_index_scan_key_not_found())) + DBUG_RETURN(error); + /* + If the queue top changed, i.e. one of the partitions that gave + HA_ERR_KEY_NOT_FOUND in index_read_map found the next record, + return it. + Otherwise replace the old with a call to index_next (fall through). + */ + if (old_elements != m_queue.elements && part_id != m_top_entry) + { + return_top_record(buf); + DBUG_RETURN(0); + } + } + } + if (part_id >= m_tot_parts) + { + /* This should never happen! */ + DBUG_ASSERT(0); + DBUG_RETURN(HA_ERR_END_OF_FILE); + } + + file= m_file[part_id]; + if (m_index_scan_type == partition_read_range) { error= file->read_range_next(); diff --git a/sql/ha_partition.h b/sql/ha_partition.h index 294e9f8adf6..24f04ee596b 100644 --- a/sql/ha_partition.h +++ b/sql/ha_partition.h @@ -183,6 +183,9 @@ private: static int compare_number_of_records(ha_partition *me, const uint32 *a, const uint32 *b); + /** partitions that returned HA_ERR_KEY_NOT_FOUND. */ + MY_BITMAP m_key_not_found_partitions; + bool m_key_not_found; public: handler *clone(const char *name, MEM_ROOT *mem_root); virtual void set_part_info(partition_info *part_info) @@ -519,6 +522,7 @@ private: int handle_unordered_next(uchar * buf, bool next_same); int handle_unordered_scan_next_partition(uchar * buf); int handle_ordered_index_scan(uchar * buf, bool reverse_order); + int handle_ordered_index_scan_key_not_found(); int handle_ordered_next(uchar * buf, bool next_same); int handle_ordered_prev(uchar * buf); void return_top_record(uchar * buf); -- cgit v1.2.1 From 0678a68bd0edeaa48a6e912d5a0bf3b65fb78fb0 Mon Sep 17 00:00:00 2001 From: Andrei Elkin Date: Mon, 10 Sep 2012 17:32:04 +0300 Subject: Bug#14597605 Issue with Null-value user on slave An "orthographic" typo in User_var::set_deferred() was made in fixes for bug@14275000. While editing the signature of the initial patch to remove the only argument, the assigned value of the argument remained in the body ... to be successfully compiled (!) thanks to names coincidence: the arg to User_var method and its member. Fixed with correcting the typo. --- sql/log_event.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/log_event.h b/sql/log_event.h index 5030e1c6f3d..6b411a90382 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -2508,7 +2508,7 @@ public: and which case the applier adjusts execution path. */ bool is_deferred() { return deferred; } - void set_deferred() { deferred= val; } + void set_deferred() { deferred= true; } #endif bool is_valid() const { return 1; } -- cgit v1.2.1 From f0b52a9e7e26b761e14911a7a072d4cf91ceab54 Mon Sep 17 00:00:00 2001 From: Tor Didriksen Date: Wed, 12 Sep 2012 08:36:12 +0200 Subject: Backport Bug#13724099 --- sql/sql_list.h | 11 +++++++++-- sql/sql_select.cc | 17 ++++++++++++----- 2 files changed, 21 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/sql_list.h b/sql/sql_list.h index 81283a6ae53..2eef291d948 100644 --- a/sql/sql_list.h +++ b/sql/sql_list.h @@ -1,7 +1,6 @@ #ifndef INCLUDES_MYSQL_SQL_LIST_H #define INCLUDES_MYSQL_SQL_LIST_H -/* - Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. +/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -165,6 +164,14 @@ protected: public: uint elements; + bool operator==(const base_list &rhs) const + { + return + elements == rhs.elements && + first == rhs.first && + last == rhs.last; + } + inline void empty() { elements=0; first= &end_of_list; last=&first;} inline base_list() { empty(); } /** diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 042e7563d42..bcf601e5142 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -1,4 +1,4 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. +/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -1676,6 +1676,8 @@ JOIN::optimize() */ void JOIN::restore_tmp() { + DBUG_PRINT("info", ("restore_tmp this %p tmp_join %p", this, tmp_join)); + DBUG_ASSERT(tmp_join != this); memcpy(tmp_join, this, (size_t) sizeof(JOIN)); } @@ -7090,13 +7092,18 @@ void JOIN::cleanup(bool full) { if (tmp_join) tmp_table_param.copy_field= 0; - group_fields.delete_elements(); + /* - Ensure that the above delete_elements() would not be called + Ensure that the following delete_elements() would not be called twice for the same list. */ - if (tmp_join && tmp_join != this) - tmp_join->group_fields= group_fields; + if (tmp_join && tmp_join != this && + tmp_join->group_fields == this->group_fields) + tmp_join->group_fields.empty(); + + // Run Cached_item DTORs! + group_fields.delete_elements(); + /* We can't call delete_elements() on copy_funcs as this will cause problems in free_elements() as some of the elements are then deleted. -- cgit v1.2.1 From 5cbdb908270a052284155cd5b7eff7eacb177218 Mon Sep 17 00:00:00 2001 From: Sujatha Sivakumar Date: Mon, 17 Sep 2012 11:48:02 +0530 Subject: Bug#11750014:ASSERTION TRX_DATA->EMPTY() IN BINLOG_CLOSE_CONNECTION Problem: ======= trx_data->empty() assert happens at `binlog_close_connection' Analysis: ======== trx_data->empty() function checks for no pending events and the transaction cache to be empty.This function returns "true" if no pending events are present and cache is empty. Otherwise it returns false. `binlog_close_connection' call expects the above function to return true. But if the return value is false then assert is raised. This bug was reproducible in a diskfull scenario. In this disk full scenario try to do an insert operation so that a new pending event is created and flushing this pending event fails. Due to this failure the server goes down and invokes `binlog_close_connection' for clean closure. Since the pending event still remains the assert is caused. This assert is caused only in non transactional databases. Fix: === In a disk full scenario when the insertion fails the transaction is rolled back and `binlog_end_trans` is called to flush the pending events. But flush operation fails as the disk is full and the function simply returns `1' without taking any action to delete the pending event. This leaves the event to remain till the closure of connection. `delete pending' statement has been added to do the required clean up action. sql/log.cc: Added "delete pending" statement to clean pending event --- sql/log.cc | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index 57c14b24782..7e0e90e28c0 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -4313,10 +4313,16 @@ MYSQL_BIN_LOG::flush_and_set_pending_rows_event(THD *thd, /* Write pending event to log file or transaction cache */ + DBUG_EXECUTE_IF("simulate_disk_full_at_flush_pending", + {DBUG_SET("+d,simulate_file_write_error");}); if (pending->write(file)) { pthread_mutex_unlock(&LOCK_log); set_write_error(thd); + delete pending; + trx_data->set_pending(NULL); + DBUG_EXECUTE_IF("simulate_disk_full_at_flush_pending", + {DBUG_SET("-d,simulate_file_write_error");}); DBUG_RETURN(1); } -- cgit v1.2.1 From 9d007e075d6b933df9dbd1a42d52ab00ee91827c Mon Sep 17 00:00:00 2001 From: Harin Vadodaria Date: Mon, 17 Sep 2012 17:02:17 +0530 Subject: Bug#11753779: MAX_CONNECT_ERRORS WORKS ONLY WHEN 1ST INC_HOST_ERRORS() IS CALLED. Issue : Sequence of calling inc_host_errors() and reset_host_errors() required some changes in order to maintain correct connection error count. Solution : Call to reset_host_errors() is shifted to a location after which no calls to inc_host_errors() are made. --- sql/hostname.cc | 9 ++++++++ sql/sql_connect.cc | 68 +++++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 69 insertions(+), 8 deletions(-) (limited to 'sql') diff --git a/sql/hostname.cc b/sql/hostname.cc index 9796755e9fb..38316a8ee19 100644 --- a/sql/hostname.cc +++ b/sql/hostname.cc @@ -214,6 +214,15 @@ char * ip_to_hostname(struct in_addr *in, uint *errors) } my_gethostbyname_r_free(); #else + + DBUG_EXECUTE_IF("addr_fake_ipv4", + { + const char* fake_host= "santa.claus.ipv4.example.com"; + name=my_strdup(fake_host, MYF(0)); + add_hostname(in,name); + DBUG_RETURN(name); + };); + VOID(pthread_mutex_lock(&LOCK_hostname)); if (!(hp=gethostbyaddr((char*) in,sizeof(*in), AF_INET))) { diff --git a/sql/sql_connect.cc b/sql/sql_connect.cc index 21e2701d06c..e7aa48c94f5 100644 --- a/sql/sql_connect.cc +++ b/sql/sql_connect.cc @@ -336,6 +336,7 @@ check_user(THD *thd, enum enum_server_command command, USER_RESOURCES ur; int res= acl_getroot(thd, &ur, passwd, passwd_len); + DBUG_EXECUTE_IF("password_format_mismatch",{res= -1;};); #ifndef EMBEDDED_LIBRARY if (res == -1) { @@ -346,6 +347,12 @@ check_user(THD *thd, enum enum_server_command command, in old format. */ NET *net= &thd->net; + DBUG_EXECUTE_IF("password_format_mismatch", + { + inc_host_errors(&thd->remote.sin_addr); + my_error(ER_HANDSHAKE_ERROR, MYF(0)); + DBUG_RETURN(1); + };); if (opt_secure_auth_local) { my_error(ER_SERVER_IS_IN_SECURE_AUTH_MODE, MYF(0), @@ -816,6 +823,8 @@ static int check_connection(THD *thd) size_t passwd_len; char *user; size_t user_len; + uint charset_code= 0; + size_t bytes_remaining_in_packet= 0; DBUG_PRINT("info", ("New connection received on %s", vio_description(net->vio))); @@ -832,6 +841,19 @@ static int check_connection(THD *thd) my_error(ER_BAD_HOST_ERROR, MYF(0)); return 1; } + /* BEGIN : DEBUG */ + DBUG_EXECUTE_IF("addr_fake_ipv4", + { + struct sockaddr *sa= (sockaddr *) &net->vio->remote; + sa->sa_family= AF_INET; + struct in_addr *ip4= &((struct sockaddr_in *)sa)->sin_addr; + /* See RFC 5737, 192.0.2.0/23 is reserved */ + const char* fake= "192.0.2.4"; + ip4->s_addr= inet_addr(fake); + strcpy(ip, fake); + };); + /* END : DEBUG */ + if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME)))) return 1; /* The error is set by my_strdup(). */ thd->main_security_ctx.host_or_ip= thd->main_security_ctx.ip; @@ -927,32 +949,31 @@ static int check_connection(THD *thd) (uchar*) buff, (size_t) (end-buff)) || (pkt_len= my_net_read(net)) == packet_error) { - inc_host_errors(&thd->remote.sin_addr); - my_error(ER_HANDSHAKE_ERROR, MYF(0)); - return 1; + goto error; } } #ifdef _CUSTOMCONFIG_ #include "_cust_sql_parse.h" #endif - if (connect_errors) - reset_host_errors(&thd->remote.sin_addr); if (thd->packet.alloc(thd->variables.net_buffer_length)) return 1; /* The error is set by alloc(). */ - uint charset_code= 0; end= (char *)net->read_pos; /* In order to safely scan a head for '\0' string terminators we must keep track of how many bytes remain in the allocated buffer or we might read past the end of the buffer. */ - size_t bytes_remaining_in_packet= pkt_len; + bytes_remaining_in_packet= pkt_len; /* Peek ahead on the client capability packet and determine which version of the protocol should be used. */ + DBUG_EXECUTE_IF("host_error_packet_length", + { + bytes_remaining_in_packet= 0; + };); if (bytes_remaining_in_packet < 2) goto error; @@ -1011,6 +1032,10 @@ static int check_connection(THD *thd) skip_to_ssl: + DBUG_EXECUTE_IF("host_error_charset", + { + goto error; + };); DBUG_PRINT("info", ("client_character_set: %u", charset_code)); if (thd_init_client_charset(thd, charset_code)) goto error; @@ -1079,6 +1104,10 @@ skip_to_ssl: bytes_remaining_in_packet -= AUTH_PACKET_HEADER_SIZE_PROTO_40; } + DBUG_EXECUTE_IF("host_error_SSL_layering", + { + packet_has_required_size= 0; + };); if (!packet_has_required_size) goto error; } @@ -1104,6 +1133,11 @@ skip_to_ssl: get_string= get_40_protocol_string; user= get_string(&end, &bytes_remaining_in_packet, &user_len); + DBUG_EXECUTE_IF("host_error_user", + { + user= NULL; + };); + if (user == NULL) goto error; @@ -1131,6 +1165,11 @@ skip_to_ssl: passwd= get_string(&end, &bytes_remaining_in_packet, &passwd_len); } + DBUG_EXECUTE_IF("host_error_password", + { + passwd= NULL; + };); + if (passwd == NULL) goto error; @@ -1191,7 +1230,20 @@ skip_to_ssl: if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME)))) return 1; /* The error is set by my_strdup(). */ - return check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE); + + if (!check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE)) + { + /* + Call to reset_host_errors() should be made only when all sanity checks + are done and connection is going to be a successful. + */ + reset_host_errors(&thd->remote.sin_addr); + return 0; + } + else + { + return 1; + } error: inc_host_errors(&thd->remote.sin_addr); -- cgit v1.2.1 From 5530c5e38dbefac8e5d2c333c0f35ed9f73946a4 Mon Sep 17 00:00:00 2001 From: Rohit Kalhans Date: Sat, 22 Sep 2012 17:50:51 +0530 Subject: BUG#14548159: NUMEROUS CASES OF INCORRECT IDENTIFIER QUOTING IN REPLICATION Problem: Misquoting or unquoted identifiers may lead to incorrect statements to be logged to the binary log. Fix: we use specialized functions to append quoted identifiers in the statements generated by the server. --- sql/ha_ndbcluster_binlog.cc | 31 +++++-- sql/log.cc | 35 +++++--- sql/log_event.cc | 209 ++++++++++++++++++++++++++++++++++---------- sql/log_event.h | 16 ++++ sql/sql_base.cc | 31 +++---- sql/sql_db.cc | 35 +++++--- sql/sql_insert.cc | 19 ++-- sql/sql_load.cc | 28 +++--- sql/sql_show.cc | 3 +- sql/sql_show.h | 1 + sql/sql_table.cc | 22 ++--- 11 files changed, 300 insertions(+), 130 deletions(-) (limited to 'sql') diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc index fe802ce0e2d..70e52306e14 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -22,6 +22,7 @@ #include "rpl_injector.h" #include "rpl_filter.h" #include "slave.h" +#include "log_event.h" #include "ha_ndbcluster_binlog.h" #include "NdbDictionary.hpp" #include "ndb_cluster_connection.hpp" @@ -1269,6 +1270,11 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, } char tmp_buf2[FN_REFLEN]; + char quoted_table1[2 + 2 * FN_REFLEN + 1]; + char quoted_db1[2 + 2 * FN_REFLEN + 1]; + char quoted_db2[2 + 2 * FN_REFLEN + 1]; + char quoted_table2[2 + 2 * FN_REFLEN + 1]; + int id_length= 0; const char *type_str; switch (type) { @@ -1278,16 +1284,31 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, DBUG_RETURN(0); /* redo the drop table query as is may contain several tables */ query= tmp_buf2; - query_length= (uint) (strxmov(tmp_buf2, "drop table `", - table_name, "`", NullS) - tmp_buf2); + id_length= my_strmov_quoted_identifier (thd, (char *) quoted_table1, + table_name, 0); + quoted_table1[id_length]= '\0'; + query_length= (uint) (strxmov(tmp_buf2, "drop table ", + quoted_table1, NullS) - tmp_buf2); type_str= "drop table"; break; case SOT_RENAME_TABLE: /* redo the rename table query as is may contain several tables */ query= tmp_buf2; - query_length= (uint) (strxmov(tmp_buf2, "rename table `", - db, ".", table_name, "` to `", - new_db, ".", new_table_name, "`", NullS) - tmp_buf2); + id_length= my_strmov_quoted_identifier (thd, (char *) quoted_db1, + db, 0); + quoted_db1[id_length]= '\0'; + id_length= my_strmov_quoted_identifier (thd, (char *) quoted_table1, + table_name, 0); + quoted_table1[id_length]= '\0'; + id_length= my_strmov_quoted_identifier (thd, (char *) quoted_db2, + new_db, 0); + quoted_db2[id_length]= '\0'; + id_length= my_strmov_quoted_identifier (thd, (char *) quoted_table2, + new_table_name, 0); + quoted_table2[id_length]= '\0'; + query_length= (uint) (strxmov(tmp_buf2, "rename table ", + quoted_db1, ".", quoted_table_1, " to ", + quoted_db2, ".", quoted_table2, NullS) - tmp_buf2); type_str= "rename table"; break; case SOT_CREATE_TABLE: diff --git a/sql/log.cc b/sql/log.cc index 7e0e90e28c0..93dd70b33c5 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -29,6 +29,7 @@ #include "rpl_filter.h" #include "rpl_rli.h" +#include "sql_show.h" #include #include #include // For test_if_number @@ -1708,17 +1709,24 @@ static int binlog_savepoint_set(handlerton *hton, THD *thd, void *sv) DBUG_ENTER("binlog_savepoint_set"); binlog_trans_log_savepos(thd, (my_off_t*) sv); + + // buffer to store quoted identifier + char* buffer= (char *)my_malloc(sizeof("SAVEPOINT ")+ 1 + NAME_LEN * 2 + 2, + MYF(0)); + String log_query(buffer, sizeof(buffer), system_charset_info); + log_query.length(0); + /* Write it to the binary log */ - String log_query; - if (log_query.append(STRING_WITH_LEN("SAVEPOINT ")) || - log_query.append("`") || - log_query.append(thd->lex->ident.str, thd->lex->ident.length) || - log_query.append("`")) + if (log_query.append(STRING_WITH_LEN("SAVEPOINT "))) DBUG_RETURN(1); + else + append_identifier(thd, &log_query, thd->lex->ident.str, + thd->lex->ident.length); int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); Query_log_event qinfo(thd, log_query.c_ptr_safe(), log_query.length(), TRUE, TRUE, errcode); + my_free(buffer, MYF(MY_WME)); DBUG_RETURN(mysql_bin_log.write(&qinfo)); } @@ -1731,18 +1739,23 @@ static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv) non-transactional table. Otherwise, truncate the binlog cache starting from the SAVEPOINT command. */ - if (unlikely(trans_has_updated_non_trans_table(thd) || + if (unlikely(trans_has_updated_non_trans_table(thd) || (thd->options & OPTION_KEEP_LOG))) { - String log_query; - if (log_query.append(STRING_WITH_LEN("ROLLBACK TO ")) || - log_query.append("`") || - log_query.append(thd->lex->ident.str, thd->lex->ident.length) || - log_query.append("`")) + // buffer to store rollback query with quoted identifier + char* buffer= (char *)my_malloc(12 + 1 + NAME_LEN * 2 + 2, MYF(0)); + String log_query(buffer, sizeof(buffer), system_charset_info); + log_query.length(0); + + if (log_query.append(STRING_WITH_LEN("ROLLBACK TO "))) DBUG_RETURN(1); + else + append_identifier(thd, &log_query, thd->lex->ident.str, + thd->lex->ident.length); int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED); Query_log_event qinfo(thd, log_query.c_ptr_safe(), log_query.length(), TRUE, TRUE, errcode); + my_free(buffer, MYF(MY_WME)); DBUG_RETURN(mysql_bin_log.write(&qinfo)); } binlog_trans_log_truncate(thd, *(my_off_t*)sv); diff --git a/sql/log_event.cc b/sql/log_event.cc index 2f27efa8b4e..829ee06d20e 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -34,6 +34,7 @@ #include "rpl_utility.h" #include "rpl_record.h" #include +#include "sql_show.h" // append_identifier #endif /* MYSQL_CLIENT */ @@ -1946,6 +1947,10 @@ Rows_log_event::print_verbose_one_row(IO_CACHE *file, table_def *td, void Rows_log_event::print_verbose(IO_CACHE *file, PRINT_EVENT_INFO *print_event_info) { + // Quoted length of the identifier can be twice the original length + char quoted_db[1 + NAME_LEN * 2 + 2]; + char quoted_table[1 + NAME_LEN * 2 + 2]; + int quoted_db_len, quoted_table_len; Table_map_log_event *map; table_def *td; const char *sql_command, *sql_clause1, *sql_clause2; @@ -1982,9 +1987,23 @@ void Rows_log_event::print_verbose(IO_CACHE *file, for (const uchar *value= m_rows_buf; value < m_rows_end; ) { size_t length; +#ifdef MYSQL_SERVER + quoted_db_len= my_strmov_quoted_identifier(this->thd, (char *) quoted_db, + map->get_db_name(), 0); + quoted_table_len= my_strmov_quoted_identifier(this->thd, + (char *) quoted_table, + map->get_table_name(), 0); +#else + quoted_db_len= my_strmov_quoted_identifier((char *) quoted_db, + map->get_db_name()); + quoted_table_len= my_strmov_quoted_identifier((char *) quoted_table, + map->get_table_name()); +#endif + quoted_db[quoted_db_len]= '\0'; + quoted_table[quoted_table_len]= '\0'; my_b_printf(file, "### %s %s.%s\n", sql_command, - map->get_db_name(), map->get_table_name()); + quoted_db, quoted_table); /* Print the first image */ if (!(length= print_verbose_one_row(file, td, print_event_info, &m_cols, value, @@ -2143,24 +2162,20 @@ Log_event::continue_group(Relay_log_info *rli) void Query_log_event::pack_info(Protocol *protocol) { // TODO: show the catalog ?? - char *buf, *pos; - if (!(buf= (char*) my_malloc(9 + db_len + q_len, MYF(MY_WME)))) - return; - pos= buf; + String temp_buf; + // Add use `DB` to the string if required if (!(flags & LOG_EVENT_SUPPRESS_USE_F) && db && db_len) { - pos= strmov(buf, "use `"); - memcpy(pos, db, db_len); - pos= strmov(pos+db_len, "`; "); + temp_buf.append("use "); + append_identifier(this->thd, &temp_buf, db, db_len); + temp_buf.append("; "); } + // Add the query to the string if (query && q_len) - { - memcpy(pos, query, q_len); - pos+= q_len; - } - protocol->store(buf, pos-buf, &my_charset_bin); - my_free(buf, MYF(MY_ALLOW_ZERO_PTR)); + temp_buf.append(query); + // persist the buffer in protocol + protocol->store(temp_buf.ptr(), temp_buf.length(), &my_charset_bin); } #endif @@ -2932,6 +2947,8 @@ void Query_log_event::print_query_header(IO_CACHE* file, { // TODO: print the catalog ?? char buff[40],*end; // Enough for SET TIMESTAMP + char quoted_id[1+ 2*FN_REFLEN+ 2]; + int quoted_len= 0; bool different_db= 1; uint32 tmp; @@ -2950,11 +2967,17 @@ void Query_log_event::print_query_header(IO_CACHE* file, } else if (db) { +#ifdef MYSQL_SERVER + quoted_len= my_strmov_quoted_identifier(this->thd, (char*)quoted_id, db, 0); +#else + quoted_len= my_strmov_quoted_identifier((char*)quoted_id, db); +#endif + quoted_id[quoted_len]= '\0'; different_db= memcmp(print_event_info->db, db, db_len + 1); if (different_db) memcpy(print_event_info->db, db, db_len + 1); if (db[0] && different_db) - my_b_printf(file, "use %s%s\n", db, print_event_info->delimiter); + my_b_printf(file, "use %s%s\n", quoted_id, print_event_info->delimiter); } end=int10_to_str((long) when, strmov(buff,"SET TIMESTAMP="),10); @@ -4216,7 +4239,8 @@ void Format_description_log_event::calc_server_version_split() uint Load_log_event::get_query_buffer_length() { return - 5 + db_len + 3 + // "use DB; " + //the DB name may double if we escape the quote character + 5 + 2*db_len + 3 + 18 + fname_len + 2 + // "LOAD DATA INFILE 'file''" 11 + // "CONCURRENT " 7 + // LOCAL @@ -4235,13 +4259,21 @@ uint Load_log_event::get_query_buffer_length() void Load_log_event::print_query(bool need_db, const char *cs, char *buf, char **end, char **fn_start, char **fn_end) { + char quoted_id[1 + NAME_LEN * 2 + 2];//quoted length + int quoted_id_len= 0; char *pos= buf; if (need_db && db && db_len) { - pos= strmov(pos, "use `"); - memcpy(pos, db, db_len); - pos= strmov(pos+db_len, "`; "); + pos= strmov(pos, "use "); +#ifdef MYSQL_SERVER + quoted_id_len= my_strmov_quoted_identifier(this->thd, (char *) quoted_id, + db, 0); +#else + quoted_id_len= my_strmov_quoted_identifier((char *) quoted_id, db); +#endif + pos+= quoted_id_len; + pos= strmov(pos, "; "); } pos= strmov(pos, "LOAD DATA "); @@ -4268,17 +4300,15 @@ void Load_log_event::print_query(bool need_db, const char *cs, char *buf, if (fn_end) *fn_end= pos; - pos= strmov(pos ," TABLE `"); + pos= strmov(pos ," TABLE "); memcpy(pos, table_name, table_name_len); pos+= table_name_len; if (cs != NULL) { - pos= strmov(pos ,"` CHARACTER SET "); + pos= strmov(pos ," CHARACTER SET "); pos= strmov(pos , cs); } - else - pos= strmov(pos, "`"); /* We have to create all optional fields as the default is not empty */ pos= strmov(pos, " FIELDS TERMINATED BY "); @@ -4318,9 +4348,9 @@ void Load_log_event::print_query(bool need_db, const char *cs, char *buf, *pos++= ' '; *pos++= ','; } - memcpy(pos, field, field_lens[i]); - pos+= field_lens[i]; - field+= field_lens[i] + 1; + quoted_id_len= my_strmov_quoted_identifier(this->thd, quoted_id, field, + 0); + memcpy(pos, quoted_id, quoted_id_len); } *pos++= ')'; } @@ -4560,6 +4590,8 @@ void Load_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info) void Load_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info, bool commented) { + size_t id_len= 0; + char temp_buf[1 + 2*FN_REFLEN + 2]; Write_on_release_cache cache(&print_event_info->head_cache, file_arg); DBUG_ENTER("Load_log_event::print"); @@ -4585,10 +4617,16 @@ void Load_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info, } if (db && db[0] && different_db) - my_b_printf(&cache, "%suse %s%s\n", - commented ? "# " : "", - db, print_event_info->delimiter); - + { +#ifdef MYSQL_SERVER + id_len= my_strmov_quoted_identifier(this->thd, temp_buf, db, 0); +#else + id_len= my_strmov_quoted_identifier(temp_buf, db); +#endif + temp_buf[id_len]= '\0'; + my_b_printf(&cache, "%suse %s%s\n", + commented ? "# " : "", temp_buf, print_event_info->delimiter); + } if (flags & LOG_EVENT_THREAD_SPECIFIC_F) my_b_printf(&cache,"%sSET @@session.pseudo_thread_id=%lu%s\n", commented ? "# " : "", (ulong)thread_id, @@ -4603,8 +4641,14 @@ void Load_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info, my_b_printf(&cache,"REPLACE "); else if (sql_ex.opt_flags & IGNORE_FLAG) my_b_printf(&cache,"IGNORE "); - - my_b_printf(&cache, "INTO TABLE `%s`", table_name); + +#ifdef MYSQL_SERVER + id_len= my_strmov_quoted_identifier(this->thd, temp_buf, table_name, 0); +#else + id_len= my_strmov_quoted_identifier(temp_buf, table_name); +#endif + temp_buf[id_len]= '\0'; + my_b_printf(&cache, "INTO TABLE %s", temp_buf); my_b_printf(&cache, " FIELDS TERMINATED BY "); pretty_print_str(&cache, sql_ex.field_term, sql_ex.field_term_len); @@ -4637,7 +4681,9 @@ void Load_log_event::print(FILE* file_arg, PRINT_EVENT_INFO* print_event_info, { if (i) my_b_printf(&cache, ","); - my_b_printf(&cache, "%s", field); + id_len= my_strmov_quoted_identifier((char *) temp_buf, field); + temp_buf[id_len]= '\0'; + my_b_printf(&cache, "%s", temp_buf); field += field_lens[i] + 1; } @@ -5560,7 +5606,10 @@ Xid_log_event::do_shall_skip(Relay_log_info *rli) void User_var_log_event::pack_info(Protocol* protocol) { char *buf= 0; - uint val_offset= 4 + name_len; + char quoted_id[1 + FN_REFLEN * 2 + 2];// quoted identifier + int id_len= my_strmov_quoted_identifier(this->thd, quoted_id, name, 0); + quoted_id[id_len]= '\0'; + uint val_offset= 2 + id_len; uint event_len= val_offset; if (is_null) @@ -5626,10 +5675,8 @@ void User_var_log_event::pack_info(Protocol* protocol) } } buf[0]= '@'; - buf[1]= '`'; - memcpy(buf+2, name, name_len); - buf[2+name_len]= '`'; - buf[3+name_len]= '='; + memcpy(buf + 1, quoted_id, id_len); + buf[1 + id_len]= '='; protocol->store(buf, event_len, &my_charset_bin); my_free(buf, MYF(0)); } @@ -5740,6 +5787,8 @@ bool User_var_log_event::write(IO_CACHE* file) #ifdef MYSQL_CLIENT void User_var_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info) { + char quoted_id[1 + NAME_LEN * 2 + 2];// quoted length of the identifier + int quoted_len= 0; Write_on_release_cache cache(&print_event_info->head_cache, file, Write_on_release_cache::FLUSH_F); @@ -5749,9 +5798,11 @@ void User_var_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info) my_b_printf(&cache, "\tUser_var\n"); } - my_b_printf(&cache, "SET @`"); - my_b_write(&cache, (uchar*) name, (uint) (name_len)); - my_b_printf(&cache, "`"); + my_b_printf(&cache, "SET @"); + quoted_len= my_strmov_quoted_identifier((char *) quoted_id, + (const char *) name); + quoted_id[quoted_len]= '\0'; + my_b_write(&cache, (uchar*) quoted_id, (uint) quoted_len); if (is_null) { @@ -7043,14 +7094,23 @@ void Execute_load_query_log_event::print(FILE* file, void Execute_load_query_log_event::pack_info(Protocol *protocol) { char *buf, *pos; - if (!(buf= (char*) my_malloc(9 + db_len + q_len + 10 + 21, MYF(MY_WME)))) + if (!(buf= (char*) my_malloc(9 + (db_len * 2) + 2 + q_len + 10 + 21, + MYF(MY_WME)))) return; pos= buf; if (db && db_len) { - pos= strmov(buf, "use `"); - memcpy(pos, db, db_len); - pos= strmov(pos+db_len, "`; "); + /* + Statically allocates room to store '\0' and an identifier + that may have NAME_LEN * 2 due to quoting and there are + two quoting characters that wrap them. + */ + char quoted_db[1 + NAME_LEN * 2 + 2];// quoted length of the identifier + size_t size= 0; + size= my_strmov_quoted_identifier(this->thd, quoted_db, db, 0); + pos= strmov(buf, "use "); + memcpy(pos, quoted_db, size); + pos= strmov(pos + size, "; "); } if (query && q_len) { @@ -9907,3 +9967,62 @@ st_print_event_info::st_print_event_info() open_cached_file(&body_cache, NULL, NULL, 0, flags); } #endif + +#ifdef MYSQL_SERVER +/* + This is a utility function that adds a quoted identifier into the a buffer. + This also escapes any existance of the quote string inside the identifier. + + SYNOPSIS + my_strmov_quoted_identifier + thd thread handler + buffer target buffer + identifier the identifier to be quoted + length length of the identifier +*/ +size_t my_strmov_quoted_identifier(THD* thd, char *buffer, + const char* identifier, + uint length) +{ + int q= thd ? get_quote_char_for_identifier(thd, identifier, length) : '`'; + return my_strmov_quoted_identifier_helper(q, buffer, identifier, length); +} +#else +size_t my_strmov_quoted_identifier(char *buffer, const char* identifier) +{ + int q= '`'; + return my_strmov_quoted_identifier_helper(q, buffer, identifier, 0); +} + +#endif + +size_t my_strmov_quoted_identifier_helper(int q, char *buffer, + const char* identifier, + uint length) +{ + size_t written= 0; + char quote_char; + uint id_length= (length) ? length : strlen(identifier); + + if (q == EOF) + { + (void *) strncpy(buffer, identifier, id_length); + return id_length; + } + quote_char= (char) q; + *buffer++= quote_char; + written++; + while (id_length--) + { + if (*identifier == quote_char) + { + *buffer++= quote_char; + written++; + } + *buffer++= *identifier++; + written++; + } + *buffer++= quote_char; + return ++written; +} + diff --git a/sql/log_event.h b/sql/log_event.h index 6b411a90382..ba6b9b876aa 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -3987,6 +3987,22 @@ static inline bool copy_event_cache_to_file_and_reinit(IO_CACHE *cache, bool slave_execute_deferred_events(THD *thd); #endif +#ifdef MYSQL_SERVER +/** + This is an utility function that adds a quoted identifier into the a buffer. + This also escapes any existance of the quote string inside the identifier. + */ +size_t my_strmov_quoted_identifier(THD *thd, char *buffer, + const char* identifier, + uint length); +#else +size_t my_strmov_quoted_identifier(char *buffer, const char* identifier); +#endif +size_t my_strmov_quoted_identifier_helper(int q, char *buffer, + const char* identifier, + uint length); + + /** @} (end of group Replication) */ diff --git a/sql/sql_base.cc b/sql/sql_base.cc index 2ce5ec81917..c7513f45983 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -4144,24 +4144,19 @@ retry: entry->file->implicit_emptied= 0; if (mysql_bin_log.is_open()) { - char *query, *end; - uint query_buf_size= 20 + share->db.length + share->table_name.length +1; - if ((query= (char*) my_malloc(query_buf_size,MYF(MY_WME)))) - { - /* this DELETE FROM is needed even with row-based binlogging */ - end = strxmov(strmov(query, "DELETE FROM `"), - share->db.str,"`.`",share->table_name.str,"`", NullS); - int errcode= query_error_code(thd, TRUE); - if (thd->binlog_query(THD::STMT_QUERY_TYPE, - query, (ulong)(end-query), - FALSE, FALSE, errcode)) - { - my_free(query, MYF(0)); - goto err; - } - my_free(query, MYF(0)); - } - else + bool error= false; + String temp_buf; + error= temp_buf.append("DELETE FROM "); + append_identifier(thd, &temp_buf, share->db.str, strlen(share->db.str)); + error= temp_buf.append("."); + append_identifier(thd, &temp_buf, share->table_name.str, + strlen(share->table_name.str)); + int errcode= query_error_code(thd, TRUE); + if (thd->binlog_query(THD::STMT_QUERY_TYPE, + temp_buf.ptr(), temp_buf.length(), + FALSE, FALSE, errcode)) + goto err; + if(error) { /* As replication is maybe going to be corrupted, we need to warn the diff --git a/sql/sql_db.cc b/sql/sql_db.cc index 39c33da23ef..fe3aed5c8f0 100644 --- a/sql/sql_db.cc +++ b/sql/sql_db.cc @@ -25,6 +25,7 @@ #include #include #include "log.h" +#include "log_event.h" #ifdef __WIN__ #include #endif @@ -718,12 +719,17 @@ not_silent: { char *query; uint query_length; + char db_name_quoted[2 * FN_REFLEN + sizeof("create database ") + 2]; + int id_len= 0; if (!thd->query()) // Only in replication { - query= tmp_query; - query_length= (uint) (strxmov(tmp_query,"create database `", - db, "`", NullS) - tmp_query); + id_len= my_strmov_quoted_identifier(thd, (char *) db_name_quoted, db, + 0); + db_name_quoted[id_len]= '\0'; + query= tmp_query; + query_length= (uint) (strxmov(tmp_query,"create database ", + db_name_quoted, NullS) - tmp_query); } else { @@ -889,7 +895,7 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) { long deleted=0; int error= 0; - char path[FN_REFLEN+16]; + char path[2 * FN_REFLEN + 16]; MY_DIR *dirp; uint length; TABLE_LIST* dropped_tables= 0; @@ -989,11 +995,17 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) { const char *query; ulong query_length; + // quoted db name + wraping quote + char buffer_temp [2 * FN_REFLEN + 2]; + int id_len= 0; + if (!thd->query()) { /* The client used the old obsolete mysql_drop_db() call */ query= path; - query_length= (uint) (strxmov(path, "drop database `", db, "`", + id_len= my_strmov_quoted_identifier(thd, buffer_temp, db, strlen(db)); + buffer_temp[id_len] ='\0'; + query_length= (uint) (strxmov(path, "DROP DATABASE ", buffer_temp, "", NullS) - path); } else @@ -1029,12 +1041,13 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) else if (mysql_bin_log.is_open()) { char *query, *query_pos, *query_end, *query_data_start; + char temp_identifier[ 2 * FN_REFLEN + 2]; TABLE_LIST *tbl; - uint db_len; + uint db_len, id_length=0; if (!(query= (char*) thd->alloc(MAX_DROP_TABLE_Q_LEN))) goto exit; /* not much else we can do */ - query_pos= query_data_start= strmov(query,"drop table "); + query_pos= query_data_start= strmov(query,"DROP TABLE "); query_end= query + MAX_DROP_TABLE_Q_LEN; db_len= strlen(db); @@ -1054,10 +1067,10 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent) } query_pos= query_data_start; } - - *query_pos++ = '`'; - query_pos= strmov(query_pos,tbl->table_name); - *query_pos++ = '`'; + id_length= my_strmov_quoted_identifier(thd, (char *)temp_identifier, + tbl->table_name, 0); + temp_identifier[id_length]= '\0'; + query_pos= strmov(query_pos,(char *)&temp_identifier); *query_pos++ = ','; } diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index 4cd456829ba..7e94e7e7df3 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -3426,16 +3426,16 @@ int select_create::write_to_binlog(bool is_trans, int errcode) if (thd->lex->create_select_in_comment) query.append(STRING_WITH_LEN("/*! ")); if (thd->lex->ignore) - query.append(STRING_WITH_LEN("INSERT IGNORE INTO `")); + query.append(STRING_WITH_LEN("INSERT IGNORE INTO ")); else if (thd->lex->duplicates == DUP_REPLACE) - query.append(STRING_WITH_LEN("REPLACE INTO `")); + query.append(STRING_WITH_LEN("REPLACE INTO ")); else - query.append(STRING_WITH_LEN("INSERT INTO `")); + query.append(STRING_WITH_LEN("INSERT INTO ")); - query.append(create_table->db, db_len); - query.append(STRING_WITH_LEN("`.`")); - query.append(create_info->alias, table_len); - query.append(STRING_WITH_LEN("` ")); + append_identifier(thd, &query, create_table->db, db_len); + query.append(STRING_WITH_LEN(".")); + append_identifier(thd, &query, create_info->alias, table_len ); + query.append(STRING_WITH_LEN(" ")); /* The insert items. @@ -3447,9 +3447,8 @@ int select_create::write_to_binlog(bool is_trans, int errcode) if (f != field) query.append(STRING_WITH_LEN(",")); - query.append(STRING_WITH_LEN("`")); - query.append((*f)->field_name, strlen((*f)->field_name)); - query.append(STRING_WITH_LEN("`")); + append_identifier(thd, &query, (*f)->field_name, + strlen((*f)->field_name)); } query.append(STRING_WITH_LEN(") ")); diff --git a/sql/sql_load.cc b/sql/sql_load.cc index 6a0e5fd9133..b736fa59c22 100644 --- a/sql/sql_load.cc +++ b/sql/sql_load.cc @@ -25,6 +25,7 @@ #include "sp_head.h" #include "sql_trigger.h" +#include "sql_show.h" class READ_INFO { File file; uchar *buffer, /* Buffer for read text */ @@ -619,23 +620,20 @@ static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex, const char *tbl= table_name_arg; const char *tdb= (thd->db != NULL ? thd->db : db_arg); String string_buf; - - if (!thd->db || strcmp(db_arg, thd->db)) + if (!thd->db || strcmp(db_arg, thd->db)) { /* - If used database differs from table's database, - prefix table name with database name so that it + If used database differs from table's database, + prefix table name with database name so that it becomes a FQ name. */ string_buf.set_charset(system_charset_info); - string_buf.append(db_arg); - string_buf.append("`"); + append_identifier(thd, &string_buf, db_arg, strlen(db_arg)); string_buf.append("."); - string_buf.append("`"); - string_buf.append(table_name_arg); - tbl= string_buf.c_ptr_safe(); } - + append_identifier(thd, &string_buf, table_name_arg, + strlen(table_name_arg)); + tbl= string_buf.c_ptr_safe(); Load_log_event lle(thd, ex, tdb, tbl, fv, duplicates, ignore, transactional_table); @@ -660,11 +658,7 @@ static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex, if (n++) pfields.append(", "); if (item->name) - { - pfields.append("`"); - pfields.append(item->name); - pfields.append("`"); - } + append_identifier(thd, &pfields, item->name, strlen(item->name)); else item->print(&pfields, QT_ORDINARY); } @@ -684,9 +678,7 @@ static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex, val= lv++; if (n++) pfields.append(", "); - pfields.append("`"); - pfields.append(item->name); - pfields.append("`"); + append_identifier(thd, &pfields, item->name, strlen(item->name)); pfields.append("="); val->print(&pfields, QT_ORDINARY); } diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 7847fe5b510..7859d7f61e3 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -1006,7 +1006,8 @@ append_identifier(THD *thd, String *packet, const char *name, uint length) { const char *name_end; char quote_char; - int q= get_quote_char_for_identifier(thd, name, length); + int q; + q= thd ? get_quote_char_for_identifier(thd, name, length) : '`'; if (q == EOF) { diff --git a/sql/sql_show.h b/sql/sql_show.h index fec73122e8b..3a6cd158cb4 100644 --- a/sql/sql_show.h +++ b/sql/sql_show.h @@ -40,5 +40,6 @@ int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet, int view_store_create_info(THD *thd, TABLE_LIST *table, String *buff); int copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table); +int get_quote_char_for_identifier(THD *thd, const char *name, uint length); #endif /* SQL_SHOW_H */ diff --git a/sql/sql_table.cc b/sql/sql_table.cc index 39eee62ee91..b8d57341e42 100644 --- a/sql/sql_table.cc +++ b/sql/sql_table.cc @@ -1944,6 +1944,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, for (table= tables; table; table= table->next_local) { char *db=table->db; + int db_len= table->db_length; handlerton *table_type; enum legacy_db_type frm_db_type= DB_TYPE_UNKNOWN; @@ -1966,14 +1967,14 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, built_tmp_query.append("DROP TEMPORARY TABLE IF EXISTS "); } - built_tmp_query.append("`"); if (thd->db == NULL || strcmp(db,thd->db) != 0) { - built_tmp_query.append(db); - built_tmp_query.append("`.`"); + append_identifier(thd, &built_tmp_query, db, db_len); + built_tmp_query.append("."); } - built_tmp_query.append(table->table_name); - built_tmp_query.append("`,"); + append_identifier(thd, &built_tmp_query, table->table_name, + strlen(table->table_name)); + built_tmp_query.append(","); } continue; @@ -1999,15 +2000,14 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists, Don't write the database name if it is the current one (or if thd->db is NULL). */ - built_query.append("`"); if (thd->db == NULL || strcmp(db,thd->db) != 0) { - built_query.append(db); - built_query.append("`.`"); + append_identifier(thd, &built_query, db, db_len); + built_query.append("."); } - - built_query.append(table->table_name); - built_query.append("`,"); + append_identifier(thd, &built_query, table->table_name, + strlen(table->table_name)); + built_query.append(","); } if (!drop_temporary) -- cgit v1.2.1 From 7c671a7ead96dd9115a6ae77ebbf78d0dea43485 Mon Sep 17 00:00:00 2001 From: Rohit Kalhans Date: Sun, 23 Sep 2012 15:45:22 +0530 Subject: BUG#14548159: Followup patch to fix some issues on PB2 --- sql/ha_ndbcluster_binlog.cc | 2 +- sql/log_event.cc | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc index 70e52306e14..6d2a6f06c99 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -1307,7 +1307,7 @@ int ndbcluster_log_schema_op(THD *thd, NDB_SHARE *share, new_table_name, 0); quoted_table2[id_length]= '\0'; query_length= (uint) (strxmov(tmp_buf2, "rename table ", - quoted_db1, ".", quoted_table_1, " to ", + quoted_db1, ".", quoted_table1, " to ", quoted_db2, ".", quoted_table2, NullS) - tmp_buf2); type_str= "rename table"; break; diff --git a/sql/log_event.cc b/sql/log_event.cc index 829ee06d20e..c3ba969cf1f 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -4259,7 +4259,7 @@ uint Load_log_event::get_query_buffer_length() void Load_log_event::print_query(bool need_db, const char *cs, char *buf, char **end, char **fn_start, char **fn_end) { - char quoted_id[1 + NAME_LEN * 2 + 2];//quoted length + char quoted_id[1 + NAME_LEN * 2 + 2];//quoted length int quoted_id_len= 0; char *pos= buf; @@ -4272,7 +4272,8 @@ void Load_log_event::print_query(bool need_db, const char *cs, char *buf, #else quoted_id_len= my_strmov_quoted_identifier((char *) quoted_id, db); #endif - pos+= quoted_id_len; + quoted_id[quoted_id_len]= '\0'; + pos= strmov(pos, quoted_id); pos= strmov(pos, "; "); } -- cgit v1.2.1 From 815aad69287d83a1e1e98cd7797d02ca96f74bc3 Mon Sep 17 00:00:00 2001 From: Raghav Kapoor Date: Tue, 25 Sep 2012 15:58:46 +0530 Subject: BUG#13864642: DROP/CREATE USER BEHAVING ODDLY BACKGROUND: In certain situations DROP USER fails to remove all privileges belonging to user being dropped from in-memory structures. Current workaround is to do DROP USER twice in scenario below OR doing FLUSH PRIVILEGES after doing DROP USER. ANALYSIS: In MySQL, When we grant some stored routines privileges to a user they are stored in their respective hash. When doing DROP USER all the stored routine privilege entries associated with that user has to be deleted from its respective hash. The root cause for this bug is some entries from the hash are not getting deleted. The problem is that code that deletes entries from the hash tries to do so while iterating over it, without taking enough measures to address the fact that such deletion can reshuffle elements in the hash. If the user/administrator creates the same user again he is thrown an error 'Error 1396 ER_CANNOT_USER' from MySQL. This prompts the user to either do FLUSH PRIVILEGES or do DROP USER again. This behaviour is not desirable as it is a workaround and does not solves the problem mentioned above. FIX: This bug is fixed by introducing a dynamic array to store the pointersto all stored routine privilege objects that either have to be deleted or updated. This is done in 3 steps. Step 1: Fetching the element from the hash and checking whether it is to be deleted or updated. Step 2: Storing the pointer to that privilege object in dynamic array. Step 3: Traversing the dynamic array to perform the appropriate action either delete or update. This is a much cleaner way to delete or update the privilege entries associated with some user and solves the problem mentioned above. Also the code has been refactored a bit by introducing an enum instead of hard coded numbers used for respective dynamic arrays and hashes in handle_grant_struct() function. --- sql/sql_acl.cc | 235 +++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 146 insertions(+), 89 deletions(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 6d5d34d0602..e07f668b1cf 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -195,7 +195,17 @@ static bool compare_hostname(const acl_host_and_ip *host,const char *hostname, static my_bool acl_load(THD *thd, TABLE_LIST *tables); static my_bool grant_load(THD *thd, TABLE_LIST *tables); static inline void get_grantor(THD *thd, char* grantor); - +/* + Enumeration of various ACL's and Hashes used in handle_grant_struct() +*/ +enum enum_acl_lists +{ + USER_ACL= 0, + DB_ACL, + COLUMN_PRIVILEGES_HASH, + PROC_PRIVILEGES_HASH, + FUNC_PRIVILEGES_HASH +}; /* Convert scrambled password to binary form, according to scramble type, Binary form is stored in user.salt. @@ -5390,19 +5400,19 @@ static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop, Delete from grant structure if drop is true. Update in grant structure if drop is false and user_to is not NULL. Search in grant structure if drop is false and user_to is NULL. - Structures are numbered as follows: - 0 acl_users - 1 acl_dbs - 2 column_priv_hash - 3 proc_priv_hash - 4 func_priv_hash + Structures are enumerated as follows: + 0 ACL_USER + 1 ACL_DB + 2 COLUMN_PRIVILEGES_HASH + 3 PROC_PRIVILEGES_HASH + 4 FUNC_PRIVILEGES_HASH @retval > 0 At least one element matched. @retval 0 OK, but no element matched. - @retval -1 Wrong arguments to function. + @retval -1 Wrong arguments to function or Out of Memory */ -static int handle_grant_struct(uint struct_no, bool drop, +static int handle_grant_struct(enum enum_acl_lists struct_no, bool drop, LEX_USER *user_from, LEX_USER *user_to) { int result= 0; @@ -5413,6 +5423,11 @@ static int handle_grant_struct(uint struct_no, bool drop, ACL_USER *acl_user= NULL; ACL_DB *acl_db= NULL; GRANT_NAME *grant_name= NULL; + /* + Dynamic array acl_grant_name used to store pointers to all + GRANT_NAME objects + */ + Dynamic_array acl_grant_name; HASH *grant_name_hash= NULL; DBUG_ENTER("handle_grant_struct"); DBUG_PRINT("info",("scan struct: %u search: '%s'@'%s'", @@ -5425,21 +5440,21 @@ static int handle_grant_struct(uint struct_no, bool drop, /* Get the number of elements in the in-memory structure. */ switch (struct_no) { - case 0: + case USER_ACL: elements= acl_users.elements; break; - case 1: + case DB_ACL: elements= acl_dbs.elements; break; - case 2: + case COLUMN_PRIVILEGES_HASH: elements= column_priv_hash.records; grant_name_hash= &column_priv_hash; break; - case 3: + case PROC_PRIVILEGES_HASH: elements= proc_priv_hash.records; grant_name_hash= &proc_priv_hash; break; - case 4: + case FUNC_PRIVILEGES_HASH: elements= func_priv_hash.records; grant_name_hash= &func_priv_hash; break; @@ -5458,21 +5473,21 @@ static int handle_grant_struct(uint struct_no, bool drop, Get a pointer to the element. */ switch (struct_no) { - case 0: + case USER_ACL: acl_user= dynamic_element(&acl_users, idx, ACL_USER*); user= acl_user->user; host= acl_user->host.hostname; break; - case 1: + case DB_ACL: acl_db= dynamic_element(&acl_dbs, idx, ACL_DB*); user= acl_db->user; host= acl_db->host.hostname; break; - case 2: - case 3: - case 4: + case COLUMN_PRIVILEGES_HASH: + case PROC_PRIVILEGES_HASH: + case FUNC_PRIVILEGES_HASH: grant_name= (GRANT_NAME*) hash_element(grant_name_hash, idx); user= grant_name->user; host= grant_name->host.hostname; @@ -5498,86 +5513,60 @@ static int handle_grant_struct(uint struct_no, bool drop, if ( drop ) { switch ( struct_no ) { - case 0: + case USER_ACL: delete_dynamic_element(&acl_users, idx); + elements--; + /* + - If we are iterating through an array then we just have moved all + elements after the current element one position closer to its head. + This means that we have to take another look at the element at + current position as it is a new element from the array's tail. + - This is valid for USER_ACL, DB_ACL. + */ + idx--; break; - case 1: + case DB_ACL: delete_dynamic_element(&acl_dbs, idx); + elements--; + idx--; break; - case 2: - case 3: - case 4: - hash_delete(grant_name_hash, (uchar*) grant_name); + case COLUMN_PRIVILEGES_HASH: + case PROC_PRIVILEGES_HASH: + case FUNC_PRIVILEGES_HASH: + /* + Deleting while traversing a hash table is not valid procedure and + hence we save pointers to GRANT_NAME objects for later processing. + */ + if (acl_grant_name.append(grant_name)) + DBUG_RETURN(-1); break; } - elements--; - /* - - If we are iterating through an array then we just have moved all - elements after the current element one position closer to its head. - This means that we have to take another look at the element at - current position as it is a new element from the array's tail. - - If we are iterating through a hash the current element was replaced - with one of elements from the tail. So we also have to take a look - at the new element in current position. - Note that in our HASH implementation hash_delete() won't move any - elements with position after current one to position before the - current (i.e. from the tail to the head), so it is safe to continue - iteration without re-starting. - */ - idx--; } else if ( user_to ) { switch ( struct_no ) { - case 0: + case USER_ACL: acl_user->user= strdup_root(&mem, user_to->user.str); acl_user->host.hostname= strdup_root(&mem, user_to->host.str); break; - case 1: + case DB_ACL: acl_db->user= strdup_root(&mem, user_to->user.str); acl_db->host.hostname= strdup_root(&mem, user_to->host.str); break; - case 2: - case 3: - case 4: - { - /* - Save old hash key and its length to be able properly update - element position in hash. - */ - char *old_key= grant_name->hash_key; - size_t old_key_length= grant_name->key_length; - - /* - Update the grant structure with the new user name and host name. - */ - grant_name->set_user_details(user_to->host.str, grant_name->db, - user_to->user.str, grant_name->tname, - TRUE); - - /* - Since username is part of the hash key, when the user name - is renamed, the hash key is changed. Update the hash to - ensure that the position matches the new hash key value - */ - hash_update(grant_name_hash, (uchar*) grant_name, (uchar*) old_key, - old_key_length); - /* - hash_update() operation could have moved element from the tail - of the hash to the current position. So we need to take a look - at the element in current position once again. - Thanks to the fact that hash_update() for our HASH implementation - won't move any elements from the tail of the hash to the positions - before the current one (a.k.a. head) it is safe to continue - iteration without restarting. - */ - idx--; - break; - } + case COLUMN_PRIVILEGES_HASH: + case PROC_PRIVILEGES_HASH: + case FUNC_PRIVILEGES_HASH: + /* + Updating while traversing a hash table is not valid procedure and + hence we save pointers to GRANT_NAME objects for later processing. + */ + if (acl_grant_name.append(grant_name)) + DBUG_RETURN(-1); + break; } } else @@ -5586,6 +5575,48 @@ static int handle_grant_struct(uint struct_no, bool drop, break; } } + + if (drop || user_to) + { + /* + Traversing the elements stored in acl_grant_name dynamic array + to either delete or update them. + */ + for (int i= 0; i < acl_grant_name.elements(); ++i) + { + grant_name= acl_grant_name.at(i); + + if (drop) + { + my_hash_delete(grant_name_hash, (uchar *) grant_name); + } + else + { + /* + Save old hash key and its length to be able properly update + element position in hash. + */ + char *old_key= grant_name->hash_key; + size_t old_key_length= grant_name->key_length; + + /* + Update the grant structure with the new user name and host name. + */ + grant_name->set_user_details(user_to->host.str, grant_name->db, + user_to->user.str, grant_name->tname, + TRUE); + + /* + Since username is part of the hash key, when the user name + is renamed, the hash key is changed. Update the hash to + ensure that the position matches the new hash key value + */ + my_hash_update(grant_name_hash, (uchar*) grant_name, (uchar*) old_key, + old_key_length); + } + } + } + #ifdef EXTRA_DEBUG DBUG_PRINT("loop",("scan struct: %u result %d", struct_no, result)); #endif @@ -5623,6 +5654,7 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop, { int result= 0; int found; + int ret; DBUG_ENTER("handle_grant_data"); /* Handle user table. */ @@ -5634,14 +5666,19 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop, else { /* Handle user array. */ - if ((handle_grant_struct(0, drop, user_from, user_to) && ! result) || - found) + if (((ret= handle_grant_struct(USER_ACL, drop, user_from, user_to) > 0) && + ! result) || found) { result= 1; /* At least one record/element found. */ /* If search is requested, we do not need to search further. */ if (! drop && ! user_to) goto end; } + else if (ret < 0) + { + result= -1; + goto end; + } } /* Handle db table. */ @@ -5653,14 +5690,19 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop, else { /* Handle db array. */ - if (((handle_grant_struct(1, drop, user_from, user_to) && ! result) || - found) && ! result) + if ((((ret= handle_grant_struct(DB_ACL, drop, user_from, user_to) > 0) && + ! result) || found) && ! result) { result= 1; /* At least one record/element found. */ /* If search is requested, we do not need to search further. */ if (! drop && ! user_to) goto end; } + else if (ret < 0) + { + result= -1; + goto end; + } } /* Handle stored routines table. */ @@ -5672,23 +5714,35 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop, else { /* Handle procs array. */ - if (((handle_grant_struct(3, drop, user_from, user_to) && ! result) || - found) && ! result) + if ((((ret= handle_grant_struct(PROC_PRIVILEGES_HASH, drop, user_from, + user_to) > 0) && ! result) || found) && + ! result) { result= 1; /* At least one record/element found. */ /* If search is requested, we do not need to search further. */ if (! drop && ! user_to) goto end; } + else if (ret < 0) + { + result= -1; + goto end; + } /* Handle funcs array. */ - if (((handle_grant_struct(4, drop, user_from, user_to) && ! result) || - found) && ! result) + if ((((ret= handle_grant_struct(FUNC_PRIVILEGES_HASH, drop, user_from, + user_to) > 0) && ! result) || found) && + ! result) { result= 1; /* At least one record/element found. */ /* If search is requested, we do not need to search further. */ if (! drop && ! user_to) goto end; } + else if (ret < 0) + { + result= -1; + goto end; + } } /* Handle tables table. */ @@ -5716,9 +5770,12 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop, else { /* Handle columns hash. */ - if (((handle_grant_struct(2, drop, user_from, user_to) && ! result) || - found) && ! result) + if ((((ret= handle_grant_struct(COLUMN_PRIVILEGES_HASH, drop, user_from, + user_to) > 0) && ! result) || found) && + ! result) result= 1; /* At least one record/element found. */ + else if (ret < 0) + result= -1; } } end: -- cgit v1.2.1 From 58de1660629890abfeeb50eb6bc9cf998c145894 Mon Sep 17 00:00:00 2001 From: Jon Olav Hauglid Date: Tue, 25 Sep 2012 13:09:53 +0200 Subject: Bug#14621627 THREAD CACHE IS UNFAIR When a client connects to a MySQL server, first a THD object is created. If there are any idle server threads waiting, the THD object is then added to a list and a server thread is woken up. This thread then retrieves the THD object from the list and starts executing. The problem was that this list of THD objects waiting for a server thread, was not working in a FIFO fashion, but rather LIFO. This is unfair, as it means that the last THD added (=last client connected) will be assigned a server thread first. Note however that for this to be a problem, several clients must be able to connect and have THD objects constructed before any server threads manages to be woken up. This is not a very likely scenario. This patch fixes the problem by changing the THD list to work FIFO rather than LIFO. This is the 5.1/5.5 version of the patch. --- sql/mysqld.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/mysqld.cc b/sql/mysqld.cc index bc8d4162272..11e756381ab 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -4808,7 +4808,7 @@ void create_thread_to_handle_connection(THD *thd) if (cached_thread_count > wake_thread) { /* Get thread from cache */ - thread_cache.append(thd); + thread_cache.push_back(thd); wake_thread++; pthread_cond_signal(&COND_thread_cache); } -- cgit v1.2.1 From b079b388a50dfa1fdaa4da0cb22154b0cc6d885e Mon Sep 17 00:00:00 2001 From: Tor Didriksen Date: Tue, 25 Sep 2012 16:03:05 +0200 Subject: Backport Bug #11764313 57135: CRASH IN ITEM_FUNC_CASE::FIND_ITEM WITH CASE WHEN Bug #11764818 57692: Crash in item_func_in::val_int() with ZEROFILL --- sql/item_cmpfunc.cc | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index 23f081e1cc0..6e8fa9a5f75 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -1,4 +1,4 @@ -/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. +/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -3045,6 +3045,15 @@ void Item_func_case::fix_length_and_dec() return; } } + /* + Set cmp_context of all WHEN arguments. This prevents + Item_field::equal_fields_propagator() from transforming a + zerofill argument into a string constant. Such a change would + require rebuilding cmp_items. + */ + for (i= 0; i < ncases; i+= 2) + args[i]->cmp_context= item_cmp_type(left_result_type, + args[i]->result_type()); } if (else_expr_num == -1 || args[else_expr_num]->maybe_null) @@ -4032,6 +4041,16 @@ void Item_func_in::fix_length_and_dec() } } } + /* + Set cmp_context of all arguments. This prevents + Item_field::equal_fields_propagator() from transforming a zerofill integer + argument into a string constant. Such a change would require rebuilding + cmp_itmes. + */ + for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++) + { + arg[0]->cmp_context= item_cmp_type(left_result_type, arg[0]->result_type()); + } max_length= 1; } -- cgit v1.2.1 From 7327cd9717f0b98499f0f5b19c84e5e3e48241df Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Sep 2012 14:01:17 +0300 Subject: =?UTF-8?q?MDEV-377=20Name=20support=20for=20dynamic=20columns=20M?= =?UTF-8?q?DEV-127=20Optimization=20of=20memory=20allocation=20MDEV-483=20?= =?UTF-8?q?Make=20column=5Fcheck=20function=20which=20che=D1=81ks=20dynami?= =?UTF-8?q?c=20columns=20integrit=20JSON=20conversion=20function?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sql/item.h | 2 +- sql/item_cmpfunc.cc | 73 +++++++++++++++-- sql/item_cmpfunc.h | 8 ++ sql/item_create.cc | 14 ++-- sql/item_create.h | 1 + sql/item_strfunc.cc | 226 +++++++++++++++++++++++++++++++++++++++++++--------- sql/item_strfunc.h | 18 ++++- sql/lex.h | 2 + sql/sql_string.cc | 73 ----------------- sql/sql_yacc.yy | 20 ++++- 10 files changed, 313 insertions(+), 124 deletions(-) (limited to 'sql') diff --git a/sql/item.h b/sql/item.h index f7f3edda384..906d3d21d6f 100644 --- a/sql/item.h +++ b/sql/item.h @@ -523,7 +523,7 @@ public: struct st_dyncall_create_def { - Item *num, *value; + Item *key, *value; CHARSET_INFO *cs; uint len, frac; DYNAMIC_COLUMN_TYPE type; diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index 2a0ca19a4e9..72d28bb2e7e 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -6048,24 +6048,87 @@ Item* Item_equal::get_first(JOIN_TAB *context, Item *field_item) return NULL; } - -longlong Item_func_dyncol_exists::val_int() +longlong Item_func_dyncol_check::val_int() { char buff[STRING_BUFFER_USUAL_SIZE]; String tmp(buff, sizeof(buff), &my_charset_bin); DYNAMIC_COLUMN col; String *str; - ulonglong num; enum enum_dyncol_func_result rc; - num= args[1]->val_int(); + str= args[0]->val_str(&tmp); + if (args[0]->null_value) + goto null; + col.length= str->length(); + /* We do not change the string, so could do this trick */ + col.str= (char *)str->ptr(); + rc= dynamic_column_check(&col); + if (rc < 0 && rc != ER_DYNCOL_FORMAT) + { + dynamic_column_error_message(rc); + goto null; + } + null_value= FALSE; + return rc == ER_DYNCOL_OK; + +null: + null_value= TRUE; + return 0; +} + +longlong Item_func_dyncol_exists::val_int() +{ + char buff[STRING_BUFFER_USUAL_SIZE], nmstrbuf[11]; + String tmp(buff, sizeof(buff), &my_charset_bin), + nmbuf(nmstrbuf, sizeof(nmstrbuf), system_charset_info); + DYNAMIC_COLUMN col; + String *str; + LEX_STRING buf, *name= NULL; + ulonglong num= 0; + enum enum_dyncol_func_result rc; + + if (args[1]->result_type() == INT_RESULT) + num= args[1]->val_int(); + else + { + String *nm= args[1]->val_str(&nmbuf); + if (!nm || args[1]->null_value) + { + null_value= 1; + return 1; + } + if (my_charset_same(nm->charset(), &my_charset_utf8_general_ci)) + { + buf.str= (char *) nm->ptr(); + buf.length= nm->length(); + } + else + { + uint strlen; + uint dummy_errors; + buf.str= (char *)sql_alloc((strlen= nm->length() * + my_charset_utf8_general_ci.mbmaxlen + 1)); + if (buf.str) + { + buf.length= + copy_and_convert(buf.str, strlen, &my_charset_utf8_general_ci, + nm->ptr(), nm->length(), nm->charset(), + &dummy_errors); + } + else + buf.length= 0; + } + name= &buf; + } str= args[0]->val_str(&tmp); if (args[0]->null_value || args[1]->null_value || num > UINT_MAX16) goto null; col.length= str->length(); /* We do not change the string, so could do this trick */ col.str= (char *)str->ptr(); - rc= dynamic_column_exists(&col, (uint) num); + rc= ((name == NULL) ? + dynamic_column_exists(&col, (uint) num) : + dynamic_column_exists_str(&col, name)); if (rc < 0) { dynamic_column_error_message(rc); diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index 34d1a0bd0ae..f183ee9f8a8 100644 --- a/sql/item_cmpfunc.h +++ b/sql/item_cmpfunc.h @@ -1861,6 +1861,14 @@ public: Item *neg_transformer(THD *thd); }; +class Item_func_dyncol_check :public Item_bool_func +{ +public: + Item_func_dyncol_check(Item *str) :Item_bool_func(str) {} + longlong val_int(); + const char *func_name() const { return "column_check"; } +}; + class Item_func_dyncol_exists :public Item_bool_func { public: diff --git a/sql/item_create.cc b/sql/item_create.cc index 96837a8f262..f886b3d598b 100644 --- a/sql/item_create.cc +++ b/sql/item_create.cc @@ -5704,7 +5704,7 @@ static List *create_func_dyncol_prepare(THD *thd, for (uint i= 0; (def= li++) ;) { dfs[0][i++]= *def; - args->push_back(def->num); + args->push_back(def->key); args->push_back(def->value); } return args; @@ -5720,6 +5720,10 @@ Item *create_func_dyncol_create(THD *thd, List &list) return new (thd->mem_root) Item_func_dyncol_create(*args, dfs); } +Item *create_func_dyncol_json(THD *thd, Item *str) +{ + return new (thd->mem_root) Item_func_dyncol_json(str); +} Item *create_func_dyncol_add(THD *thd, Item *str, List &list) @@ -5740,7 +5744,7 @@ Item *create_func_dyncol_add(THD *thd, Item *str, Item *create_func_dyncol_delete(THD *thd, Item *str, List &nums) { DYNCALL_CREATE_DEF *dfs; - Item *num; + Item *key; List_iterator_fast it(nums); List *args= new (thd->mem_root) List; @@ -5750,12 +5754,12 @@ Item *create_func_dyncol_delete(THD *thd, Item *str, List &nums) if (!args || !dfs) return NULL; - for (uint i= 0; (num= it++); i++) + for (uint i= 0; (key= it++); i++) { - dfs[i].num= num; + dfs[i].key= key; dfs[i].value= new Item_null(); dfs[i].type= DYN_COL_INT; - args->push_back(dfs[i].num); + args->push_back(dfs[i].key); args->push_back(dfs[i].value); } diff --git a/sql/item_create.h b/sql/item_create.h index ac6b0f8454f..5ecb45e9eae 100644 --- a/sql/item_create.h +++ b/sql/item_create.h @@ -180,5 +180,6 @@ Item *create_func_dyncol_get(THD *thd, Item *num, Item *str, Cast_target cast_type, const char *c_len, const char *c_dec, CHARSET_INFO *cs); +Item *create_func_dyncol_json(THD *thd, Item *str); #endif diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index c5d1edbe475..ca6a6b2cea3 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -3760,7 +3760,8 @@ String *Item_func_uuid::val_str(String *str) Item_func_dyncol_create::Item_func_dyncol_create(List &args, DYNCALL_CREATE_DEF *dfs) - : Item_str_func(args), defs(dfs), vals(0), nums(0) + : Item_str_func(args), defs(dfs), vals(0), keys(NULL), names(FALSE), + force_names(FALSE) { DBUG_ASSERT((args.elements & 0x1) == 0); // even number of arguments } @@ -3768,13 +3769,26 @@ Item_func_dyncol_create::Item_func_dyncol_create(List &args, bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref) { + uint i; bool res= Item_func::fix_fields(thd, ref); // no need Item_str_func here - vals= (DYNAMIC_COLUMN_VALUE *) alloc_root(thd->mem_root, - sizeof(DYNAMIC_COLUMN_VALUE) * - (arg_count / 2)); - nums= (uint *) alloc_root(thd->mem_root, - sizeof(uint) * (arg_count / 2)); - return res || vals == 0 || nums == 0; + if (!res) + { + vals= (DYNAMIC_COLUMN_VALUE *) alloc_root(thd->mem_root, + sizeof(DYNAMIC_COLUMN_VALUE) * + (arg_count / 2)); + for (i= 0; i + 1 < arg_count && args[i]->result_type() == INT_RESULT; i+= 2); + if (i + 1 < arg_count) + { + names= TRUE; + } + + keys= (uchar *) alloc_root(thd->mem_root, + (sizeof(LEX_STRING) > sizeof(uint) ? + sizeof(LEX_STRING) : + sizeof(uint)) * + (arg_count / 2)); + } + return res || vals == 0 || keys == 0; } @@ -3785,13 +3799,14 @@ void Item_func_dyncol_create::fix_length_and_dec() decimals= 0; } -void Item_func_dyncol_create::prepare_arguments() +bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) { char buff[STRING_BUFFER_USUAL_SIZE]; String *res, tmp(buff, sizeof(buff), &my_charset_bin); uint column_count= (arg_count / 2); uint i; my_decimal dtmp, *dres; + force_names= force_names_arg; /* get values */ for (i= 0; i < column_count; i++) @@ -3850,7 +3865,54 @@ void Item_func_dyncol_create::prepare_arguments() break; } } - nums[i]= (uint) args[i * 2]->val_int(); + if (names || force_names) + { + res= args[i * 2]->val_str(&tmp); + if (res) + { + // guaranty UTF-8 string for names + if (my_charset_same(res->charset(), &my_charset_utf8_general_ci)) + { + ((LEX_STRING *)keys)[i].length= res->length(); + if (!(((LEX_STRING *)keys)[i].str= + (char *)sql_memdup(res->ptr(), res->length()))) + ((LEX_STRING *)keys)[i].length= 0; + } + else + { + uint strlen; + uint dummy_errors; + char *str= + (char *)sql_alloc((strlen= res->length() * + my_charset_utf8_general_ci.mbmaxlen + 1)); + if (str) + { + ((LEX_STRING *)keys)[i].length= + copy_and_convert(str, strlen, &my_charset_utf8_general_ci, + res->ptr(), res->length(), res->charset(), + &dummy_errors); + ((LEX_STRING *)keys)[i].str= str; + } + else + ((LEX_STRING *)keys)[i].length= 0; + + } + } + else + { + ((LEX_STRING *)keys)[i].length= 0; + ((LEX_STRING *)keys)[i].str= NULL; + } + } + else + ((uint *)keys)[i]= (uint) args[i * 2]->val_int(); + if (args[i * 2]->null_value) + { + /* to make cleanup possible */ + for (; i < column_count; i++) + vals[i].type= DYN_COL_NULL; + return 1; + } vals[i].type= type; switch (type) { case DYN_COL_NULL: @@ -3918,6 +3980,7 @@ void Item_func_dyncol_create::prepare_arguments() vals[i].type= DYN_COL_NULL; } } + return FALSE; } void Item_func_dyncol_create::cleanup_arguments() @@ -3930,6 +3993,7 @@ void Item_func_dyncol_create::cleanup_arguments() if (vals[i].type == DYN_COL_STRING) my_free(vals[i].x.string.value.str); } + force_names= FALSE; } String *Item_func_dyncol_create::val_str(String *str) @@ -3940,25 +4004,32 @@ String *Item_func_dyncol_create::val_str(String *str) enum enum_dyncol_func_result rc; DBUG_ASSERT((arg_count & 0x1) == 0); // even number of arguments - prepare_arguments(); - - if ((rc= dynamic_column_create_many(&col, column_count, nums, vals))) + if (prepare_arguments(FALSE)) { - dynamic_column_error_message(rc); - dynamic_column_column_free(&col); res= NULL; - null_value= TRUE; + null_value= 1; } else { - /* Move result from DYNAMIC_COLUMN to str_value */ - char *ptr; - size_t length, alloc_length; - dynamic_column_reassociate(&col, &ptr, &length, &alloc_length); - str_value.reassociate(ptr, (uint32) length, (uint32) alloc_length, - &my_charset_bin); - res= &str_value; - null_value= FALSE; + if ((rc= dynamic_column_create_many_fmt(&col, column_count, keys, + vals, names || force_names))) + { + dynamic_column_error_message(rc); + dynamic_column_column_free(&col); + res= NULL; + null_value= TRUE; + } + else + { + /* Move result from DYNAMIC_COLUMN to str_value */ + char *ptr; + size_t length, alloc_length; + dynamic_column_reassociate(&col, &ptr, &length, &alloc_length); + str_value.reassociate(ptr, (uint32) length, (uint32) alloc_length, + &my_charset_bin); + res= &str_value; + null_value= FALSE; + } } /* cleanup */ @@ -4026,6 +4097,40 @@ void Item_func_dyncol_create::print(String *str, str->append(')'); } +String *Item_func_dyncol_json::val_str(String *str) +{ + DYNAMIC_STRING json, col; + String *res; + enum enum_dyncol_func_result rc; + + res= args[0]->val_str(str); + if (args[0]->null_value) + goto null; + + col.str= (char *)res->ptr(); + col.length= res->length(); + if ((rc= dynamic_column_json(&col, &json))) + { + dynamic_column_error_message(rc); + goto null; + } + bzero(&col, sizeof(col)); + { + /* Move result from DYNAMIC_COLUMN to str */ + char *ptr; + size_t length, alloc_length; + dynstr_reassociate(&json, &ptr, &length, &alloc_length); + str->reassociate(ptr, (uint32) length, (uint32) alloc_length, + &my_charset_utf8_general_ci); + null_value= FALSE; + } + return str; + +null: + bzero(&col, sizeof(col)); + null_value= TRUE; + return NULL; +} String *Item_func_dyncol_add::val_str(String *str) { @@ -4037,17 +4142,19 @@ String *Item_func_dyncol_add::val_str(String *str) /* We store the packed data last */ res= args[arg_count - 1]->val_str(str); - if (args[arg_count - 1]->null_value) + if (args[arg_count - 1]->null_value || + init_dynamic_string(&col, NULL, res->length() + STRING_BUFFER_USUAL_SIZE, + STRING_BUFFER_USUAL_SIZE)) goto null; - init_dynamic_string(&col, NULL, res->length() + STRING_BUFFER_USUAL_SIZE, - STRING_BUFFER_USUAL_SIZE); col.length= res->length(); memcpy(col.str, res->ptr(), col.length); - prepare_arguments(); + if (prepare_arguments(dynamic_column_has_names(&col))) + goto null; - if ((rc= dynamic_column_update_many(&col, column_count, nums, vals))) + if ((rc= dynamic_column_update_many_fmt(&col, column_count, keys, + vals, names || force_names))) { dynamic_column_error_message(rc); dynamic_column_column_free(&col); @@ -4066,7 +4173,6 @@ String *Item_func_dyncol_add::val_str(String *str) } /* cleanup */ - dynamic_column_column_free(&col); cleanup_arguments(); return str; @@ -4100,10 +4206,48 @@ bool Item_dyncol_get::get_dyn_value(DYNAMIC_COLUMN_VALUE *val, String *tmp) { DYNAMIC_COLUMN dyn_str; String *res; - longlong num; + longlong num= 0; + LEX_STRING buf, *name= NULL; + char nmstrbuf[11]; + String nmbuf(nmstrbuf, sizeof(nmstrbuf), system_charset_info); enum enum_dyncol_func_result rc; - num= args[1]->val_int(); + if (args[1]->result_type() == INT_RESULT) + num= args[1]->val_int(); + else + { + String *nm= args[1]->val_str(&nmbuf); + if (!nm || args[1]->null_value) + { + null_value= 1; + return 1; + } + + if (my_charset_same(nm->charset(), &my_charset_utf8_general_ci)) + { + buf.str= (char *) nm->ptr(); + buf.length= nm->length(); + } + else + { + uint strlen; + uint dummy_errors; + buf.str= (char *)sql_alloc((strlen= nm->length() * + my_charset_utf8_general_ci.mbmaxlen + 1)); + if (buf.str) + { + buf.length= + copy_and_convert(buf.str, strlen, &my_charset_utf8_general_ci, + nm->ptr(), nm->length(), nm->charset(), + &dummy_errors); + } + else + buf.length= 0; + } + name= &buf; + } + + if (args[1]->null_value || num < 0 || num > INT_MAX) { null_value= 1; @@ -4119,7 +4263,9 @@ bool Item_dyncol_get::get_dyn_value(DYNAMIC_COLUMN_VALUE *val, String *tmp) dyn_str.str= (char*) res->ptr(); dyn_str.length= res->length(); - if ((rc= dynamic_column_get(&dyn_str, (uint) num, val))) + if ((rc= ((name == NULL) ? + dynamic_column_get(&dyn_str, (uint) num, val) : + dynamic_column_get_str(&dyn_str, name, val)))) { dynamic_column_error_message(rc); null_value= 1; @@ -4468,6 +4614,8 @@ null: return 1; } +void +append_identifier(THD *thd, String *packet, const char *name, uint length); void Item_dyncol_get::print(String *str, enum_query_type query_type) { @@ -4492,26 +4640,30 @@ String *Item_func_dyncol_list::val_str(String *str) col.length= res->length(); /* We do not change the string, so could do this trick */ col.str= (char *)res->ptr(); - if ((rc= dynamic_column_list(&col, &arr))) + if ((rc= dynamic_column_list_str(&col, &arr))) { dynamic_column_error_message(rc); + for (i= 0; i < arr.elements; i++) + my_free(dynamic_element(&arr, i, LEX_STRING*)->str); delete_dynamic(&arr); goto null; } /* - We support elements from 0 - 65536, so max size for one element is - 6 (including ,). + We estimate average name length as 10 */ - if (str->alloc(arr.elements * 6)) + if (str->alloc(arr.elements * 13)) goto null; str->length(0); + str->set_charset(&my_charset_utf8_general_ci); for (i= 0; i < arr.elements; i++) { - str->qs_append(*dynamic_element(&arr, i, uint*)); + LEX_STRING *name= dynamic_element(&arr, i, LEX_STRING *); + append_identifier(current_thd, str, name->str, name->length); if (i < arr.elements - 1) str->qs_append(','); + my_free(name->str); } null_value= FALSE; diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h index 9ed2627a518..e6a7e1291b8 100644 --- a/sql/item_strfunc.h +++ b/sql/item_strfunc.h @@ -1001,8 +1001,9 @@ class Item_func_dyncol_create: public Item_str_func protected: DYNCALL_CREATE_DEF *defs; DYNAMIC_COLUMN_VALUE *vals; - uint *nums; - void prepare_arguments(); + uchar *keys; + bool names, force_names; + bool prepare_arguments(bool force_names); void cleanup_arguments(); void print_arguments(String *str, enum_query_type query_type); public: @@ -1026,6 +1027,19 @@ public: virtual void print(String *str, enum_query_type query_type); }; +class Item_func_dyncol_json: public Item_str_func +{ +public: + Item_func_dyncol_json(Item *str) :Item_str_func(str) {} + const char *func_name() const{ return "column_json"; } + String *val_str(String *); + void fix_length_and_dec() + { + maybe_null= TRUE; + collation.set(&my_charset_bin); + decimals= 0; + } +}; /* The following functions is always called from an Item_cast function diff --git a/sql/lex.h b/sql/lex.h index 9f4369630a0..ea68ea0972a 100644 --- a/sql/lex.h +++ b/sql/lex.h @@ -123,10 +123,12 @@ static SYMBOL symbols[] = { { "COLUMN_NAME", SYM(COLUMN_NAME_SYM)}, { "COLUMNS", SYM(COLUMNS)}, { "COLUMN_ADD", SYM(COLUMN_ADD_SYM)}, + { "COLUMN_CHECK", SYM(COLUMN_CHECK_SYM)}, { "COLUMN_CREATE", SYM(COLUMN_CREATE_SYM)}, { "COLUMN_DELETE", SYM(COLUMN_DELETE_SYM)}, { "COLUMN_EXISTS", SYM(COLUMN_EXISTS_SYM)}, { "COLUMN_GET", SYM(COLUMN_GET_SYM)}, + { "COLUMN_JSON", SYM(COLUMN_JSON_SYM)}, { "COLUMN_LIST", SYM(COLUMN_LIST_SYM)}, { "COMMENT", SYM(COMMENT_SYM)}, { "COMMIT", SYM(COMMIT_SYM)}, diff --git a/sql/sql_string.cc b/sql/sql_string.cc index c4f5f315b08..bfd0d82c40a 100644 --- a/sql/sql_string.cc +++ b/sql/sql_string.cc @@ -750,79 +750,6 @@ String *copy_if_not_alloced(String *to,String *from,uint32 from_length) Help functions ****************************************************************************/ -/* - copy a string from one character set to another - - SYNOPSIS - copy_and_convert() - to Store result here - to_cs Character set of result string - from Copy from here - from_length Length of from string - from_cs From character set - - NOTES - 'to' must be big enough as form_length * to_cs->mbmaxlen - - RETURN - length of bytes copied to 'to' -*/ - - -static uint32 -copy_and_convert_extended(char *to, uint32 to_length, CHARSET_INFO *to_cs, - const char *from, uint32 from_length, - CHARSET_INFO *from_cs, - uint *errors) -{ - int cnvres; - my_wc_t wc; - const uchar *from_end= (const uchar*) from+from_length; - char *to_start= to; - uchar *to_end= (uchar*) to+to_length; - my_charset_conv_mb_wc mb_wc= from_cs->cset->mb_wc; - my_charset_conv_wc_mb wc_mb= to_cs->cset->wc_mb; - uint error_count= 0; - - while (1) - { - if ((cnvres= (*mb_wc)(from_cs, &wc, (uchar*) from, - from_end)) > 0) - from+= cnvres; - else if (cnvres == MY_CS_ILSEQ) - { - error_count++; - from++; - wc= '?'; - } - else if (cnvres > MY_CS_TOOSMALL) - { - /* - A correct multibyte sequence detected - But it doesn't have Unicode mapping. - */ - error_count++; - from+= (-cnvres); - wc= '?'; - } - else - break; // Not enough characters - -outp: - if ((cnvres= (*wc_mb)(to_cs, wc, (uchar*) to, to_end)) > 0) - to+= cnvres; - else if (cnvres == MY_CS_ILUNI && wc != '?') - { - error_count++; - wc= '?'; - goto outp; - } - else - break; - } - *errors= error_count; - return (uint32) (to - to_start); -} /* diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index 4e3629080be..48dd47bccea 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -882,10 +882,12 @@ bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize); %token COLLATION_SYM /* SQL-2003-N */ %token COLUMNS %token COLUMN_ADD_SYM +%token COLUMN_CHECK_SYM %token COLUMN_CREATE_SYM %token COLUMN_DELETE_SYM %token COLUMN_EXISTS_SYM %token COLUMN_GET_SYM +%token COLUMN_JSON_SYM %token COLUMN_LIST_SYM %token COLUMN_SYM /* SQL-2003-R */ %token COLUMN_NAME_SYM /* SQL-2003-N */ @@ -8245,7 +8247,7 @@ dyncall_create_element: alloc_root(YYTHD->mem_root, sizeof(DYNCALL_CREATE_DEF)); if ($$ == NULL) MYSQL_YYABORT; - $$->num= $1; + $$->key= $1; $$->value= $3; $$->type= (DYNAMIC_COLUMN_TYPE)$4; $$->cs= lex->charset; @@ -8798,6 +8800,13 @@ function_call_nonkeyword: if ($$ == NULL) MYSQL_YYABORT; } + | + COLUMN_CHECK_SYM '(' expr ')' + { + $$= new (YYTHD->mem_root) Item_func_dyncol_check($3); + if ($$ == NULL) + MYSQL_YYABORT; + } | COLUMN_EXISTS_SYM '(' expr ',' expr ')' { @@ -8819,6 +8828,13 @@ function_call_nonkeyword: if ($$ == NULL) MYSQL_YYABORT; } + | + COLUMN_JSON_SYM '(' expr ')' + { + $$= create_func_dyncol_json(YYTHD, $3); + if ($$ == NULL) + MYSQL_YYABORT; + } | COLUMN_GET_SYM '(' expr ',' expr AS cast_type ')' { @@ -12908,10 +12924,12 @@ keyword: | CHECKPOINT_SYM {} | CLOSE_SYM {} | COLUMN_ADD_SYM {} + | COLUMN_CHECK_SYM {} | COLUMN_CREATE_SYM {} | COLUMN_DELETE_SYM {} | COLUMN_EXISTS_SYM {} | COLUMN_GET_SYM {} + | COLUMN_JSON_SYM {} | COLUMN_LIST_SYM {} | COMMENT_SYM {} | COMMIT_SYM {} -- cgit v1.2.1 From 245298f25debbeb9556abbea195fc24c4a2845de Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Sep 2012 15:27:16 +0300 Subject: MDEV-506 Cassandra dynamic columns access --- sql/sql_base.cc | 1 + sql/sql_base.h | 1 + 2 files changed, 2 insertions(+) (limited to 'sql') diff --git a/sql/sql_base.cc b/sql/sql_base.cc index acd330dd4d2..8f793f641ce 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -9773,6 +9773,7 @@ int dynamic_column_error_message(enum_dyncol_func_result rc) switch (rc) { case ER_DYNCOL_YES: case ER_DYNCOL_OK: + case ER_DYNCOL_TRUNCATED: break; // it is not an error case ER_DYNCOL_FORMAT: my_error(ER_DYN_COL_WRONG_FORMAT, MYF(0)); diff --git a/sql/sql_base.h b/sql/sql_base.h index 3deb97c9730..cb7abc972ea 100644 --- a/sql/sql_base.h +++ b/sql/sql_base.h @@ -272,6 +272,7 @@ bool rename_temporary_table(THD* thd, TABLE *table, const char *new_db, const char *table_name); bool is_equal(const LEX_STRING *a, const LEX_STRING *b); +class Open_tables_backup; /* Functions to work with system tables. */ bool open_system_tables_for_read(THD *thd, TABLE_LIST *table_list, Open_tables_backup *backup); -- cgit v1.2.1 From 540d0cd28eeb11abab578d189bbe748b930d8edc Mon Sep 17 00:00:00 2001 From: Tor Didriksen Date: Mon, 1 Oct 2012 13:12:38 +0200 Subject: Bug#14683676 ENDLESS MEMORY CONSUMPTION IN SETUP_REF_ARRAY WITH MAX IN SUBQUERY n_child_sum_items kept increasing. Since it is used for calculating the size of ref_pointer_array, we will allocate larger and larger chunks of memory, until we hit some operating system limit. The memory is free()d at disconnect, but is most likely *not* returned to the operating system. --- sql/sql_lex.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'sql') diff --git a/sql/sql_lex.cc b/sql/sql_lex.cc index fd9367b99f2..e171cf1c06d 100644 --- a/sql/sql_lex.cc +++ b/sql/sql_lex.cc @@ -1616,6 +1616,7 @@ void st_select_lex::init_query() ref_pointer_array= 0; select_n_where_fields= 0; select_n_having_items= 0; + n_child_sum_items= 0; subquery_in_having= explicit_limit= 0; is_item_list_lookup= 0; first_execution= 1; -- cgit v1.2.1 From 2943c8131a180de40d94a28bec89d3c1ba1f3687 Mon Sep 17 00:00:00 2001 From: Jon Olav Hauglid Date: Wed, 3 Oct 2012 15:00:43 +0200 Subject: Bug#14495351: CRASH IN HA_PARTITION::HANDLE_UNORDERED_NEXT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up patch - Fix broken build: error: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘key_part_map {aka long unsigned int}’ [-Werror=format] --- sql/ha_partition.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index e9ffc7abbac..2f39f201f80 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -4476,7 +4476,7 @@ int ha_partition::common_index_read(uchar *buf, bool have_start_key) m_start_key.length= key_len= calculate_key_len(table, active_index, m_start_key.key, m_start_key.keypart_map); - DBUG_PRINT("info", ("have_start_key map %u find_flag %u len %u", + DBUG_PRINT("info", ("have_start_key map %lu find_flag %u len %u", m_start_key.keypart_map, m_start_key.flag, key_len)); DBUG_ASSERT(key_len); } -- cgit v1.2.1 From 30d35590a3bce929679cdc38d36fc67f7923a39e Mon Sep 17 00:00:00 2001 From: Tor Didriksen Date: Wed, 3 Oct 2012 16:05:07 +0200 Subject: Bug#13713525 CREATE_INITIAL_DB.CMAKE IS FAILING ON WINDOWS, STILL "DEVENV" RETURNS 0 This bug depends on cmake version. For cmake 2.6 (which is still in use for some pushbuild trees) the main build would succeed, even if create_initial_db failed. The problem was the chaining of commands in the CUSTOM_COMMAND to produce 'initdb.dep'. It first invokes cmake to run mysqld, then invokes 'touch' to create the file. Moving the 'touch' command makes the error propagate properly for both cmake 2.6 and 2.8 --- sql/CMakeLists.txt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/CMakeLists.txt b/sql/CMakeLists.txt index a3df9e7948b..d79b732005b 100644 --- a/sql/CMakeLists.txt +++ b/sql/CMakeLists.txt @@ -291,15 +291,17 @@ IF(WIN32 AND MYSQLD_EXECUTABLE) COMMAND ${CMAKE_COMMAND} ${CONFIG_PARAM} -P ${CMAKE_CURRENT_BINARY_DIR}/create_initial_db.cmake WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/data - COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/initdb.dep DEPENDS mysqld ) ADD_CUSTOM_TARGET(initial_database ALL DEPENDS initdb.dep ) - INSTALL(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/data DESTINATION . - COMPONENT DataFiles PATTERN "initdb.dep" EXCLUDE PATTERN "bootstrap.sql" EXCLUDE) + INSTALL(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/data + DESTINATION . + COMPONENT DataFiles + PATTERN "initdb.dep" EXCLUDE + PATTERN "bootstrap.sql" EXCLUDE) ELSE() # Not windows or cross compiling, just install an empty directory INSTALL(FILES ${DUMMY_FILE} DESTINATION data/mysql COMPONENT DataFiles) -- cgit v1.2.1 From bfba296d4084eab4b580cddc04e889ad2abdaeb2 Mon Sep 17 00:00:00 2001 From: Jon Olav Hauglid Date: Thu, 4 Oct 2012 16:15:13 +0200 Subject: Bug#14640599 MEMORY LEAK WHEN EXECUTING STORED ROUTINE EXCEPTION HANDLER When a SP handler is activated, memory is allocated to hold the MESSAGE_TEXT for the condition that caused the activation. The problem was that this memory was allocated on the MEM_ROOT belonging to the stored program. Since this MEM_ROOT is not freed until the stored program ends, a stored program that causes lots of handler activations can start using lots of memory. In 5.1 and earlier the problem did not exist as no MESSAGE_TEXT was allocated if a condition was raised with a handler present. However, this behavior lead to a number of other issues such as Bug#23032. This patch fixes the problem by allocating enough memory for the necessary MESSAGE_TEXTs in the SP MEM_ROOT when the SP starts and then re-using this memory each time a handler is activated. This is the 5.5 version of the patch. --- sql/sp_rcontext.cc | 11 +++-------- sql/sp_rcontext.h | 45 ++++++++++++++++++++++++++++++++++++++++++--- sql/sql_signal.cc | 12 +++++++++--- 3 files changed, 54 insertions(+), 14 deletions(-) (limited to 'sql') diff --git a/sql/sp_rcontext.cc b/sql/sp_rcontext.cc index fba6a56b37c..09f48d824b0 100644 --- a/sql/sp_rcontext.cc +++ b/sql/sp_rcontext.cc @@ -67,19 +67,15 @@ sp_rcontext::~sp_rcontext() bool sp_rcontext::init(THD *thd) { uint handler_count= m_root_parsing_ctx->max_handler_index(); - uint i; in_sub_stmt= thd->in_sub_stmt; if (init_var_table(thd) || init_var_items()) return TRUE; - if (!(m_raised_conditions= new (thd->mem_root) MYSQL_ERROR[handler_count])) + if (!(m_raised_conditions= new (thd->mem_root) Sql_condition_info[handler_count])) return TRUE; - for (i= 0; imem_root); - return !(m_handler= (sp_handler_t*)thd->alloc(handler_count * sizeof(sp_handler_t))) || @@ -446,13 +442,12 @@ sp_rcontext::exit_handler() DBUG_VOID_RETURN; } -MYSQL_ERROR* -sp_rcontext::raised_condition() const +Sql_condition_info* sp_rcontext::raised_condition() const { if (m_ihsp > 0) { uint hindex= m_in_handler[m_ihsp - 1].index; - MYSQL_ERROR *raised= & m_raised_conditions[hindex]; + Sql_condition_info *raised= & m_raised_conditions[hindex]; return raised; } diff --git a/sql/sp_rcontext.h b/sql/sp_rcontext.h index 84d5a1227fe..c89ada3f3c8 100644 --- a/sql/sp_rcontext.h +++ b/sql/sp_rcontext.h @@ -58,6 +58,46 @@ typedef struct uint index; } sp_active_handler_t; + +class Sql_condition_info : public Sql_alloc +{ +public: + /** SQL error code. */ + uint m_sql_errno; + + /** Error level. */ + MYSQL_ERROR::enum_warning_level m_level; + + /** SQLSTATE. */ + char m_sql_state[SQLSTATE_LENGTH + 1]; + + /** Text message. */ + char m_message[MYSQL_ERRMSG_SIZE]; + + void set(uint sql_errno, const char* sqlstate, + MYSQL_ERROR::enum_warning_level level, + const char* msg) + { + m_sql_errno= sql_errno; + m_level= level; + + memcpy(m_sql_state, sqlstate, SQLSTATE_LENGTH); + m_sql_state[SQLSTATE_LENGTH]= '\0'; + + strncpy(m_message, msg, MYSQL_ERRMSG_SIZE); + } + + void clear() + { + m_sql_errno= 0; + m_level= MYSQL_ERROR::WARN_LEVEL_ERROR; + + m_sql_state[0]= '\0'; + m_message[0]= '\0'; + } +}; + + /* This class is a runtime context of a Stored Routine. It is used in an execution and is intended to contain all dynamic objects (i.e. objects, which @@ -146,8 +186,7 @@ class sp_rcontext : public Sql_alloc MYSQL_ERROR::enum_warning_level level, const char *msg); - MYSQL_ERROR * - raised_condition() const; + Sql_condition_info *raised_condition() const; void push_hstack(uint h); @@ -232,7 +271,7 @@ private: SQL conditions caught by each handler. This is an array indexed by handler index. */ - MYSQL_ERROR *m_raised_conditions; + Sql_condition_info *m_raised_conditions; uint m_hcount; // Stack pointer for m_handler uint *m_hstack; // Return stack for continue handlers diff --git a/sql/sql_signal.cc b/sql/sql_signal.cc index 9910dfc924e..e0c2a96ac84 100644 --- a/sql/sql_signal.cc +++ b/sql/sql_signal.cc @@ -478,7 +478,7 @@ bool Signal_statement::execute(THD *thd) bool Resignal_statement::execute(THD *thd) { - MYSQL_ERROR *signaled; + Sql_condition_info *signaled; int result= TRUE; DBUG_ENTER("Resignal_statement::execute"); @@ -491,15 +491,21 @@ bool Resignal_statement::execute(THD *thd) DBUG_RETURN(result); } + MYSQL_ERROR signaled_err(thd->mem_root); + signaled_err.set(signaled->m_sql_errno, + signaled->m_sql_state, + signaled->m_level, + signaled->m_message); + if (m_cond == NULL) { /* RESIGNAL without signal_value */ - result= raise_condition(thd, signaled); + result= raise_condition(thd, &signaled_err); DBUG_RETURN(result); } /* RESIGNAL with signal_value */ - result= raise_condition(thd, signaled); + result= raise_condition(thd, &signaled_err); DBUG_RETURN(result); } -- cgit v1.2.1 From 378a7d1ef5e60884d21f3e4059aad29d0e4dcefa Mon Sep 17 00:00:00 2001 From: Annamalai Gurusami Date: Mon, 8 Oct 2012 19:40:30 +0530 Subject: Bug #14036214 MYSQLD CRASHES WHEN EXECUTING UPDATE IN TRX WITH CONSISTENT SNAPSHOT OPTION A transaction is started with a consistent snapshot. After the transaction is started new indexes are added to the table. Now when we issue an update statement, the optimizer chooses an index. When the index scan is being initialized via ha_innobase::change_active_index(), InnoDB reports the error code HA_ERR_TABLE_DEF_CHANGED, with message stating that "insufficient history for index". This error message is propagated up to the SQL layer. But the my_error() api is never called. The statement level diagnostics area is not updated with the correct error status (it remains in Diagnostics_area::DA_EMPTY). Hence the following check in the Protocol::end_statement() fails. 516 case Diagnostics_area::DA_EMPTY: 517 default: 518 DBUG_ASSERT(0); 519 error= send_ok(thd->server_status, 0, 0, 0, NULL); 520 break; The fix is to backport the fix of bugs 14365043, 11761652 and 11746399. 14365043 PROTOCOL::END_STATEMENT(): ASSERTION `0' FAILED 11761652 HA_RND_INIT() RESULT CODE NOT CHECKED 11746399 RETURN VALUES OF HA_INDEX_INIT() AND INDEX_INIT() IGNORED rb://1227 approved by guilhem and mattiasj. --- sql/event_db_repository.cc | 10 +++++-- sql/filesort.cc | 8 +++++- sql/handler.cc | 47 ++++++++++++++++++++++++++------ sql/handler.h | 2 ++ sql/item_subselect.cc | 31 +++++++++++++++------ sql/log_event.cc | 12 ++++++-- sql/log_event_old.cc | 36 ++++++++++++++++++------ sql/opt_range.cc | 32 ++++++++++++++-------- sql/opt_sum.cc | 9 ++++-- sql/records.cc | 10 +++++-- sql/sp.cc | 17 ++++++++++-- sql/sql_acl.cc | 38 +++++++++++++++++++++----- sql/sql_handler.cc | 25 +++++++++-------- sql/sql_help.cc | 10 +++++-- sql/sql_select.cc | 68 +++++++++++++++++++++++++++++++++++++--------- sql/sql_show.cc | 12 ++++++-- sql/sql_update.cc | 14 +++++++--- sql/tztime.cc | 32 ++++++++++------------ 18 files changed, 304 insertions(+), 109 deletions(-) (limited to 'sql') diff --git a/sql/event_db_repository.cc b/sql/event_db_repository.cc index 59d168e01b5..74da4d8f587 100644 --- a/sql/event_db_repository.cc +++ b/sql/event_db_repository.cc @@ -406,7 +406,6 @@ Event_db_repository::index_read_for_db_for_i_s(THD *thd, TABLE *schema_table, TABLE *event_table, const char *db) { - int ret=0; CHARSET_INFO *scs= system_charset_info; KEY *key_info; uint key_len; @@ -416,7 +415,14 @@ Event_db_repository::index_read_for_db_for_i_s(THD *thd, TABLE *schema_table, DBUG_ENTER("Event_db_repository::index_read_for_db_for_i_s"); DBUG_PRINT("info", ("Using prefix scanning on PK")); - event_table->file->ha_index_init(0, 1); + + int ret= event_table->file->ha_index_init(0, 1); + if (ret) + { + event_table->file->print_error(ret, MYF(0)); + DBUG_RETURN(true); + } + key_info= event_table->key_info; if (key_info->key_parts == 0 || diff --git a/sql/filesort.cc b/sql/filesort.cc index a11be501991..b64f5221606 100644 --- a/sql/filesort.cc +++ b/sql/filesort.cc @@ -567,7 +567,13 @@ static ha_rows find_all_keys(SORTPARAM *param, SQL_SELECT *select, if (!quick_select) { next_pos=(uchar*) 0; /* Find records in sequence */ - file->ha_rnd_init(1); + DBUG_EXECUTE_IF("bug14365043_1", + DBUG_SET("+d,ha_rnd_init_fail");); + if ((error= file->ha_rnd_init(1))) + { + file->print_error(error, MYF(0)); + DBUG_RETURN(HA_POS_ERROR); + } file->extra_opt(HA_EXTRA_CACHE, current_thd->variables.read_buff_size); } diff --git a/sql/handler.cc b/sql/handler.cc index 27309a4b1d7..f4eb89912e9 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -2291,16 +2291,25 @@ int handler::read_first_row(uchar * buf, uint primary_key) if (stats.deleted < 10 || primary_key >= MAX_KEY || !(index_flags(primary_key, 0, 0) & HA_READ_ORDER)) { - (void) ha_rnd_init(1); - while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) ; - (void) ha_rnd_end(); + if (!(error= ha_rnd_init(1))) + { + while ((error= rnd_next(buf)) == HA_ERR_RECORD_DELETED) + /* skip deleted row */; + const int end_error= ha_rnd_end(); + if (!error) + error= end_error; + } } else { /* Find the first row through the primary key */ - (void) ha_index_init(primary_key, 0); - error=index_first(buf); - (void) ha_index_end(); + if (!(error= ha_index_init(primary_key, 0))) + { + error= index_first(buf); + const int end_error= ha_index_end(); + if (!error) + error= end_error; + } } DBUG_RETURN(error); } @@ -2695,7 +2704,15 @@ void handler::get_auto_increment(ulonglong offset, ulonglong increment, table->mark_columns_used_by_index_no_reset(table->s->next_number_index, table->read_set); column_bitmaps_signal(); - index_init(table->s->next_number_index, 1); + + if (ha_index_init(table->s->next_number_index, 1)) + { + /* This should never happen, assert in debug, and fail in release build */ + DBUG_ASSERT(0); + *first_value= ULONGLONG_MAX; + return; + } + if (table->s->next_number_keypart == 0) { // Autoincrement at key-start error=index_last(table->record[1]); @@ -2725,13 +2742,25 @@ void handler::get_auto_increment(ulonglong offset, ulonglong increment, } if (error) - nr=1; + { + if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND) + { + /* No entry found, start with 1. */ + nr= 1; + } + else + { + DBUG_ASSERT(0); + nr= ULONGLONG_MAX; + } + } else nr= ((ulonglong) table->next_number_field-> val_int_offset(table->s->rec_buff_length)+1); - index_end(); + ha_index_end(); (void) extra(HA_EXTRA_NO_KEYREAD); *first_value= nr; + return; } diff --git a/sql/handler.h b/sql/handler.h index 0b970a1349d..5eb2d6b440a 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -1351,6 +1351,7 @@ public: int ha_open(TABLE *table, const char *name, int mode, int test_if_locked); int ha_index_init(uint idx, bool sorted) { + DBUG_EXECUTE_IF("ha_index_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); int result; DBUG_ENTER("ha_index_init"); DBUG_ASSERT(inited==NONE); @@ -1367,6 +1368,7 @@ public: } int ha_rnd_init(bool scan) { + DBUG_EXECUTE_IF("ha_rnd_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); int result; DBUG_ENTER("ha_rnd_init"); DBUG_ASSERT(inited==NONE || (inited==RND && scan)); diff --git a/sql/item_subselect.cc b/sql/item_subselect.cc index bc81e5b01c1..d3b06f5983a 100644 --- a/sql/item_subselect.cc +++ b/sql/item_subselect.cc @@ -2058,10 +2058,14 @@ int subselect_uniquesubquery_engine::scan_table() TABLE *table= tab->table; DBUG_ENTER("subselect_uniquesubquery_engine::scan_table"); - if (table->file->inited) - table->file->ha_index_end(); - - table->file->ha_rnd_init(1); + if ((table->file->inited && + (error= table->file->ha_index_end())) || + (error= table->file->ha_rnd_init(1))) + { + (void) report_error(table, error); + DBUG_RETURN(true); + } + table->file->extra_opt(HA_EXTRA_CACHE, current_thd->variables.read_buff_size); table->null_row= 0; @@ -2238,9 +2242,14 @@ int subselect_uniquesubquery_engine::exec() if (null_keypart) DBUG_RETURN(scan_table()); - - if (!table->file->inited) - table->file->ha_index_init(tab->ref.key, 0); + + if (!table->file->inited && + (error= table->file->ha_index_init(tab->ref.key, 0))) + { + (void) report_error(table, error); + DBUG_RETURN(true); + } + error= table->file->index_read_map(table->record[0], tab->ref.key_buff, make_prev_keypart_map(tab->ref.key_parts), @@ -2360,8 +2369,12 @@ int subselect_indexsubquery_engine::exec() if (null_keypart) DBUG_RETURN(scan_table()); - if (!table->file->inited) - table->file->ha_index_init(tab->ref.key, 1); + if (!table->file->inited && + (error= table->file->ha_index_init(tab->ref.key, 1))) + { + (void) report_error(table, error); + DBUG_RETURN(true); + } error= table->file->index_read_map(table->record[0], tab->ref.key_buff, make_prev_keypart_map(tab->ref.key_parts), diff --git a/sql/log_event.cc b/sql/log_event.cc index c4a6ebb9a71..a31e5f71c37 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -9777,19 +9777,25 @@ int Rows_log_event::find_row(const Relay_log_info *rli) case HA_ERR_END_OF_FILE: if (++restart_count < 2) - table->file->ha_rnd_init(1); + { + if ((error= table->file->ha_rnd_init(1))) + { + table->file->print_error(error, MYF(0)); + goto err; + } + } break; default: DBUG_PRINT("info", ("Failed to get next record" " (rnd_next returns %d)",error)); table->file->print_error(error, MYF(0)); - table->file->ha_rnd_end(); + (void) table->file->ha_rnd_end(); goto err; } } while (restart_count < 2 && record_compare(table)); - + /* Note: above record_compare will take into accout all record fields which might be incorrect in case a partial row was given in the event diff --git a/sql/log_event_old.cc b/sql/log_event_old.cc index d68c474d00a..55d8d72ec5d 100644 --- a/sql/log_event_old.cc +++ b/sql/log_event_old.cc @@ -725,7 +725,10 @@ static int find_and_fetch_row(TABLE *table, uchar *key) int error; /* We have a key: search the table using the index */ if (!table->file->inited && (error= table->file->ha_index_init(0, FALSE))) + { + table->file->print_error(error, MYF(0)); DBUG_RETURN(error); + } /* Don't print debug messages when running valgrind since they can @@ -823,7 +826,10 @@ static int find_and_fetch_row(TABLE *table, uchar *key) /* We don't have a key: search the table using rnd_next() */ if ((error= table->file->ha_rnd_init(1))) - return error; + { + table->file->print_error(error, MYF(0)); + DBUG_RETURN(error); + } /* Continue until we find the right record or have made a full loop */ do @@ -846,15 +852,21 @@ static int find_and_fetch_row(TABLE *table, uchar *key) goto restart_rnd_next; case HA_ERR_END_OF_FILE: - if (++restart_count < 2) - table->file->ha_rnd_init(1); - break; + if (++restart_count < 2) + { + if ((error= table->file->ha_rnd_init(1))) + { + table->file->print_error(error, MYF(0)); + DBUG_RETURN(error); + } + } + break; default: - table->file->print_error(error, MYF(0)); + table->file->print_error(error, MYF(0)); DBUG_PRINT("info", ("Record not found")); - table->file->ha_rnd_end(); - DBUG_RETURN(error); + (void) table->file->ha_rnd_end(); + DBUG_RETURN(error); } } while (restart_count < 2 && record_compare(table)); @@ -2417,7 +2429,7 @@ int Old_rows_log_event::find_row(const Relay_log_info *rli) continue; DBUG_PRINT("info",("no record matching the given row found")); table->file->print_error(error, MYF(0)); - table->file->ha_index_end(); + (void) table->file->ha_index_end(); DBUG_RETURN(error); } } @@ -2458,7 +2470,13 @@ int Old_rows_log_event::find_row(const Relay_log_info *rli) case HA_ERR_END_OF_FILE: if (++restart_count < 2) - table->file->ha_rnd_init(1); + { + if ((error= table->file->ha_rnd_init(1))) + { + table->file->print_error(error, MYF(0)); + DBUG_RETURN(error); + } + } break; default: diff --git a/sql/opt_range.cc b/sql/opt_range.cc index ce48a8da958..ffd66253eaa 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -1183,7 +1183,7 @@ int QUICK_RANGE_SELECT::init() { DBUG_ENTER("QUICK_RANGE_SELECT::init"); - if (file->inited != handler::NONE) + if (file->inited) file->ha_index_or_rnd_end(); DBUG_RETURN(FALSE); } @@ -1191,7 +1191,7 @@ int QUICK_RANGE_SELECT::init() void QUICK_RANGE_SELECT::range_end() { - if (file->inited != handler::NONE) + if (file->inited) file->ha_index_or_rnd_end(); } @@ -1450,8 +1450,9 @@ int QUICK_ROR_INTERSECT_SELECT::init_ror_merged_scan(bool reuse_handler) There is no use of this->file. Use it for the first of merged range selects. */ - if (quick->init_ror_merged_scan(TRUE)) - DBUG_RETURN(1); + int error= quick->init_ror_merged_scan(TRUE); + if (error) + DBUG_RETURN(error); quick->file->extra(HA_EXTRA_KEYREAD_PRESERVE_FIELDS); } while ((quick= quick_it++)) @@ -1522,7 +1523,7 @@ QUICK_ROR_INTERSECT_SELECT::~QUICK_ROR_INTERSECT_SELECT() quick_selects.delete_elements(); delete cpk_quick; free_root(&alloc,MYF(0)); - if (need_to_fetch_row && head->file->inited != handler::NONE) + if (need_to_fetch_row && head->file->inited) head->file->ha_rnd_end(); DBUG_VOID_RETURN; } @@ -1626,8 +1627,8 @@ int QUICK_ROR_UNION_SELECT::reset() List_iterator_fast it(quick_selects); while ((quick= it++)) { - if (quick->reset()) - DBUG_RETURN(1); + if ((error= quick->reset())) + DBUG_RETURN(error); if ((error= quick->get_next())) { if (error == HA_ERR_END_OF_FILE) @@ -1638,10 +1639,10 @@ int QUICK_ROR_UNION_SELECT::reset() queue_insert(&queue, (uchar*)quick); } - if (head->file->ha_rnd_init(1)) + if ((error= head->file->ha_rnd_init(1))) { DBUG_PRINT("error", ("ROR index_merge rnd_init call failed")); - DBUG_RETURN(1); + DBUG_RETURN(error); } DBUG_RETURN(0); @@ -1659,7 +1660,7 @@ QUICK_ROR_UNION_SELECT::~QUICK_ROR_UNION_SELECT() DBUG_ENTER("QUICK_ROR_UNION_SELECT::~QUICK_ROR_UNION_SELECT"); delete_queue(&queue); quick_selects.delete_elements(); - if (head->file->inited != handler::NONE) + if (head->file->inited) head->file->ha_rnd_end(); free_root(&alloc,MYF(0)); DBUG_VOID_RETURN; @@ -8316,7 +8317,7 @@ int QUICK_INDEX_MERGE_SELECT::read_keys_and_merge() if (!cur_quick) break; - if (cur_quick->file->inited != handler::NONE) + if (cur_quick->file->inited) cur_quick->file->ha_index_end(); if (cur_quick->init() || cur_quick->reset()) DBUG_RETURN(1); @@ -8568,8 +8569,14 @@ int QUICK_RANGE_SELECT::reset() { if (in_ror_merged_scan) head->column_bitmaps_set_no_signal(&column_bitmap, &column_bitmap); + + DBUG_EXECUTE_IF("bug14365043_2", + DBUG_SET("+d,ha_index_init_fail");); if ((error= file->ha_index_init(index,1))) + { + file->print_error(error, MYF(0)); DBUG_RETURN(error); + } } /* Do not allocate the buffers twice. */ @@ -10783,7 +10790,10 @@ int QUICK_GROUP_MIN_MAX_SELECT::reset(void) head->set_keyread(TRUE); /* We need only the key attributes */ if ((result= file->ha_index_init(index,1))) + { + head->file->print_error(result, MYF(0)); DBUG_RETURN(result); + } if (quick_prefix_select && quick_prefix_select->reset()) DBUG_RETURN(1); result= file->index_last(record); diff --git a/sql/opt_sum.cc b/sql/opt_sum.cc index e187cf19917..aaf279395dc 100644 --- a/sql/opt_sum.cc +++ b/sql/opt_sum.cc @@ -380,9 +380,14 @@ int opt_sum_query(THD *thd, const_result= 0; break; } - table->file->ha_index_init((uint) ref.key, 1); + if ((error= table->file->ha_index_init((uint) ref.key, 1))) + { + table->file->print_error(error, MYF(0)); + table->set_keyread(FALSE); + DBUG_RETURN(error); + } - error= is_max ? + error= is_max ? get_index_max_value(table, &ref, range_fl) : get_index_min_value(table, &ref, item_field, range_fl, prefix_len); diff --git a/sql/records.cc b/sql/records.cc index 55859e05f29..7f74b84b2d7 100644 --- a/sql/records.cc +++ b/sql/records.cc @@ -67,6 +67,7 @@ static int rr_index_desc(READ_RECORD *info); void init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table, bool print_error, uint idx, bool reverse) { + int error; empty_record(table); bzero((char*) info,sizeof(*info)); info->thd= thd; @@ -77,8 +78,13 @@ void init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table, info->unlock_row= rr_unlock_row; table->status=0; /* And it's always found */ - if (!table->file->inited) - table->file->ha_index_init(idx, 1); + if (!table->file->inited && + (error= table->file->ha_index_init(idx, 1))) + { + if (print_error) + table->file->print_error(error, MYF(0)); + } + /* read_record will be changed to rr_index in rr_index_first */ info->read_record= reverse ? rr_index_last : rr_index_first; } diff --git a/sql/sp.cc b/sql/sp.cc index b257e23c8c7..6300329398d 100644 --- a/sql/sp.cc +++ b/sql/sp.cc @@ -1442,7 +1442,6 @@ bool lock_db_routines(THD *thd, char *db) { TABLE *table; uint key_len; - int nxtres= 0; Open_tables_backup open_tables_state_backup; MDL_request_list mdl_requests; Lock_db_routines_error_handler err_handler; @@ -1468,7 +1467,13 @@ bool lock_db_routines(THD *thd, char *db) table->field[MYSQL_PROC_FIELD_DB]->store(db, strlen(db), system_charset_info); key_len= table->key_info->key_part[0].store_length; - table->file->ha_index_init(0, 1); + int nxtres= table->file->ha_index_init(0, 1); + if (nxtres) + { + table->file->print_error(nxtres, MYF(0)); + close_system_tables(thd, &open_tables_state_backup); + DBUG_RETURN(true); + } if (! table->file->index_read_map(table->record[0], table->field[MYSQL_PROC_FIELD_DB]->ptr, @@ -1532,7 +1537,12 @@ sp_drop_db_routines(THD *thd, char *db) key_len= table->key_info->key_part[0].store_length; ret= SP_OK; - table->file->ha_index_init(0, 1); + if (table->file->ha_index_init(0, 1)) + { + ret= SP_KEY_NOT_FOUND; + goto err_idx_init; + } + if (! table->file->index_read_map(table->record[0], (uchar *)table->field[MYSQL_PROC_FIELD_DB]->ptr, (key_part_map)1, HA_READ_KEY_EXACT)) @@ -1560,6 +1570,7 @@ sp_drop_db_routines(THD *thd, char *db) } table->file->ha_index_end(); +err_idx_init: close_thread_tables(thd); /* Make sure to only release the MDL lock on mysql.proc, not other diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 201335f16b5..5c4a144247f 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -2659,7 +2659,13 @@ replace_proxies_priv_table(THD *thd, TABLE *table, const LEX_USER *user, get_grantor(thd, grantor); - table->file->ha_index_init(0, 1); + if ((error= table->file->ha_index_init(0, 1))) + { + table->file->print_error(error, MYF(0)); + DBUG_PRINT("info", ("ha_index_init error")); + DBUG_RETURN(-1); + } + if (table->file->index_read_map(table->record[0], user_key, HA_WHOLE_KEY, HA_READ_KEY_EXACT)) @@ -2901,7 +2907,12 @@ GRANT_TABLE::GRANT_TABLE(TABLE *form, TABLE *col_privs) key_copy(key, col_privs->record[0], col_privs->key_info, key_prefix_len); col_privs->field[4]->store("",0, &my_charset_latin1); - col_privs->file->ha_index_init(0, 1); + if (col_privs->file->ha_index_init(0, 1)) + { + cols= 0; + return; + } + if (col_privs->file->index_read_map(col_privs->record[0], (uchar*) key, (key_part_map)15, HA_READ_KEY_EXACT)) { @@ -3032,7 +3043,7 @@ static int replace_column_table(GRANT_TABLE *g_t, const char *db, const char *table_name, ulong rights, bool revoke_grant) { - int error=0,result=0; + int result=0; uchar key[MAX_KEY_LENGTH]; uint key_prefix_length; KEY_PART_INFO *key_part= table->key_info->key_part; @@ -3059,7 +3070,13 @@ static int replace_column_table(GRANT_TABLE *g_t, List_iterator iter(columns); class LEX_COLUMN *column; - table->file->ha_index_init(0, 1); + int error= table->file->ha_index_init(0, 1); + if (error) + { + table->file->print_error(error, MYF(0)); + DBUG_RETURN(-1); + } + while ((column= iter++)) { ulong privileges= column->rights; @@ -4180,7 +4197,10 @@ static my_bool grant_load_procs_priv(TABLE *p_table) (void) my_hash_init(&func_priv_hash, &my_charset_utf8_bin, 0,0,0, (my_hash_get_key) get_grant_table, 0,0); - p_table->file->ha_index_init(0, 1); + + if (p_table->file->ha_index_init(0, 1)) + DBUG_RETURN(TRUE); + p_table->use_all_columns(); if (!p_table->file->index_first(p_table->record[0])) @@ -4281,7 +4301,10 @@ static my_bool grant_load(THD *thd, TABLE_LIST *tables) t_table = tables[0].table; c_table = tables[1].table; - t_table->file->ha_index_init(0, 1); + + if (t_table->file->ha_index_init(0, 1)) + goto end_index_init; + t_table->use_all_columns(); c_table->use_all_columns(); @@ -4326,9 +4349,10 @@ static my_bool grant_load(THD *thd, TABLE_LIST *tables) return_val=0; // Return ok end_unlock: - thd->variables.sql_mode= old_sql_mode; t_table->file->ha_index_end(); my_pthread_setspecific_ptr(THR_MALLOC, save_mem_root_ptr); +end_index_init: + thd->variables.sql_mode= old_sql_mode; DBUG_RETURN(return_val); } diff --git a/sql/sql_handler.cc b/sql/sql_handler.cc index 4435dfab9ea..e7973850194 100644 --- a/sql/sql_handler.cc +++ b/sql/sql_handler.cc @@ -665,14 +665,14 @@ retry: case RFIRST: if (keyname) { - table->file->ha_index_or_rnd_end(); - table->file->ha_index_init(keyno, 1); - error= table->file->index_first(table->record[0]); + if (!(error= table->file->ha_index_or_rnd_end()) && + !(error= table->file->ha_index_init(keyno, 1))) + error= table->file->index_first(table->record[0]); } else { - table->file->ha_index_or_rnd_end(); - if (!(error= table->file->ha_rnd_init(1))) + if (!(error= table->file->ha_index_or_rnd_end()) && + !(error= table->file->ha_rnd_init(1))) error= table->file->rnd_next(table->record[0]); } mode=RNEXT; @@ -689,9 +689,9 @@ retry: /* else fall through */ case RLAST: DBUG_ASSERT(keyname != 0); - table->file->ha_index_or_rnd_end(); - table->file->ha_index_init(keyno, 1); - error= table->file->index_last(table->record[0]); + if (!(error= table->file->ha_index_or_rnd_end()) && + !(error= table->file->ha_index_init(keyno, 1))) + error= table->file->index_last(table->record[0]); mode=RPREV; break; case RNEXT_SAME: @@ -734,11 +734,12 @@ retry: if (!(key= (uchar*) thd->calloc(ALIGN_SIZE(key_len)))) goto err; - table->file->ha_index_or_rnd_end(); - table->file->ha_index_init(keyno, 1); + if ((error= table->file->ha_index_or_rnd_end())) + break; key_copy(key, table->record[0], table->key_info + keyno, key_len); - error= table->file->index_read_map(table->record[0], - key, keypart_map, ha_rkey_mode); + if (!(error= table->file->ha_index_init(keyno, 1))) + error= table->file->index_read_map(table->record[0], + key, keypart_map, ha_rkey_mode); mode=rkey_to_rnext[(int)ha_rkey_mode]; break; } diff --git a/sql/sql_help.cc b/sql/sql_help.cc index 99203ef98ba..0dca1f6a75a 100644 --- a/sql/sql_help.cc +++ b/sql/sql_help.cc @@ -297,8 +297,14 @@ int get_topics_for_keyword(THD *thd, TABLE *topics, TABLE *relations, rtopic_id= find_fields[help_relation_help_topic_id].field; rkey_id= find_fields[help_relation_help_keyword_id].field; - topics->file->ha_index_init(iindex_topic,1); - relations->file->ha_index_init(iindex_relations,1); + if (topics->file->ha_index_init(iindex_topic,1) || + relations->file->ha_index_init(iindex_relations,1)) + { + if (topics->file->inited) + topics->file->ha_index_end(); + my_message(ER_CORRUPT_HELP_DB, ER(ER_CORRUPT_HELP_DB), MYF(0)); + DBUG_RETURN(-1); + } rkey_id->store((longlong) key_id, TRUE); rkey_id->get_key_image(buff, rkey_id->pack_length(), Field::itRAW); diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 3bde5aa8f6a..5c216a44d70 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -11466,7 +11466,14 @@ do_select(JOIN *join,List *fields,TABLE *table,Procedure *procedure) empty_record(table); if (table->group && join->tmp_table_param.sum_func_count && table->s->keys && !table->file->inited) - table->file->ha_index_init(0, 0); + { + rc= table->file->ha_index_init(0, 0); + if (rc) + { + table->file->print_error(rc, MYF(0)); + DBUG_RETURN(rc); + } + } } /* Set up select_end */ Next_select_func end_select= setup_end_select_func(join); @@ -12286,8 +12293,13 @@ join_read_key(JOIN_TAB *tab) if (!table->file->inited) { - table->file->ha_index_init(tab->ref.key, tab->sorted); + if ((error= table->file->ha_index_init(tab->ref.key, tab->sorted))) + { + (void) report_error(table, error); + return 1; + } } + if (cmp_buffer_with_ref(tab) || (table->status & (STATUS_GARBAGE | STATUS_NO_PARENT | STATUS_NULL_ROW))) { @@ -12371,8 +12383,12 @@ join_read_always_key(JOIN_TAB *tab) TABLE *table= tab->table; /* Initialize the index first */ - if (!table->file->inited) - table->file->ha_index_init(tab->ref.key, tab->sorted); + if (!table->file->inited && + (error= table->file->ha_index_init(tab->ref.key, tab->sorted))) + { + (void) report_error(table, error); + return 1; + } /* Perform "Late NULLs Filtering" (see internals manual for explanations) */ for (uint i= 0 ; i < tab->ref.key_parts ; i++) @@ -12407,8 +12423,13 @@ join_read_last_key(JOIN_TAB *tab) int error; TABLE *table= tab->table; - if (!table->file->inited) - table->file->ha_index_init(tab->ref.key, tab->sorted); + if (!table->file->inited && + (error= table->file->ha_index_init(tab->ref.key, tab->sorted))) + { + (void) report_error(table, error); + return 1; + } + if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref)) return -1; if ((error=table->file->index_read_last_map(table->record[0], @@ -12520,8 +12541,14 @@ join_read_first(JOIN_TAB *tab) tab->read_record.file=table->file; tab->read_record.index=tab->index; tab->read_record.record=table->record[0]; - if (!table->file->inited) - table->file->ha_index_init(tab->index, tab->sorted); + + if (!table->file->inited && + (error= table->file->ha_index_init(tab->index, tab->sorted))) + { + (void) report_error(table, error); + return 1; + } + if ((error=tab->table->file->index_first(tab->table->record[0]))) { if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) @@ -12555,8 +12582,13 @@ join_read_last(JOIN_TAB *tab) tab->read_record.file=table->file; tab->read_record.index=tab->index; tab->read_record.record=table->record[0]; - if (!table->file->inited) - table->file->ha_index_init(tab->index, 1); + if (!table->file->inited && + (error= table->file->ha_index_init(tab->index, 1))) + { + (void) report_error(table, error); + return 1; + } + if ((error= tab->table->file->index_last(tab->table->record[0]))) return report_error(table, error); return 0; @@ -12579,8 +12611,13 @@ join_ft_read_first(JOIN_TAB *tab) int error; TABLE *table= tab->table; - if (!table->file->inited) - table->file->ha_index_init(tab->ref.key, 1); + if (!table->file->inited && + (error= table->file->ha_index_init(tab->ref.key, 1))) + { + (void) report_error(table, error); + return 1; + } + table->file->ft_init(); if ((error= table->file->ft_read(table->record[0]))) @@ -12973,7 +13010,12 @@ end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), error, 0)) DBUG_RETURN(NESTED_LOOP_ERROR); // Not a table_is_full error /* Change method to update rows */ - table->file->ha_index_init(0, 0); + if ((error= table->file->ha_index_init(0, 0))) + { + table->file->print_error(error, MYF(0)); + DBUG_RETURN(NESTED_LOOP_ERROR); + } + join->join_tab[join->tables-1].next_select=end_unique_update; } join->send_records++; diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 81e18ccd6c3..b921b2c782e 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -4925,7 +4925,13 @@ int fill_schema_proc(THD *thd, TABLE_LIST *tables, COND *cond) { DBUG_RETURN(1); } - proc_table->file->ha_index_init(0, 1); + + if (proc_table->file->ha_index_init(0, 1)) + { + res= 1; + goto err; + } + if ((res= proc_table->file->index_first(proc_table->record[0]))) { res= (res == HA_ERR_END_OF_FILE) ? 0 : 1; @@ -4951,7 +4957,9 @@ int fill_schema_proc(THD *thd, TABLE_LIST *tables, COND *cond) } err: - proc_table->file->ha_index_end(); + if (proc_table->file->inited) + (void) proc_table->file->ha_index_end(); + close_system_tables(thd, &open_tables_state_backup); DBUG_RETURN(res); } diff --git a/sql/sql_update.cc b/sql/sql_update.cc index c4a95edcfc2..222b3d9470a 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -2038,7 +2038,8 @@ int multi_update::do_updates() org_updated= updated; tmp_table= tmp_tables[cur_table->shared]; tmp_table->file->extra(HA_EXTRA_CACHE); // Change to read cache - (void) table->file->ha_rnd_init(0); + if (local_error= table->file->ha_rnd_init(0)) + goto err; table->file->extra(HA_EXTRA_NO_CACHE); check_opt_it.rewind(); @@ -2163,11 +2164,16 @@ err: } err2: - (void) table->file->ha_rnd_end(); - (void) tmp_table->file->ha_rnd_end(); + if (table->file->inited) + (void) table->file->ha_rnd_end(); + if (tmp_table->file->inited) + (void) tmp_table->file->ha_rnd_end(); check_opt_it.rewind(); while (TABLE *tbl= check_opt_it++) - tbl->file->ha_rnd_end(); + { + if (tbl->file->inited) + (void) tbl->file->ha_rnd_end(); + } if (updated != org_updated) { diff --git a/sql/tztime.cc b/sql/tztime.cc index f245b736f52..72898ccc706 100644 --- a/sql/tztime.cc +++ b/sql/tztime.cc @@ -1706,14 +1706,11 @@ my_tz_init(THD *org_thd, const char *default_tzname, my_bool bootstrap) } table= tz_tables[0].table; - /* - It is OK to ignore ha_index_init()/ha_index_end() return values since - mysql.time_zone* tables are MyISAM and these operations always succeed - for MyISAM. - */ - (void)table->file->ha_index_init(0, 1); - table->use_all_columns(); + if (table->file->ha_index_init(0, 1)) + goto end_with_close; + + table->use_all_columns(); tz_leapcnt= 0; res= table->file->index_first(table->record[0]); @@ -1899,12 +1896,8 @@ tz_load_from_open_tables(const String *tz_name, TABLE_LIST *tz_tables) tz_tables= tz_tables->next_local; table->field[0]->store(tz_name->ptr(), tz_name->length(), &my_charset_latin1); - /* - It is OK to ignore ha_index_init()/ha_index_end() return values since - mysql.time_zone* tables are MyISAM and these operations always succeed - for MyISAM. - */ - (void)table->file->ha_index_init(0, 1); + if (table->file->ha_index_init(0, 1)) + goto end; if (table->file->index_read_map(table->record[0], table->field[0]->ptr, HA_WHOLE_KEY, HA_READ_KEY_EXACT)) @@ -1932,7 +1925,8 @@ tz_load_from_open_tables(const String *tz_name, TABLE_LIST *tz_tables) table= tz_tables->table; tz_tables= tz_tables->next_local; table->field[0]->store((longlong) tzid, TRUE); - (void)table->file->ha_index_init(0, 1); + if (table->file->ha_index_init(0, 1)) + goto end; if (table->file->index_read_map(table->record[0], table->field[0]->ptr, HA_WHOLE_KEY, HA_READ_KEY_EXACT)) @@ -1959,7 +1953,8 @@ tz_load_from_open_tables(const String *tz_name, TABLE_LIST *tz_tables) table= tz_tables->table; tz_tables= tz_tables->next_local; table->field[0]->store((longlong) tzid, TRUE); - (void)table->file->ha_index_init(0, 1); + if (table->file->ha_index_init(0, 1)) + goto end; res= table->file->index_read_map(table->record[0], table->field[0]->ptr, (key_part_map)1, HA_READ_KEY_EXACT); @@ -2030,7 +2025,8 @@ tz_load_from_open_tables(const String *tz_name, TABLE_LIST *tz_tables) */ table= tz_tables->table; table->field[0]->store((longlong) tzid, TRUE); - (void)table->file->ha_index_init(0, 1); + if (table->file->ha_index_init(0, 1)) + goto end; res= table->file->index_read_map(table->record[0], table->field[0]->ptr, (key_part_map)1, HA_READ_KEY_EXACT); @@ -2165,8 +2161,8 @@ tz_load_from_open_tables(const String *tz_name, TABLE_LIST *tz_tables) end: - if (table) - (void)table->file->ha_index_end(); + if (table && table->file->inited) + (void) table->file->ha_index_end(); DBUG_RETURN(return_val); } -- cgit v1.2.1 From d5d53d190293af440f6a7d116df63c21fa391bd1 Mon Sep 17 00:00:00 2001 From: Annamalai Gurusami Date: Tue, 9 Oct 2012 12:25:02 +0530 Subject: Fixing a compilation issue. --- sql/sql_update.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_update.cc b/sql/sql_update.cc index 222b3d9470a..e7600fe248e 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -2038,7 +2038,7 @@ int multi_update::do_updates() org_updated= updated; tmp_table= tmp_tables[cur_table->shared]; tmp_table->file->extra(HA_EXTRA_CACHE); // Change to read cache - if (local_error= table->file->ha_rnd_init(0)) + if ((local_error= table->file->ha_rnd_init(0))) goto err; table->file->extra(HA_EXTRA_NO_CACHE); -- cgit v1.2.1 From 5427d33e6248caa4e6a2b92c9ab9317fadcb5c2f Mon Sep 17 00:00:00 2001 From: Harin Vadodaria Date: Tue, 9 Oct 2012 18:15:40 +0530 Subject: Bug #14211140: CRASH WHEN GRANTING OR REVOKING PROXY PRIVILEGES Description: (user,host) pair from security context is used privilege checking at the time of granting or revoking proxy privileges. This creates problem when server is started with --skip-name-resolve option because host will not contain any value. Checks should be dependent on consistent values regardless the way server is started. Further, privilege check should use (priv_user,priv_host) pair rather than values obtained from inbound connection because this pair represents the correct account context obtained from mysql.user table. --- sql/sql_acl.cc | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 5c4a144247f..d99ca3ceb99 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -7256,14 +7256,25 @@ acl_check_proxy_grant_access(THD *thd, const char *host, const char *user, DBUG_RETURN(FALSE); } - /* one can grant proxy to himself to others */ - if (!strcmp(thd->security_ctx->user, user) && + /* + one can grant proxy for self to others. + Security context in THD contains two pairs of (user,host): + 1. (user,host) pair referring to inbound connection. + 2. (priv_user,priv_host) pair obtained from mysql.user table after doing + authnetication of incoming connection. + Privileges should be checked wrt (priv_user, priv_host) tuple, because + (user,host) pair obtained from inbound connection may have different + values than what is actually stored in mysql.user table and while granting + or revoking proxy privilege, user is expected to provide entries mentioned + in mysql.user table. + */ + if (!strcmp(thd->security_ctx->priv_user, user) && !my_strcasecmp(system_charset_info, host, - thd->security_ctx->host)) + thd->security_ctx->priv_host)) { DBUG_PRINT("info", ("strcmp (%s, %s) my_casestrcmp (%s, %s) equal", - thd->security_ctx->user, user, - host, thd->security_ctx->host)); + thd->security_ctx->priv_user, user, + host, thd->security_ctx->priv_host)); DBUG_RETURN(FALSE); } -- cgit v1.2.1 From f1d3b0f19011217c13927f44a82e8e17291fbba7 Mon Sep 17 00:00:00 2001 From: Nuno Carvalho Date: Fri, 12 Oct 2012 08:32:10 +0100 Subject: BUG#14629727: USER_VAR_EVENT IS MISSING RANGE CHECKS This bug had two problems: P1) Reads out of bounds; P2) Writes out of bounds. PROBLEM P1 ---------- User_var_log_event unmarshalling from binlog was not performing range checks when using name_len and val_len variables to walk on event buffer. Added range checks to User_var_log_event unmarshalling to prevent unmarshalling errors. PROBLEM P2 ---------- User_var_log_event value was allocated on thread stack, what caused stack frame errors when User_var_log_event value was bigger than thread stack size. Currently value is allocated on heap memory. --- sql/log_event.cc | 45 ++++++++++++++++++++++++++++++++++++++++----- sql/log_event.h | 4 ++-- sql/mysql_priv.h | 44 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/log_event.cc b/sql/log_event.cc index c3ba969cf1f..0ad258f7073 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -1286,7 +1286,7 @@ Log_event* Log_event::read_log_event(const char* buf, uint event_len, ev = new Rand_log_event(buf, description_event); break; case USER_VAR_EVENT: - ev = new User_var_log_event(buf, description_event); + ev = new User_var_log_event(buf, event_len, description_event); break; case FORMAT_DESCRIPTION_EVENT: ev = new Format_description_log_event(buf, event_len, description_event); @@ -5685,18 +5685,34 @@ void User_var_log_event::pack_info(Protocol* protocol) User_var_log_event:: -User_var_log_event(const char* buf, +User_var_log_event(const char* buf, uint event_len, const Format_description_log_event* description_event) :Log_event(buf, description_event) #ifndef MYSQL_CLIENT , deferred(false) #endif { + bool error= false; + const char* buf_start= buf; /* The Post-Header is empty. The Variable Data part begins immediately. */ buf+= description_event->common_header_len + description_event->post_header_len[USER_VAR_EVENT-1]; name_len= uint4korr(buf); name= (char *) buf + UV_NAME_LEN_SIZE; + + /* + We don't know yet is_null value, so we must assume that name_len + may have the bigger value possible, is_null= True and there is no + payload for val. + */ + if (0 == name_len || + !valid_buffer_range(name_len, buf_start, name, + event_len - UV_VAL_IS_NULL)) + { + error= true; + goto err; + } + buf+= UV_NAME_LEN_SIZE + name_len; is_null= (bool) *buf; if (is_null) @@ -5708,13 +5724,31 @@ User_var_log_event(const char* buf, } else { + if (!valid_buffer_range(UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE + + UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE, + buf_start, buf, event_len)) + { + error= true; + goto err; + } + type= (Item_result) buf[UV_VAL_IS_NULL]; charset_number= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE); val_len= uint4korr(buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE + UV_CHARSET_NUMBER_SIZE); val= (char *) (buf + UV_VAL_IS_NULL + UV_VAL_TYPE_SIZE + UV_CHARSET_NUMBER_SIZE + UV_VAL_LEN_SIZE); + + if (!valid_buffer_range(val_len, buf_start, val, event_len)) + { + error= true; + goto err; + } } + +err: + if (error) + name= 0; } @@ -5860,8 +5894,9 @@ void User_var_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info) char *hex_str; CHARSET_INFO *cs; - if (!(hex_str= (char *)my_alloca(2*val_len+1+2))) // 2 hex digits / byte - break; // no error, as we are 'void' + hex_str= (char *)my_malloc(2*val_len+1+2,MYF(MY_WME)); // 2 hex digits / byte + if (!hex_str) + return; str_to_hex(hex_str, val, val_len); /* For proper behaviour when mysqlbinlog|mysql, we need to explicitely @@ -5879,7 +5914,7 @@ void User_var_log_event::print(FILE* file, PRINT_EVENT_INFO* print_event_info) my_b_printf(&cache, ":=_%s %s COLLATE `%s`%s\n", cs->csname, hex_str, cs->name, print_event_info->delimiter); - my_afree(hex_str); + my_free(hex_str, MYF(MY_WME)); } break; case ROW_RESULT: diff --git a/sql/log_event.h b/sql/log_event.h index ba6b9b876aa..c36564fcde8 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -2496,7 +2496,7 @@ public: void print(FILE* file, PRINT_EVENT_INFO* print_event_info); #endif - User_var_log_event(const char* buf, + User_var_log_event(const char* buf, uint event_len, const Format_description_log_event *description_event); ~User_var_log_event() {} Log_event_type get_type_code() { return USER_VAR_EVENT;} @@ -2510,7 +2510,7 @@ public: bool is_deferred() { return deferred; } void set_deferred() { deferred= true; } #endif - bool is_valid() const { return 1; } + bool is_valid() const { return name != 0; } private: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h index 937617032dd..05a37228e17 100644 --- a/sql/mysql_priv.h +++ b/sql/mysql_priv.h @@ -501,6 +501,50 @@ protected: */ #define MAX_TIME_ZONE_NAME_LENGTH (NAME_LEN + 1) +/* + Check how many bytes are available on buffer. + + @param buf_start Pointer to buffer start. + @param buf_current Pointer to the current position on buffer. + @param buf_len Buffer length. + + @return Number of bytes available on event buffer. +*/ +template T available_buffer(const char* buf_start, + const char* buf_current, + T buf_len) +{ + return buf_len - (buf_current - buf_start); +} +/* Explicit instantion to unsigned int. */ +template unsigned int available_buffer(const char*, + const char*, + unsigned int); + +/* + Check if jump value is within buffer limits. + + @param jump Number of positions we want to advance. + @param buf_start Pointer to buffer start + @param buf_current Pointer to the current position on buffer. + @param buf_len Buffer length. + + @return True If jump value is within buffer limits. + False Otherwise. +*/ +template bool valid_buffer_range(T jump, + const char* buf_start, + const char* buf_current, + T buf_len) +{ + return (jump <= available_buffer(buf_start, buf_current, buf_len)); +} +/* Explicit instantion to unsigned int. */ +template bool valid_buffer_range(unsigned int, + const char*, + const char*, + unsigned int); + /* The rest of the file is included in the server only */ #ifndef MYSQL_CLIENT -- cgit v1.2.1 From fc1fbe159afa043d647711c83778d6911e5dfe39 Mon Sep 17 00:00:00 2001 From: Marc Alff Date: Fri, 12 Oct 2012 19:38:45 +0200 Subject: Bug#14629232 SECURITY VULNERABILITY WITH SHOW PROFILE This fix resolves a security vulnerability of SHOW PROFILE. See the bug report for details. --- sql/sql_profile.cc | 29 +++++++++++++++++++---------- sql/sql_profile.h | 6 ++++-- 2 files changed, 23 insertions(+), 12 deletions(-) (limited to 'sql') diff --git a/sql/sql_profile.cc b/sql/sql_profile.cc index 49666dde476..f3a95e6479b 100644 --- a/sql/sql_profile.cc +++ b/sql/sql_profile.cc @@ -39,6 +39,7 @@ #define TIME_I_S_DECIMAL_SIZE (TIME_FLOAT_DIGITS*100)+(TIME_FLOAT_DIGITS-3) #define MAX_QUERY_LENGTH 300 +#define MAX_QUERY_HISTORY 101 /* Reserved for systems that can't record the function name in source. */ const char * const _unknown_func_ = ""; @@ -233,9 +234,12 @@ void PROF_MEASUREMENT::collect() QUERY_PROFILE::QUERY_PROFILE(PROFILING *profiling_arg, const char *status_arg) :profiling(profiling_arg), profiling_query_id(0), query_source(NULL) { - profile_start= new PROF_MEASUREMENT(this, status_arg); - entries.push_back(profile_start); - profile_end= profile_start; + m_seq_counter= 1; + PROF_MEASUREMENT *prof= new PROF_MEASUREMENT(this, status_arg); + prof->m_seq= m_seq_counter++; + m_start_time_usecs= prof->time_usecs; + m_end_time_usecs= m_start_time_usecs; + entries.push_back(prof); } QUERY_PROFILE::~QUERY_PROFILE() @@ -275,9 +279,14 @@ void QUERY_PROFILE::new_status(const char *status_arg, else prof= new PROF_MEASUREMENT(this, status_arg); - profile_end= prof; + prof->m_seq= m_seq_counter++; + m_end_time_usecs= prof->time_usecs; entries.push_back(prof); + /* Maintain the query history size. */ + while (entries.elements > MAX_QUERY_HISTORY) + delete entries.pop(); + DBUG_VOID_RETURN; } @@ -437,8 +446,7 @@ bool PROFILING::show_profiles() String elapsed; - PROF_MEASUREMENT *ps= prof->profile_start; - PROF_MEASUREMENT *pe= prof->profile_end; + double query_time_usecs= prof->m_end_time_usecs - prof->m_start_time_usecs; if (++idx <= unit->offset_limit_cnt) continue; @@ -447,7 +455,7 @@ bool PROFILING::show_profiles() protocol->prepare_for_resend(); protocol->store((uint32)(prof->profiling_query_id)); - protocol->store((double)(pe->time_usecs - ps->time_usecs)/(1000.0*1000), + protocol->store((double)(query_time_usecs/(1000.0*1000)), (uint32) TIME_FLOAT_DIGITS-1, &elapsed); if (prof->query_source != NULL) protocol->store(prof->query_source, strlen(prof->query_source), @@ -507,17 +515,18 @@ int PROFILING::fill_statistics_info(THD *thd_arg, TABLE_LIST *tables, Item *cond us also include a numbering of each state per query. The query_id and the "seq" together are unique. */ - ulonglong seq; + ulong seq; void *entry_iterator; PROF_MEASUREMENT *entry, *previous= NULL; /* ...and for each query, go through all its state-change steps. */ - for (seq= 0, entry_iterator= query->entries.new_iterator(); + for (entry_iterator= query->entries.new_iterator(); entry_iterator != NULL; entry_iterator= query->entries.iterator_next(entry_iterator), - seq++, previous=entry, row_number++) + previous=entry, row_number++) { entry= query->entries.iterator_value(entry_iterator); + seq= entry->m_seq; /* Skip the first. We count spans of fence, not fence-posts. */ if (previous == NULL) continue; diff --git a/sql/sql_profile.h b/sql/sql_profile.h index b21216f290f..c59b342e502 100644 --- a/sql/sql_profile.h +++ b/sql/sql_profile.h @@ -182,6 +182,7 @@ private: char *file; unsigned int line; + ulong m_seq; double time_usecs; char *allocated_status_memory; @@ -213,8 +214,9 @@ private: query_id_t profiling_query_id; /* Session-specific id. */ char *query_source; - PROF_MEASUREMENT *profile_start; - PROF_MEASUREMENT *profile_end; + double m_start_time_usecs; + double m_end_time_usecs; + ulong m_seq_counter; Queue entries; -- cgit v1.2.1 From bdb4104cf6b658b0b614f2b5b3c690535fde3726 Mon Sep 17 00:00:00 2001 From: Neeraj Bisht Date: Tue, 16 Oct 2012 23:18:48 +0530 Subject: Bug#11745891 - LAST_INSERT(ID) DOES NOT SUPPORT BIGINT UNSIGNED Problem:- using last_insert_id() on an auto_incremented bigint unsigned does not work for values which are greater than max-bigint-signed. Analysis:- last_insert_id() returns the first auto_incremented value for a column and an auto_incremented value can have only positive values. In our code, when we are initializing a last_insert_id object, we are taking it as a signed BIGINT, So when the auto_incremented value reaches greater than max signed bigint, last_insert_id gives negative result. Solution: When we are fetching the value from last_insert_id, We are setting the unsigned_flag, so that it take only unsigned BIGINT value. sql/item_func.cc: here unsigned value is converted to signed value. sql/item_func.h: last_insert_id() gives an auto_incremented value which can be positive only,so defined it as a unsigned longlong sets the unsigned_flag to 1. --- sql/item_func.cc | 3 ++- sql/item_func.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/item_func.cc b/sql/item_func.cc index feb87fe5fd7..21efaf83aa8 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -3596,7 +3596,8 @@ longlong Item_func_last_insert_id::val_int() thd->first_successful_insert_id_in_prev_stmt= value; return value; } - return thd->read_first_successful_insert_id_in_prev_stmt(); + return + static_cast(thd->read_first_successful_insert_id_in_prev_stmt()); } diff --git a/sql/item_func.h b/sql/item_func.h index de1338b4081..ec410ed3d3d 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -1043,6 +1043,7 @@ public: const char *func_name() const { return "last_insert_id"; } void fix_length_and_dec() { + unsigned_flag= TRUE; if (arg_count) max_length= args[0]->max_length; } -- cgit v1.2.1 From eef1a1957e75a4153e44be26e0e32dee5f6069ad Mon Sep 17 00:00:00 2001 From: Neeraj Bisht Date: Thu, 18 Oct 2012 23:45:15 +0530 Subject: Bug#13726751 - 8 BYTE MEMORY LEAK IN DO_SAVE_BLOB Problem:- When we execute a query which has subquery with GROUP BY, ORDER BY and have a BLOB column,results a memory leak. Analysis:- In case of subquery, which have GROUP BY on BLOB and a ORDER BY on other field and BLOB is not a key. We allocate a tmp buffer to copy_field to take care of BLOB value.This copy_field value can have copies of its in two join(objects), so while freeing this copy_field we have to take care that it is not deleted twice. The double deletion of tmp_table_param.copy_field is handled by two patches. One by Kostja : revid:sp1r-konstantin@mysql.com-20050627101056-55153 Fix the broken test suite in -debug build. and other by Oleksandr revid:sp1r-bell@sanja.is.com.ua-20060118114857-19905 Excluded posibility of tmp_table_param.copy_field double deletion (BUG#14851). both of this patches are commited in different branch and while merging they both get placed,but there is no need for Kostja patch as Oleksandr patch handle this. sql/sql_select.cc: Bug13726751, tmp_join clean up is not necessary as later in the code we are taking care of cleaning up of tmp_join copy_field. --- sql/sql_select.cc | 7 ------- 1 file changed, 7 deletions(-) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index bcf601e5142..de9f0ead7a3 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -7084,15 +7084,8 @@ void JOIN::cleanup(bool full) } } } - /* - We are not using tables anymore - Unlock all tables. We may be in an INSERT .... SELECT statement. - */ if (full) { - if (tmp_join) - tmp_table_param.copy_field= 0; - /* Ensure that the following delete_elements() would not be called twice for the same list. -- cgit v1.2.1 From 6ff71d0dd38e39e67580f598b400fa3fb8888da3 Mon Sep 17 00:00:00 2001 From: Annamalai Gurusami Date: Fri, 19 Oct 2012 16:43:48 +0530 Subject: Bug #14226171 EXCESSIVE ROW LOCKING WITH UPDATE IN 5.5.25 When a DML statement is issued, and if the index merge access method is chosen, then many rows from the storage engine will be locked because of the way the algorithm works. Many rows will be locked, but they will not be part of the final result set. To reduce the excessive locking, the locks of unmatched rows are released by this patch. This patch will affect only transactions with isolation level equal to or less stricter than READ COMMITTED. This is because of the behaviour of ha_innobase::unlock_row(). rb://1296 approved by jorgen and olav. --- sql/opt_range.cc | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'sql') diff --git a/sql/opt_range.cc b/sql/opt_range.cc index ffd66253eaa..ce87bdd5381 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -8412,6 +8412,13 @@ int QUICK_INDEX_MERGE_SELECT::get_next() If a Clustered PK scan is present, it is used only to check if row satisfies its condition (and never used for row retrieval). + Locking: to ensure that exclusive locks are only set on records that + are included in the final result we must release the lock + on all rows we read but do not include in the final result. This + must be done on each index that reads the record and the lock + must be released using the same handler (the same quick object) as + used when reading the record. + RETURN 0 - Ok other - Error code if any error occurred. @@ -8421,6 +8428,12 @@ int QUICK_ROR_INTERSECT_SELECT::get_next() { List_iterator_fast quick_it(quick_selects); QUICK_RANGE_SELECT* quick; + + /* quick that reads the given rowid first. This is needed in order + to be able to unlock the row using the same handler object that locked + it */ + QUICK_RANGE_SELECT* quick_with_last_rowid; + int error, cmp; uint last_rowid_count=0; DBUG_ENTER("QUICK_ROR_INTERSECT_SELECT::get_next"); @@ -8433,7 +8446,10 @@ int QUICK_ROR_INTERSECT_SELECT::get_next() if (cpk_quick) { while (!error && !cpk_quick->row_in_ranges()) + { + quick->file->unlock_row(); /* row not in range; unlock */ error= quick->get_next(); + } } if (error) DBUG_RETURN(error); @@ -8441,6 +8457,7 @@ int QUICK_ROR_INTERSECT_SELECT::get_next() quick->file->position(quick->record); memcpy(last_rowid, quick->file->ref, head->file->ref_length); last_rowid_count= 1; + quick_with_last_rowid= quick; while (last_rowid_count < quick_selects.elements) { @@ -8453,9 +8470,17 @@ int QUICK_ROR_INTERSECT_SELECT::get_next() do { if ((error= quick->get_next())) + { + quick_with_last_rowid->file->unlock_row(); DBUG_RETURN(error); + } quick->file->position(quick->record); cmp= head->file->cmp_ref(quick->file->ref, last_rowid); + if (cmp < 0) + { + /* This row is being skipped. Release lock on it. */ + quick->file->unlock_row(); + } } while (cmp < 0); /* Ok, current select 'caught up' and returned ref >= cur_ref */ @@ -8466,13 +8491,19 @@ int QUICK_ROR_INTERSECT_SELECT::get_next() { while (!cpk_quick->row_in_ranges()) { + quick->file->unlock_row(); /* row not in range; unlock */ if ((error= quick->get_next())) + { + quick_with_last_rowid->file->unlock_row(); DBUG_RETURN(error); + } } quick->file->position(quick->record); } memcpy(last_rowid, quick->file->ref, head->file->ref_length); + quick_with_last_rowid->file->unlock_row(); last_rowid_count= 1; + quick_with_last_rowid= quick; } else { -- cgit v1.2.1 From 62503f9cf5af989107e887925816add9b4aec950 Mon Sep 17 00:00:00 2001 From: Nuno Carvalho Date: Sun, 21 Oct 2012 20:28:19 +0100 Subject: BUG#14629727: USER_VAR_EVENT IS MISSING RANGE CHECKS Moved explicit instantiation of available_buffer and valid_buffer_range template functions to sql/log_event.cc. --- sql/log_event.cc | 16 ++++++++++++++++ sql/mysql_priv.h | 9 --------- 2 files changed, 16 insertions(+), 9 deletions(-) (limited to 'sql') diff --git a/sql/log_event.cc b/sql/log_event.cc index 0ad258f7073..58de0d310d7 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -54,6 +54,22 @@ */ #define FMT_G_BUFSIZE(PREC) (3 + (PREC) + 5 + 1) +/* + Explicit instantiation to unsigned int of template available_buffer + function. +*/ +template unsigned int available_buffer(const char*, + const char*, + unsigned int); + +/* + Explicit instantiation to unsigned int of template valid_buffer_range + function. +*/ +template bool valid_buffer_range(unsigned int, + const char*, + const char*, + unsigned int); #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) static int rows_event_stmt_cleanup(Relay_log_info const *rli, THD* thd); diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h index 05a37228e17..4741562cab3 100644 --- a/sql/mysql_priv.h +++ b/sql/mysql_priv.h @@ -516,10 +516,6 @@ template T available_buffer(const char* buf_start, { return buf_len - (buf_current - buf_start); } -/* Explicit instantion to unsigned int. */ -template unsigned int available_buffer(const char*, - const char*, - unsigned int); /* Check if jump value is within buffer limits. @@ -539,11 +535,6 @@ template bool valid_buffer_range(T jump, { return (jump <= available_buffer(buf_start, buf_current, buf_len)); } -/* Explicit instantion to unsigned int. */ -template bool valid_buffer_range(unsigned int, - const char*, - const char*, - unsigned int); /* The rest of the file is included in the server only */ #ifndef MYSQL_CLIENT -- cgit v1.2.1 From 154860eab5499cf44160f253694a87b8147a2965 Mon Sep 17 00:00:00 2001 From: Ashish Agarwal Date: Wed, 31 Oct 2012 12:40:48 +0530 Subject: BUG#14485479: INSTALL AUDIT PLUGIN HANGS IF WE TRY TO DISABLE AND ENABLED DURING DDL OPERATION PROBLEM: Same thread trying to acquire the same mutex second time leads to hang/server crash. While [un]installing audit_log plugin a thread acquires the LOCK_plugin mutex and after successful initialization tries to write in mysql.plugin table. It holds this mutex for a long time. If some how plugin table is corrupted then a write to plugin table will throw an error, thread try to log this error in the audit_log plugin, doing so it tries to acquire the mutex again and results is server hang/crash. SOLUTION: Releasing the LOCK_plugin mutex before writing in mysql.plugin table. We dont need to hold this mutex as thread already acquired a TL_WRITE lock on mysql.plugin table. --- sql/sql_plugin.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index 4c42f3798dd..13623078265 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -1820,6 +1820,7 @@ bool mysql_install_plugin(THD *thd, const LEX_STRING *name, const LEX_STRING *dl { if (plugin_initialize(tmp)) { + mysql_mutex_unlock(&LOCK_plugin); my_error(ER_CANT_INITIALIZE_UDF, MYF(0), name->str, "Plugin initialization function failed."); goto deinit; @@ -1831,6 +1832,7 @@ bool mysql_install_plugin(THD *thd, const LEX_STRING *name, const LEX_STRING *dl of the insert into the plugin table, so that it is not replicated in row based mode. */ + mysql_mutex_unlock(&LOCK_plugin); tmp_disable_binlog(thd); table->use_all_columns(); restore_record(table, s->default_values); @@ -1843,10 +1845,9 @@ bool mysql_install_plugin(THD *thd, const LEX_STRING *name, const LEX_STRING *dl table->file->print_error(error, MYF(0)); goto deinit; } - - mysql_mutex_unlock(&LOCK_plugin); DBUG_RETURN(FALSE); deinit: + mysql_mutex_lock(&LOCK_plugin); tmp->state= PLUGIN_IS_DELETED; reap_needed= true; reap_plugins(); -- cgit v1.2.1 From db1db8fa8cbcf95fdc2c77a744be7b2f9f31b170 Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Wed, 21 Nov 2012 21:55:04 -0800 Subject: Fixed LP bug #1002146 (bug mdev-645). If the setting of system variables does not allow to use join buffer for a join query with GROUP BY / ORDER BY then filesort is not needed if the first joined table is scanned in the order compatible with order specified by the list . --- sql/sql_select.cc | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 1e57f11e399..a3d3f84806c 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -7422,8 +7422,9 @@ get_best_combination(JOIN *join) if ( !(keyuse= join->best_positions[tablenr].key)) { j->type=JT_ALL; - if (tablenr != join->const_tables) - join->full_join=1; + if (join->best_positions[tablenr].use_join_buffer && + tablenr != join->const_tables) + join->full_join= 1; } /*if (join->best_positions[tablenr].sj_strategy == SJ_OPT_LOOSE_SCAN) @@ -8436,7 +8437,9 @@ make_join_select(JOIN *join,SQL_SELECT *select,COND *cond) We will use join cache here : prevent sorting of the first table only and sort at the end. */ - if (i != join->const_tables && join->table_count > join->const_tables + 1) + if (i != join->const_tables && + join->table_count > join->const_tables + 1 && + join->best_positions[i].use_join_buffer) join->full_join= 1; } -- cgit v1.2.1 From 2cbf2e643bc9b6e048905ba4d49da875f45018e7 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 29 Nov 2012 19:34:47 +0100 Subject: applying patch for BUG15912213 --- sql/sql_acl.cc | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index e07f668b1cf..80662832140 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -1356,10 +1356,19 @@ ulong acl_get(const char *host, const char *ip, { ulong host_access= ~(ulong)0, db_access= 0; uint i; - size_t key_length; + size_t key_length, copy_length; char key[ACL_KEY_LENGTH],*tmp_db,*end; acl_entry *entry; DBUG_ENTER("acl_get"); + + copy_length= (size_t) (strlen(ip ? ip : "") + + strlen(user ? user : "") + + strlen(db ? db : "")); + /* + Make sure that strmov() operations do not result in buffer overflow. + */ + if (copy_length >= ACL_KEY_LENGTH) + DBUG_RETURN(0); VOID(pthread_mutex_lock(&acl_cache->lock)); end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db); @@ -4340,6 +4349,16 @@ bool check_grant_db(THD *thd,const char *db) char helping [NAME_LEN+USERNAME_LENGTH+2]; uint len; bool error= TRUE; + size_t copy_length; + + copy_length= (size_t) (strlen(sctx->priv_user ? sctx->priv_user : "") + + strlen(db ? db : "")); + + /* + Make sure that strmov() operations do not result in buffer overflow. + */ + if (copy_length >= (NAME_LEN+USERNAME_LENGTH+2)) + return 1; len= (uint) (strmov(strmov(helping, sctx->priv_user) + 1, db) - helping) + 1; -- cgit v1.2.1 From eff07bf08e29afab76c7688ec063ef6881ee464f Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 4 Dec 2012 17:08:02 +0100 Subject: proactive s/strmov/strnmov/ in sql_acl.cc and related test cases --- sql/sql_acl.cc | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 020aa042722..4f4c0eeb06b 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -341,7 +341,12 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) convert db to lower case and give a warning if the db wasn't already in lower case */ - (void) strmov(tmp_name, host.db); + char *end = strnmov(tmp_name, host.db, sizeof(tmp_name)); + if (end >= tmp_name + sizeof(tmp_name)) + { + sql_print_warning(ER(ER_WRONG_DB_NAME), host.db); + continue; + } my_casedn_str(files_charset_info, host.db); if (strcmp(host.db, tmp_name) != 0) sql_print_warning("'host' entry '%s|%s' had database in mixed " @@ -595,7 +600,12 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) convert db to lower case and give a warning if the db wasn't already in lower case */ - (void)strmov(tmp_name, db.db); + char *end = strnmov(tmp_name, db.db, sizeof(tmp_name)); + if (end >= tmp_name + sizeof(tmp_name)) + { + sql_print_warning(ER(ER_WRONG_DB_NAME), db.db); + continue; + } my_casedn_str(files_charset_info, db.db); if (strcmp(db.db, tmp_name) != 0) { @@ -2474,15 +2484,23 @@ static GRANT_NAME *name_hash_search(HASH *name_hash, const char *user, const char *tname, bool exact, bool name_tolower) { - char helping [SAFE_NAME_LEN*2+USERNAME_LENGTH+3], *name_ptr; + char helping[SAFE_NAME_LEN*2+USERNAME_LENGTH+3]; + char *hend = helping + sizeof(helping); uint len; GRANT_NAME *grant_name,*found=0; HASH_SEARCH_STATE state; - name_ptr= strmov(strmov(helping, user) + 1, db) + 1; - len = (uint) (strmov(name_ptr, tname) - helping) + 1; + char *db_ptr= strmov(helping, user) + 1; + char *tname_ptr= strnmov(db_ptr, db, hend - db_ptr) + 1; + if (tname_ptr > hend) + return 0; // invalid name = not found + char *end= strnmov(tname_ptr, tname, hend - tname_ptr) + 1; + if (end > hend) + return 0; // invalid name = not found + + len = (uint) (end - helping); if (name_tolower) - my_casedn_str(files_charset_info, name_ptr); + my_casedn_str(files_charset_info, tname_ptr); for (grant_name= (GRANT_NAME*) hash_first(name_hash, (uchar*) helping, len, &state); grant_name ; @@ -3466,7 +3484,12 @@ bool mysql_grant(THD *thd, const char *db, List &list, if (lower_case_table_names && db) { - strmov(tmp_db,db); + char *end= strnmov(tmp_db,db, sizeof(tmp_db)); + if (end >= tmp_db + sizeof(tmp_db)) + { + my_error(ER_WRONG_DB_NAME ,MYF(0), db); + DBUG_RETURN(TRUE); + } my_casedn_str(files_charset_info, tmp_db); db=tmp_db; } -- cgit v1.2.1 From d538d394b86d4095e78c891e40876f4b9e031d7f Mon Sep 17 00:00:00 2001 From: Gleb Shchepa Date: Wed, 5 Dec 2012 17:24:45 +0400 Subject: Bug #15948123: SERVER WORKS INCORRECT WITH LONG TABLE ALIASES Code in MDL subsystem assumes that identifiers of objects can't be longer than NAME_LEN characters. This assumption was broken when one tried to construct MDL_key based on table alias, which can have arbitrary length. Since MDL_key's (and MDL locks) are not really used for table aliases this patch changes code to not initialize MDL_key object for table list element representing aliases. --- sql/mdl.h | 2 ++ sql/sql_parse.cc | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/mdl.h b/sql/mdl.h index d30d30ac2fa..6d29ad968c6 100644 --- a/sql/mdl.h +++ b/sql/mdl.h @@ -246,6 +246,8 @@ public: } void mdl_key_init(const MDL_key *rhs) { + DBUG_ASSERT(rhs->m_length <= NAME_LEN); + DBUG_ASSERT(rhs->m_db_name_length <= NAME_LEN); memcpy(m_ptr, rhs->m_ptr, rhs->m_length); m_length= rhs->m_length; m_db_name_length= rhs->m_db_name_length; diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index ea07bfce0cb..2e995f58c5c 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -6000,8 +6000,13 @@ TABLE_LIST *st_select_lex::add_table_to_list(THD *thd, ptr->next_name_resolution_table= NULL; /* Link table in global list (all used tables) */ lex->add_to_query_tables(ptr); - ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type, - MDL_TRANSACTION); + + // Pure table aliases do not need to be locked: + if (!test(table_options & TL_OPTION_ALIAS)) + { + ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type, + MDL_TRANSACTION); + } DBUG_RETURN(ptr); } -- cgit v1.2.1 From e5424d196b9c392b71fc1b2c8dcf67f610f6a746 Mon Sep 17 00:00:00 2001 From: Gleb Shchepa Date: Wed, 5 Dec 2012 20:47:21 +0400 Subject: Bug #15948123: SERVER WORKS INCORRECT WITH LONG TABLE ALIASES After-push cleanup: removal of unneeded assertions. --- sql/mdl.h | 2 -- 1 file changed, 2 deletions(-) (limited to 'sql') diff --git a/sql/mdl.h b/sql/mdl.h index 6d29ad968c6..d30d30ac2fa 100644 --- a/sql/mdl.h +++ b/sql/mdl.h @@ -246,8 +246,6 @@ public: } void mdl_key_init(const MDL_key *rhs) { - DBUG_ASSERT(rhs->m_length <= NAME_LEN); - DBUG_ASSERT(rhs->m_db_name_length <= NAME_LEN); memcpy(m_ptr, rhs->m_ptr, rhs->m_length); m_length= rhs->m_length; m_db_name_length= rhs->m_db_name_length; -- cgit v1.2.1 From 0aad592f49f0fb790f712aa6a644653cf9a0218f Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 5 Dec 2012 21:06:00 +0200 Subject: MDEV-3914 fix. Fixed algorithm of detecting of first real table in view/subquery-in-the-FROM-clase. --- sql/table.cc | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) (limited to 'sql') diff --git a/sql/table.cc b/sql/table.cc index d42fd14120c..abdd0b0f9e6 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -4457,19 +4457,33 @@ TABLE *TABLE_LIST::get_real_join_table() DBUG_ASSERT(tbl->derived == NULL || tbl->derived->first_select()->next_select() == NULL); - if (tbl->table) - table= tbl->table; - tbl= (tbl->view != NULL ? - tbl->view->select_lex.get_table_list() : - tbl->derived->first_select()->get_table_list()); - - /* find left table in outer join on this level */ - while(tbl->outer_join & JOIN_TYPE_RIGHT) { - DBUG_ASSERT(tbl->next_local); - tbl= tbl->next_local; + List_iterator_fast ti; + { + List_iterator_fast + ti(tbl->view != NULL ? + tbl->view->select_lex.top_join_list : + tbl->derived->first_select()->top_join_list); + for (;;) + { + tbl= NULL; + /* + Find left table in outer join on this level + (the list is reverted). + */ + for (TABLE_LIST *t= ti++; t; t= ti++) + tbl= t; + /* + It is impossible that the list is empty + so tbl can't be NULL after above loop. + */ + if (!tbl->nested_join) + break; + /* go deeper if we've found nested join */ + ti= tbl->nested_join->join_list; + } + } } - } return tbl->table; -- cgit v1.2.1 From d8876ff2fb2fac75a23678bd5b251780c66756a1 Mon Sep 17 00:00:00 2001 From: Harin Vadodaria Date: Thu, 6 Dec 2012 17:02:09 +0530 Subject: Bug#15912213: BUFFER OVERFLOW IN ACL_GET() Description: A very large database name causes buffer overflow in functions acl_get() and check_grant_db() in sql_acl.cc. It happens due to an unguarded string copy operation. This puts required sanity checks before copying db string to destination buffer. --- sql/sql_acl.cc | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index d99ca3ceb99..fdd9b107bf2 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -1581,11 +1581,20 @@ ulong acl_get(const char *host, const char *ip, { ulong host_access= ~(ulong)0, db_access= 0; uint i; - size_t key_length; + size_t key_length, copy_length; char key[ACL_KEY_LENGTH],*tmp_db,*end; acl_entry *entry; DBUG_ENTER("acl_get"); + copy_length= (size_t) (strlen(ip ? ip : "") + + strlen(user ? user : "") + + strlen(db ? db : "")); + /* + Make sure that strmov() operations do not result in buffer overflow. + */ + if (copy_length >= ACL_KEY_LENGTH) + DBUG_RETURN(0); + mysql_mutex_lock(&acl_cache->lock); end=strmov((tmp_db=strmov(strmov(key, ip ? ip : "")+1,user)+1),db); if (lower_case_table_names) @@ -4942,6 +4951,16 @@ bool check_grant_db(THD *thd,const char *db) char helping [NAME_LEN+USERNAME_LENGTH+2]; uint len; bool error= TRUE; + size_t copy_length; + + copy_length= (size_t) (strlen(sctx->priv_user ? sctx->priv_user : "") + + strlen(db ? db : "")); + + /* + Make sure that strmov() operations do not result in buffer overflow. + */ + if (copy_length >= (NAME_LEN+USERNAME_LENGTH+2)) + return 1; len= (uint) (strmov(strmov(helping, sctx->priv_user) + 1, db) - helping) + 1; -- cgit v1.2.1 From d07b5f1ca295d4eb6eeba0b88c93f04e9e21cb5c Mon Sep 17 00:00:00 2001 From: Joerg Bruehe Date: Fri, 7 Dec 2012 10:47:57 +0100 Subject: Last-minute fix to 5.1.67, taking a change done to main 5.1 by Dmitri Lenev. This is the original comment: > committer: Dmitry Lenev > branch nick: mysql-5.1-15954896 > timestamp: Wed 2012-12-05 19:26:56 +0400 > message: > Bug #15954896 "SP, MULTI-TABLE DELETE AND LONG ALIAS". Using too long table aliases in stored routines might have caused server crashes. Code in sp_head::merge_table_list() which is responsible for collecting information about tables used in stored routine was not aware of the fact that table alias might have arbitrary length. I.e. it assumed that table alias can't be longer than NAME_LEN bytes and allocated buffer for a key identifying table accordingly. This patch fixes the issue by ensuring that we use dynamically allocated buffer for table key when table alias is too long. By default stack based buffer is used in which NAME_LEN bytes are reserved for table alias. --- sql/sp_head.cc | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) (limited to 'sql') diff --git a/sql/sp_head.cc b/sql/sp_head.cc index 7eef9f5ab28..054fc5e223e 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -3839,8 +3839,6 @@ typedef struct st_sp_table Multi-set key: db_name\0table_name\0alias\0 - for normal tables db_name\0table_name\0 - for temporary tables - Note that in both cases we don't take last '\0' into account when - we count length of key. */ LEX_STRING qname; uint db_length, table_name_length; @@ -3897,19 +3895,26 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) for (; table ; table= table->next_global) if (!table->derived && !table->schema_table) { - char tname[(NAME_LEN + 1) * 3]; // db\0table\0alias\0 - uint tlen, alen; - - tlen= table->db_length; - memcpy(tname, table->db, tlen); - tname[tlen++]= '\0'; - memcpy(tname+tlen, table->table_name, table->table_name_length); - tlen+= table->table_name_length; - tname[tlen++]= '\0'; - alen= strlen(table->alias); - memcpy(tname+tlen, table->alias, alen); - tlen+= alen; - tname[tlen]= '\0'; + /* + Structure of key for the multi-set is "db\0table\0alias\0". + Since "alias" part can have arbitrary length we use String + object to construct the key. By default String will use + buffer allocated on stack with NAME_LEN bytes reserved for + alias, since in most cases it is going to be smaller than + NAME_LEN bytes. + */ + char tname_buff[(NAME_LEN + 1) * 3]; + String tname(tname_buff, sizeof(tname_buff), &my_charset_bin); + uint temp_table_key_length; + + tname.length(0); + tname.append(table->db, table->db_length); + tname.append('\0'); + tname.append(table->table_name, table->table_name_length); + tname.append('\0'); + temp_table_key_length= tname.length(); + tname.append(table->alias); + tname.append('\0'); /* Upgrade the lock type because this table list will be used @@ -3924,9 +3929,10 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) (and therefore should not be prelocked). Otherwise we will erroneously treat table with same name but with different alias as non-temporary. */ - if ((tab= (SP_TABLE *)hash_search(&m_sptabs, (uchar *)tname, tlen)) || - ((tab= (SP_TABLE *)hash_search(&m_sptabs, (uchar *)tname, - tlen - alen - 1)) && + if ((tab= (SP_TABLE *)hash_search(&m_sptabs, (uchar *)tname.ptr(), + tname.length())) || + ((tab= (SP_TABLE *)hash_search(&m_sptabs, (uchar *)tname.ptr(), + temp_table_key_length)) && tab->temp)) { if (tab->lock_type < table->lock_type) @@ -3945,11 +3951,11 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE) { tab->temp= TRUE; - tab->qname.length= tlen - alen - 1; + tab->qname.length= temp_table_key_length; } else - tab->qname.length= tlen; - tab->qname.str= (char*) thd->memdup(tname, tab->qname.length + 1); + tab->qname.length= tname.length(); + tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length); if (!tab->qname.str) return FALSE; tab->table_name_length= table->table_name_length; @@ -4018,7 +4024,7 @@ sp_head::add_used_tables_to_table_list(THD *thd, if (!(tab_buff= (char *)thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST)) * stab->lock_count)) || !(key_buff= (char*)thd->memdup(stab->qname.str, - stab->qname.length + 1))) + stab->qname.length))) DBUG_RETURN(FALSE); for (uint j= 0; j < stab->lock_count; j++) -- cgit v1.2.1 From 14ba37f76f87cc48cae62eb6bdf3cda294dff78d Mon Sep 17 00:00:00 2001 From: Dmitry Lenev Date: Mon, 10 Dec 2012 10:06:37 +0400 Subject: Bug #15954896 "SP, MULTI-TABLE DELETE AND LONG ALIAS". Using too long table aliases in stored routines might have caused server crashes. Code in sp_head::merge_table_list() which is responsible for collecting information about tables used in stored routine was not aware of the fact that table alias might have arbitrary length. I.e. it assumed that table alias can't be longer than NAME_LEN bytes and allocated buffer for a key identifying table accordingly. This patch fixes the issue by ensuring that we use dynamically allocated buffer for table key when table alias is too long. By default stack based buffer is used in which NAME_LEN bytes are reserved for table alias. --- sql/sp_head.cc | 50 ++++++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 22 deletions(-) (limited to 'sql') diff --git a/sql/sp_head.cc b/sql/sp_head.cc index 09795156102..f20c205886d 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -4022,8 +4022,6 @@ typedef struct st_sp_table Multi-set key: db_name\0table_name\0alias\0 - for normal tables db_name\0table_name\0 - for temporary tables - Note that in both cases we don't take last '\0' into account when - we count length of key. */ LEX_STRING qname; uint db_length, table_name_length; @@ -4080,19 +4078,26 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) for (; table ; table= table->next_global) if (!table->derived && !table->schema_table) { - char tname[(NAME_LEN + 1) * 3]; // db\0table\0alias\0 - uint tlen, alen; - - tlen= table->db_length; - memcpy(tname, table->db, tlen); - tname[tlen++]= '\0'; - memcpy(tname+tlen, table->table_name, table->table_name_length); - tlen+= table->table_name_length; - tname[tlen++]= '\0'; - alen= strlen(table->alias); - memcpy(tname+tlen, table->alias, alen); - tlen+= alen; - tname[tlen]= '\0'; + /* + Structure of key for the multi-set is "db\0table\0alias\0". + Since "alias" part can have arbitrary length we use String + object to construct the key. By default String will use + buffer allocated on stack with NAME_LEN bytes reserved for + alias, since in most cases it is going to be smaller than + NAME_LEN bytes. + */ + char tname_buff[(NAME_LEN + 1) * 3]; + String tname(tname_buff, sizeof(tname_buff), &my_charset_bin); + uint temp_table_key_length; + + tname.length(0); + tname.append(table->db, table->db_length); + tname.append('\0'); + tname.append(table->table_name, table->table_name_length); + tname.append('\0'); + temp_table_key_length= tname.length(); + tname.append(table->alias); + tname.append('\0'); /* Upgrade the lock type because this table list will be used @@ -4107,9 +4112,10 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) (and therefore should not be prelocked). Otherwise we will erroneously treat table with same name but with different alias as non-temporary. */ - if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname, tlen)) || - ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname, - tlen - alen - 1)) && + if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(), + tname.length())) || + ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(), + temp_table_key_length)) && tab->temp)) { if (tab->lock_type < table->lock_type) @@ -4128,11 +4134,11 @@ sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE) { tab->temp= TRUE; - tab->qname.length= tlen - alen - 1; + tab->qname.length= temp_table_key_length; } else - tab->qname.length= tlen; - tab->qname.str= (char*) thd->memdup(tname, tab->qname.length + 1); + tab->qname.length= tname.length(); + tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length); if (!tab->qname.str) return FALSE; tab->table_name_length= table->table_name_length; @@ -4201,7 +4207,7 @@ sp_head::add_used_tables_to_table_list(THD *thd, if (!(tab_buff= (char *)thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST)) * stab->lock_count)) || !(key_buff= (char*)thd->memdup(stab->qname.str, - stab->qname.length + 1))) + stab->qname.length))) DBUG_RETURN(FALSE); for (uint j= 0; j < stab->lock_count; j++) -- cgit v1.2.1 From e99aa91e90adfd54cc1f460dd8cdd19614f30abc Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Dec 2012 15:56:57 +0200 Subject: MDEV-3928: Assertion `example' failed in Item_cache::is_expensive_processor with a 2-level IN subquery Analysis: The following call stack shows that it is possible to set Item_cache::value_cached, and the relevant value without setting Item_cache::example. #0 Item_cache_temporal::store_packed at item.cc:8395 #1 get_datetime_value at item_cmpfunc.cc:915 #2 resolve_const_item at item.cc:7987 #3 propagate_cond_constants at sql_select.cc:12264 #4 propagate_cond_constants at sql_select.cc:12227 #5 optimize_cond at sql_select.cc:13026 #6 JOIN::optimize at sql_select.cc:1016 #7 st_select_lex::optimize_unflattened_subqueries at sql_lex.cc:3161 #8 JOIN::optimize_unflattened_subqueries at opt_subselect.cc:4880 #9 JOIN::optimize at sql_select.cc:1554 The fix is to set Item_cache_temporal::example even when the value is set directly by Item_cache_temporal::store_packed. This makes the Item_cache_temporal object consistent. --- sql/item.cc | 3 ++- sql/item.h | 4 ++-- sql/item_cmpfunc.cc | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) (limited to 'sql') diff --git a/sql/item.cc b/sql/item.cc index 98c27266415..16dbd011f22 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -8388,9 +8388,10 @@ int Item_cache_temporal::save_in_field(Field *field, bool no_conversions) } -void Item_cache_temporal::store_packed(longlong val_arg) +void Item_cache_temporal::store_packed(longlong val_arg, Item *example) { /* An explicit values is given, save it. */ + store(example); value_cached= true; value= val_arg; null_value= false; diff --git a/sql/item.h b/sql/item.h index 6324e900f24..0852287cc7f 100644 --- a/sql/item.h +++ b/sql/item.h @@ -3799,7 +3799,7 @@ public: bool cache_value(); bool get_date(MYSQL_TIME *ltime, uint fuzzydate); int save_in_field(Field *field, bool no_conversions); - void store_packed(longlong val_arg); + void store_packed(longlong val_arg, Item *example); /* Having a clone_item method tells optimizer that this object is a constant and need not be optimized further. @@ -3808,7 +3808,7 @@ public: Item *clone_item() { Item_cache_temporal *item= new Item_cache_temporal(cached_field_type); - item->store_packed(value); + item->store_packed(value, example); return item; } }; diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index fed246ef812..b3b20a55ed9 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -912,7 +912,7 @@ get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg, if (save_arena) thd->set_query_arena(save_arena); - cache->store_packed(value); + cache->store_packed(value, item); *cache_arg= cache; *item_arg= cache_arg; } -- cgit v1.2.1 From 40ae63dd65fb9e812f29d3520acb0ba6b64d3005 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 23 Dec 2012 20:57:54 +0200 Subject: backport to 5.5 dyncol changes and names support --- sql/item_cmpfunc.cc | 7 ++- sql/item_create.cc | 89 +++++++++++++++++++++++++++-- sql/item_func.h | 2 +- sql/item_strfunc.cc | 154 ++++++++++++++++++++++++++++++-------------------- sql/item_strfunc.h | 6 +- sql/lex.h | 3 - sql/sql_join_cache.cc | 4 +- sql/sql_yacc.yy | 27 --------- 8 files changed, 189 insertions(+), 103 deletions(-) (limited to 'sql') diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index 72d28bb2e7e..ad01f9f83fc 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -6048,6 +6048,7 @@ Item* Item_equal::get_first(JOIN_TAB *context, Item *field_item) return NULL; } + longlong Item_func_dyncol_check::val_int() { char buff[STRING_BUFFER_USUAL_SIZE]; @@ -6062,7 +6063,7 @@ longlong Item_func_dyncol_check::val_int() col.length= str->length(); /* We do not change the string, so could do this trick */ col.str= (char *)str->ptr(); - rc= dynamic_column_check(&col); + rc= mariadb_dyncol_check(&col); if (rc < 0 && rc != ER_DYNCOL_FORMAT) { dynamic_column_error_message(rc); @@ -6127,8 +6128,8 @@ longlong Item_func_dyncol_exists::val_int() /* We do not change the string, so could do this trick */ col.str= (char *)str->ptr(); rc= ((name == NULL) ? - dynamic_column_exists(&col, (uint) num) : - dynamic_column_exists_str(&col, name)); + mariadb_dyncol_exists(&col, (uint) num) : + mariadb_dyncol_exists_named(&col, name)); if (rc < 0) { dynamic_column_error_message(rc); diff --git a/sql/item_create.cc b/sql/item_create.cc index f886b3d598b..bc449b0aaf2 100644 --- a/sql/item_create.cc +++ b/sql/item_create.cc @@ -526,6 +526,54 @@ protected: virtual ~Create_func_coercibility() {} }; +class Create_func_dyncol_check : public Create_func_arg1 +{ +public: + virtual Item *create_1_arg(THD *thd, Item *arg1); + + static Create_func_dyncol_check s_singleton; + +protected: + Create_func_dyncol_check() {} + virtual ~Create_func_dyncol_check() {} +}; + +class Create_func_dyncol_exists : public Create_func_arg2 +{ +public: + virtual Item *create_2_arg(THD *thd, Item *arg1, Item *arg2); + + static Create_func_dyncol_exists s_singleton; + +protected: + Create_func_dyncol_exists() {} + virtual ~Create_func_dyncol_exists() {} +}; + +class Create_func_dyncol_list : public Create_func_arg1 +{ +public: + virtual Item *create_1_arg(THD *thd, Item *arg1); + + static Create_func_dyncol_list s_singleton; + +protected: + Create_func_dyncol_list() {} + virtual ~Create_func_dyncol_list() {} +}; + +class Create_func_dyncol_json : public Create_func_arg1 +{ +public: + virtual Item *create_1_arg(THD *thd, Item *arg1); + + static Create_func_dyncol_json s_singleton; + +protected: + Create_func_dyncol_json() {} + virtual ~Create_func_dyncol_json() {} +}; + class Create_func_compress : public Create_func_arg1 { @@ -3108,6 +3156,38 @@ Create_func_coercibility::create_1_arg(THD *thd, Item *arg1) } +Create_func_dyncol_check Create_func_dyncol_check::s_singleton; + +Item* +Create_func_dyncol_check::create_1_arg(THD *thd, Item *arg1) +{ + return new (thd->mem_root) Item_func_dyncol_check(arg1); +} + +Create_func_dyncol_exists Create_func_dyncol_exists::s_singleton; + +Item* +Create_func_dyncol_exists::create_2_arg(THD *thd, Item *arg1, Item *arg2) +{ + return new (thd->mem_root) Item_func_dyncol_exists(arg1, arg2); +} + +Create_func_dyncol_list Create_func_dyncol_list::s_singleton; + +Item* +Create_func_dyncol_list::create_1_arg(THD *thd, Item *arg1) +{ + return new (thd->mem_root) Item_func_dyncol_list(arg1); +} + +Create_func_dyncol_json Create_func_dyncol_json::s_singleton; + +Item* +Create_func_dyncol_json::create_1_arg(THD *thd, Item *arg1) +{ + return new (thd->mem_root) Item_func_dyncol_json(arg1); +} + Create_func_concat Create_func_concat::s_singleton; Item* @@ -5245,6 +5325,10 @@ static Native_func_registry func_array[] = { { C_STRING_WITH_LEN("CHARACTER_LENGTH") }, BUILDER(Create_func_char_length)}, { { C_STRING_WITH_LEN("CHAR_LENGTH") }, BUILDER(Create_func_char_length)}, { { C_STRING_WITH_LEN("COERCIBILITY") }, BUILDER(Create_func_coercibility)}, + { { C_STRING_WITH_LEN("COLUMN_CHECK") }, BUILDER(Create_func_dyncol_check)}, + { { C_STRING_WITH_LEN("COLUMN_EXISTS") }, BUILDER(Create_func_dyncol_exists)}, + { { C_STRING_WITH_LEN("COLUMN_LIST") }, BUILDER(Create_func_dyncol_list)}, + { { C_STRING_WITH_LEN("COLUMN_JSON") }, BUILDER(Create_func_dyncol_json)}, { { C_STRING_WITH_LEN("COMPRESS") }, BUILDER(Create_func_compress)}, { { C_STRING_WITH_LEN("CONCAT") }, BUILDER(Create_func_concat)}, { { C_STRING_WITH_LEN("CONCAT_WS") }, BUILDER(Create_func_concat_ws)}, @@ -5720,11 +5804,6 @@ Item *create_func_dyncol_create(THD *thd, List &list) return new (thd->mem_root) Item_func_dyncol_create(*args, dfs); } -Item *create_func_dyncol_json(THD *thd, Item *str) -{ - return new (thd->mem_root) Item_func_dyncol_json(str); -} - Item *create_func_dyncol_add(THD *thd, Item *str, List &list) { diff --git a/sql/item_func.h b/sql/item_func.h index cb9c1929d7d..ccb86fd03e5 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -58,7 +58,7 @@ public: NOW_FUNC, TRIG_COND_FUNC, SUSERVAR_FUNC, GUSERVAR_FUNC, COLLATE_FUNC, EXTRACT_FUNC, CHAR_TYPECAST_FUNC, FUNC_SP, UDF_FUNC, - NEG_FUNC, GSYSVAR_FUNC }; + NEG_FUNC, GSYSVAR_FUNC, DYNCOL }; enum optimize_type { OPTIMIZE_NONE,OPTIMIZE_KEY,OPTIMIZE_OP, OPTIMIZE_NULL, OPTIMIZE_EQUAL }; enum Type type() const { return FUNC_ITEM; } diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index ca6a6b2cea3..706fbbff94d 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -3760,8 +3760,8 @@ String *Item_func_uuid::val_str(String *str) Item_func_dyncol_create::Item_func_dyncol_create(List &args, DYNCALL_CREATE_DEF *dfs) - : Item_str_func(args), defs(dfs), vals(0), keys(NULL), names(FALSE), - force_names(FALSE) + : Item_str_func(args), defs(dfs), vals(0), keys_num(NULL), keys_str(NULL), + names(FALSE), force_names(FALSE) { DBUG_ASSERT((args.elements & 0x1) == 0); // even number of arguments } @@ -3782,13 +3782,15 @@ bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref) names= TRUE; } - keys= (uchar *) alloc_root(thd->mem_root, + keys_num= (uint *) alloc_root(thd->mem_root, (sizeof(LEX_STRING) > sizeof(uint) ? sizeof(LEX_STRING) : sizeof(uint)) * (arg_count / 2)); + keys_str= (LEX_STRING *) keys_num; + //status_var_increment(thd->status_var.feature_dynamic_columns); } - return res || vals == 0 || keys == 0; + return res || vals == 0 || keys_num == 0; } @@ -3808,6 +3810,41 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) my_decimal dtmp, *dres; force_names= force_names_arg; + if (!(names || force_names)) + { + for (i= 0; i < column_count; i++) + { + uint valpos= i * 2 + 1; + DYNAMIC_COLUMN_TYPE type= defs[i].type; + if (type == DYN_COL_NULL) + switch (args[valpos]->field_type()) + { + case MYSQL_TYPE_VARCHAR: + case MYSQL_TYPE_ENUM: + case MYSQL_TYPE_SET: + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_VAR_STRING: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_GEOMETRY: + type= DYN_COL_STRING; + break; + default: + break; + } + + if (type == DYN_COL_STRING && + args[valpos]->type() == Item::FUNC_ITEM && + ((Item_func *)args[valpos])->functype() == DYNCOL) + { + force_names= 1; + break; + } + } + } + /* get values */ for (i= 0; i < column_count; i++) { @@ -3865,6 +3902,13 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) break; } } + if (type == DYN_COL_STRING && + args[valpos]->type() == Item::FUNC_ITEM && + ((Item_func *)args[valpos])->functype() == DYNCOL) + { + DBUG_ASSERT(names || force_names); + type= DYN_COL_DYNCOL; + } if (names || force_names) { res= args[i * 2]->val_str(&tmp); @@ -3873,10 +3917,8 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) // guaranty UTF-8 string for names if (my_charset_same(res->charset(), &my_charset_utf8_general_ci)) { - ((LEX_STRING *)keys)[i].length= res->length(); - if (!(((LEX_STRING *)keys)[i].str= - (char *)sql_memdup(res->ptr(), res->length()))) - ((LEX_STRING *)keys)[i].length= 0; + keys_str[i].length= res->length(); + keys_str[i].str= sql_strmake(res->ptr(), res->length()); } else { @@ -3887,25 +3929,25 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) my_charset_utf8_general_ci.mbmaxlen + 1)); if (str) { - ((LEX_STRING *)keys)[i].length= + keys_str[i].length= copy_and_convert(str, strlen, &my_charset_utf8_general_ci, res->ptr(), res->length(), res->charset(), &dummy_errors); - ((LEX_STRING *)keys)[i].str= str; + keys_str[i].str= str; } else - ((LEX_STRING *)keys)[i].length= 0; + keys_str[i].length= 0; } } else { - ((LEX_STRING *)keys)[i].length= 0; - ((LEX_STRING *)keys)[i].str= NULL; + keys_str[i].length= 0; + keys_str[i].str= NULL; } } else - ((uint *)keys)[i]= (uint) args[i * 2]->val_int(); + keys_num[i]= (uint) args[i * 2]->val_int(); if (args[i * 2]->null_value) { /* to make cleanup possible */ @@ -3927,11 +3969,11 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) case DYN_COL_DOUBLE: vals[i].x.double_value= args[valpos]->val_real(); break; + case DYN_COL_DYNCOL: case DYN_COL_STRING: res= args[valpos]->val_str(&tmp); if (res && - (vals[i].x.string.value.str= my_strndup(res->ptr(), res->length(), - MYF(MY_WME)))) + (vals[i].x.string.value.str= sql_strmake(res->ptr(), res->length()))) { vals[i].x.string.value.length= res->length(); vals[i].x.string.charset= res->charset(); @@ -3975,26 +4017,12 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) } if (vals[i].type != DYN_COL_NULL && args[valpos]->null_value) { - if (vals[i].type == DYN_COL_STRING) - my_free(vals[i].x.string.value.str); vals[i].type= DYN_COL_NULL; } } return FALSE; } -void Item_func_dyncol_create::cleanup_arguments() -{ - uint column_count= (arg_count / 2); - uint i; - - for (i= 0; i < column_count; i++) - { - if (vals[i].type == DYN_COL_STRING) - my_free(vals[i].x.string.value.str); - } - force_names= FALSE; -} String *Item_func_dyncol_create::val_str(String *str) { @@ -4011,8 +4039,11 @@ String *Item_func_dyncol_create::val_str(String *str) } else { - if ((rc= dynamic_column_create_many_fmt(&col, column_count, keys, - vals, names || force_names))) + if ((rc= ((names || force_names) ? + mariadb_dyncol_create_many_named(&col, column_count, keys_str, + vals, TRUE) : + mariadb_dyncol_create_many(&col, column_count, keys_num, + vals, TRUE)))) { dynamic_column_error_message(rc); dynamic_column_column_free(&col); @@ -4024,7 +4055,7 @@ String *Item_func_dyncol_create::val_str(String *str) /* Move result from DYNAMIC_COLUMN to str_value */ char *ptr; size_t length, alloc_length; - dynamic_column_reassociate(&col, &ptr, &length, &alloc_length); + mariadb_dyncol_reassociate(&col, &ptr, &length, &alloc_length); str_value.reassociate(ptr, (uint32) length, (uint32) alloc_length, &my_charset_bin); res= &str_value; @@ -4032,9 +4063,6 @@ String *Item_func_dyncol_create::val_str(String *str) } } - /* cleanup */ - cleanup_arguments(); - return res; } @@ -4060,6 +4088,7 @@ void Item_func_dyncol_create::print_arguments(String *str, case DYN_COL_DOUBLE: str->append(STRING_WITH_LEN(" AS double")); break; + case DYN_COL_DYNCOL: case DYN_COL_STRING: str->append(STRING_WITH_LEN(" AS char")); if (defs[i].cs) @@ -4109,7 +4138,7 @@ String *Item_func_dyncol_json::val_str(String *str) col.str= (char *)res->ptr(); col.length= res->length(); - if ((rc= dynamic_column_json(&col, &json))) + if ((rc= mariadb_dyncol_json(&col, &json))) { dynamic_column_error_message(rc); goto null; @@ -4150,15 +4179,17 @@ String *Item_func_dyncol_add::val_str(String *str) col.length= res->length(); memcpy(col.str, res->ptr(), col.length); - if (prepare_arguments(dynamic_column_has_names(&col))) + if (prepare_arguments(mariadb_dyncol_has_names(&col))) goto null; - if ((rc= dynamic_column_update_many_fmt(&col, column_count, keys, - vals, names || force_names))) + if ((rc= ((names || force_names) ? + mariadb_dyncol_update_many_named(&col, column_count, + keys_str, vals) : + mariadb_dyncol_update_many(&col, column_count, + keys_num, vals)))) { dynamic_column_error_message(rc); dynamic_column_column_free(&col); - cleanup_arguments(); goto null; } @@ -4166,15 +4197,12 @@ String *Item_func_dyncol_add::val_str(String *str) /* Move result from DYNAMIC_COLUMN to str */ char *ptr; size_t length, alloc_length; - dynamic_column_reassociate(&col, &ptr, &length, &alloc_length); + mariadb_dyncol_reassociate(&col, &ptr, &length, &alloc_length); str->reassociate(ptr, (uint32) length, (uint32) alloc_length, &my_charset_bin); null_value= FALSE; } - /* cleanup */ - cleanup_arguments(); - return str; null: @@ -4264,8 +4292,8 @@ bool Item_dyncol_get::get_dyn_value(DYNAMIC_COLUMN_VALUE *val, String *tmp) dyn_str.str= (char*) res->ptr(); dyn_str.length= res->length(); if ((rc= ((name == NULL) ? - dynamic_column_get(&dyn_str, (uint) num, val) : - dynamic_column_get_str(&dyn_str, name, val)))) + mariadb_dyncol_get(&dyn_str, (uint) num, val) : + mariadb_dyncol_get_named(&dyn_str, name, val)))) { dynamic_column_error_message(rc); null_value= 1; @@ -4297,6 +4325,7 @@ String *Item_dyncol_get::val_str(String *str_result) case DYN_COL_DOUBLE: str_result->set_real(val.x.double_value, NOT_FIXED_DEC, &my_charset_latin1); break; + case DYN_COL_DYNCOL: case DYN_COL_STRING: if ((char*) tmp.ptr() <= val.x.string.value.str && (char*) tmp.ptr() + tmp.length() >= val.x.string.value.str) @@ -4373,6 +4402,7 @@ longlong Item_dyncol_get::val_int() return 0; switch (val.type) { + case DYN_COL_DYNCOL: case DYN_COL_NULL: goto null; case DYN_COL_UINT: @@ -4453,6 +4483,7 @@ double Item_dyncol_get::val_real() return 0.0; switch (val.type) { + case DYN_COL_DYNCOL: case DYN_COL_NULL: goto null; case DYN_COL_UINT: @@ -4510,6 +4541,7 @@ my_decimal *Item_dyncol_get::val_decimal(my_decimal *decimal_value) return NULL; switch (val.type) { + case DYN_COL_DYNCOL: case DYN_COL_NULL: goto null; case DYN_COL_UINT: @@ -4569,6 +4601,7 @@ bool Item_dyncol_get::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date) return 1; // Error switch (val.type) { + case DYN_COL_DYNCOL: case DYN_COL_NULL: goto null; case DYN_COL_INT: @@ -4631,7 +4664,8 @@ String *Item_func_dyncol_list::val_str(String *str) { uint i; enum enum_dyncol_func_result rc; - DYNAMIC_ARRAY arr; + LEX_STRING *names= 0; + uint count; DYNAMIC_COLUMN col; String *res= args[0]->val_str(str); @@ -4640,37 +4674,37 @@ String *Item_func_dyncol_list::val_str(String *str) col.length= res->length(); /* We do not change the string, so could do this trick */ col.str= (char *)res->ptr(); - if ((rc= dynamic_column_list_str(&col, &arr))) + if ((rc= mariadb_dyncol_list_named(&col, &count, &names))) { + bzero(&col, sizeof(col)); dynamic_column_error_message(rc); - for (i= 0; i < arr.elements; i++) - my_free(dynamic_element(&arr, i, LEX_STRING*)->str); - delete_dynamic(&arr); goto null; } + bzero(&col, sizeof(col)); /* We estimate average name length as 10 */ - if (str->alloc(arr.elements * 13)) + if (str->alloc(count * 13)) goto null; str->length(0); str->set_charset(&my_charset_utf8_general_ci); - for (i= 0; i < arr.elements; i++) + for (i= 0; i < count; i++) { - LEX_STRING *name= dynamic_element(&arr, i, LEX_STRING *); - append_identifier(current_thd, str, name->str, name->length); - if (i < arr.elements - 1) + append_identifier(current_thd, str, names[i].str, names[i].length); + if (i < count - 1) str->qs_append(','); - my_free(name->str); } - null_value= FALSE; - delete_dynamic(&arr); + if (names) + my_free(names); return str; null: null_value= TRUE; + if (names) + my_free(names); return NULL; } + diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h index e6a7e1291b8..8ef67654b35 100644 --- a/sql/item_strfunc.h +++ b/sql/item_strfunc.h @@ -1001,10 +1001,10 @@ class Item_func_dyncol_create: public Item_str_func protected: DYNCALL_CREATE_DEF *defs; DYNAMIC_COLUMN_VALUE *vals; - uchar *keys; + uint *keys_num; + LEX_STRING *keys_str; bool names, force_names; bool prepare_arguments(bool force_names); - void cleanup_arguments(); void print_arguments(String *str, enum_query_type query_type); public: Item_func_dyncol_create(List &args, DYNCALL_CREATE_DEF *dfs); @@ -1013,6 +1013,7 @@ public: const char *func_name() const{ return "column_create"; } String *val_str(String *); virtual void print(String *str, enum_query_type query_type); + virtual enum Functype functype() const { return DYNCOL; } }; @@ -1081,3 +1082,4 @@ public: extern String my_empty_string; #endif /* ITEM_STRFUNC_INCLUDED */ + diff --git a/sql/lex.h b/sql/lex.h index ea68ea0972a..34eda613e71 100644 --- a/sql/lex.h +++ b/sql/lex.h @@ -126,10 +126,7 @@ static SYMBOL symbols[] = { { "COLUMN_CHECK", SYM(COLUMN_CHECK_SYM)}, { "COLUMN_CREATE", SYM(COLUMN_CREATE_SYM)}, { "COLUMN_DELETE", SYM(COLUMN_DELETE_SYM)}, - { "COLUMN_EXISTS", SYM(COLUMN_EXISTS_SYM)}, { "COLUMN_GET", SYM(COLUMN_GET_SYM)}, - { "COLUMN_JSON", SYM(COLUMN_JSON_SYM)}, - { "COLUMN_LIST", SYM(COLUMN_LIST_SYM)}, { "COMMENT", SYM(COMMENT_SYM)}, { "COMMIT", SYM(COMMIT_SYM)}, { "COMMITTED", SYM(COMMITTED_SYM)}, diff --git a/sql/sql_join_cache.cc b/sql/sql_join_cache.cc index d785366ae69..14d4d5fca6c 100644 --- a/sql/sql_join_cache.cc +++ b/sql/sql_join_cache.cc @@ -3872,10 +3872,10 @@ int JOIN_TAB_SCAN_MRR::next() int rc= join_tab->table->file->multi_range_read_next((range_id_t*)ptr) ? -1 : 0; if (!rc) { - /* + /* If a record in in an incremental cache contains no fields then the association for the last record in cache will be equal to cache->end_pos - */ + */ /* psergey: this makes no sense where HA_MRR_NO_ASSOC is used. DBUG_ASSERT(cache->buff <= (uchar *) (*ptr) && diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index 48dd47bccea..87a7df34986 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -885,10 +885,7 @@ bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize); %token COLUMN_CHECK_SYM %token COLUMN_CREATE_SYM %token COLUMN_DELETE_SYM -%token COLUMN_EXISTS_SYM %token COLUMN_GET_SYM -%token COLUMN_JSON_SYM -%token COLUMN_LIST_SYM %token COLUMN_SYM /* SQL-2003-R */ %token COLUMN_NAME_SYM /* SQL-2003-N */ %token COMMENT_SYM @@ -8807,20 +8804,6 @@ function_call_nonkeyword: if ($$ == NULL) MYSQL_YYABORT; } - | - COLUMN_EXISTS_SYM '(' expr ',' expr ')' - { - $$= new (YYTHD->mem_root) Item_func_dyncol_exists($3, $5); - if ($$ == NULL) - MYSQL_YYABORT; - } - | - COLUMN_LIST_SYM '(' expr ')' - { - $$= new (YYTHD->mem_root) Item_func_dyncol_list($3); - if ($$ == NULL) - MYSQL_YYABORT; - } | COLUMN_CREATE_SYM '(' dyncall_create_list ')' { @@ -8828,13 +8811,6 @@ function_call_nonkeyword: if ($$ == NULL) MYSQL_YYABORT; } - | - COLUMN_JSON_SYM '(' expr ')' - { - $$= create_func_dyncol_json(YYTHD, $3); - if ($$ == NULL) - MYSQL_YYABORT; - } | COLUMN_GET_SYM '(' expr ',' expr AS cast_type ')' { @@ -12927,10 +12903,7 @@ keyword: | COLUMN_CHECK_SYM {} | COLUMN_CREATE_SYM {} | COLUMN_DELETE_SYM {} - | COLUMN_EXISTS_SYM {} | COLUMN_GET_SYM {} - | COLUMN_JSON_SYM {} - | COLUMN_LIST_SYM {} | COMMENT_SYM {} | COMMIT_SYM {} | CONTAINS_SYM {} -- cgit v1.2.1 From 082ff5931770ed70df0ec1e85f81fa880a4d9e62 Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 23 Dec 2012 22:17:22 +0200 Subject: Post-post review fixes. --- sql/item_func.h | 2 +- sql/item_strfunc.cc | 12 ++++++------ sql/item_strfunc.h | 8 +++----- 3 files changed, 10 insertions(+), 12 deletions(-) (limited to 'sql') diff --git a/sql/item_func.h b/sql/item_func.h index ccb86fd03e5..e13fa0834f0 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -58,7 +58,7 @@ public: NOW_FUNC, TRIG_COND_FUNC, SUSERVAR_FUNC, GUSERVAR_FUNC, COLLATE_FUNC, EXTRACT_FUNC, CHAR_TYPECAST_FUNC, FUNC_SP, UDF_FUNC, - NEG_FUNC, GSYSVAR_FUNC, DYNCOL }; + NEG_FUNC, GSYSVAR_FUNC, DYNCOL_FUNC }; enum optimize_type { OPTIMIZE_NONE,OPTIMIZE_KEY,OPTIMIZE_OP, OPTIMIZE_NULL, OPTIMIZE_EQUAL }; enum Type type() const { return FUNC_ITEM; } diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 706fbbff94d..5559ffa6c20 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -3837,7 +3837,7 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) if (type == DYN_COL_STRING && args[valpos]->type() == Item::FUNC_ITEM && - ((Item_func *)args[valpos])->functype() == DYNCOL) + ((Item_func *)args[valpos])->functype() == DYNCOL_FUNC) { force_names= 1; break; @@ -3904,7 +3904,7 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) } if (type == DYN_COL_STRING && args[valpos]->type() == Item::FUNC_ITEM && - ((Item_func *)args[valpos])->functype() == DYNCOL) + ((Item_func *)args[valpos])->functype() == DYNCOL_FUNC) { DBUG_ASSERT(names || force_names); type= DYN_COL_DYNCOL; @@ -3988,7 +3988,7 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) case DYN_COL_DECIMAL: if ((dres= args[valpos]->val_decimal(&dtmp))) { - dynamic_column_prepare_decimal(&vals[i]); + mariadb_dyncol_prepare_decimal(&vals[i]); DBUG_ASSERT(vals[i].x.decimal.value.len == dres->len); vals[i].x.decimal.value.intg= dres->intg; vals[i].x.decimal.value.frac= dres->frac; @@ -3998,7 +3998,7 @@ bool Item_func_dyncol_create::prepare_arguments(bool force_names_arg) } else { - dynamic_column_prepare_decimal(&vals[i]); // just to be safe + mariadb_dyncol_prepare_decimal(&vals[i]); // just to be safe DBUG_ASSERT(args[valpos]->null_value); } break; @@ -4055,7 +4055,7 @@ String *Item_func_dyncol_create::val_str(String *str) /* Move result from DYNAMIC_COLUMN to str_value */ char *ptr; size_t length, alloc_length; - mariadb_dyncol_reassociate(&col, &ptr, &length, &alloc_length); + dynstr_reassociate(&col, &ptr, &length, &alloc_length); str_value.reassociate(ptr, (uint32) length, (uint32) alloc_length, &my_charset_bin); res= &str_value; @@ -4197,7 +4197,7 @@ String *Item_func_dyncol_add::val_str(String *str) /* Move result from DYNAMIC_COLUMN to str */ char *ptr; size_t length, alloc_length; - mariadb_dyncol_reassociate(&col, &ptr, &length, &alloc_length); + dynstr_reassociate(&col, &ptr, &length, &alloc_length); str->reassociate(ptr, (uint32) length, (uint32) alloc_length, &my_charset_bin); null_value= FALSE; diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h index 8ef67654b35..d21c938f378 100644 --- a/sql/item_strfunc.h +++ b/sql/item_strfunc.h @@ -1013,7 +1013,7 @@ public: const char *func_name() const{ return "column_create"; } String *val_str(String *); virtual void print(String *str, enum_query_type query_type); - virtual enum Functype functype() const { return DYNCOL; } + virtual enum Functype functype() const { return DYNCOL_FUNC; } }; @@ -1051,11 +1051,9 @@ class Item_dyncol_get: public Item_str_func public: Item_dyncol_get(Item *str, Item *num) :Item_str_func(str, num) - { - max_length= MAX_DYNAMIC_COLUMN_LENGTH; - } + {} void fix_length_and_dec() - { maybe_null= 1; } + { maybe_null= 1; max_length= MAX_BLOB_WIDTH; } /* Mark that collation can change between calls */ bool dynamic_result() { return 1; } -- cgit v1.2.1 From 6f26aac9409e3456798e58a4ee4306e43c7ebf7b Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Dec 2012 14:41:46 +0200 Subject: MDEV-3873 & MDEV-3876 & MDEV-3912 : Wrong result (extra rows) with ALL subquery from a MERGE view. The problem was in the lost ability to be null for the table of a left join if it is a view/derived table. It hapenned because setup_table_map(), was called earlier then we merged the view or derived. Fixed by propagating new maybe_null flag during Item::update_used_tables(). Change in join_outer.test and join_outer_jcl6.test appeared because IS NULL reported no used tables (i.e. constant) for argument which could not be NULL and new maybe_null flag was propagated for IS NULL argument (Item_field) because table the Item_field belonged to changed its maybe_null status. --- sql/item.cc | 11 +++++++++-- sql/item.h | 16 +++++++++++++--- sql/item_cmpfunc.cc | 20 ++++++++++++-------- sql/item_cmpfunc.h | 28 +++++++++++++++++++++++++--- sql/item_func.cc | 25 ++++++++++++++----------- sql/item_func.h | 48 +++++++++++++++++++++++++++++------------------- sql/item_geofunc.cc | 4 ++-- sql/item_geofunc.h | 30 +++++++++++++++--------------- sql/item_strfunc.cc | 26 +++++++++++++------------- sql/item_strfunc.h | 28 +++++++++++++++------------- sql/item_timefunc.cc | 10 +++++----- sql/item_timefunc.h | 40 ++++++++++++++++++++-------------------- sql/item_xmlfunc.cc | 1 + sql/item_xmlfunc.h | 8 ++------ 14 files changed, 175 insertions(+), 120 deletions(-) (limited to 'sql') diff --git a/sql/item.cc b/sql/item.cc index 16dbd011f22..aee35b611e7 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -9166,11 +9166,18 @@ table_map Item_ref::used_tables() const void Item_ref::update_used_tables() -{ +{ if (!get_depended_from()) - (*ref)->update_used_tables(); + (*ref)->update_used_tables(); + maybe_null= (*ref)->maybe_null; } +void Item_direct_view_ref::update_used_tables() +{ + Item_ref::update_used_tables(); + if (view->table && view->table->maybe_null) + maybe_null= TRUE; +} table_map Item_direct_view_ref::used_tables() const { diff --git a/sql/item.h b/sql/item.h index 0852287cc7f..2b5e867feb7 100644 --- a/sql/item.h +++ b/sql/item.h @@ -1849,9 +1849,14 @@ public: bitmap_fast_test_and_set(tab->read_set, field->field_index); if (field->vcol_info) tab->mark_virtual_col(field); - } + } + } + void update_used_tables() + { + update_table_bitmaps(); + if (field && field->table) + maybe_null= field->maybe_null(); } - void update_used_tables() { update_table_bitmaps(); } Item *get_tmp_table_item(THD *thd); bool collect_item_field_processor(uchar * arg); bool add_field_to_set_processor(uchar * arg); @@ -2874,7 +2879,11 @@ public: enum Item_result result_type () const { return orig_item->result_type(); } enum_field_types field_type() const { return orig_item->field_type(); } table_map used_tables() const { return orig_item->used_tables(); } - void update_used_tables() { orig_item->update_used_tables(); } + void update_used_tables() + { + orig_item->update_used_tables(); + maybe_null= orig_item->maybe_null; + } bool const_item() const { return orig_item->const_item(); } table_map not_null_tables() const { return orig_item->not_null_tables(); } bool walk(Item_processor processor, bool walk_subquery, uchar *arg) @@ -2966,6 +2975,7 @@ public: Item *replace_equal_field(uchar *arg); table_map used_tables() const; table_map not_null_tables() const; + void update_used_tables(); bool walk(Item_processor processor, bool walk_subquery, uchar *arg) { return (*ref)->walk(processor, walk_subquery, arg) || diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc index b3b20a55ed9..75d3f31d4cd 100644 --- a/sql/item_cmpfunc.cc +++ b/sql/item_cmpfunc.cc @@ -1351,7 +1351,7 @@ int Arg_comparator::compare_e_row() void Item_func_truth::fix_length_and_dec() { - maybe_null= 0; + set_persist_maybe_null(0); null_value= 0; decimals= 0; max_length= 1; @@ -1859,7 +1859,8 @@ longlong Item_func_eq::val_int() void Item_func_equal::fix_length_and_dec() { Item_bool_func2::fix_length_and_dec(); - maybe_null=null_value=0; + set_persist_maybe_null(0); + null_value= 0; } longlong Item_func_equal::val_int() @@ -1999,7 +2000,7 @@ void Item_func_interval::fix_length_and_dec() } } } - maybe_null= 0; + set_persist_maybe_null(0); max_length= 2; used_tables_cache|= row->used_tables(); not_null_tables_cache= row->not_null_tables(); @@ -2670,7 +2671,7 @@ void Item_func_nullif::fix_length_and_dec() { Item_bool_func2::fix_length_and_dec(); - maybe_null=1; + set_persist_maybe_null(1); if (args[0]) // Only false if EOM { max_length=args[0]->max_length; @@ -4465,6 +4466,8 @@ void Item_cond::update_used_tables() item->update_used_tables(); used_tables_cache|= item->used_tables(); const_item_cache&= item->const_item(); + if (!persistent_maybe_null && item->maybe_null) + maybe_null= 1; } } @@ -4639,10 +4642,9 @@ longlong Item_is_not_null_test::val_int() */ void Item_is_not_null_test::update_used_tables() { + args[0]->update_used_tables(); if (!args[0]->maybe_null) used_tables_cache= 0; /* is always true */ - else - args[0]->update_used_tables(); } @@ -4925,7 +4927,7 @@ Item_func_regex::fix_fields(THD *thd, Item **ref) int comp_res= regcomp(TRUE); if (comp_res == -1) { // Will always return NULL - maybe_null=1; + set_persist_maybe_null(1); fixed= 1; return FALSE; } @@ -4935,7 +4937,7 @@ Item_func_regex::fix_fields(THD *thd, Item **ref) maybe_null= args[0]->maybe_null; } else - maybe_null=1; + set_persist_maybe_null(1); fixed= 1; return FALSE; } @@ -5729,6 +5731,8 @@ void Item_equal::update_used_tables() item->update_used_tables(); used_tables_cache|= item->used_tables(); const_item_cache&= item->const_item(); + if (!persistent_maybe_null && item->maybe_null) + maybe_null= 1; } } diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index 143fef87abd..dca139e6321 100644 --- a/sql/item_cmpfunc.h +++ b/sql/item_cmpfunc.h @@ -757,6 +757,11 @@ public: my_decimal *decimal_op(my_decimal *); enum_field_types field_type() const; void fix_length_and_dec(); + void update_used_tables() + { + Item_func_coalesce::update_used_tables(); + maybe_null= args[1]->maybe_null; + } const char *func_name() const { return "ifnull"; } Field *tmp_table_field(TABLE *table); uint decimal_precision() const; @@ -779,6 +784,11 @@ public: enum_field_types field_type() const { return cached_field_type; } bool fix_fields(THD *, Item **); void fix_length_and_dec(); + void update_used_tables() + { + Item_func::update_used_tables(); + maybe_null= args[1]->maybe_null || args[2]->maybe_null; + } uint decimal_precision() const; const char *func_name() const { return "if"; } bool eval_not_null_tables(uchar *opt_arg); @@ -1242,6 +1252,12 @@ public: my_decimal *val_decimal(my_decimal *); bool fix_fields(THD *thd, Item **ref); void fix_length_and_dec(); + void update_used_tables() + { + Item_func::update_used_tables(); + if (else_expr_num == -1 || args[else_expr_num]->maybe_null) + maybe_null= 1; + } uint decimal_precision() const; table_map not_null_tables() const { return 0; } enum Item_result result_type () const { return cached_result_type; } @@ -1363,13 +1379,14 @@ public: enum Functype functype() const { return ISNULL_FUNC; } void fix_length_and_dec() { - decimals=0; max_length=1; maybe_null=0; + decimals=0; max_length=1; set_persist_maybe_null(0); update_used_tables(); } const char *func_name() const { return "isnull"; } /* Optimize case of not_null_column IS NULL */ virtual void update_used_tables() { + args[0]->update_used_tables(); if (!args[0]->maybe_null) { used_tables_cache= 0; /* is always false */ @@ -1377,7 +1394,6 @@ public: } else { - args[0]->update_used_tables(); used_tables_cache= args[0]->used_tables(); const_item_cache= args[0]->const_item(); } @@ -1424,7 +1440,7 @@ public: enum Functype functype() const { return ISNOTNULL_FUNC; } void fix_length_and_dec() { - decimals=0; max_length=1; maybe_null=0; + decimals=0; max_length=1; set_persist_maybe_null(0); } const char *func_name() const { return "isnotnull"; } optimize_type select_optimize() const { return OPTIMIZE_NULL; } @@ -1495,6 +1511,12 @@ public: void cleanup(); longlong val_int(); bool fix_fields(THD *thd, Item **ref); + void update_used_tables() + { + Item_bool_func::update_used_tables(); + if (regex_is_const) + maybe_null= 1; + } const char *func_name() const { return "regexp"; } virtual inline void print(String *str, enum_query_type query_type) diff --git a/sql/item_func.cc b/sql/item_func.cc index 42332d6b1b2..0cd96619023 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -86,7 +86,7 @@ void Item_func::set_arguments(List &list) } Item_func::Item_func(List &list) - :allowed_arg_cols(1) + :allowed_arg_cols(1), persistent_maybe_null(0) { set_arguments(list); } @@ -94,6 +94,7 @@ Item_func::Item_func(List &list) Item_func::Item_func(THD *thd, Item_func *item) :Item_result_field(thd, item), allowed_arg_cols(item->allowed_arg_cols), + persistent_maybe_null(0), arg_count(item->arg_count), used_tables_cache(item->used_tables_cache), not_null_tables_cache(item->not_null_tables_cache), @@ -423,6 +424,8 @@ void Item_func::update_used_tables() args[i]->update_used_tables(); used_tables_cache|=args[i]->used_tables(); const_item_cache&=args[i]->const_item(); + if (!persistent_maybe_null && args[i]->maybe_null) + maybe_null= 1; } } @@ -1496,7 +1499,7 @@ void Item_func_div::fix_length_and_dec() case IMPOSSIBLE_RESULT: DBUG_ASSERT(0); } - maybe_null= 1; // devision by zero + set_persist_maybe_null(1); // devision by zero DBUG_VOID_RETURN; } @@ -1531,7 +1534,7 @@ void Item_func_int_div::fix_length_and_dec() max_length=args[0]->max_length - (argtype == DECIMAL_RESULT || argtype == INT_RESULT ? args[0]->decimals : 0); - maybe_null=1; + set_persist_maybe_null(1); unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag; } @@ -1612,7 +1615,7 @@ void Item_func_mod::result_precision() void Item_func_mod::fix_length_and_dec() { Item_num_op::fix_length_and_dec(); - maybe_null= 1; + set_persist_maybe_null(1); unsigned_flag= args[0]->unsigned_flag; } @@ -2778,7 +2781,7 @@ longlong Item_func_field::val_int() void Item_func_field::fix_length_and_dec() { - maybe_null=0; max_length=3; + set_persist_maybe_null(0); max_length=3; cmp_type= args[0]->result_type(); for (uint i=1; i < arg_count ; i++) cmp_type= item_cmp_type(cmp_type, args[i]->result_type()); @@ -4843,7 +4846,7 @@ void Item_func_get_user_var::fix_length_and_dec() { THD *thd=current_thd; int error; - maybe_null=1; + set_persist_maybe_null(1); decimals=NOT_FIXED_DEC; max_length=MAX_BLOB_WIDTH; @@ -5049,7 +5052,7 @@ void Item_func_get_system_var::update_null_value() void Item_func_get_system_var::fix_length_and_dec() { char *cptr; - maybe_null= TRUE; + set_persist_maybe_null(1); max_length= 0; if (var->check_type(var_type)) @@ -5580,7 +5583,7 @@ bool Item_func_match::fix_fields(THD *thd, Item **ref) DBUG_ASSERT(fixed == 0); Item *UNINIT_VAR(item); // Safe as arg_count is > 1 - maybe_null=1; + set_persist_maybe_null(1); join_key=0; /* @@ -5914,7 +5917,7 @@ longlong Item_func_row_count::val_int() Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name) :Item_func(), context(context_arg), m_name(name), m_sp(NULL), sp_result_field(NULL) { - maybe_null= 1; + set_persist_maybe_null(1); m_name->init_qname(current_thd); dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); dummy_table->s= (TABLE_SHARE*) (dummy_table+1); @@ -5925,7 +5928,7 @@ Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name, List &list) :Item_func(list), context(context_arg), m_name(name), m_sp(NULL),sp_result_field(NULL) { - maybe_null= 1; + set_persist_maybe_null(1); m_name->init_qname(current_thd); dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE)); dummy_table->s= (TABLE_SHARE*) (dummy_table+1); @@ -6066,7 +6069,7 @@ void Item_func_sp::fix_length_and_dec() decimals= sp_result_field->decimals(); max_length= sp_result_field->field_length; collation.set(sp_result_field->charset()); - maybe_null= 1; + set_persist_maybe_null(1); unsigned_flag= test(sp_result_field->flags & UNSIGNED_FLAG); DBUG_VOID_RETURN; diff --git a/sql/item_func.h b/sql/item_func.h index 082c9b83296..3ab1fbad4e3 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -38,6 +38,8 @@ protected: 0 means get this number from first argument */ uint allowed_arg_cols; + /* maybe_null can't be changed by parameters or used table state */ + bool persistent_maybe_null; public: uint arg_count; table_map used_tables_cache, not_null_tables_cache; @@ -63,13 +65,13 @@ public: enum Type type() const { return FUNC_ITEM; } virtual enum Functype functype() const { return UNKNOWN_FUNC; } Item_func(void): - allowed_arg_cols(1), arg_count(0) + allowed_arg_cols(1), persistent_maybe_null(0), arg_count(0) { with_sum_func= 0; with_field= 0; } Item_func(Item *a): - allowed_arg_cols(1), arg_count(1) + allowed_arg_cols(1), persistent_maybe_null(0), arg_count(1) { args= tmp_arg; args[0]= a; @@ -77,7 +79,7 @@ public: with_field= a->with_field; } Item_func(Item *a,Item *b): - allowed_arg_cols(1), arg_count(2) + allowed_arg_cols(1), persistent_maybe_null(0), arg_count(2) { args= tmp_arg; args[0]= a; args[1]= b; @@ -85,7 +87,7 @@ public: with_field= a->with_field || b->with_field; } Item_func(Item *a,Item *b,Item *c): - allowed_arg_cols(1) + allowed_arg_cols(1), persistent_maybe_null(0) { arg_count= 0; if ((args= (Item**) sql_alloc(sizeof(Item*)*3))) @@ -97,7 +99,7 @@ public: } } Item_func(Item *a,Item *b,Item *c,Item *d): - allowed_arg_cols(1) + allowed_arg_cols(1), persistent_maybe_null(0) { arg_count= 0; if ((args= (Item**) sql_alloc(sizeof(Item*)*4))) @@ -111,7 +113,7 @@ public: } } Item_func(Item *a,Item *b,Item *c,Item *d,Item* e): - allowed_arg_cols(1) + allowed_arg_cols(1), persistent_maybe_null(0) { arg_count= 5; if ((args= (Item**) sql_alloc(sizeof(Item*)*5))) @@ -300,6 +302,11 @@ public: info.bool_function= &Item::restore_to_before_no_rows_in_result; walk(&Item::call_bool_func_processor, FALSE, (uchar*) &info); } + inline void set_persist_maybe_null(bool mb_null) + { + maybe_null= mb_null; + persistent_maybe_null= 1; + } }; @@ -506,7 +513,7 @@ public: } double val_real(); enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE; } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } const char *func_name() const { return "double_typecast"; } virtual void print(String *str, enum_query_type query_type); }; @@ -647,7 +654,7 @@ class Item_dec_func :public Item_real_func void fix_length_and_dec() { decimals=NOT_FIXED_DEC; max_length=float_length(decimals); - maybe_null=1; + set_persist_maybe_null(1); } }; @@ -971,7 +978,7 @@ public: Item_func_coercibility(Item *a) :Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "coercibility"; } - void fix_length_and_dec() { max_length=10; maybe_null= 0; } + void fix_length_and_dec() { max_length=10; set_persist_maybe_null(0); } table_map not_null_tables() const { return 0; } }; @@ -1132,7 +1139,7 @@ public: {} longlong val_int(); const char *func_name() const { return "benchmark"; } - void fix_length_and_dec() { max_length=1; maybe_null=0; } + void fix_length_and_dec() { max_length=1; set_persist_maybe_null(0); } virtual void print(String *str, enum_query_type query_type); bool check_vcol_func_processor(uchar *int_arg) { @@ -1385,7 +1392,7 @@ public: double val_real() { DBUG_ASSERT(fixed == 1); null_value= 1; return 0.0; } longlong val_int() { DBUG_ASSERT(fixed == 1); null_value=1; return 0; } enum Item_result result_type () const { return STRING_RESULT; } - void fix_length_and_dec() { maybe_null=1; max_length=0; } + void fix_length_and_dec() { set_persist_maybe_null(1); max_length=0; } }; #endif /* HAVE_DLOPEN */ @@ -1406,7 +1413,7 @@ class Item_func_get_lock :public Item_int_func Item_func_get_lock(Item *a,Item *b) :Item_int_func(a,b) {} longlong val_int(); const char *func_name() const { return "get_lock"; } - void fix_length_and_dec() { max_length=1; maybe_null=1;} + void fix_length_and_dec() { max_length=1; set_persist_maybe_null(1);} bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); @@ -1420,7 +1427,7 @@ public: Item_func_release_lock(Item *a) :Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "release_lock"; } - void fix_length_and_dec() { max_length=1; maybe_null=1;} + void fix_length_and_dec() { max_length=1; set_persist_maybe_null(1);} bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); @@ -1437,7 +1444,7 @@ public: Item_master_pos_wait(Item *a,Item *b,Item *c) :Item_int_func(a,b,c) {} longlong val_int(); const char *func_name() const { return "master_pos_wait"; } - void fix_length_and_dec() { max_length=21; maybe_null=1;} + void fix_length_and_dec() { max_length=21; set_persist_maybe_null(1);} bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); @@ -1653,7 +1660,8 @@ public: Item_func_inet_aton(Item *a) :Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "inet_aton"; } - void fix_length_and_dec() { decimals= 0; max_length= 21; maybe_null= 1; unsigned_flag= 1;} + void fix_length_and_dec() + { decimals= 0; max_length= 21; set_persist_maybe_null(1); unsigned_flag= 1; } }; @@ -1722,7 +1730,8 @@ public: Item_func_is_free_lock(Item *a) :Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "is_free_lock"; } - void fix_length_and_dec() { decimals=0; max_length=1; maybe_null=1;} + void fix_length_and_dec() + { decimals= 0; max_length= 1; set_persist_maybe_null(1); } bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); @@ -1736,7 +1745,8 @@ public: Item_func_is_used_lock(Item *a) :Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "is_used_lock"; } - void fix_length_and_dec() { decimals=0; max_length=10; maybe_null=1;} + void fix_length_and_dec() + { decimals= 0; max_length= 10; set_persist_maybe_null(1);} bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); @@ -1759,7 +1769,7 @@ public: Item_func_row_count() :Item_int_func() {} longlong val_int(); const char *func_name() const { return "row_count"; } - void fix_length_and_dec() { decimals= 0; maybe_null=0; } + void fix_length_and_dec() { decimals= 0; set_persist_maybe_null(0); } bool check_vcol_func_processor(uchar *int_arg) { @@ -1893,7 +1903,7 @@ public: Item_func_found_rows() :Item_int_func() {} longlong val_int(); const char *func_name() const { return "found_rows"; } - void fix_length_and_dec() { decimals= 0; maybe_null=0; } + void fix_length_and_dec() { decimals= 0; set_persist_maybe_null(0); } bool check_vcol_func_processor(uchar *int_arg) { return trace_unsupported_by_check_vcol_func_processor(func_name()); diff --git a/sql/item_geofunc.cc b/sql/item_geofunc.cc index 522be28558f..ba330ba3b96 100644 --- a/sql/item_geofunc.cc +++ b/sql/item_geofunc.cc @@ -52,7 +52,7 @@ void Item_geometry_func::fix_length_and_dec() collation.set(&my_charset_bin); decimals=0; max_length= (uint32) 4294967295U; - maybe_null= 1; + set_persist_maybe_null(1); } @@ -145,7 +145,7 @@ void Item_func_as_wkt::fix_length_and_dec() { collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII); max_length=MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } diff --git a/sql/item_geofunc.h b/sql/item_geofunc.h index d2030ee7bb9..eae6f425f4d 100644 --- a/sql/item_geofunc.h +++ b/sql/item_geofunc.h @@ -89,7 +89,7 @@ public: { // "GeometryCollection" is the longest max_length= 20; - maybe_null= 1; + set_persist_maybe_null(1); }; }; @@ -224,7 +224,7 @@ public: { Item_func::print(str, query_type); } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } bool is_null() { (void) val_int(); return null_value; } }; @@ -251,7 +251,7 @@ public: Item_func::print(str, query_type); } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } bool is_null() { (void) val_int(); return null_value; } }; @@ -342,7 +342,7 @@ public: longlong val_int(); optimize_type select_optimize() const { return OPTIMIZE_NONE; } const char *func_name() const { return "st_isempty"; } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } }; class Item_func_issimple: public Item_bool_func @@ -356,7 +356,7 @@ public: longlong val_int(); optimize_type select_optimize() const { return OPTIMIZE_NONE; } const char *func_name() const { return "st_issimple"; } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } }; class Item_func_isclosed: public Item_bool_func @@ -366,7 +366,7 @@ public: longlong val_int(); optimize_type select_optimize() const { return OPTIMIZE_NONE; } const char *func_name() const { return "st_isclosed"; } - void fix_length_and_dec() { maybe_null= 1; } + void fix_length_and_dec() { set_persist_maybe_null(1); } }; class Item_func_dimension: public Item_int_func @@ -376,7 +376,7 @@ public: Item_func_dimension(Item *a): Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "st_dimension"; } - void fix_length_and_dec() { max_length= 10; maybe_null= 1; } + void fix_length_and_dec() { max_length= 10; set_persist_maybe_null(1); } }; class Item_func_x: public Item_real_func @@ -389,7 +389,7 @@ public: void fix_length_and_dec() { Item_real_func::fix_length_and_dec(); - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -404,7 +404,7 @@ public: void fix_length_and_dec() { Item_real_func::fix_length_and_dec(); - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -416,7 +416,7 @@ public: Item_func_numgeometries(Item *a): Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "st_numgeometries"; } - void fix_length_and_dec() { max_length= 10; maybe_null= 1; } + void fix_length_and_dec() { max_length= 10; set_persist_maybe_null(1); } }; @@ -427,7 +427,7 @@ public: Item_func_numinteriorring(Item *a): Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "st_numinteriorrings"; } - void fix_length_and_dec() { max_length= 10; maybe_null= 1; } + void fix_length_and_dec() { max_length= 10; set_persist_maybe_null(1); } }; @@ -438,7 +438,7 @@ public: Item_func_numpoints(Item *a): Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "st_numpoints"; } - void fix_length_and_dec() { max_length= 10; maybe_null= 1; } + void fix_length_and_dec() { max_length= 10; set_persist_maybe_null(1); } }; @@ -452,7 +452,7 @@ public: void fix_length_and_dec() { Item_real_func::fix_length_and_dec(); - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -467,7 +467,7 @@ public: void fix_length_and_dec() { Item_real_func::fix_length_and_dec(); - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -479,7 +479,7 @@ public: Item_func_srid(Item *a): Item_int_func(a) {} longlong val_int(); const char *func_name() const { return "srid"; } - void fix_length_and_dec() { max_length= 10; maybe_null= 1; } + void fix_length_and_dec() { max_length= 10; set_persist_maybe_null(1); } }; diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 1b228a344f4..d0b284a363d 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -272,7 +272,7 @@ String *Item_func_aes_decrypt::val_str(String *str) void Item_func_aes_decrypt::fix_length_and_dec() { max_length=args[0]->max_length; - maybe_null= 1; + set_persist_maybe_null(1); } @@ -435,7 +435,7 @@ void Item_func_concat::fix_length_and_dec() if (max_result_length >= MAX_BLOB_WIDTH) { max_result_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) max_result_length; } @@ -795,7 +795,7 @@ void Item_func_concat_ws::fix_length_and_dec() if (max_result_length >= MAX_BLOB_WIDTH) { max_result_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) max_result_length; } @@ -997,7 +997,7 @@ void Item_func_replace::fix_length_and_dec() if (max_result_length >= MAX_BLOB_WIDTH) { max_result_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) max_result_length; @@ -1081,7 +1081,7 @@ void Item_func_insert::fix_length_and_dec() if (max_result_length >= MAX_BLOB_WIDTH) { max_result_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) max_result_length; } @@ -2184,7 +2184,7 @@ void Item_func_elt::fix_length_and_dec() set_if_bigger(max_length,args[i]->max_length); set_if_bigger(decimals,args[i]->decimals); } - maybe_null=1; // NULL if wrong first arg + set_persist_maybe_null(1); // NULL if wrong first arg } @@ -2419,14 +2419,14 @@ void Item_func_repeat::fix_length_and_dec() if (max_result_length >= MAX_BLOB_WIDTH) { max_result_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) max_result_length; } else { max_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } } @@ -2509,14 +2509,14 @@ void Item_func_rpad::fix_length_and_dec() if (length >= MAX_BLOB_WIDTH) { length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) length; } else { max_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } } @@ -2626,14 +2626,14 @@ void Item_func_lpad::fix_length_and_dec() if (length >= MAX_BLOB_WIDTH) { length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } max_length= (ulong) length; } else { max_length= MAX_BLOB_WIDTH; - maybe_null= 1; + set_persist_maybe_null(1); } } @@ -3548,7 +3548,7 @@ bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref) void Item_func_dyncol_create::fix_length_and_dec() { - maybe_null= TRUE; + set_persist_maybe_null(1); collation.set(&my_charset_bin); decimals= 0; } diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h index fc4e888e6ea..e3b040a2e55 100644 --- a/sql/item_strfunc.h +++ b/sql/item_strfunc.h @@ -319,7 +319,7 @@ public: String *val_str(String *); void fix_length_and_dec() { - maybe_null=1; + set_persist_maybe_null(1); /* 9 = MAX ((8- (arg_len % 8)) + 1) */ max_length = args[0]->max_length + 9; } @@ -335,7 +335,7 @@ public: String *val_str(String *); void fix_length_and_dec() { - maybe_null=1; + set_persist_maybe_null(1); /* 9 = MAX ((8- (arg_len % 8)) + 1) */ max_length = args[0]->max_length - 9; } @@ -361,7 +361,7 @@ public: constructor_helper(); } String *val_str(String *); - void fix_length_and_dec() { maybe_null=1; max_length = 13; } + void fix_length_and_dec() { set_persist_maybe_null(1); max_length = 13; } const char *func_name() const { return "encrypt"; } bool check_vcol_func_processor(uchar *int_arg) { @@ -431,7 +431,7 @@ public: void fix_length_and_dec() { max_length= MAX_FIELD_NAME * system_charset_info->mbmaxlen; - maybe_null=1; + set_persist_maybe_null(1); } const char *func_name() const { return "database"; } const char *fully_qualified_func_name() const { return "database()"; } @@ -607,7 +607,7 @@ public: { collation.set(default_charset()); max_length=64; - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -634,7 +634,7 @@ public: Item_func_unhex(Item *a) :Item_str_func(a) { /* there can be bad hex strings */ - maybe_null= 1; + set_persist_maybe_null(1); } const char *func_name() const { return "unhex"; } String *val_str(String *); @@ -680,7 +680,7 @@ public: void fix_length_and_dec() { collation.set(&my_charset_bin, DERIVATION_COERCIBLE); - maybe_null=1; + set_persist_maybe_null(1); max_length=MAX_BLOB_WIDTH; } bool check_vcol_func_processor(uchar *int_arg) @@ -713,7 +713,7 @@ public: { decimals= 0; max_length= 3 * 8 + 7; - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -804,7 +804,7 @@ public: { collation.set(system_charset_info); max_length= 64 * collation.collation->mbmaxlen; // should be enough - maybe_null= 0; + set_persist_maybe_null(0); }; table_map not_null_tables() const { return 0; } }; @@ -819,7 +819,7 @@ public: { collation.set(system_charset_info); max_length= 64 * collation.collation->mbmaxlen; // should be enough - maybe_null= 0; + set_persist_maybe_null(0); }; table_map not_null_tables() const { return 0; } }; @@ -865,7 +865,8 @@ class Item_func_uncompress: public Item_str_func String buffer; public: Item_func_uncompress(Item *a): Item_str_func(a){} - void fix_length_and_dec(){ maybe_null= 1; max_length= MAX_BLOB_WIDTH; } + void fix_length_and_dec() + { set_persist_maybe_null(1); max_length= MAX_BLOB_WIDTH; } const char *func_name() const{return "uncompress";} String *val_str(String *) ZLIB_DEPENDED_FUNCTION }; @@ -937,7 +938,7 @@ public: max_length= MAX_DYNAMIC_COLUMN_LENGTH; } void fix_length_and_dec() - { maybe_null= 1; } + { set_persist_maybe_null(1); } /* Mark that collation can change between calls */ bool dynamic_result() { return 1; } @@ -956,7 +957,8 @@ class Item_func_dyncol_list: public Item_str_func { public: Item_func_dyncol_list(Item *str) :Item_str_func(str) {}; - void fix_length_and_dec() { maybe_null= 1; max_length= MAX_BLOB_WIDTH; }; + void fix_length_and_dec() + { set_persist_maybe_null(1); max_length= MAX_BLOB_WIDTH; }; const char *func_name() const{ return "column_list"; } String *val_str(String *); }; diff --git a/sql/item_timefunc.cc b/sql/item_timefunc.cc index bdad96f12ef..eaddd39fa58 100644 --- a/sql/item_timefunc.cc +++ b/sql/item_timefunc.cc @@ -877,7 +877,7 @@ void Item_func_monthname::fix_length_and_dec() collation.set(cs, DERIVATION_COERCIBLE, repertoire); decimals=0; max_length= locale->max_month_name_length * collation.collation->mbmaxlen; - maybe_null=1; + set_persist_maybe_null(1); } @@ -1030,7 +1030,7 @@ void Item_func_dayname::fix_length_and_dec() collation.set(cs, DERIVATION_COERCIBLE, repertoire); decimals=0; max_length= locale->max_day_name_length * collation.collation->mbmaxlen; - maybe_null=1; + set_persist_maybe_null(1); } @@ -1404,7 +1404,7 @@ void Item_func_curdate::fix_length_and_dec() ltime.hour= ltime.minute= ltime.second= 0; ltime.time_type= MYSQL_TIMESTAMP_DATE; Item_datefunc::fix_length_and_dec(); - maybe_null= false; + set_persist_maybe_null(0); } /** @@ -1643,7 +1643,7 @@ void Item_func_date_format::fix_length_and_dec() collation.collation->mbmaxlen; set_if_smaller(max_length,MAX_BLOB_WIDTH); } - maybe_null=1; // If wrong date + set_persist_maybe_null(1); // If wrong date } @@ -1992,7 +1992,7 @@ void Item_extract::print(String *str, enum_query_type query_type) void Item_extract::fix_length_and_dec() { - maybe_null=1; // If wrong date + set_persist_maybe_null(1); // If wrong date switch (int_type) { case INTERVAL_YEAR: max_length=4; date_value=1; break; case INTERVAL_YEAR_MONTH: max_length=6; date_value=1; break; diff --git a/sql/item_timefunc.h b/sql/item_timefunc.h index 8d19e59ddfb..25a160d91f6 100644 --- a/sql/item_timefunc.h +++ b/sql/item_timefunc.h @@ -67,7 +67,7 @@ public: { decimals=0; max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } enum_monotonicity_info get_monotonicity_info() const; longlong val_int_endpoint(bool left_endp, bool *incl_endp); @@ -90,7 +90,7 @@ public: { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -123,7 +123,7 @@ public: collation.set(&my_charset_bin); decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -158,7 +158,7 @@ public: { decimals=0; max_length=3*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -179,7 +179,7 @@ public: { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -200,7 +200,7 @@ public: { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -221,7 +221,7 @@ public: { decimals=0; max_length=1*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -242,7 +242,7 @@ public: { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -263,7 +263,7 @@ public: { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } }; @@ -277,7 +277,7 @@ public: { decimals=0; max_length=6*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -300,7 +300,7 @@ public: { decimals=0; max_length=4*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -335,7 +335,7 @@ public: collation.set(&my_charset_bin); decimals=0; max_length=1*MY_CHARSET_BIN_MB_MAXLEN; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -415,7 +415,7 @@ public: const char *func_name() const { return "time_to_sec"; } void fix_num_length_and_dec() { - maybe_null= true; + set_persist_maybe_null(1); Item_func_seconds_hybrid::fix_num_length_and_dec(); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} @@ -454,7 +454,7 @@ public: { MAX_DATETIME_WIDTH, MAX_DATETIME_WIDTH, MAX_DATE_WIDTH, MAX_DATETIME_WIDTH, MIN_TIME_WIDTH }; - maybe_null= true; + set_persist_maybe_null(1); max_length= max_time_type_width[mysql_type_to_time_type(field_type())+2]; if (decimals) { @@ -470,7 +470,7 @@ public: We set maybe_null to 1 as default as any bad argument with date or time can get us to return NULL. */ - maybe_null= 1; + set_persist_maybe_null(1); } }; @@ -507,7 +507,7 @@ public: { store_now_in_TIME(<ime); Item_timefunc::fix_length_and_dec(); - maybe_null= false; + set_persist_maybe_null(0); } bool get_date(MYSQL_TIME *res, uint fuzzy_date); /* @@ -589,7 +589,7 @@ public: { store_now_in_TIME(<ime); Item_temporal_func::fix_length_and_dec(); - maybe_null= false; + set_persist_maybe_null(0); } bool get_date(MYSQL_TIME *res, uint fuzzy_date); virtual void store_now_in_TIME(MYSQL_TIME *now_time)=0; @@ -930,7 +930,7 @@ public: void fix_length_and_dec() { decimals=0; - maybe_null=1; + set_persist_maybe_null(1); } bool check_partition_func_processor(uchar *int_arg) {return FALSE;} bool check_vcol_func_processor(uchar *int_arg) { return FALSE;} @@ -952,7 +952,7 @@ public: void fix_length_and_dec() { decimals=0; - maybe_null=1; + set_persist_maybe_null(1); } virtual void print(String *str, enum_query_type query_type); }; @@ -974,7 +974,7 @@ public: const char *func_name() const { return "get_format"; } void fix_length_and_dec() { - maybe_null= 1; + set_persist_maybe_null(1); decimals=0; max_length=17*MY_CHARSET_BIN_MB_MAXLEN; } diff --git a/sql/item_xmlfunc.cc b/sql/item_xmlfunc.cc index 57995b2b643..faf5f345171 100644 --- a/sql/item_xmlfunc.cc +++ b/sql/item_xmlfunc.cc @@ -2579,6 +2579,7 @@ void Item_xml_str_func::fix_length_and_dec() int rc; nodeset_func= 0; + set_persist_maybe_null(1); if (agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1)) return; diff --git a/sql/item_xmlfunc.h b/sql/item_xmlfunc.h index ce33d161c79..be56a83349f 100644 --- a/sql/item_xmlfunc.h +++ b/sql/item_xmlfunc.h @@ -30,14 +30,10 @@ protected: public: Item_xml_str_func(Item *a, Item *b): Item_str_func(a,b) - { - maybe_null= TRUE; - } + {} Item_xml_str_func(Item *a, Item *b, Item *c): Item_str_func(a,b,c) - { - maybe_null= TRUE; - } + {} void fix_length_and_dec(); String *parse_xml(String *raw_xml, String *parsed_xml_buf); bool check_vcol_func_processor(uchar *int_arg) -- cgit v1.2.1 From 78d9fdb134c58ccf792fdec2bb745cb5ff6ec2ec Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Mon, 7 Jan 2013 20:21:05 +0100 Subject: non-functional cleanup, clarifying CONVERT_IF_BIGGER_TO_BLOB --- sql/item.cc | 6 +++--- sql/item.h | 2 ++ sql/item_sum.h | 2 +- sql/opt_subselect.cc | 4 ++-- sql/sql_const.h | 4 ++-- sql/sql_select.cc | 2 +- 6 files changed, 11 insertions(+), 9 deletions(-) (limited to 'sql') diff --git a/sql/item.cc b/sql/item.cc index bc98a9a3184..8be339541e1 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -5579,7 +5579,7 @@ bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs) /** Create a field to hold a string value from an item. - If max_length > CONVERT_IF_BIGGER_TO_BLOB create a blob @n + If too_big_for_varchar() create a blob @n If max_length > 0 create a varchar @n If max_length == 0 create a CHAR(0) @@ -5594,7 +5594,7 @@ Field *Item::make_string_field(TABLE *table) Note: the following check is repeated in subquery_types_allow_materialization(): */ - if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB) + if (too_big_for_varchar()) field= new Field_blob(max_length, maybe_null, name, collation.collation, TRUE); /* Item_type_holder holds the exact type, do not change it */ @@ -5699,7 +5699,7 @@ Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length) DBUG_ASSERT(0); /* If something goes awfully wrong, it's better to get a string than die */ case MYSQL_TYPE_STRING: - if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB) + if (fixed_length && !too_big_for_varchar()) { field= new Field_string(max_length, maybe_null, name, collation.collation); diff --git a/sql/item.h b/sql/item.h index 3136bb00394..42815c34286 100644 --- a/sql/item.h +++ b/sql/item.h @@ -1424,6 +1424,8 @@ public: bool eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs); uint32 max_char_length() const { return max_length / collation.collation->mbmaxlen; } + bool too_big_for_varchar() const + { return max_char_length() > CONVERT_IF_BIGGER_TO_BLOB; } void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs) { max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen); diff --git a/sql/item_sum.h b/sql/item_sum.h index c8dce60c7d4..40a28d8beae 100644 --- a/sql/item_sum.h +++ b/sql/item_sum.h @@ -1439,7 +1439,7 @@ public: virtual Field *make_string_field(TABLE *table); enum_field_types field_type() const { - if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB ) + if (too_big_for_varchar()) return MYSQL_TYPE_BLOB; else return MYSQL_TYPE_VARCHAR; diff --git a/sql/opt_subselect.cc b/sql/opt_subselect.cc index e70e5a784ba..753722fac08 100644 --- a/sql/opt_subselect.cc +++ b/sql/opt_subselect.cc @@ -853,8 +853,7 @@ bool subquery_types_allow_materialization(Item_in_subselect *in_subs) create a blob column because item->max_length is too big. The following check is copied from Item::make_string_field(): */ - if (inner->max_length / inner->collation.collation->mbmaxlen > - CONVERT_IF_BIGGER_TO_BLOB) + if (inner->too_big_for_varchar()) { DBUG_RETURN(FALSE); } @@ -3865,6 +3864,7 @@ SJ_TMP_TABLE::create_sj_weedout_tmp_table(THD *thd) fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME); /* STEP 2: Figure if we'll be using a key or blob+constraint */ + /* it always has my_charset_bin, so mbmaxlen==1 */ if (uniq_tuple_length_arg >= CONVERT_IF_BIGGER_TO_BLOB) using_unique_constraint= TRUE; diff --git a/sql/sql_const.h b/sql/sql_const.h index cfbf077bd91..de2704a8553 100644 --- a/sql/sql_const.h +++ b/sql/sql_const.h @@ -42,8 +42,8 @@ #define MAX_MBWIDTH 3 /* Max multibyte sequence */ #define MAX_FIELD_CHARLENGTH 255 #define MAX_FIELD_VARCHARLENGTH 65535 -#define MAX_FIELD_BLOBLENGTH UINT_MAX32 /* cf field_blob::get_length() */ -#define CONVERT_IF_BIGGER_TO_BLOB 512 /* Used for CREATE ... SELECT */ +#define MAX_FIELD_BLOBLENGTH UINT_MAX32 /* cf field_blob::get_length() */ +#define CONVERT_IF_BIGGER_TO_BLOB 512 /* Threshold *in characters* */ /* Max column width +1 */ #define MAX_FIELD_WIDTH (MAX_FIELD_CHARLENGTH*MAX_MBWIDTH+1) diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 8914341e0f3..424d2d4a56b 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -14185,7 +14185,7 @@ create_tmp_table(THD *thd, TMP_TABLE_PARAM *param, List &fields, can't index BIT fields. */ (*tmp->item)->marker=4; // Store null in key - if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB) + if ((*tmp->item)->too_big_for_varchar()) using_unique_constraint=1; } if (param->group_length >= MAX_BLOB_WIDTH) -- cgit v1.2.1 From 8aaacc9102b3d536cc2682fe429c5023956a6eea Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 8 Jan 2013 21:21:28 +0100 Subject: MDEV-3987 uninitialized read in Item_cond::fix_fields leads to crash: select .. where .. in ( select ... ) change Item_func_group_concat to use max_length according to the expected semantics --- sql/item.h | 8 ++++++-- sql/item_sum.cc | 25 ++++++++++--------------- 2 files changed, 16 insertions(+), 17 deletions(-) (limited to 'sql') diff --git a/sql/item.h b/sql/item.h index 42815c34286..0d38c5eb5f8 100644 --- a/sql/item.h +++ b/sql/item.h @@ -2,7 +2,7 @@ #define SQL_ITEM_INCLUDED /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2009-2011 Monty Program Ab + Copyright (c) 2009, 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -611,7 +611,11 @@ public: @see Query_arena::free_list */ Item *next; - uint32 max_length; /* Maximum length, in bytes */ + /* + The maximum value length in characters multiplied by collation->mbmaxlen. + Almost always it's the maximum value length in bytes. + */ + uint32 max_length; /* TODO: convert name and name_length fields into LEX_STRING to keep them in sync (see bug #11829681/60295 etc). Then also remove some strlen(name) diff --git a/sql/item_sum.cc b/sql/item_sum.cc index b04fda55736..e00ef3e592c 100644 --- a/sql/item_sum.cc +++ b/sql/item_sum.cc @@ -1,5 +1,5 @@ /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2008-2011 Monty Program Ab + Copyright (c) 2008, 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -2986,6 +2986,7 @@ int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)), { Item_func_group_concat *item= (Item_func_group_concat *) item_arg; TABLE *table= item->table; + uint max_length= table->in_use->variables.group_concat_max_len; String tmp((char *)table->record[1], table->s->reclength, default_charset_info); String tmp2; @@ -3028,7 +3029,7 @@ int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)), item->row_count++; /* stop if length of result more than max_length */ - if (result->length() > item->max_length) + if (result->length() > max_length) { int well_formed_error; CHARSET_INFO *cs= item->collation.collation; @@ -3041,7 +3042,7 @@ int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)), */ add_length= cs->cset->well_formed_len(cs, ptr + old_length, - ptr + item->max_length, + ptr + max_length, result->length(), &well_formed_error); result->length(old_length + add_length); @@ -3205,19 +3206,11 @@ Field *Item_func_group_concat::make_string_field(TABLE *table) { Field *field; DBUG_ASSERT(collation.collation); - /* - max_characters is maximum number of characters - what can fit into max_length size. It's necessary - to use field size what allows to store group_concat - result without truncation. For this purpose we use - max_characters * CS->mbmaxlen. - */ - const uint32 max_characters= max_length / collation.collation->mbminlen; - if (max_characters > CONVERT_IF_BIGGER_TO_BLOB) - field= new Field_blob(max_characters * collation.collation->mbmaxlen, + if (too_big_for_varchar()) + field= new Field_blob(max_length, maybe_null, name, collation.collation, TRUE); else - field= new Field_varstring(max_characters * collation.collation->mbmaxlen, + field= new Field_varstring(max_length, maybe_null, name, table->s, collation.collation); if (field) @@ -3332,7 +3325,9 @@ Item_func_group_concat::fix_fields(THD *thd, Item **ref) result.set_charset(collation.collation); result_field= 0; null_value= 1; - max_length= thd->variables.group_concat_max_len; + max_length= thd->variables.group_concat_max_len + / collation.collation->mbminlen + * collation.collation->mbmaxlen; uint32 offset; if (separator->needs_conversion(separator->length(), separator->charset(), -- cgit v1.2.1 From b0ee31c89480519490537b89dca1e8cc65e2b73b Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 8 Jan 2013 21:23:03 +0100 Subject: MDEV-3942 FROM_DAYS() returns different result in MariaDB comparing to MySQL: NULL vs 0000-00-00 fixed a regression, introduced while fixing MDEV-456 --- sql/item_timefunc.cc | 8 +++----- sql/time.cc | 4 ++-- 2 files changed, 5 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/item_timefunc.cc b/sql/item_timefunc.cc index eaddd39fa58..9f2f9b2950d 100644 --- a/sql/item_timefunc.cc +++ b/sql/item_timefunc.cc @@ -1,5 +1,6 @@ /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. + Copyright (c) 2010, 2013, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -1386,13 +1387,10 @@ bool Item_func_from_days::get_date(MYSQL_TIME *ltime, uint fuzzy_date) if (get_date_from_daynr((long) value, <ime->year, <ime->month, <ime->day)) - return (null_value= 1); - - if ((fuzzy_date & TIME_NO_ZERO_DATE) && ltime->year == 0) - return (null_value= 1); + return 0; ltime->time_type= MYSQL_TIMESTAMP_DATE; - return (null_value= 0); + return 0; } diff --git a/sql/time.cc b/sql/time.cc index 21ecc3f8050..3b1613282fb 100644 --- a/sql/time.cc +++ b/sql/time.cc @@ -1,6 +1,6 @@ /* Copyright (c) 2000-2007 MySQL AB, 2009 Sun Microsystems, Inc. - Copyright (c) 2009-2011 Monty Program Ab + Copyright (c) 2009-2013 Monty Program Ab Use is subject to license terms. This program is free software; you can redistribute it and/or modify @@ -153,7 +153,7 @@ bool get_date_from_daynr(long daynr,uint *ret_year,uint *ret_month, uchar *month_pos; DBUG_ENTER("get_date_from_daynr"); - if (daynr < 365 || daynr > MAX_DAY_NUMBER) + if (daynr < 366 || daynr > MAX_DAY_NUMBER) DBUG_RETURN(1); year= (uint) (daynr*100 / 36525L); -- cgit v1.2.1 From a128c50ac1b0d93f804aee98066588183c347607 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 8 Jan 2013 21:23:40 +0100 Subject: MDEV-3883 Show global status not in order --- sql/log.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index 70e74de5a31..b7218615f58 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -1,5 +1,5 @@ /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. - Copyright (c) 2010-2011 Monty Program Ab + Copyright (c) 2010, 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -7665,7 +7665,7 @@ static int show_binlog_vars(THD *thd, SHOW_VAR *var, char *buff) } static SHOW_VAR binlog_status_vars_top[]= { - {"binlog", (char *) &show_binlog_vars, SHOW_FUNC}, + {"Binlog", (char *) &show_binlog_vars, SHOW_FUNC}, {NullS, NullS, SHOW_LONG} }; -- cgit v1.2.1 From c9ff25f568df9112cb581348e865c79d8d663b4a Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 9 Jan 2013 17:29:51 +0100 Subject: MDEV-3985 crash: uninstall soname 'a' --- sql/sql_plugin.cc | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) (limited to 'sql') diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index dee48a28037..3d529c7a332 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -1,6 +1,6 @@ /* Copyright (c) 2005, 2012, Oracle and/or its affiliates. - Copyright (c) 2010, 2011, Monty Program Ab + Copyright (c) 2010, 2013, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -2260,11 +2260,19 @@ bool mysql_uninstall_plugin(THD *thd, const LEX_STRING *name, { fix_dl_name(thd->mem_root, &dl); st_plugin_dl *plugin_dl= plugin_dl_find(&dl); - struct st_maria_plugin *plugin; - for (plugin= plugin_dl->plugins; plugin->info; plugin++) + if (plugin_dl) { - LEX_STRING str= { const_cast(plugin->name), strlen(plugin->name) }; - error|= do_uninstall(thd, table, &str); + for (struct st_maria_plugin *plugin= plugin_dl->plugins; + plugin->info; plugin++) + { + LEX_STRING str= { const_cast(plugin->name), strlen(plugin->name) }; + error|= do_uninstall(thd, table, &str); + } + } + else + { + my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "SONAME", dl.str); + error= true; } } reap_plugins(); -- cgit v1.2.1 From d27d9d76a8c13f339b6789c02d3e6eb71bdbf497 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 9 Jan 2013 22:32:21 +0200 Subject: fixed feature counter. --- sql/item_strfunc.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 8ea19078524..53a7b9a1fca 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -3805,7 +3805,7 @@ bool Item_func_dyncol_create::fix_fields(THD *thd, Item **ref) sizeof(uint)) * (arg_count / 2)); keys_str= (LEX_STRING *) keys_num; - //status_var_increment(thd->status_var.feature_dynamic_columns); + status_var_increment(thd->status_var.feature_dynamic_columns); } return res || vals == 0 || keys_num == 0; } -- cgit v1.2.1 From 363436ede1abb1afcb679db351991b9bbe9ad70b Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 10 Jan 2013 00:07:44 +0200 Subject: Make cassandra module and do not load it by default. --- sql/sql_plugin.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index e15f6339847..45e8adf1f5f 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -175,7 +175,8 @@ static struct /* we disable few other plugins by default */ { "ndbcluster", PLUGIN_OFF }, { "feedback", PLUGIN_OFF }, - { "pbxt", PLUGIN_OFF } + { "pbxt", PLUGIN_OFF }, + { "cassandra", PLUGIN_OFF } }; /* support for Services */ -- cgit v1.2.1 From cd2f2c539566d907405cc9225b4a0c82d6e24563 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 10 Jan 2013 13:47:47 +0200 Subject: append_identifier() declaration fixed. --- sql/item_strfunc.cc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 53a7b9a1fca..a2bbdd63b40 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -57,6 +57,7 @@ C_MODE_START #include "../mysys/my_static.h" // For soundex_map C_MODE_END +#include "sql_show.h" // append_identifier /** @todo Remove this. It is not safe to use a shared String object. @@ -4664,9 +4665,6 @@ null: return 1; } -void -append_identifier(THD *thd, String *packet, const char *name, uint length); - void Item_dyncol_get::print(String *str, enum_query_type query_type) { str->append(STRING_WITH_LEN("column_get(")); -- cgit v1.2.1 From 7b81b641665fcba5aaaebe179c4ebf30c00143df Mon Sep 17 00:00:00 2001 From: Sergey Petrunya Date: Thu, 10 Jan 2013 17:10:58 +0400 Subject: MDEV-3982: show_explain.test fails, times out or crashes Backport the fix from 10.0 tree - The problem was that thd_killed() may be called by innodb from an internal innodb thread. - Fixed by not processing APC requests when we're not in the thread that owns the APC target. --- sql/sql_class.cc | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 5da1cbc90cc..d6a0eaf9b52 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -3860,12 +3860,16 @@ void THD::restore_backup_open_tables_state(Open_tables_backup *backup) extern "C" int thd_killed(const MYSQL_THD thd) { + THD* current= current_thd; if (!thd) thd= current_thd; - Apc_target *apc_target= (Apc_target*)&thd->apc_target; - if (apc_target->have_apc_requests()) - apc_target->process_apc_requests(); + if (thd == current) + { + Apc_target *apc_target= (Apc_target*)&thd->apc_target; + if (apc_target->have_apc_requests()) + apc_target->process_apc_requests(); + } if (!(thd->killed & KILL_HARD_BIT)) return 0; -- cgit v1.2.1 From 396f4d62c69335b8f7aefd43bbe099e8bb9e6905 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Thu, 10 Jan 2013 23:40:18 +0200 Subject: Fix for MDEV-4009: main.delayed sporadically fails with "query 'REPLACE DELAYED t1 VALUES (5)' failed: 1317: Query execution was interrupted" - Fixed broadcast without a proper mutex - Don't break existing locks if we are just testing if we can get the lock mysql-test/r/create_delayed.result: Added test case for failures with INSERT DELAYED with CREATE and DROP TABLE mysql-test/t/create_delayed.test: Added test case for failures with INSERT DELAYED with CREATE and DROP TABLE sql/mdl.cc: Don't break existing locks for timeout=0 (ie, just check if there are conflicting locks). This fixed the bug that INSERT DELAYED didn't work properly with CREATE TABLE sql/sql_base.cc: One neads to hold the mutex before doing a mysql_cond_broadcast() This fixed the bug that INSERT DELAYED didn't work properly with DROP TABLE sql/sql_insert.cc: Protect setting of mysys_var->current_mutex. --- sql/mdl.cc | 6 +++++- sql/sql_base.cc | 4 ++++ sql/sql_insert.cc | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/mdl.cc b/sql/mdl.cc index 5e297051377..a2113909116 100644 --- a/sql/mdl.cc +++ b/sql/mdl.cc @@ -2078,7 +2078,11 @@ MDL_context::acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout) */ m_wait.reset_status(); - if (lock->needs_notification(ticket)) + /* + Don't break conflicting locks if timeout is 0 as 0 is used + To check if there is any conflicting locks... + */ + if (lock->needs_notification(ticket) && lock_wait_timeout) lock->notify_conflicting_locks(this); mysql_prlock_unlock(&lock->m_rwlock); diff --git a/sql/sql_base.cc b/sql/sql_base.cc index c7f93c955f3..83ed29064b5 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -9299,7 +9299,11 @@ bool mysql_notify_thread_having_shared_lock(THD *thd, THD *in_use, in_use->killed= KILL_SYSTEM_THREAD; mysql_mutex_lock(&in_use->mysys_var->mutex); if (in_use->mysys_var->current_cond) + { + mysql_mutex_lock(in_use->mysys_var->current_mutex); mysql_cond_broadcast(in_use->mysys_var->current_cond); + mysql_mutex_unlock(in_use->mysys_var->current_mutex); + } mysql_mutex_unlock(&in_use->mysys_var->mutex); signalled= TRUE; } diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index 231671d172b..f18a9548704 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2823,8 +2823,12 @@ pthread_handler_t handle_delayed_insert(void *arg) set_timespec(abstime, delayed_insert_timeout); /* Information for pthread_kill */ + mysql_mutex_unlock(&di->mutex); + mysql_mutex_lock(&di->thd.mysys_var->mutex); di->thd.mysys_var->current_mutex= &di->mutex; di->thd.mysys_var->current_cond= &di->cond; + mysql_mutex_unlock(&di->thd.mysys_var->mutex); + mysql_mutex_lock(&di->mutex); thd_proc_info(&(di->thd), "Waiting for INSERT"); DBUG_PRINT("info",("Waiting for someone to insert rows")); -- cgit v1.2.1 From 6e9a48b67fceab17089ca4cd1406e302386a601b Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Fri, 11 Jan 2013 00:22:14 +0200 Subject: Fixed some race conditons and bugs related to killed queries KILL now breaks locks inside InnoDB Fixed possible deadlock when running INNODB STATUS Added ha_kill_query() and kill_query() to send kill signal to all storage engines Added reset_killed() to ensure we don't reset killed state while awake() is getting called include/mysql/plugin.h: Added thd_mark_as_hard_kill() include/mysql/plugin_audit.h.pp: Added thd_mark_as_hard_kill() include/mysql/plugin_auth.h.pp: Added thd_mark_as_hard_kill() include/mysql/plugin_ftparser.h.pp: Added thd_mark_as_hard_kill() sql/handler.cc: Added ha_kill_query() to send kill signal to all storage engines sql/handler.h: Added ha_kill_query() and kill_query() to send kill signal to all storage engines sql/log_event.cc: Use reset_killed() sql/mdl.cc: use thd->killed instead of thd_killed() to abort on soft kill sql/sp_rcontext.cc: Use reset_killed() sql/sql_class.cc: Fixed possible deadlock in INNODB STATUS by not getting thd->LOCK_thd_data if it's locked. Use reset_killed() Tell storge engines that KILL has been sent sql/sql_class.h: Added reset_killed() to ensure we don't reset killed state while awake() is getting called. Added mark_as_hard_kill() sql/sql_insert.cc: Use reset_killed() sql/sql_parse.cc: Simplify detection of killed queries. Use reset_killed() sql/sql_select.cc: Use reset_killed() sql/sql_union.cc: Use reset_killed() storage/innobase/handler/ha_innodb.cc: Added innobase_kill_query() Fixed error reporting for interrupted queries. storage/xtradb/handler/ha_innodb.cc: Added innobase_kill_query() Fixed error reporting for interrupted queries. --- sql/handler.cc | 21 ++++++++++++++++++++- sql/handler.h | 8 ++++++++ sql/log_event.cc | 2 +- sql/mdl.cc | 6 +++--- sql/sp_rcontext.cc | 2 +- sql/sql_class.cc | 44 ++++++++++++++++++++++++++++++-------------- sql/sql_class.h | 24 ++++++++++++++++++++++++ sql/sql_insert.cc | 5 ++++- sql/sql_parse.cc | 22 +++++++++++++--------- sql/sql_select.cc | 4 ++-- sql/sql_union.cc | 2 +- 11 files changed, 107 insertions(+), 33 deletions(-) (limited to 'sql') diff --git a/sql/handler.cc b/sql/handler.cc index 356ae330201..5108e3abc40 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -663,7 +663,6 @@ static my_bool closecon_handlerton(THD *thd, plugin_ref plugin, return FALSE; } - /** @note don't bother to rollback here, it's done already @@ -673,6 +672,26 @@ void ha_close_connection(THD* thd) plugin_foreach(thd, closecon_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, 0); } +static my_bool kill_handlerton(THD *thd, plugin_ref plugin, + void *hard_kill) +{ + handlerton *hton= plugin_data(plugin, handlerton *); + + if (hton->state == SHOW_OPTION_YES && hton->kill_query && + thd_get_ha_data(thd, hton)) + hton->kill_query(hton, thd, * (my_bool*) hard_kill); + return FALSE; +} + +void ha_kill_query(THD* thd, my_bool hard_kill) +{ + DBUG_ENTER("ha_kill_query"); + plugin_foreach(thd, kill_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, + &hard_kill); + DBUG_VOID_RETURN; +} + + /* ======================================================================== ======================= TRANSACTIONS ===================================*/ diff --git a/sql/handler.h b/sql/handler.h index 4a6fc2f1bd5..e5da92b0d40 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -864,6 +864,13 @@ struct handlerton this storage engine was accessed in this connection */ int (*close_connection)(handlerton *hton, THD *thd); + /* + Tell handler that query has been killed. + hard_kill is set in case of HARD KILL (abort query even if + it may corrupt table). + Return 1 if the handler wants to upgrade the kill to a hard kill + */ + void (*kill_query)(handlerton *hton, THD *thd, my_bool hard_kill); /* sv points to an uninitialized storage area of requested size (see savepoint_offset description) @@ -2975,6 +2982,7 @@ int ha_finalize_handlerton(st_plugin_int *plugin); TYPELIB *ha_known_exts(void); int ha_panic(enum ha_panic_function flag); void ha_close_connection(THD* thd); +void ha_kill_query(THD* thd, my_bool hard_kill); bool ha_flush_logs(handlerton *db_type); void ha_drop_database(char* path); void ha_checkpoint_state(bool disable); diff --git a/sql/log_event.cc b/sql/log_event.cc index 6fc116d2b92..a46da2304b2 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -3884,7 +3884,7 @@ Default database: '%s'. Query: '%s'", { DBUG_PRINT("info",("error ignored")); clear_all_errors(thd, const_cast(rli)); - thd->killed= NOT_KILLED; + thd->reset_killed(); } /* Other cases: mostly we expected no error and get one. diff --git a/sql/mdl.cc b/sql/mdl.cc index a2113909116..415d56887d5 100644 --- a/sql/mdl.cc +++ b/sql/mdl.cc @@ -14,7 +14,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "mdl.h" +#include "sql_class.h" #include "debug_sync.h" #include #include @@ -1185,7 +1185,7 @@ MDL_wait::timed_wait(THD *thd, struct timespec *abs_timeout, wait_state_name); thd_wait_begin(thd, THD_WAIT_META_DATA_LOCK); - while (!m_wait_status && !thd_killed(thd) && + while (!m_wait_status && !thd->killed && wait_result != ETIMEDOUT && wait_result != ETIME) { wait_result= mysql_cond_timedwait(&m_COND_wait_status, &m_LOCK_wait_status, @@ -1207,7 +1207,7 @@ MDL_wait::timed_wait(THD *thd, struct timespec *abs_timeout, false, which means that the caller intends to restart the wait. */ - if (thd_killed(thd)) + if (thd->killed) m_wait_status= KILLED; else if (set_status_on_timeout) m_wait_status= TIMEOUT; diff --git a/sql/sp_rcontext.cc b/sql/sp_rcontext.cc index 6fe4be989db..d78f2a162f5 100644 --- a/sql/sp_rcontext.cc +++ b/sql/sp_rcontext.cc @@ -419,7 +419,7 @@ sp_rcontext::activate_handler(THD *thd, /* Reset error state. */ thd->clear_error(); - thd->killed= NOT_KILLED; // Some errors set thd->killed + thd->reset_killed(); // Some errors set thd->killed // (e.g. "bad data"). /* Return IP of the activated SQL handler. */ diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 42952585e07..312de8c74e4 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -701,7 +701,7 @@ char *thd_security_context(THD *thd, char *buffer, unsigned int length, values doesn't have to very accurate and the memory it points to is static, but we need to attempt a snapshot on the pointer values to avoid using NULL values. The pointer to thd->query however, doesn't point to static memory - and has to be protected by LOCK_thread_count or risk pointing to + and has to be protected by thd->LOCK_thd_data or risk pointing to uninitialized memory. */ const char *proc_info= thd->proc_info; @@ -736,20 +736,21 @@ char *thd_security_context(THD *thd, char *buffer, unsigned int length, str.append(proc_info); } - mysql_mutex_lock(&thd->LOCK_thd_data); - - if (thd->query()) + /* Don't wait if LOCK_thd_data is used as this could cause a deadlock */ + if (!mysql_mutex_trylock(&thd->LOCK_thd_data)) { - if (max_query_len < 1) - len= thd->query_length(); - else - len= min(thd->query_length(), max_query_len); - str.append('\n'); - str.append(thd->query(), len); + if (thd->query()) + { + if (max_query_len < 1) + len= thd->query_length(); + else + len= min(thd->query_length(), max_query_len); + str.append('\n'); + str.append(thd->query(), len); + } + mysql_mutex_unlock(&thd->LOCK_thd_data); } - mysql_mutex_unlock(&thd->LOCK_thd_data); - if (str.c_ptr_safe() == buffer) return buffer; @@ -1355,7 +1356,7 @@ void THD::change_user(void) mysql_mutex_unlock(&LOCK_status); cleanup(); - killed= NOT_KILLED; + reset_killed(); cleanup_done= 0; init(); stmt_map.reset(); @@ -1610,6 +1611,10 @@ void THD::awake(killed_state state_to_set) MYSQL_CALLBACK(scheduler, post_kill_notification, (this)); } + /* Interrupt target waiting inside a storage engine. */ + if (state_to_set != NOT_KILLED) + ha_kill_query(this, test(state_to_set & KILL_HARD_BIT)); + /* Broadcast a condition to kick the target if it is waiting on it. */ if (mysys_var) { @@ -3848,6 +3853,18 @@ extern "C" int thd_killed(const MYSQL_THD thd) return thd->killed; } +/** + Change kill level to hard. + This ensures that thd_killed() will return true. + This is important for storage engines that uses thd_killed() to + verify if thread is killed. +*/ + +extern "C" void thd_mark_as_hard_kill(MYSQL_THD thd) +{ + thd->mark_as_hard_kill(); +} + /** Send an out-of-band progress report to the client @@ -5603,4 +5620,3 @@ bool Discrete_intervals_list::append(Discrete_interval *new_interval) } #endif /* !defined(MYSQL_CLIENT) */ - diff --git a/sql/sql_class.h b/sql/sql_class.h index f50d1442a3f..2561effb478 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -2703,6 +2703,19 @@ public: { return ::killed_errno(killed); } + inline void reset_killed() + { + /* + Resetting killed has to be done under a mutex to ensure + its not done during an awake() call. + */ + if (killed != NOT_KILLED) + { + mysql_mutex_lock(&LOCK_thd_data); + killed= NOT_KILLED; + mysql_mutex_unlock(&LOCK_thd_data); + } + } inline void send_kill_message() const { int err= killed_errno(); @@ -2716,6 +2729,17 @@ public: (!transaction.stmt.modified_non_trans_table || (variables.sql_mode & MODE_STRICT_ALL_TABLES))); } + /* + Increase level of kill ; Ensures that thd_killed() returns true. + + Needed if storage engine wants to abort things because of a 'soft' (ie, + safe) kill but still uses thd_killed() to check if it's killed. + */ + inline void mark_as_hard_kill() + { + DBUG_ASSERT(killed != NOT_KILLED); + killed= (killed_state) (killed | KILL_HARD_BIT); + } void set_status_var_init(); void reset_n_backup_open_tables_state(Open_tables_backup *backup); void restore_backup_open_tables_state(Open_tables_backup *backup); diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index f18a9548704..ef3f81f18c5 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2724,7 +2724,10 @@ pthread_handler_t handle_delayed_insert(void *arg) thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; thd->set_current_time(); threads.append(thd); - thd->killed=abort_loop ? KILL_CONNECTION : NOT_KILLED; + if (abort_loop) + thd->killed= KILL_CONNECTION; + else + thd->reset_killed(); mysql_mutex_unlock(&LOCK_thread_count); mysql_thread_set_psi_id(thd->thread_id); diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index de35d2f3d27..2ae4adb4e33 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -4495,16 +4495,20 @@ finish: if (! thd->in_sub_stmt) { - /* report error issued during command execution */ - if (thd->killed_errno()) + if (thd->killed != NOT_KILLED) { - if (! thd->stmt_da->is_set()) - thd->send_kill_message(); - } - if (thd->killed < KILL_CONNECTION) - { - thd->killed= NOT_KILLED; - thd->mysys_var->abort= 0; + /* report error issued during command execution */ + if (thd->killed_errno()) + { + /* If we already sent 'ok', we can ignore any kill query statements */ + if (! thd->stmt_da->is_set()) + thd->send_kill_message(); + } + if (thd->killed < KILL_CONNECTION) + { + thd->reset_killed(); + thd->mysys_var->abort= 0; + } } if (thd->is_error() || (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR)) trans_rollback_stmt(thd); diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 424d2d4a56b..9bbc139927e 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -331,7 +331,7 @@ bool handle_select(THD *thd, LEX *lex, select_result *result, ER(ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT), thd->accessed_rows_and_keys, thd->lex->limit_rows_examined->val_uint()); - thd->killed= NOT_KILLED; + thd->reset_killed(); } /* Disable LIMIT ROWS EXAMINED after query execution. */ thd->lex->limit_rows_examined_cnt= ULONGLONG_MAX; @@ -19213,7 +19213,7 @@ remove_duplicates(JOIN *join, TABLE *entry,List &fields, Item *having) */ thd->lex->limit_rows_examined_cnt= ULONGLONG_MAX; if (thd->killed == ABORT_QUERY) - thd->killed= NOT_KILLED; + thd->reset_killed(); free_io_cache(entry); // Safety entry->file->info(HA_STATUS_VARIABLE); if (entry->s->db_type() == heap_hton || diff --git a/sql/sql_union.cc b/sql/sql_union.cc index 8dcae907926..77d4df1b398 100644 --- a/sql/sql_union.cc +++ b/sql/sql_union.cc @@ -716,7 +716,7 @@ bool st_select_lex_unit::exec() ER(ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT), thd->accessed_rows_and_keys, thd->lex->limit_rows_examined->val_uint()); - thd->killed= NOT_KILLED; + thd->reset_killed(); break; } } -- cgit v1.2.1 From a42e1e3885ce4519bb5db2f02f2448d0a29cd7a7 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Fri, 11 Jan 2013 00:35:33 +0200 Subject: Fixed MDEV-4013: Password length in replication setup Give error for wrong parameters to CHANGE MASTER Extend MASTER_PASSWORD and MASTER_HOST lengths mysql-test/suite/rpl/r/rpl_password_boundaries.result: Test length of MASTER_PASSWORD, MASTER_HOST and MASTER_USER mysql-test/suite/rpl/r/rpl_semi_sync.result: Use different password than user name for better test coverage mysql-test/suite/rpl/t/rpl_password_boundaries.test: Test length of MASTER_PASSWORD, MASTER_HOST and MASTER_USER mysql-test/suite/rpl/t/rpl_semi_sync.test: Use different password than user name for better test coverage sql/rpl_mi.h: Extend MASTER_PASSWORD and MASTER_HOST lengths sql/sql_repl.cc: Give error for wrong parameters to CHANGE MASTER sql/sql_repl.h: Extend MASTER_PASSWORD and MASTER_HOST lengths --- sql/rpl_mi.h | 6 +++--- sql/sql_repl.cc | 42 ++++++++++++++++++++++++++++++++++++------ sql/sql_repl.h | 4 ++-- 3 files changed, 41 insertions(+), 11 deletions(-) (limited to 'sql') diff --git a/sql/rpl_mi.h b/sql/rpl_mi.h index a885576ef1c..64525f81603 100644 --- a/sql/rpl_mi.h +++ b/sql/rpl_mi.h @@ -66,9 +66,9 @@ class Master_info : public Slave_reporting_capability /* the variables below are needed because we can change masters on the fly */ char master_log_name[FN_REFLEN]; - char host[HOSTNAME_LENGTH+1]; - char user[USERNAME_LENGTH+1]; - char password[MAX_PASSWORD_LENGTH+1]; + char host[HOSTNAME_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; + char user[USERNAME_LENGTH*+1]; + char password[MAX_PASSWORD_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; bool ssl; // enables use of SSL connection if true char ssl_ca[FN_REFLEN], ssl_capath[FN_REFLEN], ssl_cert[FN_REFLEN]; char ssl_cipher[FN_REFLEN], ssl_key[FN_REFLEN]; diff --git a/sql/sql_repl.cc b/sql/sql_repl.cc index 53ac103dda1..631825f0527 100644 --- a/sql/sql_repl.cc +++ b/sql/sql_repl.cc @@ -1541,6 +1541,31 @@ void kill_zombie_dump_threads(uint32 slave_server_id) } } +/** + Get value for a string parameter with error checking + + Note that in case of error the original string should not be updated! + + @ret 0 ok + @ret 1 error +*/ + +static bool get_string_parameter(char *to, const char *from, size_t length, + const char *name) +{ + if (from) // Empty paramaters allowed + { + size_t from_length; + if ((from_length= strlen(from)) > length) + { + my_error(ER_WRONG_STRING_LENGTH, MYF(0), from, name, (int) length); + return 1; + } + memcpy(to, from, from_length+1); + } + return 0; +} + /** Execute a CHANGE MASTER statement. @@ -1633,12 +1658,17 @@ bool change_master(THD* thd, Master_info* mi) } DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->master_log_pos)); - if (lex_mi->host) - strmake(mi->host, lex_mi->host, sizeof(mi->host)-1); - if (lex_mi->user) - strmake(mi->user, lex_mi->user, sizeof(mi->user)-1); - if (lex_mi->password) - strmake(mi->password, lex_mi->password, sizeof(mi->password)-1); + if (get_string_parameter(mi->host, lex_mi->host, sizeof(mi->host)-1, + "MASTER_HOST") || + get_string_parameter(mi->user, lex_mi->user, sizeof(mi->user)-1, + "MASTER_USER") || + get_string_parameter(mi->password, lex_mi->password, + sizeof(mi->password)-1, "MASTER_PASSWORD")) + { + ret= TRUE; + goto err; + } + if (lex_mi->port) mi->port = lex_mi->port; if (lex_mi->connect_retry) diff --git a/sql/sql_repl.h b/sql/sql_repl.h index 7dc58c47d52..c5a0b31388e 100644 --- a/sql/sql_repl.h +++ b/sql/sql_repl.h @@ -25,9 +25,9 @@ typedef struct st_slave_info { uint32 server_id; uint32 rpl_recovery_rank, master_id; - char host[HOSTNAME_LENGTH+1]; + char host[HOSTNAME_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; char user[USERNAME_LENGTH+1]; - char password[MAX_PASSWORD_LENGTH+1]; + char password[MAX_PASSWORD_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; uint16 port; THD* thd; } SLAVE_INFO; -- cgit v1.2.1 From 9684140f02981f78a3fd0bbf0bd886a1ee2abbd4 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Fri, 11 Jan 2013 01:31:50 +0200 Subject: Fixed crashing bug in GROUP_CONCAT with ROLLUP Fixed MDEV-4002: Server crash or valgrind errors in Item_func_group_concat::setup and Item_func_group_concat::add mysql-test/r/group_by.result: Added test case for failing GROUP_CONCAT ... ROLLUP queries mysql-test/t/group_by.test: Added test case for failing GROUP_CONCAT ... ROLLUP queries sql/item_sum.cc: Fixed issue where field->table pointed to different temporary table than expected. Ensure that order->next points to the right object (could cause problems with setup_order()) --- sql/item_sum.cc | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) (limited to 'sql') diff --git a/sql/item_sum.cc b/sql/item_sum.cc index e00ef3e592c..58d605478af 100644 --- a/sql/item_sum.cc +++ b/sql/item_sum.cc @@ -2905,13 +2905,12 @@ int group_concat_key_cmp_with_distinct(void* arg, const void* key1, const void* key2) { Item_func_group_concat *item_func= (Item_func_group_concat*)arg; - TABLE *table= item_func->table; for (uint i= 0; i < item_func->arg_count_field; i++) { Item *item= item_func->args[i]; /* - If field_item is a const item then either get_tp_table_field returns 0 + If field_item is a const item then either get_tmp_table_field returns 0 or it is an item over a const table. */ if (item->const_item()) @@ -2923,7 +2922,8 @@ int group_concat_key_cmp_with_distinct(void* arg, const void* key1, */ Field *field= item->get_tmp_table_field(); int res; - uint offset= field->offset(field->table->record[0])-table->s->null_bytes; + uint offset= (field->offset(field->table->record[0]) - + field->table->s->null_bytes); if((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset))) return res; } @@ -2941,28 +2941,37 @@ int group_concat_key_cmp_with_order(void* arg, const void* key1, { Item_func_group_concat* grp_item= (Item_func_group_concat*) arg; ORDER **order_item, **end; - TABLE *table= grp_item->table; for (order_item= grp_item->order, end=order_item+ grp_item->arg_count_order; order_item < end; order_item++) { Item *item= *(*order_item)->item; + /* + If field_item is a const item then either get_tmp_table_field returns 0 + or it is an item over a const table. + */ + if (item->const_item()) + continue; /* We have to use get_tmp_table_field() instead of real_item()->get_tmp_table_field() because we want the field in the temporary table, not the original field + + Note that for the case of ROLLUP, field may point to another table + tham grp_item->table. This is howver ok as the table definitions are + the same. */ Field *field= item->get_tmp_table_field(); /* - If item is a const item then either get_tp_table_field returns 0 + If item is a const item then either get_tmp_table_field returns 0 or it is an item over a const table. */ - if (field && !item->const_item()) + if (field) { int res; uint offset= (field->offset(field->table->record[0]) - - table->s->null_bytes); + field->table->s->null_bytes); if ((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset))) return (*order_item)->asc ? res : -res; } @@ -3156,12 +3165,13 @@ Item_func_group_concat::Item_func_group_concat(THD *thd, */ ORDER *tmp; if (!(tmp= (ORDER *) thd->alloc(sizeof(ORDER *) * arg_count_order + - sizeof(ORDER) * arg_count_order))) + sizeof(ORDER) * arg_count_order))) return; order= (ORDER **)(tmp + arg_count_order); for (uint i= 0; i < arg_count_order; i++, tmp++) { memcpy(tmp, item->order[i], sizeof(ORDER)); + tmp->next= i == arg_count_order-1 ? 0 : tmp+1; order[i]= tmp; } } @@ -3445,7 +3455,8 @@ bool Item_func_group_concat::setup(THD *thd) */ if (!(table= create_tmp_table(thd, tmp_table_param, all_fields, (ORDER*) 0, 0, TRUE, - (select_lex->options | thd->variables.option_bits), + (select_lex->options | + thd->variables.option_bits), HA_POS_ERROR, (char*) ""))) DBUG_RETURN(TRUE); table->file->extra(HA_EXTRA_NO_ROWS); -- cgit v1.2.1 From edc89f7511ac924f1c3ce14b356894939dea58c0 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Fri, 11 Jan 2013 02:03:43 +0200 Subject: Buildbot fixes and cleanups: - Added --verbose to BUILD scripts to get make to write out compile commands. - Detect if AM_EXTRA_MAKEFLAGS=VERBOSE=1 was used with build scripts. - Don't write warnings about replication variables when doing bootstrap. - Fixed that mysql_cond_wait() and mysql_cond_timedwait() will report original source file in case of errors. - Ignore some compiler warnings BUILD/FINISH.sh: Detect if AM_EXTRA_MAKEFLAGS=VERBOSE=1 or --verbose was used BUILD/SETUP.sh: Added --verbose to print out the full compile lines Updated help message client/mysqltest.cc: Fixed that one can use 'replace' with cat_file cmake/configure.pl: If --verbose is used, get make to write out compile commands debian/dist/Debian/rules: Added $AM_EXTRA_MAKEFLAGS to get VERBOSE=1 on buildbot builds debian/dist/Ubuntu/rules: Added $AM_EXTRA_MAKEFLAGS to get VERBOSE=1 on buildbot builds include/my_pthread.h: Made set_timespec_time_nsec() more portable. include/mysql/psi/mysql_thread.h: Fixed that mysql_cond_wait() and mysql_cond_timedwait() will report original source file in case of errors. mysql-test/suite/innodb/r/auto_increment_dup.result: Fixed wrong DBUG_SYNC mysql-test/suite/innodb/t/auto_increment_dup.test: Fixed wrong DBUG_SYNC mysql-test/suite/perfschema/include/upgrade_check.inc: Make test more portable for changes in *.sql files mysql-test/suite/perfschema/r/pfs_upgrade.result: Updated test results mysql-test/valgrind.supp: Ignore running Aria checkpoint thread scripts/mysqlaccess.sh: Changed reference of bugs database Ensure that also client-server group is read. sql/handler.cc: Added missing syncpoint sql/mysqld.cc: Don't write warnings about replication variables when doing bootstrap sql/mysqld.h: Don't write warnings about replication variables when doing bootstrap sql/rpl_rli.cc: Don't write warnings about replication variables when doing bootstrap sql/sql_insert.cc: Don't mask SERVER_SHUTDOWN in insert_delayed This is done to be able to distingush between shutdown and interrupt errors support-files/compiler_warnings.supp: Ignore some compiler warnings in xtradb,innobase, oqgraph, yassl, string3.h --- sql/handler.cc | 1 + sql/mysqld.cc | 4 ++-- sql/mysqld.h | 2 +- sql/rpl_rli.cc | 3 ++- sql/sql_insert.cc | 9 +++------ 5 files changed, 9 insertions(+), 10 deletions(-) (limited to 'sql') diff --git a/sql/handler.cc b/sql/handler.cc index 5108e3abc40..679ef346fbb 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -5125,6 +5125,7 @@ int handler::ha_write_row(uchar *buf) int error; Log_func *log_func= Write_rows_log_event::binlog_row_logging_function; DBUG_ENTER("handler::ha_write_row"); + DEBUG_SYNC_C("ha_write_row_start"); MYSQL_INSERT_ROW_START(table_share->db.str, table_share->table_name.str); mark_trx_read_write(); diff --git a/sql/mysqld.cc b/sql/mysqld.cc index c4c65977e60..37e54a6638c 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -706,8 +706,8 @@ char *opt_logname, *opt_slow_logname, *opt_bin_logname; static volatile sig_atomic_t kill_in_progress; my_bool opt_stack_trace; -my_bool opt_expect_abort= 0; -static my_bool opt_bootstrap, opt_myisam_log; +my_bool opt_expect_abort= 0, opt_bootstrap= 0; +static my_bool opt_myisam_log; static int cleanup_done; static ulong opt_specialflag; static char *opt_binlog_index_name; diff --git a/sql/mysqld.h b/sql/mysqld.h index 554c662e90f..293c20ade55 100644 --- a/sql/mysqld.h +++ b/sql/mysqld.h @@ -77,7 +77,7 @@ extern CHARSET_INFO *character_set_filesystem; extern MY_BITMAP temp_pool; extern bool opt_large_files, server_id_supplied; extern bool opt_update_log, opt_bin_log, opt_error_log; -extern my_bool opt_log, opt_slow_log; +extern my_bool opt_log, opt_slow_log, opt_bootstrap; extern my_bool opt_backup_history_log; extern my_bool opt_backup_progress_log; extern ulonglong log_output_options; diff --git a/sql/rpl_rli.cc b/sql/rpl_rli.cc index 252b4f3f5b9..cbd7ac8f5ef 100644 --- a/sql/rpl_rli.cc +++ b/sql/rpl_rli.cc @@ -188,7 +188,8 @@ a file name for --relay-log-index option", opt_relaylog_index_name); ln= rli->relay_log.generate_name(opt_relay_logname, "-relay-bin", 1, buf); /* We send the warning only at startup, not after every RESET SLAVE */ - if (!opt_relay_logname && !opt_relaylog_index_name && !name_warning_sent) + if (!opt_relay_logname && !opt_relaylog_index_name && !name_warning_sent && + !opt_bootstrap) { /* User didn't give us info to name the relay log index file. diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index ef3f81f18c5..45cc7357155 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2269,11 +2269,8 @@ bool delayed_get_table(THD *thd, MDL_request *grl_protection_request, want to send "Server shutdown in progress" in the INSERT THREAD. */ - if (di->thd.stmt_da->sql_errno() == ER_SERVER_SHUTDOWN) - my_message(ER_QUERY_INTERRUPTED, ER(ER_QUERY_INTERRUPTED), MYF(0)); - else - my_message(di->thd.stmt_da->sql_errno(), di->thd.stmt_da->message(), - MYF(0)); + my_message(di->thd.stmt_da->sql_errno(), di->thd.stmt_da->message(), + MYF(0)); } di->unlock(); goto end_create; @@ -2358,7 +2355,7 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) killed using mysql_notify_thread_having_shared_lock() or kill_delayed_threads_for_table(). */ - if (!thd.is_error() || thd.stmt_da->sql_errno() == ER_SERVER_SHUTDOWN) + if (!thd.is_error()) my_message(ER_QUERY_INTERRUPTED, ER(ER_QUERY_INTERRUPTED), MYF(0)); else my_message(thd.stmt_da->sql_errno(), thd.stmt_da->message(), MYF(0)); -- cgit v1.2.1 From 12bf6fe85893f6a69a74ec1c733e533051058dd3 Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Fri, 11 Jan 2013 20:26:34 -0800 Subject: Fixed bug mdev-4025. The bug could lead to a wrong estimate of the number of expected rows in the output of the EXPLAIN commands for queries with GROUP BY. This could be observed in the test case for LP bug 934348. --- sql/sql_select.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index ca7e1bf2a66..aa47793df8f 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -18371,8 +18371,9 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit_arg, and as result we'll choose an index scan when using ref/range access + filesort will be cheaper. */ - select_limit= (ha_rows) (select_limit < fanout ? - 1 : select_limit/fanout); + if (select_limit_arg != HA_POS_ERROR) + select_limit= (ha_rows) (select_limit < fanout ? + 1 : select_limit/fanout); /* We assume that each of the tested indexes is not correlated with ref_key. Thus, to select first N records we have to scan -- cgit v1.2.1 From 7d5c56cb410bd0363e1c66c31149a79086584bbb Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Sun, 13 Jan 2013 00:40:38 -0800 Subject: Fixed bug mdev-4019. The bug could cause a crash when several connections needed persistent statistics for the same table. Also added a missing call of set_statistics_for_table() in the code of the function mysql_update. --- sql/sql_base.cc | 1 + sql/sql_statistics.cc | 10 ++++++++-- sql/sql_update.cc | 2 ++ sql/table.h | 1 + 4 files changed, 12 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_base.cc b/sql/sql_base.cc index b7f321e6290..cb1555ea142 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -4654,6 +4654,7 @@ open_and_process_table(THD *thd, LEX *lex, TABLE_LIST *tables, Field **table_field_ptr= tables->table->field; for ( ; *field_ptr; field_ptr++, table_field_ptr++) (*table_field_ptr)->read_stats= (*field_ptr)->read_stats; + tables->table->stats_is_read= table_share->stats_cb.stats_is_read; } } } diff --git a/sql/sql_statistics.cc b/sql/sql_statistics.cc index 9de5aa080e1..68f26ebf90b 100644 --- a/sql/sql_statistics.cc +++ b/sql/sql_statistics.cc @@ -2501,6 +2501,8 @@ int read_statistics_for_table(THD *thd, TABLE *table, TABLE_LIST *stat_tables) } } + table->stats_is_read= TRUE; + DBUG_RETURN(0); } @@ -2559,6 +2561,8 @@ bool statistics_for_tables_is_needed(THD *thd, TABLE_LIST *tables) table_share->stats_cb.stats_can_be_read && !table_share->stats_cb.stats_is_read) return TRUE; + if (table_share->stats_cb.stats_is_read) + tl->table->stats_is_read= TRUE; } } @@ -2618,6 +2622,8 @@ int read_statistics_for_tables_if_needed(THD *thd, TABLE_LIST *tables) (void) read_statistics_for_table(thd, tl->table, stat_tables); table_share->stats_cb.stats_is_read= TRUE; } + if (table_share->stats_cb.stats_is_read) + tl->table->stats_is_read= TRUE; } } @@ -3045,7 +3051,7 @@ void set_statistics_for_table(THD *thd, TABLE *table) Use_stat_tables_mode use_stat_table_mode= get_use_stat_tables_mode(thd); table->used_stat_records= (use_stat_table_mode <= COMPLEMENTARY || - !stats_cb->stats_is_read || read_stats->cardinality_is_null) ? + !table->stats_is_read || read_stats->cardinality_is_null) ? table->file->stats.records : read_stats->cardinality; KEY *key_info, *key_info_end; for (key_info= table->key_info, key_info_end= key_info+table->s->keys; @@ -3053,7 +3059,7 @@ void set_statistics_for_table(THD *thd, TABLE *table) { key_info->is_statistics_from_stat_tables= (use_stat_table_mode > COMPLEMENTARY && - stats_cb->stats_is_read && + table->stats_is_read && key_info->read_stats->avg_frequency_is_inited() && key_info->read_stats->get_avg_frequency(0) > 0.5); } diff --git a/sql/sql_update.cc b/sql/sql_update.cc index 78b693c5237..31df7a2a4b1 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -32,6 +32,7 @@ #include "sql_view.h" // check_key_in_view #include "sp_head.h" #include "sql_trigger.h" +#include "sql_statistics.h" #include "probes_mysql.h" #include "debug_sync.h" #include "key.h" // is_key_used @@ -404,6 +405,7 @@ int mysql_update(THD *thd, #endif /* Update the table->file->stats.records number */ table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); + set_statistics_for_table(thd, table); select= make_select(table, 0, 0, conds, 0, &error); if (error || !limit || thd->is_error() || diff --git a/sql/table.h b/sql/table.h index a2b197ac1f3..ac0eb0dad89 100644 --- a/sql/table.h +++ b/sql/table.h @@ -1189,6 +1189,7 @@ public: bool no_partitions_used; /* If true, all partitions have been pruned away */ #endif uint max_keys; /* Size of allocated key_info array. */ + bool stats_is_read; /* Persistent statistics is read for the table */ MDL_ticket *mdl_ticket; void init(THD *thd, TABLE_LIST *tl); -- cgit v1.2.1 From cf79c01cc7b9071c68055c90659da58c3b3b7363 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 14 Jan 2013 15:05:05 +0200 Subject: Fix for bug MDEV-3992 Analysis: The crash is a result of incorrect analysis of whether a secondary key can be extended with a primary in order to compute ORDER BY. The analysis is done in test_if_order_by_key(). This function doesn't take into account that the primary key may in fact index the same columns as the secondary key. For the test query test_if_order_by_key says that there is an extended key with total 2 keyparts. At the same time, the condition if (pkinfo->key_part[i].field->key_start.is_set(nr)) in test_if_cheaper_oredring() becomes true for (i == 0), which results in an invalid access to rec_per_key[-1]. Solution: The best solution would be to reuse KEY::ext_key_parts that is already computed by open_binary_frm(), however after detailed analysis the conclusion is that the change would be too intrusive for a GA release. The solution for 5.5 is to add a guard for the case when the 0-th key part is considered, and to assume that all keys will be scanned in this case. --- sql/sql_select.cc | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 9bbc139927e..cb9faecb772 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -18144,7 +18144,15 @@ static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx, key_part_end=key_part+table->key_info[table->s->primary_key].key_parts; const_key_parts=table->const_key_parts[table->s->primary_key]; - for (; const_key_parts & 1 ; const_key_parts>>= 1) + /* + Check for constness only those keyparts of the PK suffix, that will + be used to extend the secondary key 'idx'. This handles the case when + some columns of the PK are used in the secondary index. + */ + for (uint pk_part_idx= 0; + ((const_key_parts & 1) && + (table->key_info[idx].ext_key_part_map & (1 << pk_part_idx))); + const_key_parts>>= 1, pk_part_idx++) key_part++; /* The primary and secondary key parts were all const (i.e. there's @@ -23009,7 +23017,8 @@ test_if_cheaper_ordering(const JOIN_TAB *tab, ORDER *order, TABLE *table, if rec_per_key[0] != 0. */ DBUG_ASSERT(pkinfo->rec_per_key[i]); - rec_per_key*= pkinfo->rec_per_key[i-1]; + rec_per_key*= (i == 0) ? table_records : + pkinfo->rec_per_key[i-1]; rec_per_key/= pkinfo->rec_per_key[i]; } } -- cgit v1.2.1 From a87eab6061068491ec9004ae54c46630619cb531 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 15 Jan 2013 14:33:08 +0200 Subject: Fix for bug MDEV-3992, second attempt The previous fix for MDEV-3992 was incomplete, because it still computed incorrectly the number of keyparts of the extended secondary key in the case when columns of the PK participate in the secondary key. This patch by Monty corrects the above problem. --- sql/sql_select.cc | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index cb9faecb772..79cef2c3538 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -18139,26 +18139,36 @@ static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx, table->s->primary_key != MAX_KEY && table->s->primary_key != idx) { + KEY_PART_INFO *start,*end; + uint pk_part_idx= 0; on_pk_suffix= TRUE; - key_part= table->key_info[table->s->primary_key].key_part; - key_part_end=key_part+table->key_info[table->s->primary_key].key_parts; + start= key_part= table->key_info[table->s->primary_key].key_part; const_key_parts=table->const_key_parts[table->s->primary_key]; /* - Check for constness only those keyparts of the PK suffix, that will - be used to extend the secondary key 'idx'. This handles the case when - some columns of the PK are used in the secondary index. + Calculate true key_part_end and const_key_parts + (we have to stop as first not continous primary key part) */ - for (uint pk_part_idx= 0; - ((const_key_parts & 1) && - (table->key_info[idx].ext_key_part_map & (1 << pk_part_idx))); - const_key_parts>>= 1, pk_part_idx++) - key_part++; + for (key_part_end= key_part, + end= key_part+table->key_info[table->s->primary_key].key_parts; + key_part_end < end; key_part_end++, pk_part_idx++) + { + /* Found hole in the pk_parts; Abort */ + if (!(table->key_info[idx].ext_key_part_map & + (((key_part_map) 1) << pk_part_idx))) + break; + } + /* Adjust const_key_parts */ + const_key_parts&= (((key_part_map) 1) << pk_part_idx) -1; + + for (; const_key_parts & 1 ; const_key_parts>>= 1) + key_part++; /* - The primary and secondary key parts were all const (i.e. there's - one row). The sorting doesn't matter. + Test if the primary key parts were all const (i.e. there's one row). + The sorting doesn't matter. */ - if (key_part == key_part_end && reverse == 0) + if (key_part == start+table->key_info[table->s->primary_key].key_parts && + reverse == 0) { key_parts= 0; reverse= 1; @@ -18178,7 +18188,8 @@ static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx, if (reverse && flag != reverse) DBUG_RETURN(0); reverse=flag; // Remember if reverse - key_part++; + if (key_part < key_part_end) + key_part++; } if (on_pk_suffix) { @@ -22940,7 +22951,7 @@ test_if_cheaper_ordering(const JOIN_TAB *tab, ORDER *order, TABLE *table, { int direction; ha_rows select_limit= select_limit_arg; - uint used_key_parts; + uint used_key_parts= 0; if (keys.is_set(nr) && (direction= test_if_order_by_key(order, table, nr, &used_key_parts))) @@ -23017,8 +23028,8 @@ test_if_cheaper_ordering(const JOIN_TAB *tab, ORDER *order, TABLE *table, if rec_per_key[0] != 0. */ DBUG_ASSERT(pkinfo->rec_per_key[i]); - rec_per_key*= (i == 0) ? table_records : - pkinfo->rec_per_key[i-1]; + DBUG_ASSERT(i > 0); + rec_per_key*= pkinfo->rec_per_key[i-1]; rec_per_key/= pkinfo->rec_per_key[i]; } } -- cgit v1.2.1 From 750b9147fced7202b541be946e044eb739b20a03 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 15 Jan 2013 17:46:46 +0100 Subject: remove thd_mark_as_hard_kill() (because it's conceptually wrong. only the user can decide whether the kill is allowed to leave tables in the inconsistent state, storage engine has no say in that) --- sql/handler.h | 1 - sql/sql_class.cc | 12 ------------ sql/sql_class.h | 11 ----------- 3 files changed, 24 deletions(-) (limited to 'sql') diff --git a/sql/handler.h b/sql/handler.h index e5da92b0d40..af5d7e6d606 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -868,7 +868,6 @@ struct handlerton Tell handler that query has been killed. hard_kill is set in case of HARD KILL (abort query even if it may corrupt table). - Return 1 if the handler wants to upgrade the kill to a hard kill */ void (*kill_query)(handlerton *hton, THD *thd, my_bool hard_kill); /* diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 312de8c74e4..616e827a552 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -3853,18 +3853,6 @@ extern "C" int thd_killed(const MYSQL_THD thd) return thd->killed; } -/** - Change kill level to hard. - This ensures that thd_killed() will return true. - This is important for storage engines that uses thd_killed() to - verify if thread is killed. -*/ - -extern "C" void thd_mark_as_hard_kill(MYSQL_THD thd) -{ - thd->mark_as_hard_kill(); -} - /** Send an out-of-band progress report to the client diff --git a/sql/sql_class.h b/sql/sql_class.h index 2561effb478..f1b3652c15c 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -2729,17 +2729,6 @@ public: (!transaction.stmt.modified_non_trans_table || (variables.sql_mode & MODE_STRICT_ALL_TABLES))); } - /* - Increase level of kill ; Ensures that thd_killed() returns true. - - Needed if storage engine wants to abort things because of a 'soft' (ie, - safe) kill but still uses thd_killed() to check if it's killed. - */ - inline void mark_as_hard_kill() - { - DBUG_ASSERT(killed != NOT_KILLED); - killed= (killed_state) (killed | KILL_HARD_BIT); - } void set_status_var_init(); void reset_n_backup_open_tables_state(Open_tables_backup *backup); void restore_backup_open_tables_state(Open_tables_backup *backup); -- cgit v1.2.1 From 9b9c138e2aaa036c0cb4e833e45be3f612b7d131 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 15 Jan 2013 19:16:18 +0100 Subject: small cleanups --- sql/log.cc | 13 ++++++++----- sql/sql_load.cc | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index abda8c52d88..567b3c69833 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -2070,15 +2070,17 @@ static int binlog_savepoint_set(handlerton *hton, THD *thd, void *sv) binlog_trans_log_savepos(thd, (my_off_t*) sv); /* Write it to the binary log */ - String log_query; - if (log_query.append(STRING_WITH_LEN("SAVEPOINT ")) || + char buf[1024]; + String log_query(buf, sizeof(buf), &my_charset_bin); + if (log_query.copy(STRING_WITH_LEN("SAVEPOINT "), &my_charset_bin) || append_identifier(thd, &log_query, thd->lex->ident.str, thd->lex->ident.length)) DBUG_RETURN(1); int errcode= query_error_code(thd, thd->killed == NOT_KILLED); Query_log_event qinfo(thd, log_query.ptr(), log_query.length(), TRUE, FALSE, TRUE, errcode); - DBUG_RETURN(mysql_bin_log.write(&qinfo)); + int ret= mysql_bin_log.write(&qinfo); + DBUG_RETURN(ret); } static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv) @@ -2093,8 +2095,9 @@ static int binlog_savepoint_rollback(handlerton *hton, THD *thd, void *sv) if (unlikely(trans_has_updated_non_trans_table(thd) || (thd->variables.option_bits & OPTION_KEEP_LOG))) { - String log_query; - if (log_query.append(STRING_WITH_LEN("ROLLBACK TO ")) || + char buf[1024]; + String log_query(buf, sizeof(buf), &my_charset_bin); + if (log_query.copy(STRING_WITH_LEN("ROLLBACK TO "), &my_charset_bin) || append_identifier(thd, &log_query, thd->lex->ident.str, thd->lex->ident.length)) DBUG_RETURN(1); diff --git a/sql/sql_load.cc b/sql/sql_load.cc index 98031c96225..6c27a9d123a 100644 --- a/sql/sql_load.cc +++ b/sql/sql_load.cc @@ -741,14 +741,14 @@ static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex, List_iterator lu(thd->lex->update_list); List_iterator lv(thd->lex->value_list); - query_str.append(" SET "); + query_str.append(STRING_WITH_LEN(" SET ")); n= 0; while ((item= lu++)) { val= lv++; if (n++) - query_str.append(", "); + query_str.append(STRING_WITH_LEN(", ")); append_identifier(thd, &query_str, item->name, strlen(item->name)); query_str.append(val->name); } -- cgit v1.2.1 From 4ce53556ce5f31ec6b811c0803285cf0c29f4540 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Tue, 15 Jan 2013 19:16:29 +0100 Subject: Test case and a different fix for MySQL bug#14485479 --- sql/sql_audit.cc | 45 +++++++++++++++++++++++++++++++++++---------- sql/sql_audit.h | 2 +- sql/sql_plugin.cc | 17 ++++++++++++++--- 3 files changed, 50 insertions(+), 14 deletions(-) (limited to 'sql') diff --git a/sql/sql_audit.cc b/sql/sql_audit.cc index 131a71c1d6b..523f07592bc 100644 --- a/sql/sql_audit.cc +++ b/sql/sql_audit.cc @@ -132,12 +132,9 @@ static const uint audit_handlers_count= static my_bool acquire_plugins(THD *thd, plugin_ref plugin, void *arg) { - uint event_class= *(uint*) arg; - unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; + ulong *event_class_mask= (ulong*) arg; st_mysql_audit *data= plugin_data(plugin, struct st_mysql_audit *); - set_audit_mask(event_class_mask, event_class); - /* Check if this plugin is interested in the event */ if (check_audit_mask(data->class_mask, event_class_mask)) return 0; @@ -176,15 +173,13 @@ static my_bool acquire_plugins(THD *thd, plugin_ref plugin, void *arg) @details Ensure that audit plugins interested in given event class are locked by current thread. */ -void mysql_audit_acquire_plugins(THD *thd, uint event_class) +void mysql_audit_acquire_plugins(THD *thd, ulong *event_class_mask) { - unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; DBUG_ENTER("mysql_audit_acquire_plugins"); - set_audit_mask(event_class_mask, event_class); if (thd && !check_audit_mask(mysql_global_audit_mask, event_class_mask) && check_audit_mask(thd->audit_class_mask, event_class_mask)) { - plugin_foreach(thd, acquire_plugins, MYSQL_AUDIT_PLUGIN, &event_class); + plugin_foreach(thd, acquire_plugins, MYSQL_AUDIT_PLUGIN, event_class_mask); add_audit_mask(thd->audit_class_mask, event_class_mask); } DBUG_VOID_RETURN; @@ -206,7 +201,9 @@ void mysql_audit_notify(THD *thd, uint event_class, uint event_subtype, ...) va_list ap; audit_handler_t *handlers= audit_handlers + event_class; DBUG_ASSERT(event_class < audit_handlers_count); - mysql_audit_acquire_plugins(thd, event_class); + unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; + set_audit_mask(event_class_mask, event_class); + mysql_audit_acquire_plugins(thd, event_class_mask); va_start(ap, event_subtype); (*handlers)(thd, event_subtype, ap); va_end(ap); @@ -364,6 +361,34 @@ int initialize_audit_plugin(st_plugin_int *plugin) add_audit_mask(mysql_global_audit_mask, data->class_mask); mysql_mutex_unlock(&LOCK_audit_mask); + /* + Pre-acquire the newly inslalled audit plugin for events that + may potentially occur further during INSTALL PLUGIN. + + When audit event is triggered, audit subsystem acquires interested + plugins by walking through plugin list. Evidently plugin list + iterator protects plugin list by acquiring LOCK_plugin, see + plugin_foreach_with_mask(). + + On the other hand [UN]INSTALL PLUGIN is acquiring LOCK_plugin + rather for a long time. + + When audit event is triggered during [UN]INSTALL PLUGIN, plugin + list iterator acquires the same lock (within the same thread) + second time. + + This hack should be removed when LOCK_plugin is fixed so it + protects only what it supposed to protect. + + See also mysql_install_plugin() and mysql_uninstall_plugin() + */ + THD *thd= current_thd; + if (thd) + { + acquire_plugins(thd, plugin_int_to_ref(plugin), data->class_mask); + add_audit_mask(thd->audit_class_mask, data->class_mask); + } + return 0; } @@ -494,7 +519,7 @@ static void event_class_dispatch(THD *thd, unsigned int event_class, #else /* EMBEDDED_LIBRARY */ -void mysql_audit_acquire_plugins(THD *thd, uint event_class) +void mysql_audit_acquire_plugins(THD *thd, ulong *event_class_mask) { } diff --git a/sql/sql_audit.h b/sql/sql_audit.h index b2ce31f1d26..46afe4b7596 100644 --- a/sql/sql_audit.h +++ b/sql/sql_audit.h @@ -31,7 +31,7 @@ extern void mysql_audit_finalize(); extern void mysql_audit_init_thd(THD *thd); extern void mysql_audit_free_thd(THD *thd); -extern void mysql_audit_acquire_plugins(THD *thd, uint event_class); +extern void mysql_audit_acquire_plugins(THD *thd, ulong *event_class_mask); #ifndef EMBEDDED_LIBRARY diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index 3d529c7a332..cec577b2273 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -2018,7 +2018,7 @@ static bool finalize_install(THD *thd, TABLE *table, const LEX_STRING *name) struct st_plugin_int *tmp= plugin_find_internal(name, MYSQL_ANY_PLUGIN); int error; DBUG_ASSERT(tmp); - mysql_mutex_assert_owner(&LOCK_plugin); + mysql_mutex_assert_owner(&LOCK_plugin); // because of tmp->state if (tmp->state == PLUGIN_IS_DISABLED) { @@ -2105,8 +2105,12 @@ bool mysql_install_plugin(THD *thd, const LEX_STRING *name, This hack should be removed when LOCK_plugin is fixed so it protects only what it supposed to protect. + + See also mysql_uninstall_plugin() and initialize_audit_plugin() */ - mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GENERAL_CLASS); + unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE] = + { MYSQL_AUDIT_GENERAL_CLASSMASK }; + mysql_audit_acquire_plugins(thd, event_class_mask); mysql_mutex_lock(&LOCK_plugin); mysql_rwlock_wrlock(&LOCK_system_variables_hash); @@ -2249,8 +2253,15 @@ bool mysql_uninstall_plugin(THD *thd, const LEX_STRING *name, When audit event is triggered during [UN]INSTALL PLUGIN, plugin list iterator acquires the same lock (within the same thread) second time. + + This hack should be removed when LOCK_plugin is fixed so it + protects only what it supposed to protect. + + See also mysql_install_plugin() and initialize_audit_plugin() */ - mysql_audit_acquire_plugins(thd, MYSQL_AUDIT_GENERAL_CLASS); + unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE] = + { MYSQL_AUDIT_GENERAL_CLASSMASK }; + mysql_audit_acquire_plugins(thd, event_class_mask); mysql_mutex_lock(&LOCK_plugin); -- cgit v1.2.1 From f8f90aa75fbe8ab5c543d788f2afe55926ae34cb Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Tue, 15 Jan 2013 16:46:27 -0800 Subject: Fixed bug mdev-3938. The original patch with the implementation of virtual columns did not support INSERT DELAYED into tables with virtual columns. This patch fixes the problem. --- sql/mysql_priv.h | 3 +++ sql/sql_base.cc | 3 ++- sql/sql_insert.cc | 29 +++++++++++++++++++++++++++++ sql/table.cc | 12 ++++++++---- 4 files changed, 42 insertions(+), 5 deletions(-) (limited to 'sql') diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h index b40e40792f9..e9973f4c3de 100644 --- a/sql/mysql_priv.h +++ b/sql/mysql_priv.h @@ -2292,6 +2292,9 @@ void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg); int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, uint db_stat, uint prgflag, uint ha_open_flags, TABLE *outparam, bool is_create_table); +bool unpack_vcol_info_from_frm(THD *thd, MEM_ROOT *mem_root, + TABLE *table, Field *field, + LEX_STRING *vcol_expr, bool *error_reported); int readfrm(const char *name, uchar **data, size_t *length); int writefrm(const char* name, const uchar* data, size_t len); int closefrm(TABLE *table, bool free_share); diff --git a/sql/sql_base.cc b/sql/sql_base.cc index 04198af84b9..f1257a3668f 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -8429,7 +8429,8 @@ fill_record(THD * thd, List &fields, List &values, rfield->field_name, table->s->table_name.str); thd->abort_on_warning= abort_on_warning_saved; } - if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors) + if ((!rfield->vcol_info || rfield->stored_in_db) && + (value->save_in_field(rfield, 0) < 0) && !ignore_errors) { my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0)); goto err; diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index 9962789029e..f76c2252eb9 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2084,6 +2084,7 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) { my_ptrdiff_t adjust_ptrs; Field **field,**org_field, *found_next_number_field; + Field **vfield; TABLE *copy; TABLE_SHARE *share; uchar *bitmap; @@ -2127,12 +2128,20 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) if (!copy_tmp) goto error; + if (share->vfields) + { + vfield= (Field **) client_thd->alloc((share->vfields+1)*sizeof(Field*)); + if (!vfield) + goto error; + } + /* Copy the TABLE object. */ copy= new (copy_tmp) TABLE; *copy= *table; /* We don't need to change the file handler here */ /* Assign the pointers for the field pointers array and the record. */ field= copy->field= (Field**) (copy + 1); + copy->vfield= vfield; bitmap= (uchar*) (field + share->fields + 1); copy->record[0]= (bitmap + share->column_bitmap_size*3); memcpy((char*) copy->record[0], (char*) table->record[0], share->reclength); @@ -2156,6 +2165,26 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) } *field=0; + if (table->vfield) + { + for (field= copy->field; *field; field++) + { + if ((*field)->vcol_info) + { + bool error_reported= FALSE; + if (unpack_vcol_info_from_frm(client_thd, + client_thd->mem_root, + copy, + *field, + &(*field)->vcol_info->expr_str, + &error_reported)) + goto error; + *vfield++= *field; + } + } + *vfield= 0; + } + /* Adjust timestamp */ if (table->timestamp_field) { diff --git a/sql/table.cc b/sql/table.cc index 5c1e27b87c7..dfc9c2d933c 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -1925,8 +1925,10 @@ end: @brief Unpack the definition of a virtual column from its linear representation - @parm + @param thd The thread object + @param + mem_root The mem_root object where to allocated memory @param table The table containing the virtual column @param @@ -1956,6 +1958,7 @@ end: TRUE Otherwise */ bool unpack_vcol_info_from_frm(THD *thd, + MEM_ROOT *mem_root, TABLE *table, Field *field, LEX_STRING *vcol_expr, @@ -1981,7 +1984,7 @@ bool unpack_vcol_info_from_frm(THD *thd, "PARSE_VCOL_EXPR ()". */ - if (!(vcol_expr_str= (char*) alloc_root(&table->mem_root, + if (!(vcol_expr_str= (char*) alloc_root(mem_root, vcol_expr->length + parse_vcol_keyword.length + 3))) { @@ -2011,8 +2014,8 @@ bool unpack_vcol_info_from_frm(THD *thd, vcol_arena= table->expr_arena; if (!vcol_arena) { - Query_arena expr_arena(&table->mem_root, Query_arena::INITIALIZED); - if (!(vcol_arena= (Query_arena *) alloc_root(&table->mem_root, + Query_arena expr_arena(mem_root, Query_arena::INITIALIZED); + if (!(vcol_arena= (Query_arena *) alloc_root(mem_root, sizeof(Query_arena)))) goto err; *vcol_arena= expr_arena; @@ -2265,6 +2268,7 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, if ((*field_ptr)->vcol_info) { if (unpack_vcol_info_from_frm(thd, + &outparam->mem_root, outparam, *field_ptr, &(*field_ptr)->vcol_info->expr_str, -- cgit v1.2.1 From a716b061676d01920fa83298cd1fbb57725d6ad9 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 16 Jan 2013 15:11:13 +0200 Subject: MDEV-3988 fix. Subquery turned into constant too late to be excluded from grouping list so test for constant added to the create_temp_table(). --- sql/sql_select.cc | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'sql') diff --git a/sql/sql_select.cc b/sql/sql_select.cc index aa47793df8f..0897aa287db 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -13797,10 +13797,20 @@ create_tmp_table(THD *thd, TMP_TABLE_PARAM *param, List &fields, if (group) { + ORDER **prev= &group; if (!param->quick_group) group=0; // Can't use group key else for (ORDER *tmp=group ; tmp ; tmp=tmp->next) { + /* Exclude found constant from the list */ + if ((*tmp->item)->const_item()) + { + *prev= tmp->next; + param->group_parts--; + continue; + } + else + prev= &(tmp->next); /* marker == 4 means two things: - store NULLs in the key, and -- cgit v1.2.1 From 8a296e6ca2e55f9f1f3ce25d311291a20ee1c9e7 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 17 Jan 2013 13:53:15 +0200 Subject: backport of: Don't reset maybe_null in update_used_tables(); This breaks ROLLUP This fixed failing test in group_by.test --- sql/item.cc | 2 +- sql/item.h | 4 ++-- sql/item_cmpfunc.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'sql') diff --git a/sql/item.cc b/sql/item.cc index aee35b611e7..2e023168f34 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -9169,7 +9169,7 @@ void Item_ref::update_used_tables() { if (!get_depended_from()) (*ref)->update_used_tables(); - maybe_null= (*ref)->maybe_null; + maybe_null|= (*ref)->maybe_null; } void Item_direct_view_ref::update_used_tables() diff --git a/sql/item.h b/sql/item.h index 2b5e867feb7..1e35c7839de 100644 --- a/sql/item.h +++ b/sql/item.h @@ -1855,7 +1855,7 @@ public: { update_table_bitmaps(); if (field && field->table) - maybe_null= field->maybe_null(); + maybe_null|= field->maybe_null(); } Item *get_tmp_table_item(THD *thd); bool collect_item_field_processor(uchar * arg); @@ -2882,7 +2882,7 @@ public: void update_used_tables() { orig_item->update_used_tables(); - maybe_null= orig_item->maybe_null; + maybe_null|= orig_item->maybe_null; } bool const_item() const { return orig_item->const_item(); } table_map not_null_tables() const { return orig_item->not_null_tables(); } diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index dca139e6321..8c505b36758 100644 --- a/sql/item_cmpfunc.h +++ b/sql/item_cmpfunc.h @@ -760,7 +760,7 @@ public: void update_used_tables() { Item_func_coalesce::update_used_tables(); - maybe_null= args[1]->maybe_null; + maybe_null|= args[1]->maybe_null; } const char *func_name() const { return "ifnull"; } Field *tmp_table_field(TABLE *table); @@ -787,7 +787,7 @@ public: void update_used_tables() { Item_func::update_used_tables(); - maybe_null= args[1]->maybe_null || args[2]->maybe_null; + maybe_null|= args[1]->maybe_null || args[2]->maybe_null; } uint decimal_precision() const; const char *func_name() const { return "if"; } -- cgit v1.2.1 From d51f96b16754cad5d2c9a91bb5b5e0673e59ded0 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 17 Jan 2013 16:08:05 +0200 Subject: MDEV-3900 Optimizer difference between MySQL and MariaDB with stored functions in WHERE clause of UPDATE or DELETE statements Analysis The reason for the less efficient plan was result of a prior design decision - to limit the eveluation of constant expressions during optimization to only non-expensive ones. With this approach all stored procedures were considered expensive, and were not evaluated during optimization. As a result, SPs didn't participate in range optimization, which resulted in a plan with table scan rather than index range scan. Solution Instead of considering all SPs expensive, consider expensive only those SPs that are non-deterministic. If an SP is deterministic, the optimizer will checj if it is constant, and may eventually evaluate it during optimization. --- sql/item_func.cc | 13 +++++++++++++ sql/item_func.h | 5 +++-- 2 files changed, 16 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/item_func.cc b/sql/item_func.cc index 18d0ce3a822..c1767fb71ca 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -6056,6 +6056,19 @@ Item_func_sp::init_result_field(THD *thd) } +/** + @note + Deterministic stored procedures are considered inexpensive. + Consequently such procedures may be evaluated during optimization, + if they are constant (checked by the optimizer). +*/ + +bool Item_func_sp::is_expensive() +{ + return !(m_sp->m_chistics->detistic); +} + + /** @brief Initialize local members with values from the Field interface. diff --git a/sql/item_func.h b/sql/item_func.h index b144b393225..2db8ab76ffe 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -1807,7 +1807,8 @@ private: bool init_result_field(THD *thd); protected: - bool is_expensive_processor(uchar *arg) { return TRUE; } + bool is_expensive_processor(uchar *arg) + { return is_expensive(); } public: @@ -1881,7 +1882,7 @@ public: bool fix_fields(THD *thd, Item **ref); void fix_length_and_dec(void); - bool is_expensive() { return 1; } + bool is_expensive(); inline Field *get_sp_result_field() { -- cgit v1.2.1 From 2255132f200940186c6e9dfcedae6edb85e7cee7 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 16 Jan 2013 21:07:26 +0200 Subject: MDEV-4056 fix. The problem was that maybe_null of Item_row and its componetes was unsynced after update_used_tables() (and so pushed_cond_guards was not initialized but then requested). Fix updates Item_row::maybe_null on update_used_tables(). --- sql/item_row.cc | 2 ++ 1 file changed, 2 insertions(+) (limited to 'sql') diff --git a/sql/item_row.cc b/sql/item_row.cc index 5136c0100d6..72bae6f0900 100644 --- a/sql/item_row.cc +++ b/sql/item_row.cc @@ -139,11 +139,13 @@ void Item_row::update_used_tables() { used_tables_cache= 0; const_item_cache= 1; + maybe_null= 0; for (uint i= 0; i < arg_count; i++) { items[i]->update_used_tables(); used_tables_cache|= items[i]->used_tables(); const_item_cache&= items[i]->const_item(); + maybe_null|= items[i]->maybe_null; } } -- cgit v1.2.1 From 63afbba419fcf9fe1fd2acb3355c112453c15a66 Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Wed, 16 Jan 2013 11:17:58 -0800 Subject: Corrected the fix for bug mdev-3938. --- sql/sql_insert.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index f76c2252eb9..f9179843810 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2141,7 +2141,6 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) /* We don't need to change the file handler here */ /* Assign the pointers for the field pointers array and the record. */ field= copy->field= (Field**) (copy + 1); - copy->vfield= vfield; bitmap= (uchar*) (field + share->fields + 1); copy->record[0]= (bitmap + share->column_bitmap_size*3); memcpy((char*) copy->record[0], (char*) table->record[0], share->reclength); @@ -2165,8 +2164,9 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) } *field=0; - if (table->vfield) + if (share->vfields) { + copy->vfield= vfield; for (field= copy->field; *field; field++) { if ((*field)->vcol_info) -- cgit v1.2.1 From c65f9a1914b8abd26dd7f31099ed09116e429b9d Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Thu, 17 Jan 2013 02:27:10 +0200 Subject: Don't reset maybe_null in update_used_tables(); This breaks ROLLUP This fixed failing test in group_by.test mysql-test/r/join_outer.result: Updated test case mysql-test/r/join_outer_jcl6.result: Updated test case sql/item.cc: Don't reset maybe_null in update_used_tables(); This breaks ROLLUP sql/item.h: Don't reset maybe_null in update_used_tables(); This breaks ROLLUP sql/item_cmpfunc.h: Don't reset maybe_null in update_used_tables(); This breaks ROLLUP --- sql/item.cc | 2 +- sql/item.h | 4 ++-- sql/item_cmpfunc.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'sql') diff --git a/sql/item.cc b/sql/item.cc index e6462d1c070..2c435eb6a9f 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -9603,7 +9603,7 @@ void Item_ref::update_used_tables() { if (!get_depended_from()) (*ref)->update_used_tables(); - maybe_null= (*ref)->maybe_null; + maybe_null|= (*ref)->maybe_null; } void Item_direct_view_ref::update_used_tables() diff --git a/sql/item.h b/sql/item.h index baff64cac24..89cb9b76439 100644 --- a/sql/item.h +++ b/sql/item.h @@ -2057,7 +2057,7 @@ public: { update_table_bitmaps(); if (field && field->table) - maybe_null= field->maybe_null(); + maybe_null|= field->maybe_null(); } Item *get_tmp_table_item(THD *thd); bool collect_item_field_processor(uchar * arg); @@ -3112,7 +3112,7 @@ public: void update_used_tables() { orig_item->update_used_tables(); - maybe_null= orig_item->maybe_null; + maybe_null|= orig_item->maybe_null; } bool const_item() const { return orig_item->const_item(); } table_map not_null_tables() const { return orig_item->not_null_tables(); } diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index e9b77152d12..eed9028a630 100644 --- a/sql/item_cmpfunc.h +++ b/sql/item_cmpfunc.h @@ -770,7 +770,7 @@ public: void update_used_tables() { Item_func_coalesce::update_used_tables(); - maybe_null= args[1]->maybe_null; + maybe_null|= args[1]->maybe_null; } const char *func_name() const { return "ifnull"; } Field *tmp_table_field(TABLE *table); @@ -797,7 +797,7 @@ public: void update_used_tables() { Item_func::update_used_tables(); - maybe_null= args[1]->maybe_null || args[2]->maybe_null; + maybe_null|= args[1]->maybe_null || args[2]->maybe_null; } uint decimal_precision() const; const char *func_name() const { return "if"; } -- cgit v1.2.1 From 5649377b558d182a4856a86157070e0df93097a7 Mon Sep 17 00:00:00 2001 From: Vladislav Vaintroub Date: Fri, 18 Jan 2013 18:49:07 +0100 Subject: Fix Windows installers' bootstrapper scripts , after mysql_performance_tables.sql was split off mysql_system_tables.sql --- sql/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/CMakeLists.txt b/sql/CMakeLists.txt index a5f1fcb60ec..ad22446d0c9 100644 --- a/sql/CMakeLists.txt +++ b/sql/CMakeLists.txt @@ -321,11 +321,12 @@ IF(WIN32) ADD_CUSTOM_COMMAND(OUTPUT ${my_bootstrap_sql} COMMAND ${CMAKE_COMMAND} -E chdir ${CMAKE_SOURCE_DIR}/scripts - cmd /c copy mysql_system_tables.sql+mysql_system_tables_data.sql+fill_help_tables.sql ${native_outfile} + cmd /c copy mysql_system_tables.sql+mysql_system_tables_data.sql+fill_help_tables.sql+mysql_performance_tables.sql ${native_outfile} DEPENDS ${CMAKE_SOURCE_DIR}/scripts/mysql_system_tables.sql ${CMAKE_SOURCE_DIR}/scripts/mysql_system_tables_data.sql ${CMAKE_SOURCE_DIR}/scripts/fill_help_tables.sql + ${CMAKE_SOURCE_DIR}/scripts/mysql_performance_tables.sql ) ADD_CUSTOM_COMMAND( -- cgit v1.2.1 From d41d43f42165cafe87d361f473e226fee24e91ba Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 18 Jan 2013 19:04:23 +0100 Subject: MDEV-4065 thd_kill_statement service --- sql/handler.cc | 13 +++++++------ sql/handler.h | 6 ++---- sql/sql_class.cc | 33 ++++++++++++++++++++++++--------- sql/sql_plugin.cc | 7 +++++-- sql/sql_plugin_services.h | 15 ++++++++++----- 5 files changed, 48 insertions(+), 26 deletions(-) (limited to 'sql') diff --git a/sql/handler.cc b/sql/handler.cc index 11265abb9d0..058e219f76c 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -673,21 +673,20 @@ void ha_close_connection(THD* thd) } static my_bool kill_handlerton(THD *thd, plugin_ref plugin, - void *hard_kill) + void *level) { handlerton *hton= plugin_data(plugin, handlerton *); if (hton->state == SHOW_OPTION_YES && hton->kill_query && thd_get_ha_data(thd, hton)) - hton->kill_query(hton, thd, * (my_bool*) hard_kill); + hton->kill_query(hton, thd, *(enum thd_kill_levels *) level); return FALSE; } -void ha_kill_query(THD* thd, my_bool hard_kill) +void ha_kill_query(THD* thd, enum thd_kill_levels level) { DBUG_ENTER("ha_kill_query"); - plugin_foreach(thd, kill_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, - &hard_kill); + plugin_foreach(thd, kill_handlerton, MYSQL_STORAGE_ENGINE_PLUGIN, &level); DBUG_VOID_RETURN; } @@ -4721,7 +4720,9 @@ extern "C" enum icp_result handler_index_cond_check(void* h_arg) THD *thd= h->table->in_use; enum icp_result res; - if (thd_killed(thd)) + enum thd_kill_levels abort_at= h->has_transactions() ? + THD_ABORT_SOFTLY : THD_ABORT_ASAP; + if (thd_kill_level(thd) > abort_at) return ICP_ABORTED_BY_USER; if (h->end_range && h->compare_key2(h->end_range) > 0) diff --git a/sql/handler.h b/sql/handler.h index 9e390b2a62a..4a91d989e52 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -866,10 +866,8 @@ struct handlerton int (*close_connection)(handlerton *hton, THD *thd); /* Tell handler that query has been killed. - hard_kill is set in case of HARD KILL (abort query even if - it may corrupt table). */ - void (*kill_query)(handlerton *hton, THD *thd, my_bool hard_kill); + void (*kill_query)(handlerton *hton, THD *thd, enum thd_kill_levels level); /* sv points to an uninitialized storage area of requested size (see savepoint_offset description) @@ -2983,7 +2981,7 @@ int ha_finalize_handlerton(st_plugin_int *plugin); TYPELIB *ha_known_exts(void); int ha_panic(enum ha_panic_function flag); void ha_close_connection(THD* thd); -void ha_kill_query(THD* thd, my_bool hard_kill); +void ha_kill_query(THD* thd, enum thd_kill_levels level); bool ha_flush_logs(handlerton *db_type); void ha_drop_database(char* path); void ha_checkpoint_state(bool disable); diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 616e827a552..43e72973ab9 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -1613,7 +1613,7 @@ void THD::awake(killed_state state_to_set) /* Interrupt target waiting inside a storage engine. */ if (state_to_set != NOT_KILLED) - ha_kill_query(this, test(state_to_set & KILL_HARD_BIT)); + ha_kill_query(this, thd_kill_level(this)); /* Broadcast a condition to kick the target if it is waiting on it. */ if (mysys_var) @@ -3834,15 +3834,13 @@ void THD::restore_backup_open_tables_state(Open_tables_backup *backup) DBUG_VOID_RETURN; } +#if MARIA_PLUGIN_INTERFACE_VERSION < 0x0200 /** - Check the killed state of a user thread - @param thd user thread - @retval 0 the user thread is active - @retval 1 the user thread has been killed - - This is used to signal a storage engine if it should be killed. + This is a backward compatibility method, made obsolete + by the thd_kill_statement service. Keep it here to avoid breaking the + ABI in case some binary plugins still use it. */ - +#undef thd_killed extern "C" int thd_killed(const MYSQL_THD thd) { if (!thd) @@ -3850,9 +3848,26 @@ extern "C" int thd_killed(const MYSQL_THD thd) if (!(thd->killed & KILL_HARD_BIT)) return 0; - return thd->killed; + return thd->killed != 0; } +#else +#error now thd_killed() function can go away +#endif + +/* + return thd->killed status to the client, + mapped to the API enum thd_kill_levels values. +*/ +extern "C" enum thd_kill_levels thd_kill_level(const MYSQL_THD thd) +{ + if (!thd) + thd= current_thd; + + if (likely(thd->killed == NOT_KILLED)) + return THD_IS_NOT_KILLED; + return thd->killed & KILL_HARD_BIT ? THD_ABORT_ASAP : THD_ABORT_SOFTLY; +} /** Send an out-of-band progress report to the client diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index cec577b2273..bf3537c0ed9 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -1872,8 +1872,11 @@ static bool plugin_load_list(MEM_ROOT *tmp_root, int *argc, char **argv, DBUG_RETURN(FALSE); error: mysql_mutex_unlock(&LOCK_plugin); - sql_print_error("Couldn't load plugin named '%s' with soname '%s'.", - name.str, dl.str); + if (name.str) + sql_print_error("Couldn't load plugin '%s' from '%s'.", + name.str, dl.str); + else + sql_print_error("Couldn't load plugins from '%s'.", dl.str); DBUG_RETURN(TRUE); } diff --git a/sql/sql_plugin_services.h b/sql/sql_plugin_services.h index c779547059d..e3ef338eaad 100644 --- a/sql/sql_plugin_services.h +++ b/sql/sql_plugin_services.h @@ -54,13 +54,18 @@ static struct progress_report_service_st progress_report_handler= { set_thd_proc_info }; +static struct kill_statement_service_st thd_kill_statement_handler= { + thd_kill_level +}; + static struct st_service_ref list_of_services[]= { - { "my_snprintf_service", VERSION_my_snprintf, &my_snprintf_handler }, - { "thd_alloc_service", VERSION_thd_alloc, &thd_alloc_handler }, - { "thd_wait_service", VERSION_thd_wait, &thd_wait_handler }, + { "my_snprintf_service", VERSION_my_snprintf, &my_snprintf_handler }, + { "thd_alloc_service", VERSION_thd_alloc, &thd_alloc_handler }, + { "thd_wait_service", VERSION_thd_wait, &thd_wait_handler }, { "my_thread_scheduler_service", VERSION_my_thread_scheduler, &my_thread_scheduler_handler }, - { "progress_report_service", VERSION_progress_report, &progress_report_handler }, - { "debug_sync_service", VERSION_debug_sync, 0 } // updated in plugin_init() + { "progress_report_service", VERSION_progress_report, &progress_report_handler }, + { "debug_sync_service", VERSION_debug_sync, 0 }, // updated in plugin_init() + { "thd_kill_statement_service", VERSION_kill_statement, &thd_kill_statement_handler } }; -- cgit v1.2.1 From 381f470936a84b899f9de6453ed8ec177e59bc69 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 18 Jan 2013 19:07:59 +0100 Subject: simplify THD::binlog_setup_trx_data() usage --- sql/log.cc | 31 ++++++++++--------------------- sql/sql_class.cc | 2 +- sql/sql_class.h | 2 +- 3 files changed, 12 insertions(+), 23 deletions(-) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index 567b3c69833..d078d1dfda4 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -1531,10 +1531,7 @@ binlog_trans_log_savepos(THD *thd, my_off_t *pos) { DBUG_ENTER("binlog_trans_log_savepos"); DBUG_ASSERT(pos != NULL); - if (thd_get_ha_data(thd, binlog_hton) == NULL) - thd->binlog_setup_trx_data(); - binlog_cache_mngr *const cache_mngr= - (binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton); + binlog_cache_mngr *const cache_mngr= thd->binlog_setup_trx_data(); DBUG_ASSERT(mysql_bin_log.is_open()); *pos= cache_mngr->trx_cache.get_byte_position(); DBUG_PRINT("return", ("*pos: %lu", (ulong) *pos)); @@ -4719,14 +4716,14 @@ bool stmt_has_updated_non_trans_table(const THD* thd) binlog_hton, which has internal linkage. */ -int THD::binlog_setup_trx_data() +binlog_cache_mngr *THD::binlog_setup_trx_data() { DBUG_ENTER("THD::binlog_setup_trx_data"); binlog_cache_mngr *cache_mngr= (binlog_cache_mngr*) thd_get_ha_data(this, binlog_hton); if (cache_mngr) - DBUG_RETURN(0); // Already set up + DBUG_RETURN(cache_mngr); // Already set up cache_mngr= (binlog_cache_mngr*) my_malloc(sizeof(binlog_cache_mngr), MYF(MY_ZEROFILL)); if (!cache_mngr || @@ -4736,18 +4733,18 @@ int THD::binlog_setup_trx_data() LOG_PREFIX, binlog_cache_size, MYF(MY_WME))) { my_free(cache_mngr); - DBUG_RETURN(1); // Didn't manage to set it up + DBUG_RETURN(0); // Didn't manage to set it up } thd_set_ha_data(this, binlog_hton, cache_mngr); - cache_mngr= new (thd_get_ha_data(this, binlog_hton)) + cache_mngr= new (cache_mngr) binlog_cache_mngr(max_binlog_stmt_cache_size, max_binlog_cache_size, &binlog_stmt_cache_use, &binlog_stmt_cache_disk_use, &binlog_cache_use, &binlog_cache_disk_use); - DBUG_RETURN(0); + DBUG_RETURN(cache_mngr); } /* @@ -4830,9 +4827,7 @@ binlog_start_consistent_snapshot(handlerton *hton, THD *thd) int err= 0; DBUG_ENTER("binlog_start_consistent_snapshot"); - thd->binlog_setup_trx_data(); - binlog_cache_mngr *const cache_mngr= - (binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton); + binlog_cache_mngr *const cache_mngr= thd->binlog_setup_trx_data(); /* Server layer calls us with LOCK_commit_ordered locked, so this is safe. */ strmake(cache_mngr->last_commit_pos_file, mysql_bin_log.last_commit_pos_file, @@ -4944,11 +4939,7 @@ THD::binlog_get_pending_rows_event(bool is_transactional) const void THD::binlog_set_pending_rows_event(Rows_log_event* ev, bool is_transactional) { - if (thd_get_ha_data(this, binlog_hton) == NULL) - binlog_setup_trx_data(); - - binlog_cache_mngr *const cache_mngr= - (binlog_cache_mngr*) thd_get_ha_data(this, binlog_hton); + binlog_cache_mngr *const cache_mngr= binlog_setup_trx_data(); DBUG_ASSERT(cache_mngr); @@ -5119,12 +5110,10 @@ bool MYSQL_BIN_LOG::write(Log_event *event_info, my_bool *with_annotate) } else { - if (thd->binlog_setup_trx_data()) + binlog_cache_mngr *const cache_mngr= thd->binlog_setup_trx_data(); + if (!cache_mngr) goto err; - binlog_cache_mngr *const cache_mngr= - (binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton); - is_trans_cache= use_trans_cache(thd, using_trans); file= cache_mngr->get_binlog_cache_log(is_trans_cache); cache_data= cache_mngr->get_binlog_cache_data(is_trans_cache); diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 43e72973ab9..9c53db45009 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -4909,7 +4909,7 @@ THD::binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id, There is no good place to set up the transactional data, so we have to do it here. */ - if (binlog_setup_trx_data()) + if (binlog_setup_trx_data() == NULL) DBUG_RETURN(NULL); Rows_log_event* pending= binlog_get_pending_rows_event(is_transactional); diff --git a/sql/sql_class.h b/sql/sql_class.h index f1b3652c15c..e92ba129a29 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -1734,7 +1734,7 @@ public: bool save_prep_leaf_list; #ifndef MYSQL_CLIENT - int binlog_setup_trx_data(); + binlog_cache_mngr * binlog_setup_trx_data(); /* Public interface to write RBR events to the binlog -- cgit v1.2.1 From 103c4c4906d0dc6cf1cfc807fd344d24c49b82ae Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 18 Jan 2013 19:10:20 +0100 Subject: MDEV-633 lp:1024058 - mysqld XA crash in replication slave initialize cache_mngr and write the Xid into binlog even if binlog is disabled with SQL_LOG_BIN=0 or no --log-slave-updates in the slave thread --- sql/log.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index d078d1dfda4..6c04055cfc1 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -7460,8 +7460,9 @@ TC_LOG_BINLOG::log_and_order(THD *thd, my_xid xid, bool all, int err; DBUG_ENTER("TC_LOG_BINLOG::log_and_order"); - binlog_cache_mngr *cache_mngr= - (binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton); + binlog_cache_mngr *cache_mngr= thd->binlog_setup_trx_data(); + if (!cache_mngr) + DBUG_RETURN(0); cache_mngr->using_xa= TRUE; cache_mngr->xa_xid= xid; -- cgit v1.2.1 From cc74bb3178b0296e9865ebd42588709c984b722e Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Sun, 20 Jan 2013 00:46:51 +0100 Subject: MDEV-4029 SELECT on information_schema using a subquery locks up the information_schema table due to incorrect mutexes handling Early evaluation of subqueries in the WHERE conditions on I_S.*_STATUS tables, otherwise the subquery on this same table will try to acquire LOCK_status twice. sql/item.h: remove unused method --- sql/item.h | 1 - sql/sql_show.cc | 18 ++++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/item.h b/sql/item.h index 89cb9b76439..bdf6fbe548e 100644 --- a/sql/item.h +++ b/sql/item.h @@ -1445,7 +1445,6 @@ public: */ virtual bool is_outer_field() const { DBUG_ASSERT(fixed); return FALSE; } Item* set_expr_cache(THD *thd); - virtual Item *get_cached_item() { return NULL; } virtual Item_equal *get_item_equal() { return NULL; } virtual void set_item_equal(Item_equal *item_eq) {}; diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 19146a146e4..cb96db0a46d 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -2595,7 +2595,6 @@ static bool show_status_array(THD *thd, const char *wild, int len; LEX_STRING null_lex_str; SHOW_VAR tmp, *var; - COND *partial_cond= 0; enum_check_fields save_count_cuted_fields= thd->count_cuted_fields; bool res= FALSE; CHARSET_INFO *charset= system_charset_info; @@ -2609,7 +2608,6 @@ static bool show_status_array(THD *thd, const char *wild, if (*prefix) *prefix_end++= '_'; len=name_buffer + sizeof(name_buffer) - prefix_end; - partial_cond= make_cond_for_info_schema(cond, table->pos_in_table_list); for (; variables->name; variables++) { @@ -2632,13 +2630,13 @@ static bool show_status_array(THD *thd, const char *wild, if (show_type == SHOW_ARRAY) { show_status_array(thd, wild, (SHOW_VAR *) var->value, value_type, - status_var, name_buffer, table, ucase_names, partial_cond); + status_var, name_buffer, table, ucase_names, cond); } else { if (!(wild && wild[0] && wild_case_compare(system_charset_info, name_buffer, wild)) && - (!partial_cond || partial_cond->val_int())) + (!cond || cond->val_int())) { char *value=var->value; const char *pos, *end; // We assign a lot of const's @@ -6898,9 +6896,12 @@ int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond) schema_table_idx == SCH_GLOBAL_VARIABLES) option_type= OPT_GLOBAL; + COND *partial_cond= make_cond_for_info_schema(cond, tables); + mysql_rwlock_rdlock(&LOCK_system_variables_hash); res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars, option_type), - option_type, NULL, "", tables->table, upper_case_names, cond); + option_type, NULL, "", tables->table, + upper_case_names, partial_cond); mysql_rwlock_unlock(&LOCK_system_variables_hash); DBUG_RETURN(res); } @@ -6937,13 +6938,18 @@ int fill_status(THD *thd, TABLE_LIST *tables, COND *cond) tmp1= &thd->status_var; } + COND *partial_cond= make_cond_for_info_schema(cond, tables); + // Evaluate and cache const subqueries now, before the mutex. + if (partial_cond) + partial_cond->val_int(); + mysql_mutex_lock(&LOCK_status); if (option_type == OPT_GLOBAL) calc_sum_of_all_status(&tmp); res= show_status_array(thd, wild, (SHOW_VAR *)all_status_vars.buffer, option_type, tmp1, "", tables->table, - upper_case_names, cond); + upper_case_names, partial_cond); mysql_mutex_unlock(&LOCK_status); DBUG_RETURN(res); } -- cgit v1.2.1 From 7caa80c48170f8a35ef8ece7a1881fe1f0e022dd Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Sun, 20 Jan 2013 14:06:33 +0100 Subject: MDEV-3934 Assertion `((keypart_map+1) & keypart_map) == 0' failed in _mi_pack_key with an index on a POINT column sel_arg_range_seq_next(): set keypart map also for GEOM_FLAG keys --- sql/opt_range_mrr.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'sql') diff --git a/sql/opt_range_mrr.cc b/sql/opt_range_mrr.cc index a4345059f85..1f4e36178db 100644 --- a/sql/opt_range_mrr.cc +++ b/sql/opt_range_mrr.cc @@ -248,6 +248,7 @@ walk_up_n_right: /* Here minimum contains also function code bits, and maximum is +inf */ range->start_key.key= seq->param->min_key; range->start_key.length= min_key_length; + range->start_key.keypart_map= make_prev_keypart_map(cur->min_key_parts); range->start_key.flag= (ha_rkey_function) (cur->min_key_flag ^ GEOM_FLAG); } else -- cgit v1.2.1 From a0710621bf463db66d81f42134dd66f8b03c276a Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Sun, 20 Jan 2013 21:43:11 +0100 Subject: fix a strict aliasing warning - remove a meaningless cast. --- sql/item_strfunc.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 28009e7154e..0c1f556b398 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -4192,8 +4192,7 @@ String *Item_dyncol_get::val_str(String *str_result) case DYN_COL_DECIMAL: { int res; - int length= - my_decimal_string_length((const my_decimal*)&val.x.decimal.value); + int length= decimal_string_size(&val.x.decimal.value); if (str_result->alloc(length)) goto null; if ((res= decimal2string(&val.x.decimal.value, (char*) str_result->ptr(), -- cgit v1.2.1 From 2b0f4bdf44904c5211f879edd477f0b3b80df0ef Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 21 Jan 2013 10:06:03 +0100 Subject: Fix uninitialised variable in binlog group commit (probably not reachable code). Fix test failure when $vardir does not allow executing programs. --- sql/log.cc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/log.cc b/sql/log.cc index a96dfbbf461..1ffceaf05a3 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -6379,8 +6379,6 @@ MYSQL_BIN_LOG::trx_group_commit_leader(group_commit_entry *leader) DBUG_ENTER("MYSQL_BIN_LOG::trx_group_commit_leader"); LINT_INIT(binlog_id); - DBUG_ASSERT(is_open()); - if (likely(is_open())) // Should always be true { /* Lock the LOCK_log(), and once we get it, collect any additional writes @@ -6407,7 +6405,11 @@ MYSQL_BIN_LOG::trx_group_commit_leader(group_commit_entry *leader) DBUG_ASSERT(leader == queue /* the leader should be first in queue */); /* Now we have in queue the list of transactions to be committed in order. */ + } + DBUG_ASSERT(is_open()); + if (likely(is_open())) // Should always be true + { /* Commit every transaction in the queue. -- cgit v1.2.1 From 43c6953fa1ba3aad4f065bfbd63cca6b5d0c5ce7 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Mon, 21 Jan 2013 10:52:39 +0100 Subject: MDEV-4029 SELECT on information_schema using a subquery locks up the information_schema table due to incorrect mutexes handling Early evaluation of subqueries in the WHERE conditions on I_S.*_STATUS tables, otherwise the subquery on this same table will try to acquire LOCK_status twice. --- sql/sql_show.cc | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'sql') diff --git a/sql/sql_show.cc b/sql/sql_show.cc index d544ff4c52c..f9c2d114596 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -2260,7 +2260,6 @@ static bool show_status_array(THD *thd, const char *wild, int len; LEX_STRING null_lex_str; SHOW_VAR tmp, *var; - COND *partial_cond= 0; enum_check_fields save_count_cuted_fields= thd->count_cuted_fields; bool res= FALSE; CHARSET_INFO *charset= system_charset_info; @@ -2274,7 +2273,6 @@ static bool show_status_array(THD *thd, const char *wild, if (*prefix) *prefix_end++= '_'; len=name_buffer + sizeof(name_buffer) - prefix_end; - partial_cond= make_cond_for_info_schema(cond, table->pos_in_table_list); for (; variables->name; variables++) { @@ -2297,13 +2295,13 @@ static bool show_status_array(THD *thd, const char *wild, if (show_type == SHOW_ARRAY) { show_status_array(thd, wild, (SHOW_VAR *) var->value, value_type, - status_var, name_buffer, table, ucase_names, partial_cond); + status_var, name_buffer, table, ucase_names, cond); } else { if (!(wild && wild[0] && wild_case_compare(system_charset_info, name_buffer, wild)) && - (!partial_cond || partial_cond->val_int())) + (!cond || cond->val_int())) { char *value=var->value; const char *pos, *end; // We assign a lot of const's @@ -5562,9 +5560,12 @@ int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond) schema_table_idx == SCH_GLOBAL_VARIABLES) option_type= OPT_GLOBAL; + COND *partial_cond= make_cond_for_info_schema(cond, tables); + rw_rdlock(&LOCK_system_variables_hash); res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars), - option_type, NULL, "", tables->table, upper_case_names, cond); + option_type, NULL, "", tables->table, upper_case_names, + partial_cond); rw_unlock(&LOCK_system_variables_hash); DBUG_RETURN(res); } @@ -5601,13 +5602,18 @@ int fill_status(THD *thd, TABLE_LIST *tables, COND *cond) tmp1= &thd->status_var; } + COND *partial_cond= make_cond_for_info_schema(cond, tables); + // Evaluate and cache const subqueries now, before the mutex. + if (partial_cond) + partial_cond->val_int(); + pthread_mutex_lock(&LOCK_status); if (option_type == OPT_GLOBAL) calc_sum_of_all_status(&tmp); res= show_status_array(thd, wild, (SHOW_VAR *)all_status_vars.buffer, option_type, tmp1, "", tables->table, - upper_case_names, cond); + upper_case_names, partial_cond); pthread_mutex_unlock(&LOCK_status); DBUG_RETURN(res); } -- cgit v1.2.1 From 193c6f548b3702b4259560c40ca24c1243053388 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 21 Jan 2013 14:34:39 +0200 Subject: MDEV-3873: fixed functions absend in 5.3. --- sql/item_func.h | 5 +++++ sql/item_strfunc.cc | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/item_func.h b/sql/item_func.h index 88491be44a2..516cdd548d0 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -2053,6 +2053,11 @@ public: enum_field_types field_type() const { return last_value->field_type(); } bool const_item() const { return 0; } void evaluate_sideeffects(); + void update_uesd_tables() + { + Item_func_last_value::update_used_tables(); + maybe_null= last_value->maybe_null; + } }; diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 0c1f556b398..3fc5e504b85 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -341,7 +341,7 @@ String *Item_func_sha2::val_str_ascii(String *str) void Item_func_sha2::fix_length_and_dec() { - maybe_null = 1; + set_persist_maybe_null(1); max_length = 0; #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) -- cgit v1.2.1 From 82e39cb1e1637794cc3f7c5049d2d20ce5a32576 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 22 Jan 2013 13:29:59 +0200 Subject: Fixed typo in the function name. test suite added. --- sql/item_func.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/item_func.h b/sql/item_func.h index 516cdd548d0..4306c6ea47a 100644 --- a/sql/item_func.h +++ b/sql/item_func.h @@ -2053,9 +2053,9 @@ public: enum_field_types field_type() const { return last_value->field_type(); } bool const_item() const { return 0; } void evaluate_sideeffects(); - void update_uesd_tables() + void update_used_tables() { - Item_func_last_value::update_used_tables(); + Item_func::update_used_tables(); maybe_null= last_value->maybe_null; } }; -- cgit v1.2.1 From fade3647ecb18a90d9c89a924a076d714ec45888 Mon Sep 17 00:00:00 2001 From: Igor Babaev Date: Mon, 21 Jan 2013 11:47:45 -0800 Subject: Fixed bug mdev-4063 (bug #56927). This bug could result in returning 0 for the expressions of the form (distinct field) when the system variable max_heap_table_size was set to a small enough number. It happened because the method Unique::walk() did not support the case when more than one pass was needed to merge the trees of distinct values saved in an external file. Backported a fix in grant_lowercase.test from mariadb 5.5. --- sql/item_sum.cc | 4 +- sql/sql_class.h | 4 +- sql/uniques.cc | 144 ++++++++++++++++++++++++++++++++++++-------------------- 3 files changed, 98 insertions(+), 54 deletions(-) (limited to 'sql') diff --git a/sql/item_sum.cc b/sql/item_sum.cc index 92c2ba83f23..debba23438d 100644 --- a/sql/item_sum.cc +++ b/sql/item_sum.cc @@ -1084,7 +1084,7 @@ void Item_sum_distinct::calculate_val_and_count() if (tree) { table->field[0]->set_notnull(); - tree->walk(item_sum_distinct_walk, (void*) this); + tree->walk(table, item_sum_distinct_walk, (void*) this); } is_evaluated= TRUE; } @@ -2583,7 +2583,7 @@ longlong Item_sum_count_distinct::val_int() if (tree->elements == 0) return (longlong) tree->elements_in_tree(); // everything fits in memory count= 0; - tree->walk(count_distinct_walk, (void*) &count); + tree->walk(table, count_distinct_walk, (void*) &count); is_evaluated= TRUE; return (longlong) count; } diff --git a/sql/sql_class.h b/sql/sql_class.h index fb4e13ad9c6..2fd8e8cd04b 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -3008,6 +3008,8 @@ class Unique :public Sql_alloc bool flush(); uint size; + bool merge(TABLE *table, uchar *buff, bool without_last_merge); + public: ulong elements; Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg, @@ -3035,7 +3037,7 @@ public: } void reset(); - bool walk(tree_walk_action action, void *walk_action_arg); + bool walk(TABLE *table, tree_walk_action action, void *walk_action_arg); uint get_size() const { return size; } ulonglong get_max_in_memory_size() const { return max_in_memory_size; } diff --git a/sql/uniques.cc b/sql/uniques.cc index fd6056ae8a6..5788edc673e 100644 --- a/sql/uniques.cc +++ b/sql/uniques.cc @@ -538,6 +538,7 @@ end: SYNOPSIS Unique:walk() All params are 'IN': + table parameter for the call of the merge method action function-visitor, typed in include/my_tree.h function is called for each unique element arg argument for visitor, which is passed to it on each call @@ -546,66 +547,68 @@ end: <> 0 error */ -bool Unique::walk(tree_walk_action action, void *walk_action_arg) +bool Unique::walk(TABLE *table, tree_walk_action action, void *walk_action_arg) { - int res; + int res= 0; uchar *merge_buffer; if (elements == 0) /* the whole tree is in memory */ return tree_walk(&tree, action, walk_action_arg, left_root_right); + table->sort.found_records=elements+tree.elements_in_tree; /* flush current tree to the file to have some memory for merge buffer */ if (flush()) return 1; if (flush_io_cache(&file) || reinit_io_cache(&file, READ_CACHE, 0L, 0, 0)) return 1; - if (!(merge_buffer= (uchar *) my_malloc((ulong) max_in_memory_size, MYF(0)))) + ulong buff_sz= (max_in_memory_size / size + 1) * size; + if (!(merge_buffer= (uchar *) my_malloc((ulong) buff_sz, MYF(0)))) return 1; - res= merge_walk(merge_buffer, (ulong) max_in_memory_size, size, - (BUFFPEK *) file_ptrs.buffer, - (BUFFPEK *) file_ptrs.buffer + file_ptrs.elements, - action, walk_action_arg, - tree.compare, tree.custom_arg, &file); + if (buff_sz < (ulong) (size * (file_ptrs.elements + 1))) + res= merge(table, merge_buffer, buff_sz >= size * MERGEBUFF2) ; + + if (!res) + { + res= merge_walk(merge_buffer, (ulong) max_in_memory_size, size, + (BUFFPEK *) file_ptrs.buffer, + (BUFFPEK *) file_ptrs.buffer + file_ptrs.elements, + action, walk_action_arg, + tree.compare, tree.custom_arg, &file); + } my_free((char*) merge_buffer, MYF(0)); return res; } + /* - Modify the TABLE element so that when one calls init_records() - the rows will be read in priority order. -*/ + DESCRIPTION + Perform multi-pass sort merge of the elements accessed through table->sort, + using the buffer buff as the merge buffer. The last pass is not performed + if without_last_merge is TRUE. + SYNOPSIS + Unique:merge() + All params are 'IN': + table the parameter to access sort context + buff merge buffer + without_last_merge TRUE <=> do not perform the last merge + RETURN VALUE + 0 OK + <> 0 error + */ -bool Unique::get(TABLE *table) +bool Unique::merge(TABLE *table, uchar *buff, bool without_last_merge) { SORTPARAM sort_param; - table->sort.found_records=elements+tree.elements_in_tree; - - if (my_b_tell(&file) == 0) - { - /* Whole tree is in memory; Don't use disk if you don't need to */ - if ((record_pointers=table->sort.record_pointers= (uchar*) - my_malloc(size * tree.elements_in_tree, MYF(0)))) - { - (void) tree_walk(&tree, (tree_walk_action) unique_write_to_ptrs, - this, left_root_right); - return 0; - } - } - /* Not enough memory; Save the result to file && free memory used by tree */ - if (flush()) - return 1; - - IO_CACHE *outfile=table->sort.io_cache; + IO_CACHE *outfile= table->sort.io_cache; BUFFPEK *file_ptr= (BUFFPEK*) file_ptrs.buffer; uint maxbuffer= file_ptrs.elements - 1; - uchar *sort_buffer; my_off_t save_pos; - bool error=1; - - /* Open cached file if it isn't open */ - outfile=table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), - MYF(MY_ZEROFILL)); + bool error= 1; + /* Open cached file if it isn't open */ + if (!outfile) + outfile= table->sort.io_cache= (IO_CACHE*) my_malloc(sizeof(IO_CACHE), + MYF(MY_ZEROFILL)); if (!outfile || (! my_b_inited(outfile) && open_cached_file(outfile,mysql_tmpdir,TEMP_PREFIX,READ_RECORD_BUFFER, @@ -615,42 +618,81 @@ bool Unique::get(TABLE *table) bzero((char*) &sort_param,sizeof(sort_param)); sort_param.max_rows= elements; - sort_param.sort_form=table; + sort_param.sort_form= table; sort_param.rec_length= sort_param.sort_length= sort_param.ref_length= size; sort_param.keys= (uint) (max_in_memory_size / sort_param.sort_length); - sort_param.not_killable=1; + sort_param.not_killable= 1; - if (!(sort_buffer=(uchar*) my_malloc((sort_param.keys+1) * - sort_param.sort_length, - MYF(0)))) - return 1; - sort_param.unique_buff= sort_buffer+(sort_param.keys* - sort_param.sort_length); + sort_param.unique_buff= buff + (sort_param.keys * sort_param.sort_length); sort_param.compare= (qsort2_cmp) buffpek_compare; sort_param.cmp_context.key_compare= tree.compare; sort_param.cmp_context.key_compare_arg= tree.custom_arg; /* Merge the buffers to one file, removing duplicates */ - if (merge_many_buff(&sort_param,sort_buffer,file_ptr,&maxbuffer,&file)) + if (merge_many_buff(&sort_param,buff,file_ptr,&maxbuffer,&file)) goto err; if (flush_io_cache(&file) || reinit_io_cache(&file,READ_CACHE,0L,0,0)) goto err; - if (merge_buffers(&sort_param, &file, outfile, sort_buffer, file_ptr, + if (without_last_merge) + { + file_ptrs.elements= maxbuffer+1; + return 0; + } + if (merge_buffers(&sort_param, &file, outfile, buff, file_ptr, file_ptr, file_ptr+maxbuffer,0)) goto err; - error=0; + error= 0; err: - x_free(sort_buffer); if (flush_io_cache(outfile)) - error=1; + error= 1; /* Setup io_cache for reading */ - save_pos=outfile->pos_in_file; + save_pos= outfile->pos_in_file; if (reinit_io_cache(outfile,READ_CACHE,0L,0,0)) - error=1; + error= 1; outfile->end_of_file=save_pos; return error; } + + +/* + Modify the TABLE element so that when one calls init_records() + the rows will be read in priority order. +*/ + +bool Unique::get(TABLE *table) +{ + bool rc= 1; + uchar *sort_buffer= NULL; + table->sort.found_records= elements+tree.elements_in_tree; + + if (my_b_tell(&file) == 0) + { + /* Whole tree is in memory; Don't use disk if you don't need to */ + if ((record_pointers=table->sort.record_pointers= (uchar*) + my_malloc(size * tree.elements_in_tree, MYF(0)))) + { + (void) tree_walk(&tree, (tree_walk_action) unique_write_to_ptrs, + this, left_root_right); + return 0; + } + } + /* Not enough memory; Save the result to file && free memory used by tree */ + if (flush()) + return 1; + + ulong buff_sz= (max_in_memory_size / size + 1) * size; + if (!(sort_buffer= (uchar*) my_malloc(buff_sz, MYF(0)))) + return 1; + + if (merge(table, sort_buffer, FALSE)) + goto err; + rc= 0; + +err: + x_free(sort_buffer); + return rc; +} -- cgit v1.2.1 From a260b155542179bec75a6bbe1e430bea57b70ad6 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Wed, 23 Jan 2013 16:16:14 +0100 Subject: MDEV-4011 Added per thread memory counting and usage Base code and idea from a patch from by plinux at Taobao. The idea is that we mark all memory that are thread specific with MY_THREAD_SPECIFIC. Memory counting is done per thread in the my_malloc_size_cb_func callback function from my_malloc(). There are plenty of new asserts to ensure that for a debug server the counting is correct. Information_schema.processlist gets two new columns: MEMORY_USED and EXAMINED_ROWS. - The later is there mainly to show how query is progressing. The following changes in interfaces was needed to get this to work: - init_alloc_root() amd init_sql_alloc() has extra option so that one can mark memory with MY_THREAD_SPECIFIC - One now have to use alloc_root_set_min_malloc() to set min memory to be allocated by alloc_root() - my_init_dynamic_array() has extra option so that one can mark memory with MY_THREAD_SPECIFIC - my_net_init() has extra option so that one can mark memory with MY_THREAD_SPECIFIC - Added flag for hash_init() so that one can mark hash table to be thread specific. - Added flags to init_tree() so that one can mark tree to be thread specific. - Removed with_delete option to init_tree(). Now one should instead use MY_TREE_WITH_DELETE_FLAG. - Added flag to Warning_info::Warning_info() if the structure should be fully initialized. - String elements can now be marked as thread specific. - Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC. - Changed type of myf from int to ulong, as this is always a set of bit flags. Other things: - Removed calls to net_end() and thd->cleanup() as these are now done in ~THD() - We now also show EXAMINED_ROWS in SHOW PROCESSLIST - Added new variable 'memory_used' - Fixed bug where kill_threads_for_user() was using the wrong mem_root to allocate memory. - Removed calls to the obsoleted function init_dynamic_array() - Use set_current_thd() instead of my_pthread_setspecific_ptr(THR_THD,...) client/completion_hash.cc: Updated call to init_alloc_root() client/mysql.cc: Updated call to init_alloc_root() client/mysqlbinlog.cc: init_dynamic_array() -> my_init_dynamic_array() Updated call to init_alloc_root() client/mysqlcheck.c: Updated call to my_init_dynamic_array() client/mysqldump.c: Updated call to init_alloc_root() client/mysqltest.cc: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() Fixed compiler warnings extra/comp_err.c: Updated call to my_init_dynamic_array() extra/resolve_stack_dump.c: Updated call to my_init_dynamic_array() include/hash.h: Added HASH_THREAD_SPECIFIC include/heap.h: Added flag is internal temporary table. include/my_dir.h: Safety fix: Ensure that MY_DONT_SORT and MY_WANT_STAT don't interfer with other mysys flags include/my_global.h: Changed type of myf from int to ulong, as this is always a set of bit flags. include/my_sys.h: Added MY_THREAD_SPECIFIC and MY_THREAD_MOVE Added malloc_flags to DYNAMIC_ARRAY Added extra mysys flag argument to my_init_dynamic_array() Removed deprecated functions init_dynamic_array() and my_init_dynamic_array.._ci Updated paramaters for init_alloc_root() include/my_tree.h: Added my_flags to allow one to use MY_THREAD_SPECIFIC with hash tables. Removed with_delete. One should now instead use MY_TREE_WITH_DELETE_FLAG Updated parameters to init_tree() include/myisamchk.h: Added malloc_flags to allow one to use MY_THREAD_SPECIFIC for checks. include/mysql.h: Added MYSQL_THREAD_SPECIFIC_MALLOC Used 'unused1' to mark memory as thread specific. include/mysql.h.pp: Updated file include/mysql_com.h: Used 'unused1' to mark memory as thread specific. Updated parameters for my_net_init() libmysql/libmysql.c: Updated call to init_alloc_root() to mark memory thread specific. libmysqld/emb_qcache.cc: Updated call to init_alloc_root() libmysqld/lib_sql.cc: Updated call to init_alloc_root() mysql-test/r/create.result: Updated results mysql-test/r/user_var.result: Updated results mysql-test/suite/funcs_1/datadict/processlist_priv.inc: Update to handle new format of SHOW PROCESSLIST mysql-test/suite/funcs_1/datadict/processlist_val.inc: Update to handle new format of SHOW PROCESSLIST mysql-test/suite/funcs_1/r/is_columns_is.result: Update to handle new format of SHOW PROCESSLIST mysql-test/suite/funcs_1/r/processlist_priv_no_prot.result: Updated results mysql-test/suite/funcs_1/r/processlist_val_no_prot.result: Updated results mysql-test/t/show_explain.test: Fixed usage of debug variable so that one can run test with --debug mysql-test/t/user_var.test: Added test of memory_usage variable. mysys/array.c: Added extra my_flags option to init_dynamic_array() and init_dynamic_array2() so that one can mark memory with MY_THREAD_SPECIFIC All allocated memory is marked with the given my_flags. Removed obsolete function init_dynamic_array() mysys/default.c: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() mysys/hash.c: Updated call to my_init_dynamic_array_ci(). Allocated memory is marked with MY_THREAD_SPECIFIC if HASH_THREAD_SPECIFIC is used. mysys/ma_dyncol.c: init_dynamic_array() -> my_init_dynamic_array() Added #if to get rid of compiler warnings mysys/mf_tempdir.c: Updated call to my_init_dynamic_array() mysys/my_alloc.c: Added extra parameter to init_alloc_root() so that one can mark memory with MY_THREAD_SPECIFIC Extend MEM_ROOT with a flag if memory is thread specific. This is stored in block_size, to keep the size of the MEM_ROOT object identical as before. Allocated memory is marked with MY_THREAD_SPECIFIC if used with init_alloc_root() mysys/my_chmod.c: Updated DBUG_PRINT because of change of myf type mysys/my_chsize.c: Updated DBUG_PRINT because of change of myf type mysys/my_copy.c: Updated DBUG_PRINT because of change of myf type mysys/my_create.c: Updated DBUG_PRINT because of change of myf type mysys/my_delete.c: Updated DBUG_PRINT because of change of myf type mysys/my_error.c: Updated DBUG_PRINT because of change of myf type mysys/my_fopen.c: Updated DBUG_PRINT because of change of myf type mysys/my_fstream.c: Updated DBUG_PRINT because of change of myf type mysys/my_getwd.c: Updated DBUG_PRINT because of change of myf type mysys/my_lib.c: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() Updated DBUG_PRINT because of change of myf type mysys/my_lock.c: Updated DBUG_PRINT because of change of myf type mysys/my_malloc.c: Store at start of each allocated memory block the size of the block and if the block is thread specific. Call malloc_size_cb_func, if set, with the memory allocated/freed. Updated DBUG_PRINT because of change of myf type mysys/my_open.c: Updated DBUG_PRINT because of change of myf type mysys/my_pread.c: Updated DBUG_PRINT because of change of myf type mysys/my_read.c: Updated DBUG_PRINT because of change of myf type mysys/my_redel.c: Updated DBUG_PRINT because of change of myf type mysys/my_rename.c: Updated DBUG_PRINT because of change of myf type mysys/my_seek.c: Updated DBUG_PRINT because of change of myf type mysys/my_sync.c: Updated DBUG_PRINT because of change of myf type mysys/my_thr_init.c: Ensure that one can call my_thread_dbug_id() even if thread is not properly initialized. mysys/my_write.c: Updated DBUG_PRINT because of change of myf type mysys/mysys_priv.h: Updated parameters to sf_malloc and sf_realloc() mysys/safemalloc.c: Added checking that for memory marked with MY_THREAD_SPECIFIC that it's the same thread that is allocation and freeing the memory. Added sf_malloc_dbug_id() to allow MariaDB to specify which THD is handling the memory. Added my_flags arguments to sf_malloc() and sf_realloc() to be able to mark memory with MY_THREAD_SPECIFIC. Added sf_report_leaked_memory() to get list of memory not freed by a thread. mysys/tree.c: Added flags to init_tree() so that one can mark tree to be thread specific. Removed with_delete option to init_tree(). Now one should instead use MY_TREE_WITH_DELETE_FLAG. Updated call to init_alloc_root() All allocated memory is marked with the given malloc flags mysys/waiting_threads.c: Updated call to my_init_dynamic_array() sql-common/client.c: Updated call to init_alloc_root() and my_net_init() to mark memory thread specific. Updated call to my_init_dynamic_array(). Added MYSQL_THREAD_SPECIFIC_MALLOC so that client can mark memory as MY_THREAD_SPECIFIC. sql-common/client_plugin.c: Updated call to init_alloc_root() sql/debug_sync.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/event_scheduler.cc: Removed calls to net_end() as this is now done in ~THD() Call set_current_thd() to ensure that memory is assigned to right thread. sql/events.cc: my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/filesort.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/filesort_utils.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/ha_ndbcluster.cc: Updated call to init_alloc_root() Updated call to my_net_init() Removed calls to net_end() and thd->cleanup() as these are now done in ~THD() sql/ha_ndbcluster_binlog.cc: Updated call to my_net_init() Updated call to init_sql_alloc() Removed calls to net_end() and thd->cleanup() as these are now done in ~THD() sql/ha_partition.cc: Updated call to init_alloc_root() sql/handler.cc: Added MY_THREAD_SPECIFIC to allocated memory. Added missing call to my_dir_end() sql/item_func.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/item_subselect.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/item_sum.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/log.cc: More DBUG Updated call to init_alloc_root() sql/mdl.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/mysqld.cc: Added total_memory_used Updated call to init_alloc_root() Move mysql_cond_broadcast() before my_thread_end() Added mariadb_dbug_id() to count memory per THD instead of per thread. Added my_malloc_size_cb_func() callback function for my_malloc() to count memory. Move initialization of mysqld_server_started and mysqld_server_initialized earlier. Updated call to my_init_dynamic_array(). Updated call to my_net_init(). Call my_pthread_setspecific_ptr(THR_THD,...) to ensure that memory is assigned to right thread. Added status variable 'memory_used'. Updated call to init_alloc_root() my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/mysqld.h: Added set_current_thd() sql/net_serv.cc: Added new parameter to my_net_init() so that one can mark memory with MY_THREAD_SPECIFIC. Store in net->thread_specific_malloc if memory is thread specific. Mark memory to be thread specific if requested. sql/opt_range.cc: Updated call to my_init_dynamic_array() Updated call to init_sql_alloc() Added MY_THREAD_SPECIFIC to allocated memory. sql/opt_subselect.cc: Updated call to init_sql_alloc() to mark memory thread specific. sql/protocol.cc: Fixed compiler warning sql/records.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/rpl_filter.cc: Updated call to my_init_dynamic_array() sql/rpl_handler.cc: Updated call to my_init_dynamic_array2() sql/rpl_handler.h: Updated call to init_sql_alloc() sql/rpl_mi.cc: Updated call to my_init_dynamic_array() sql/rpl_tblmap.cc: Updated call to init_alloc_root() sql/rpl_utility.cc: Updated call to my_init_dynamic_array() sql/slave.cc: Initialize things properly before calling functions that allocate memory. Removed calls to net_end() as this is now done in ~THD() sql/sp_head.cc: Updated call to init_sql_alloc() Updated call to my_init_dynamic_array() Added parameter to warning_info() that it should be fully initialized. sql/sp_pcontext.cc: Updated call to my_init_dynamic_array() sql/sql_acl.cc: Updated call to init_sql_alloc() Updated call to my_init_dynamic_array() my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_admin.cc: Added parameter to warning_info() that it should be fully initialized. sql/sql_analyse.h: Updated call to init_tree() to mark memory thread specific. sql/sql_array.h: Updated call to my_init_dynamic_array() to mark memory thread specific. sql/sql_audit.cc: Updated call to my_init_dynamic_array() sql/sql_base.cc: Updated call to init_sql_alloc() my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_cache.cc: Updated comment sql/sql_class.cc: Added parameter to warning_info() that not initialize it until THD is fully created. Updated call to init_sql_alloc() Mark THD::user_vars has to be thread specific. Updated call to my_init_dynamic_array() Ensure that memory allocated by THD is assigned to the THD. More DBUG Always acll net_end() in ~THD() Assert that all memory signed to this THD is really deleted at ~THD. Fixed set_status_var_init() to not reset memory_used. my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_class.h: Added MY_THREAD_SPECIFIC to allocated memory. Added malloc_size to THD to record allocated memory per THD. sql/sql_delete.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/sql_error.cc: Added 'initialize' parameter to Warning_info() to say if should allocate memory for it's structures. This is used by THD::THD() to not allocate memory until THD is ready. Added Warning_info::free_memory() sql/sql_error.h: Updated Warning_info() class. sql/sql_handler.cc: Updated call to init_alloc_root() to mark memory thread specific. sql/sql_insert.cc: More DBUG sql/sql_join_cache.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/sql_lex.cc: Updated call to my_init_dynamic_array() sql/sql_lex.h: Updated call to my_init_dynamic_array() sql/sql_load.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/sql_parse.cc: Removed calls to net_end() and thd->cleanup() as these are now done in ~THD() Ensure that examined_row_count() is reset before query. Fixed bug where kill_threads_for_user() was using the wrong mem_root to allocate memory. my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() Don't restore thd->status_var.memory_used when restoring thd->status_var sql/sql_plugin.cc: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() Don't allocate THD on the stack, as this causes problems with valgrind when doing thd memory counting. my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_prepare.cc: Added parameter to warning_info() that it should be fully initialized. Updated call to init_sql_alloc() to mark memory thread specific. sql/sql_reload.cc: my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_select.cc: Updated call to my_init_dynamic_array() and init_sql_alloc() to mark memory thread specific. Added MY_THREAD_SPECIFIC to allocated memory. More DBUG sql/sql_servers.cc: Updated call to init_sql_alloc() to mark memory some memory thread specific. my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_show.cc: Updated call to my_init_dynamic_array() Mark my_dir() memory thread specific. Use my_pthread_setspecific_ptr(THR_THD,...) to mark that allocated memory should be allocated to calling thread. More DBUG. Added malloc_size and examined_row_count to SHOW PROCESSLIST. Added MY_THREAD_SPECIFIC to allocated memory. Updated call to init_sql_alloc() Added parameter to warning_info() that it should be fully initialized. sql/sql_statistics.cc: Fixed compiler warning sql/sql_string.cc: String elements can now be marked as thread specific. sql/sql_string.h: String elements can now be marked as thread specific. sql/sql_table.cc: Updated call to init_sql_alloc() and my_malloc() to mark memory thread specific my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() Fixed compiler warning sql/sql_test.cc: Updated call to my_init_dynamic_array() to mark memory thread specific. sql/sql_trigger.cc: Updated call to init_sql_alloc() sql/sql_udf.cc: Updated call to init_sql_alloc() my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/sql_update.cc: Added MY_THREAD_SPECIFIC to allocated memory. sql/table.cc: Updated call to init_sql_alloc(). Mark memory used by temporary tables, that are not for slave threads, as MY_THREAD_SPECIFIC Updated call to init_sql_alloc() sql/thr_malloc.cc: Added my_flags argument to init_sql_alloc() to be able to mark memory as MY_THREAD_SPECIFIC. sql/thr_malloc.h: Updated prototype for init_sql_alloc() sql/tztime.cc: Updated call to init_sql_alloc() Updated call to init_alloc_root() to mark memory thread specific. my_pthread_setspecific_ptr(THR_THD,...) -> set_current_thd() sql/uniques.cc: Updated calls to init_tree(), my_init_dynamic_array() and my_malloc() to mark memory thread specific. sql/unireg.cc: Added MY_THREAD_SPECIFIC to allocated memory. storage/csv/ha_tina.cc: Updated call to init_alloc_root() storage/federated/ha_federated.cc: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() Ensure that memory allocated by fedarated is registered for the system, not for the thread. storage/federatedx/federatedx_io_mysql.cc: Updated call to my_init_dynamic_array() storage/federatedx/ha_federatedx.cc: Updated call to init_alloc_root() Updated call to my_init_dynamic_array() storage/heap/ha_heap.cc: Added MY_THREAD_SPECIFIC to allocated memory. storage/heap/heapdef.h: Added parameter to hp_get_new_block() to be able to do thread specific memory tagging. storage/heap/hp_block.c: Added parameter to hp_get_new_block() to be able to do thread specific memory tagging. storage/heap/hp_create.c: - Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC. - Use MY_TREE_WITH_DELETE instead of removed option 'with_delete'. storage/heap/hp_open.c: Internal HEAP tables are now marking it's memory as MY_THREAD_SPECIFIC. storage/heap/hp_write.c: Added new parameter to hp_get_new_block() storage/maria/ma_bitmap.c: Updated call to my_init_dynamic_array() storage/maria/ma_blockrec.c: Updated call to my_init_dynamic_array() storage/maria/ma_check.c: Updated call to init_alloc_root() storage/maria/ma_ft_boolean_search.c: Updated calls to init_tree() and init_alloc_root() storage/maria/ma_ft_nlq_search.c: Updated call to init_tree() storage/maria/ma_ft_parser.c: Updated call to init_tree() Updated call to init_alloc_root() storage/maria/ma_loghandler.c: Updated call to my_init_dynamic_array() storage/maria/ma_open.c: Updated call to my_init_dynamic_array() storage/maria/ma_sort.c: Updated call to my_init_dynamic_array() storage/maria/ma_write.c: Updated calls to my_init_dynamic_array() and init_tree() storage/maria/maria_pack.c: Updated call to init_tree() storage/maria/unittest/sequence_storage.c: Updated call to my_init_dynamic_array() storage/myisam/ft_boolean_search.c: Updated call to init_tree() Updated call to init_alloc_root() storage/myisam/ft_nlq_search.c: Updated call to init_tree() storage/myisam/ft_parser.c: Updated call to init_tree() Updated call to init_alloc_root() storage/myisam/ft_stopwords.c: Updated call to init_tree() storage/myisam/mi_check.c: Updated call to init_alloc_root() storage/myisam/mi_write.c: Updated call to my_init_dynamic_array() Updated call to init_tree() storage/myisam/myisamlog.c: Updated call to init_tree() storage/myisam/myisampack.c: Updated call to init_tree() storage/myisam/sort.c: Updated call to my_init_dynamic_array() storage/myisammrg/ha_myisammrg.cc: Updated call to init_sql_alloc() storage/perfschema/pfs_check.cc: Rest current_thd storage/perfschema/pfs_instr.cc: Removed DBUG_ENTER/DBUG_VOID_RETURN as at this point my_thread_var is not allocated anymore, which can cause problems. support-files/compiler_warnings.supp: Disable compiler warning from offsetof macro. --- sql/debug_sync.cc | 3 +- sql/event_data_objects.cc | 2 +- sql/event_scheduler.cc | 15 +++--- sql/events.cc | 2 +- sql/filesort.cc | 15 ++++-- sql/filesort_utils.cc | 6 +-- sql/ha_ndbcluster.cc | 6 +-- sql/ha_ndbcluster_binlog.cc | 6 +-- sql/ha_partition.cc | 6 +-- sql/handler.cc | 5 +- sql/item_func.cc | 7 ++- sql/item_subselect.cc | 4 +- sql/item_sum.cc | 3 +- sql/log.cc | 7 +-- sql/mdl.cc | 3 +- sql/mysqld.cc | 119 ++++++++++++++++++++++++++++++++++++-------- sql/mysqld.h | 1 + sql/net_serv.cc | 15 ++++-- sql/opt_range.cc | 29 +++++++---- sql/opt_subselect.cc | 2 +- sql/protocol.cc | 2 +- sql/records.cc | 2 +- sql/rpl_filter.cc | 2 +- sql/rpl_handler.cc | 2 +- sql/rpl_handler.h | 2 +- sql/rpl_mi.cc | 2 +- sql/rpl_tblmap.cc | 2 +- sql/rpl_utility.cc | 2 +- sql/slave.cc | 31 ++++++------ sql/sp_head.cc | 12 ++--- sql/sp_pcontext.cc | 40 +++++++-------- sql/sql_acl.cc | 18 +++---- sql/sql_admin.cc | 2 +- sql/sql_analyse.h | 14 ++++-- sql/sql_array.h | 3 +- sql/sql_audit.cc | 2 +- sql/sql_base.cc | 4 +- sql/sql_cache.cc | 4 +- sql/sql_class.cc | 54 ++++++++++++++++---- sql/sql_class.h | 9 +++- sql/sql_delete.cc | 3 +- sql/sql_error.cc | 25 ++++++++-- sql/sql_error.h | 8 ++- sql/sql_handler.cc | 2 +- sql/sql_insert.cc | 38 ++++++++------ sql/sql_join_cache.cc | 6 +-- sql/sql_lex.cc | 2 +- sql/sql_lex.h | 2 +- sql/sql_load.cc | 6 +-- sql/sql_parse.cc | 12 ++--- sql/sql_plugin.cc | 18 +++---- sql/sql_prepare.cc | 8 +-- sql/sql_reload.cc | 2 +- sql/sql_select.cc | 17 ++++--- sql/sql_servers.cc | 6 +-- sql/sql_show.cc | 49 ++++++++++++++---- sql/sql_statistics.cc | 3 +- sql/sql_string.cc | 14 ++++-- sql/sql_string.h | 27 +++++++--- sql/sql_table.cc | 9 ++-- sql/sql_test.cc | 4 +- sql/sql_trigger.cc | 4 +- sql/sql_udf.cc | 4 +- sql/sql_update.cc | 3 +- sql/table.cc | 15 ++++-- sql/thr_malloc.cc | 5 +- sql/thr_malloc.h | 3 +- sql/tztime.cc | 8 +-- sql/uniques.cc | 17 ++++--- sql/unireg.cc | 8 +-- 70 files changed, 521 insertions(+), 272 deletions(-) (limited to 'sql') diff --git a/sql/debug_sync.cc b/sql/debug_sync.cc index 1c95869987d..28d1109a0b4 100644 --- a/sql/debug_sync.cc +++ b/sql/debug_sync.cc @@ -239,7 +239,8 @@ void debug_sync_init_thread(THD *thd) if (opt_debug_sync_timeout) { thd->debug_sync_control= (st_debug_sync_control*) - my_malloc(sizeof(st_debug_sync_control), MYF(MY_WME | MY_ZEROFILL)); + my_malloc(sizeof(st_debug_sync_control), + MYF(MY_WME | MY_ZEROFILL | MY_THREAD_SPECIFIC)); if (!thd->debug_sync_control) { /* diff --git a/sql/event_data_objects.cc b/sql/event_data_objects.cc index c41194d1a8d..a5dac4c154b 100644 --- a/sql/event_data_objects.cc +++ b/sql/event_data_objects.cc @@ -209,7 +209,7 @@ Event_basic::Event_basic() { DBUG_ENTER("Event_basic::Event_basic"); /* init memory root */ - init_sql_alloc(&mem_root, 256, 512); + init_sql_alloc(&mem_root, 256, 512, 0); dbname.str= name.str= NULL; dbname.length= name.length= 0; time_zone= NULL; diff --git a/sql/event_scheduler.cc b/sql/event_scheduler.cc index f107914f738..8c3e57778ab 100644 --- a/sql/event_scheduler.cc +++ b/sql/event_scheduler.cc @@ -153,8 +153,6 @@ void deinit_event_thread(THD *thd) { thd->proc_info= "Clearing"; - DBUG_ASSERT(thd->net.buff != 0); - net_end(&thd->net); DBUG_PRINT("exit", ("Event thread finishing")); mysql_mutex_lock(&LOCK_thread_count); thread_count--; @@ -182,12 +180,15 @@ deinit_event_thread(THD *thd) void pre_init_event_thread(THD* thd) { + THD *orig_thd= current_thd; DBUG_ENTER("pre_init_event_thread"); + + set_current_thd(thd); thd->client_capabilities= 0; thd->security_ctx->master_access= 0; thd->security_ctx->db_access= 0; thd->security_ctx->host_or_ip= (char*)my_localhost; - my_net_init(&thd->net, NULL); + my_net_init(&thd->net, NULL, MYF(MY_THREAD_SPECIFIC)); thd->security_ctx->set_user((char*)"event_scheduler"); thd->net.read_timeout= slave_net_timeout; thd->variables.option_bits|= OPTION_AUTO_IS_NULL; @@ -207,6 +208,7 @@ pre_init_event_thread(THD* thd) /* Do not use user-supplied timeout value for system threads. */ thd->variables.lock_wait_timeout= LONG_TIMEOUT; + set_current_thd(orig_thd); DBUG_VOID_RETURN; } @@ -402,6 +404,7 @@ Event_scheduler::start() ret= TRUE; goto end; } + pre_init_event_thread(new_thd); new_thd->system_thread= SYSTEM_THREAD_EVENT_SCHEDULER; new_thd->command= COM_DAEMON; @@ -413,6 +416,7 @@ Event_scheduler::start() */ new_thd->security_ctx->master_access |= SUPER_ACL; + /* This should not be marked with MY_THREAD_SPECIFIC */ scheduler_param_value= (struct scheduler_param *)my_malloc(sizeof(struct scheduler_param), MYF(0)); scheduler_param_value->thd= new_thd; @@ -432,8 +436,6 @@ Event_scheduler::start() ret= TRUE; new_thd->proc_info= "Clearing"; - DBUG_ASSERT(new_thd->net.buff != 0); - net_end(&new_thd->net); mysql_mutex_lock(&LOCK_thread_count); thread_count--; dec_thread_running(); @@ -533,6 +535,7 @@ Event_scheduler::execute_top(Event_queue_element_for_exec *event_name) pthread_t th; int res= 0; DBUG_ENTER("Event_scheduler::execute_top"); + if (!(new_thd= new THD())) goto error; @@ -567,8 +570,6 @@ error: if (new_thd) { new_thd->proc_info= "Clearing"; - DBUG_ASSERT(new_thd->net.buff != 0); - net_end(&new_thd->net); mysql_mutex_lock(&LOCK_thread_count); thread_count--; dec_thread_running(); diff --git a/sql/events.cc b/sql/events.cc index d8caa059c64..46b13056d7d 100644 --- a/sql/events.cc +++ b/sql/events.cc @@ -879,7 +879,7 @@ end: } delete thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, NULL); + set_current_thd(0); DBUG_RETURN(res); } diff --git a/sql/filesort.cc b/sql/filesort.cc index 9c40ab877a4..3f735e94a11 100644 --- a/sql/filesort.cc +++ b/sql/filesort.cc @@ -200,7 +200,8 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, table_sort.unpack= unpack_addon_fields; if (param.addon_field && !(table_sort.addon_buf= - (uchar *) my_malloc(param.addon_length, MYF(MY_WME)))) + (uchar *) my_malloc(param.addon_length, MYF(MY_WME | + MY_THREAD_SPECIFIC)))) goto err; if (select && select->quick) @@ -213,7 +214,8 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length, num_rows= table->file->estimate_rows_upper_bound(); if (multi_byte_charset && - !(param.tmp_buffer= (char*) my_malloc(param.sort_length,MYF(MY_WME)))) + !(param.tmp_buffer= (char*) my_malloc(param.sort_length, + MYF(MY_WME | MY_THREAD_SPECIFIC)))) goto err; if (check_if_pq_applicable(¶m, &table_sort, @@ -453,7 +455,7 @@ static uchar *read_buffpek_from_file(IO_CACHE *buffpek_pointers, uint count, if (count > UINT_MAX/sizeof(BUFFPEK)) return 0; /* sizeof(BUFFPEK)*count will overflow */ if (!tmp) - tmp= (uchar *)my_malloc(length, MYF(MY_WME)); + tmp= (uchar *)my_malloc(length, MYF(MY_WME | MY_THREAD_SPECIFIC)); if (tmp) { if (reinit_io_cache(buffpek_pointers,READ_CACHE,0L,0,0) || @@ -1155,7 +1157,8 @@ static bool save_index(Sort_param *param, uint count, Filesort_info *table_sort) res_length= param->res_length; offset= param->rec_length-res_length; if (!(to= table_sort->record_pointers= - (uchar*) my_malloc(res_length*count, MYF(MY_WME)))) + (uchar*) my_malloc(res_length*count, + MYF(MY_WME | MY_THREAD_SPECIFIC)))) DBUG_RETURN(1); /* purecov: inspected */ uchar **sort_keys= table_sort->get_sort_keys(); for (uchar **end= sort_keys+count ; sort_keys != end ; sort_keys++) @@ -1897,7 +1900,9 @@ get_addon_fields(ulong max_length_for_sort_data, if (length+sortlength > max_length_for_sort_data || !(addonf= (SORT_ADDON_FIELD *) my_malloc(sizeof(SORT_ADDON_FIELD)* - (fields+1), MYF(MY_WME)))) + (fields+1), + MYF(MY_WME | + MY_THREAD_SPECIFIC)))) return 0; *plength= length; diff --git a/sql/filesort_utils.cc b/sql/filesort_utils.cc index c4480a6376d..f8f6d5c9420 100644 --- a/sql/filesort_utils.cc +++ b/sql/filesort_utils.cc @@ -99,7 +99,7 @@ uchar **Filesort_buffer::alloc_sort_buffer(uint num_records, uint record_length) sort_buff_sz= num_records * (record_length + sizeof(uchar*)); set_if_bigger(sort_buff_sz, record_length * MERGEBUFF2); uchar **sort_keys= - (uchar**) my_malloc(sort_buff_sz, MYF(0)); + (uchar**) my_malloc(sort_buff_sz, MYF(MY_THREAD_SPECIFIC)); m_idx_array= Idx_array(sort_keys, num_records); m_record_length= record_length; uchar **start_of_data= m_idx_array.array() + m_idx_array.size(); @@ -130,7 +130,8 @@ void Filesort_buffer::sort_buffer(const Sort_param *param, uint count) uchar **keys= get_sort_keys(); uchar **buffer= NULL; if (radixsort_is_appliccable(count, param->sort_length) && - (buffer= (uchar**) my_malloc(count*sizeof(char*), MYF(0)))) + (buffer= (uchar**) my_malloc(count*sizeof(char*), + MYF(MY_THREAD_SPECIFIC)))) { radixsort_for_str_ptr(keys, count, param->sort_length, buffer); my_free(buffer); @@ -140,4 +141,3 @@ void Filesort_buffer::sort_buffer(const Sort_param *param, uint count) size_t size= param->sort_length; my_qsort2(keys, count, sizeof(uchar*), get_ptr_compare(size), &size); } - diff --git a/sql/ha_ndbcluster.cc b/sql/ha_ndbcluster.cc index 6ba4fe46441..44d384e7f2d 100644 --- a/sql/ha_ndbcluster.cc +++ b/sql/ha_ndbcluster.cc @@ -8649,7 +8649,7 @@ NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table, MEM_ROOT **root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC); MEM_ROOT *old_root= *root_ptr; - init_sql_alloc(&share->mem_root, 1024, 0); + init_sql_alloc(&share->mem_root, 1024, 0, 0); *root_ptr= &share->mem_root; // remember to reset before return share->state= NSS_INITIAL; /* enough space for key, db, and table_name */ @@ -9493,7 +9493,7 @@ pthread_handler_t ndb_util_thread_func(void *arg __attribute__((unused))) thd->init_for_queries(); thd->main_security_ctx.host_or_ip= ""; thd->client_capabilities = 0; - my_net_init(&thd->net, 0); + my_net_init(&thd->net, 0, MYF(MY_THREAD_SPECIFIC)); thd->main_security_ctx.master_access= ~0; thd->main_security_ctx.priv_user[0] = 0; /* Do not use user-supplied timeout value for system threads. */ @@ -9730,11 +9730,9 @@ next: mysql_mutex_lock(&LOCK_ndb_util_thread); ndb_util_thread_end: - net_end(&thd->net); ndb_util_thread_fail: if (share_list) delete [] share_list; - thd->cleanup(); delete thd; /* signal termination */ diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc index 59b9d6eab6b..e7582d695ce 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -3665,7 +3665,7 @@ pthread_handler_t ndb_binlog_thread_func(void *arg) thd->system_thread= SYSTEM_THREAD_NDBCLUSTER_BINLOG; thd->main_security_ctx.host_or_ip= ""; thd->client_capabilities= 0; - my_net_init(&thd->net, 0); + my_net_init(&thd->net, 0, MYF(MY_THREAD_SPECIFIC)); thd->main_security_ctx.master_access= ~0; thd->main_security_ctx.priv_user[0]= 0; /* Do not use user-supplied timeout value for system threads. */ @@ -3964,7 +3964,7 @@ restart: my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC); MEM_ROOT *old_root= *root_ptr; MEM_ROOT mem_root; - init_sql_alloc(&mem_root, 4096, 0); + init_sql_alloc(&mem_root, 4096, 0, 0); List post_epoch_log_list; List post_epoch_unlock_list; *root_ptr= &mem_root; @@ -4364,8 +4364,6 @@ err: my_hash_free(&ndb_schema_objects); - net_end(&thd->net); - thd->cleanup(); delete thd; ndb_binlog_thread_running= -1; diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index b87192db69f..e28c461f4ce 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -168,7 +168,7 @@ ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share) :handler(hton, share) { DBUG_ENTER("ha_partition::ha_partition(table)"); - init_alloc_root(&m_mem_root, 512, 512); + init_alloc_root(&m_mem_root, 512, 512, 0); init_handler_variables(); DBUG_VOID_RETURN; } @@ -190,7 +190,7 @@ ha_partition::ha_partition(handlerton *hton, partition_info *part_info) { DBUG_ENTER("ha_partition::ha_partition(part_info)"); DBUG_ASSERT(part_info); - init_alloc_root(&m_mem_root, 512, 512); + init_alloc_root(&m_mem_root, 512, 512, 0); init_handler_variables(); m_part_info= part_info; m_create_handler= TRUE; @@ -217,7 +217,7 @@ ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share, :handler(hton, share) { DBUG_ENTER("ha_partition::ha_partition(clone)"); - init_alloc_root(&m_mem_root, 512, 512); + init_alloc_root(&m_mem_root, 512, 512, 0); init_handler_variables(); m_part_info= part_info_arg; m_create_handler= TRUE; diff --git a/sql/handler.cc b/sql/handler.cc index 6634bd6fb7a..0fac0d756ca 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -5352,7 +5352,7 @@ fl_log_iterator_buffer_init(struct handler_iterator *iterator) /* to be able to make my_free without crash in case of error */ iterator->buffer= 0; - if (!(dirp = my_dir(fl_dir, MYF(0)))) + if (!(dirp = my_dir(fl_dir, MYF(MY_THREAD_SPECIFIC)))) { return HA_ITERATOR_ERROR; } @@ -5361,7 +5361,7 @@ fl_log_iterator_buffer_init(struct handler_iterator *iterator) sizeof(enum log_status) + + FN_REFLEN + 1) * (uint) dirp->number_off_files), - MYF(0))) == 0) + MYF(MY_THREAD_SPECIFIC))) == 0) { return HA_ITERATOR_ERROR; } @@ -5395,6 +5395,7 @@ fl_log_iterator_buffer_init(struct handler_iterator *iterator) iterator->buffer= buff; iterator->next= &fl_log_iterator_next; iterator->destroy= &fl_log_iterator_destroy; + my_dirend(dirp); return HA_ITERATOR_OK; } diff --git a/sql/item_func.cc b/sql/item_func.cc index f0ca37152a3..520b5522d38 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -4343,7 +4343,9 @@ user_var_entry *get_variable(HASH *hash, LEX_STRING &name, uint size=ALIGN_SIZE(sizeof(user_var_entry))+name.length+1+extra_size; if (!my_hash_inited(hash)) return 0; - if (!(entry = (user_var_entry*) my_malloc(size,MYF(MY_WME | ME_FATALERROR)))) + if (!(entry = (user_var_entry*) my_malloc(size, + MYF(MY_WME | ME_FATALERROR | + MY_THREAD_SPECIFIC)))) return 0; entry->name.str=(char*) entry+ ALIGN_SIZE(sizeof(user_var_entry))+ extra_size; @@ -4571,7 +4573,8 @@ update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length, entry->value=0; entry->value= (char*) my_realloc(entry->value, length, MYF(MY_ALLOW_ZERO_PTR | MY_WME | - ME_FATALERROR)); + ME_FATALERROR | + MY_THREAD_SPECIFIC)); if (!entry->value) return 1; } diff --git a/sql/item_subselect.cc b/sql/item_subselect.cc index ab77bb0e59c..2ee513320ce 100644 --- a/sql/item_subselect.cc +++ b/sql/item_subselect.cc @@ -5053,7 +5053,7 @@ bool Ordered_key::alloc_keys_buffers() DBUG_ASSERT(key_buff_elements > 0); if (!(key_buff= (rownum_t*) my_malloc((size_t)(key_buff_elements * - sizeof(rownum_t)), MYF(MY_WME)))) + sizeof(rownum_t)), MYF(MY_WME | MY_THREAD_SPECIFIC)))) return TRUE; /* @@ -5480,7 +5480,7 @@ subselect_rowid_merge_engine::init(MY_BITMAP *non_null_key_parts, !(null_bitmaps= (MY_BITMAP**) thd->alloc(merge_keys_count * sizeof(MY_BITMAP*))) || !(row_num_to_rowid= (uchar*) my_malloc((size_t)(row_count * rowid_length), - MYF(MY_WME)))) + MYF(MY_WME | MY_THREAD_SPECIFIC)))) return TRUE; /* Create the only non-NULL key if there is any. */ diff --git a/sql/item_sum.cc b/sql/item_sum.cc index 217e65e401f..b1e248032bc 100644 --- a/sql/item_sum.cc +++ b/sql/item_sum.cc @@ -3485,7 +3485,8 @@ bool Item_func_group_concat::setup(THD *thd) init_tree(tree, (uint) min(thd->variables.max_heap_table_size, thd->variables.sortbuff_size/16), 0, tree_key_length, - group_concat_key_cmp_with_order , 0, NULL, (void*) this); + group_concat_key_cmp_with_order, NULL, (void*) this, + MYF(MY_THREAD_SPECIFIC)); } if (distinct) diff --git a/sql/log.cc b/sql/log.cc index 1ffceaf05a3..c6d91b1f67e 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -8194,8 +8194,9 @@ binlog_background_thread(void *arg __attribute__((unused))) bool stop; MYSQL_BIN_LOG::xid_count_per_binlog *queue, *next; THD *thd; - my_thread_init(); + DBUG_ENTER("binlog_background_thread"); + thd= new THD; thd->system_thread= SYSTEM_THREAD_BINLOG_BACKGROUND; thd->thread_stack= (char*) &thd; /* Set approximate stack start */ @@ -8259,7 +8260,7 @@ binlog_background_thread(void *arg __attribute__((unused))) mysql_cond_signal(&mysql_bin_log.COND_binlog_background_thread_end); mysql_mutex_unlock(&mysql_bin_log.LOCK_binlog_background_thread); - return 0; + DBUG_RETURN(0); } #ifdef HAVE_PSI_INTERFACE @@ -8310,7 +8311,7 @@ int TC_LOG_BINLOG::recover(LOG_INFO *linfo, const char *last_log_name, sizeof(my_xid), 0, 0, MYF(0))) goto err1; - init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE); + init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE, 0); fdle->flags&= ~LOG_EVENT_BINLOG_IN_USE_F; // abort on the first error diff --git a/sql/mdl.cc b/sql/mdl.cc index 5e297051377..97858646652 100644 --- a/sql/mdl.cc +++ b/sql/mdl.cc @@ -2200,7 +2200,8 @@ bool MDL_context::acquire_locks(MDL_request_list *mdl_requests, /* Sort requests according to MDL_key. */ if (! (sort_buf= (MDL_request **)my_malloc(req_count * sizeof(MDL_request*), - MYF(MY_WME)))) + MYF(MY_WME | + MY_THREAD_SPECIFIC)))) DBUG_RETURN(TRUE); for (p_req= sort_buf; p_req < sort_buf + req_count; p_req++) diff --git a/sql/mysqld.cc b/sql/mysqld.cc index 6d3c5980280..ca68f8c9ae2 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -1121,7 +1121,7 @@ private: void Buffered_logs::init() { - init_alloc_root(&m_root, 1024, 0); + init_alloc_root(&m_root, 1024, 0, 0); } void Buffered_logs::cleanup() @@ -1765,6 +1765,7 @@ extern "C" void unireg_abort(int exit_code) static void mysqld_exit(int exit_code) { + DBUG_ENTER("mysqld_exit"); /* Important note: we wait for the signal thread to end, but if a kill -15 signal was sent, the signal thread did @@ -1776,6 +1777,7 @@ static void mysqld_exit(int exit_code) clean_up_error_log_mutex(); my_end((opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0)); shutdown_performance_schema(); // we do it as late as possible + DBUG_LEAVE; exit(exit_code); /* purecov: inspected */ } @@ -2485,9 +2487,13 @@ void unlink_thd(THD *thd) sync feature has been shut down at this point. */ DBUG_EXECUTE_IF("sleep_after_lock_thread_count_before_delete_thd", sleep(5);); + /* + We must delete thd inside the lock to ensure that we don't start cleanup + before THD is deleted + */ + delete thd; mysql_mutex_unlock(&LOCK_thread_count); - delete thd; DBUG_VOID_RETURN; } @@ -2594,7 +2600,7 @@ bool one_thread_per_connection_end(THD *thd, bool put_in_cache) DBUG_ENTER("one_thread_per_connection_end"); unlink_thd(thd); /* Mark that current_thd is not valid anymore */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); if (put_in_cache) { mysql_mutex_lock(&LOCK_thread_count); @@ -2606,9 +2612,10 @@ bool one_thread_per_connection_end(THD *thd, bool put_in_cache) /* It's safe to broadcast outside a lock (COND... is not deleted here) */ DBUG_PRINT("signal", ("Broadcasting COND_thread_count")); + mysql_cond_broadcast(&COND_thread_count); + DBUG_LEAVE; // Must match DBUG_ENTER() my_thread_end(); - mysql_cond_broadcast(&COND_thread_count); pthread_exit(0); return 0; // Avoid compiler warnings @@ -3142,9 +3149,9 @@ void my_message_sql(uint error, const char *str, myf MyFlags) THD *thd= current_thd; MYSQL_ERROR::enum_warning_level level; sql_print_message_func func; - DBUG_ENTER("my_message_sql"); - DBUG_PRINT("error", ("error: %u message: '%s' Flag: %d", error, str, MyFlags)); + DBUG_PRINT("error", ("error: %u message: '%s' Flag: %lu", error, str, + MyFlags)); DBUG_ASSERT(str != NULL); DBUG_ASSERT(error != 0); @@ -3430,6 +3437,28 @@ SHOW_VAR com_status_vars[]= { {NullS, NullS, SHOW_LONG} }; +#ifdef SAFEMALLOC +/* + Return the id for the current THD, to allow safemalloc to associate + the memory with the right id. +*/ + +extern "C" my_thread_id mariadb_dbug_id() +{ + THD *thd; + if ((thd= current_thd)) + { + return thd->thread_id; + } + return my_thread_dbug_id(); +} +#endif /* SAFEMALLOC */ + + +/* + Init common variables +*/ + static int init_common_variables() { umask(((~my_umask) & 0666)); @@ -3438,6 +3467,9 @@ static int init_common_variables() tzset(); // Set tzname sf_leaking_memory= 0; // no memory leaks from now on +#ifdef SAFEMALLOC + sf_malloc_dbug_id= mariadb_dbug_id; +#endif max_system_variables.pseudo_thread_id= (ulong)~0; server_start_time= flush_status_time= my_time(0); @@ -3897,6 +3929,7 @@ You should consider changing lower_case_table_names to 1 or 2", static int init_thread_environment() { + DBUG_ENTER("init_thread_environment"); mysql_mutex_init(key_LOCK_thread_count, &LOCK_thread_count, MY_MUTEX_INIT_FAST); mysql_mutex_init(key_LOCK_status, &LOCK_status, MY_MUTEX_INIT_FAST); mysql_mutex_init(key_LOCK_delayed_insert, @@ -3975,9 +4008,9 @@ static int init_thread_environment() pthread_key_create(&THR_MALLOC,NULL)) { sql_print_error("Can't create thread-keys"); - return 1; + DBUG_RETURN(1); } - return 0; + DBUG_RETURN(0); } @@ -4641,6 +4674,37 @@ static void test_lc_time_sz() } #endif//DBUG_OFF + +/* Thread Mem Usage By P.Linux */ +extern "C" +void my_malloc_size_cb_func(long long size, myf my_flags) +{ + /* If thread specific memory */ + if (my_flags) + { + THD *thd= current_thd; + if (mysqld_server_initialized || thd) + { + /* + THD may not be set if we are called from my_net_init() before THD + thread has started. + However, this should never happen, so better to assert and + fix this. + */ + DBUG_ASSERT(thd); + if (thd) + { + DBUG_PRINT("info", ("memory_used: %lld size: %lld", + (longlong) thd->status_var.memory_used, size)); + thd->status_var.memory_used+= size; + DBUG_ASSERT((longlong) thd->status_var.memory_used >= 0); + } + } + } + my_atomic_add64(&global_status_var.memory_used, size); +} + + #ifdef __WIN__ int win_main(int argc, char **argv) #else @@ -4653,6 +4717,9 @@ int mysqld_main(int argc, char **argv) */ my_progname= argv[0]; sf_leaking_memory= 1; // no safemalloc memory leak reports if we exit early + set_malloc_size_cb(my_malloc_size_cb_func); + mysqld_server_started= mysqld_server_initialized= 0; + #ifdef HAVE_NPTL ld_assume_kernel_is_set= (getenv("LD_ASSUME_KERNEL") != 0); #endif @@ -4665,7 +4732,6 @@ int mysqld_main(int argc, char **argv) } #endif - mysqld_server_started= mysqld_server_initialized= 0; orig_argc= argc; orig_argv= argv; my_getopt_use_args_separator= TRUE; @@ -4695,7 +4761,7 @@ int mysqld_main(int argc, char **argv) my_getopt_skip_unknown= TRUE; /* prepare all_early_options array */ - my_init_dynamic_array(&all_early_options, sizeof(my_option), 100, 25); + my_init_dynamic_array(&all_early_options, sizeof(my_option), 100, 25, 0); sys_var_add_options(&all_early_options, sys_var::PARSE_EARLY); add_terminator(&all_early_options); @@ -4956,8 +5022,6 @@ int mysqld_main(int argc, char **argv) if (Events::init(opt_noacl || opt_bootstrap)) unireg_abort(1); - mysqld_server_initialized= 1; - if (opt_bootstrap) { select_thread_in_use= 0; // Allow 'kill' to work @@ -4971,6 +5035,9 @@ int mysqld_main(int argc, char **argv) } } + /* It's now safe to use thread specific memory */ + mysqld_server_initialized= 1; + create_shutdown_thread(); start_handle_manager(); @@ -5000,7 +5067,6 @@ int mysqld_main(int argc, char **argv) Service.SetRunning(); #endif - /* Signal threads waiting for server to be started */ mysql_mutex_lock(&LOCK_server_started); mysqld_server_started= 1; @@ -5180,6 +5246,7 @@ int mysqld_main(int argc, char **argv) /* Must be initialized early for comparison of service name */ system_charset_info= &my_charset_utf8_general_ci; + set_malloc_size_cb(my_malloc_size_cb_func); if (my_init()) { @@ -5288,7 +5355,7 @@ static void bootstrap(MYSQL_FILE *file) THD *thd= new THD; thd->bootstrap=1; - my_net_init(&thd->net,(st_vio*) 0); + my_net_init(&thd->net,(st_vio*) 0, 0); thd->max_client_packet_length= thd->net.max_packet; thd->security_ctx->master_access= ~(ulong)0; thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; @@ -5705,17 +5772,20 @@ void handle_connections_sockets() ** Don't allow too many connections */ + DBUG_PRINT("info", ("Creating THD for new connection")); if (!(thd= new THD)) { (void) mysql_socket_shutdown(new_sock, SHUT_RDWR); (void) closesocket(new_sock); continue; } + /* Set to get io buffers to be part of THD */ + set_current_thd(thd); if (!(vio_tmp=vio_new(new_sock, sock == unix_sock ? VIO_TYPE_SOCKET : VIO_TYPE_TCPIP, sock == unix_sock ? VIO_LOCALHOST: 0)) || - my_net_init(&thd->net,vio_tmp)) + my_net_init(&thd->net, vio_tmp, MYF(MY_THREAD_SPECIFIC))) { /* Only delete the temporary vio if we didn't already attach it to the @@ -5730,6 +5800,7 @@ void handle_connections_sockets() (void) closesocket(new_sock); } delete thd; + set_current_thd(0); continue; } if (sock == unix_sock) @@ -5741,6 +5812,7 @@ void handle_connections_sockets() thd->scheduler= extra_thread_scheduler; } create_new_thread(thd); + set_current_thd(0); } DBUG_VOID_RETURN; } @@ -5834,16 +5906,19 @@ pthread_handler_t handle_connections_namedpipes(void *arg) CloseHandle(hConnectedPipe); continue; } + set_current_thd(thd); if (!(thd->net.vio= vio_new_win32pipe(hConnectedPipe)) || - my_net_init(&thd->net, thd->net.vio)) + my_net_init(&thd->net, thd->net.vio, MYF(MY_THREAD_SPECIFIC))) { close_connection(thd, ER_OUT_OF_RESOURCES); delete thd; + set_current_thd(0); continue; } /* Host is unknown */ thd->security_ctx->host= my_strdup(my_localhost, MYF(0)); create_new_thread(thd); + set_current_thd(0); } CloseHandle(connectOverlapped.hEvent); DBUG_LEAVE; @@ -6023,6 +6098,7 @@ pthread_handler_t handle_connections_shared_memory(void *arg) errmsg= "Could not set client to read mode"; goto errorconn; } + set_current_thd(thd); if (!(thd->net.vio= vio_new_win32shared_memory(handle_client_file_map, handle_client_map, event_client_wrote, @@ -6030,7 +6106,7 @@ pthread_handler_t handle_connections_shared_memory(void *arg) event_server_wrote, event_server_read, event_conn_closed)) || - my_net_init(&thd->net, thd->net.vio)) + my_net_init(&thd->net, thd->net.vio, MYF(MY_THREAD_SPECIFIC))) { close_connection(thd, ER_OUT_OF_RESOURCES); errmsg= 0; @@ -6039,6 +6115,7 @@ pthread_handler_t handle_connections_shared_memory(void *arg) thd->security_ctx->host= my_strdup(my_localhost, MYF(0)); /* Host is unknown */ create_new_thread(thd); connect_number++; + set_current_thd(thd); continue; errorconn: @@ -6066,6 +6143,7 @@ errorconn: CloseHandle(event_conn_closed); delete thd; } + set_current_thd(0); /* End shared memory handling */ error: @@ -7024,6 +7102,7 @@ SHOW_VAR status_vars[]= { {"Key", (char*) &show_default_keycache, SHOW_FUNC}, {"Last_query_cost", (char*) offsetof(STATUS_VAR, last_query_cost), SHOW_DOUBLE_STATUS}, {"Max_used_connections", (char*) &max_used_connections, SHOW_LONG}, + {"Memory_used", (char*) offsetof(STATUS_VAR, memory_used), SHOW_LONGLONG_STATUS}, {"Not_flushed_delayed_rows", (char*) &delayed_rows_in_use, SHOW_LONG_NOFLUSH}, {"Open_files", (char*) &my_file_opened, SHOW_LONG_NOFLUSH}, {"Open_streams", (char*) &my_stream_opened, SHOW_LONG_NOFLUSH}, @@ -7170,7 +7249,7 @@ static int option_cmp(my_option *a, my_option *b) static void print_help() { MEM_ROOT mem_root; - init_alloc_root(&mem_root, 4096, 4096); + init_alloc_root(&mem_root, 4096, 4096, 0); pop_dynamic(&all_options); sys_var_add_options(&all_options, sys_var::PARSE_EARLY); @@ -7862,7 +7941,7 @@ static int get_options(int *argc_ptr, char ***argv_ptr) /* prepare all_options array */ my_init_dynamic_array(&all_options, sizeof(my_option), array_elements(my_long_options), - array_elements(my_long_options)/4); + array_elements(my_long_options)/4, 0); for (my_option *opt= my_long_options; opt < my_long_options + array_elements(my_long_options) - 1; opt++) @@ -8364,7 +8443,7 @@ void refresh_status(THD *thd) add_to_status(&global_status_var, &thd->status_var); /* Reset thread's status variables */ - bzero((uchar*) &thd->status_var, sizeof(thd->status_var)); + thd->set_status_var_init(); bzero((uchar*) &thd->org_status_var, sizeof(thd->org_status_var)); thd->start_bytes_received= 0; diff --git a/sql/mysqld.h b/sql/mysqld.h index a9b41a5e116..e9c4f713182 100644 --- a/sql/mysqld.h +++ b/sql/mysqld.h @@ -534,6 +534,7 @@ inline THD *_current_thd(void) } #endif #define current_thd _current_thd() +#define set_current_thd(X) my_pthread_setspecific_ptr(THR_THD, (X)) /* @todo remove, make it static in ha_maria.cc diff --git a/sql/net_serv.cc b/sql/net_serv.cc index 08ac93f3091..cf3e962053c 100644 --- a/sql/net_serv.cc +++ b/sql/net_serv.cc @@ -120,14 +120,15 @@ static my_bool net_write_buff(NET *net,const uchar *packet,ulong len); /** Init with packet info. */ -my_bool my_net_init(NET *net, Vio* vio) +my_bool my_net_init(NET *net, Vio* vio, uint my_flags) { DBUG_ENTER("my_net_init"); + DBUG_PRINT("enter", ("my_flags: %u", my_flags)); net->vio = vio; my_net_local_init(net); /* Set some limits */ if (!(net->buff=(uchar*) my_malloc((size_t) net->max_packet+ NET_HEADER_SIZE + COMP_HEADER_SIZE +1, - MYF(MY_WME)))) + MYF(MY_WME | my_flags)))) DBUG_RETURN(1); net->buff_end=net->buff+net->max_packet; net->error=0; net->return_status=0; @@ -139,6 +140,7 @@ my_bool my_net_init(NET *net, Vio* vio) net->net_skip_rest_factor= 0; net->last_errno=0; net->unused= 0; + net->thread_specific_malloc= test(my_flags & MY_THREAD_SPECIFIC); if (vio != 0) /* If real connection */ { @@ -193,7 +195,9 @@ my_bool net_realloc(NET *net, size_t length) */ if (!(buff= (uchar*) my_realloc((char*) net->buff, pkt_length + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1, - MYF(MY_WME)))) + MYF(MY_WME | + (net->thread_specific_malloc ? + MY_THREAD_SPECIFIC : 0))))) { /* @todo: 1 and 2 codes are identical. */ net->error= 1; @@ -603,7 +607,10 @@ net_real_write(NET *net,const uchar *packet, size_t len) uchar *b; uint header_length=NET_HEADER_SIZE+COMP_HEADER_SIZE; if (!(b= (uchar*) my_malloc(len + NET_HEADER_SIZE + - COMP_HEADER_SIZE + 1, MYF(MY_WME)))) + COMP_HEADER_SIZE + 1, + MYF(MY_WME | + (net->thread_specific_malloc ? + MY_THREAD_SPECIFIC : 0))))) { net->error= 2; net->last_errno= ER_OUT_OF_RESOURCES; diff --git a/sql/opt_range.cc b/sql/opt_range.cc index 7f8d527564b..d3c2ec5a132 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -1772,7 +1772,8 @@ QUICK_RANGE_SELECT::QUICK_RANGE_SELECT(THD *thd, TABLE *table, uint key_nr, index= key_nr; head= table; key_part_info= head->key_info[index].key_part; - my_init_dynamic_array(&ranges, sizeof(QUICK_RANGE*), 16, 16); + my_init_dynamic_array(&ranges, sizeof(QUICK_RANGE*), 16, 16, + MYF(MY_THREAD_SPECIFIC)); /* 'thd' is not accessible in QUICK_RANGE_SELECT::reset(). */ mrr_buf_size= thd->variables.mrr_buff_size; @@ -1781,7 +1782,8 @@ QUICK_RANGE_SELECT::QUICK_RANGE_SELECT(THD *thd, TABLE *table, uint key_nr, if (!no_alloc && !parent_alloc) { // Allocates everything through the internal memroot - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); thd->mem_root= &alloc; } else @@ -1793,7 +1795,7 @@ QUICK_RANGE_SELECT::QUICK_RANGE_SELECT(THD *thd, TABLE *table, uint key_nr, /* Allocate a bitmap for used columns (Q: why not on MEM_ROOT?) */ if (!(bitmap= (my_bitmap_map*) my_malloc(head->s->column_bitmap_size, - MYF(MY_WME)))) + MYF(MY_WME | MY_THREAD_SPECIFIC)))) { column_bitmap.bitmap= 0; *create_error= 1; @@ -1879,7 +1881,8 @@ QUICK_INDEX_SORT_SELECT::QUICK_INDEX_SORT_SELECT(THD *thd_param, index= MAX_KEY; head= table; bzero(&read_record, sizeof(read_record)); - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); DBUG_VOID_RETURN; } @@ -1949,7 +1952,8 @@ QUICK_ROR_INTERSECT_SELECT::QUICK_ROR_INTERSECT_SELECT(THD *thd_param, head= table; record= head->record[0]; if (!parent_alloc) - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); else bzero(&alloc, sizeof(MEM_ROOT)); last_rowid= (uchar*) alloc_root(parent_alloc? parent_alloc : &alloc, @@ -2232,7 +2236,8 @@ QUICK_ROR_UNION_SELECT::QUICK_ROR_UNION_SELECT(THD *thd_param, head= table; rowid_length= table->file->ref_length; record= head->record[0]; - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); thd_param->mem_root= &alloc; } @@ -2966,7 +2971,8 @@ int SQL_SELECT::test_quick_select(THD *thd, key_map keys_to_use, param.force_default_mrr= ordered_output; thd->no_errors=1; // Don't warn about NULL - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); if (!(param.key_parts= (KEY_PART*) alloc_root(&alloc, sizeof(KEY_PART) * @@ -3411,7 +3417,8 @@ bool prune_partitions(THD *thd, TABLE *table, Item *pprune_cond) my_bitmap_map *old_sets[2]; prune_param.part_info= part_info; - init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); range_par->mem_root= &alloc; range_par->old_root= thd->mem_root; @@ -12859,7 +12866,8 @@ QUICK_GROUP_MIN_MAX_SELECT(TABLE *table, JOIN *join_arg, bool have_min_arg, DBUG_ASSERT(!parent_alloc); if (!parent_alloc) { - init_sql_alloc(&alloc, join->thd->variables.range_alloc_block_size, 0); + init_sql_alloc(&alloc, join->thd->variables.range_alloc_block_size, 0, + MYF(MY_THREAD_SPECIFIC)); join->thd->mem_root= &alloc; } else @@ -12914,7 +12922,8 @@ int QUICK_GROUP_MIN_MAX_SELECT::init() if (min_max_arg_part) { - if (my_init_dynamic_array(&min_max_ranges, sizeof(QUICK_RANGE*), 16, 16)) + if (my_init_dynamic_array(&min_max_ranges, sizeof(QUICK_RANGE*), 16, 16, + MYF(MY_THREAD_SPECIFIC))) return 1; if (have_min) diff --git a/sql/opt_subselect.cc b/sql/opt_subselect.cc index 1c2e037e8cc..75566b97d3b 100644 --- a/sql/opt_subselect.cc +++ b/sql/opt_subselect.cc @@ -3872,7 +3872,7 @@ SJ_TMP_TABLE::create_sj_weedout_tmp_table(THD *thd) using_unique_constraint= TRUE; /* STEP 3: Allocate memory for temptable description */ - init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (!multi_alloc_root(&own_root, &table, sizeof(*table), &share, sizeof(*share), diff --git a/sql/protocol.cc b/sql/protocol.cc index 3af7dc88b88..f6e9e9e62e1 100644 --- a/sql/protocol.cc +++ b/sql/protocol.cc @@ -776,7 +776,7 @@ bool Protocol::send_result_set_metadata(List *list, uint flags) pos= (char*) local_packet->ptr()+local_packet->length(); *pos++= 12; // Length of packed fields /* inject a NULL to test the client */ - DBUG_EXECUTE_IF("poison_rs_fields", pos[-1]= 0xfb;); + DBUG_EXECUTE_IF("poison_rs_fields", pos[-1]= (char) 0xfb;); if (item->charset_for_protocol() == &my_charset_bin || thd_charset == NULL) { /* No conversion */ diff --git a/sql/records.cc b/sql/records.cc index d52481c36f5..c98532c1424 100644 --- a/sql/records.cc +++ b/sql/records.cc @@ -588,7 +588,7 @@ static int init_rr_cache(THD *thd, READ_RECORD *info) if (info->cache_records <= 2 || !(info->cache=(uchar*) my_malloc_lock(rec_cache_size+info->cache_records* info->struct_length+1, - MYF(0)))) + MYF(MY_THREAD_SPECIFIC)))) DBUG_RETURN(1); #ifdef HAVE_valgrind // Avoid warnings in qsort diff --git a/sql/rpl_filter.cc b/sql/rpl_filter.cc index 0380bc323a3..b44c3c7504c 100644 --- a/sql/rpl_filter.cc +++ b/sql/rpl_filter.cc @@ -573,7 +573,7 @@ void Rpl_filter::init_table_rule_array(DYNAMIC_ARRAY* a, bool* a_inited) { my_init_dynamic_array(a, sizeof(TABLE_RULE_ENT*), TABLE_RULE_ARR_SIZE, - TABLE_RULE_ARR_SIZE); + TABLE_RULE_ARR_SIZE, 0); *a_inited = 1; } diff --git a/sql/rpl_handler.cc b/sql/rpl_handler.cc index 9267190605c..07eeef57842 100644 --- a/sql/rpl_handler.cc +++ b/sql/rpl_handler.cc @@ -189,7 +189,7 @@ void delegates_destroy() DYNAMIC_ARRAY *plugins= &s.plugins; \ plugin_ref *plugins_buffer= s.plugins_buffer; \ my_init_dynamic_array2(plugins, sizeof(plugin_ref), \ - plugins_buffer, 8, 8); \ + plugins_buffer, 8, 8, 0); \ read_lock(); \ Observer_info_iterator iter= observer_info_iter(); \ Observer_info *info= iter++; \ diff --git a/sql/rpl_handler.h b/sql/rpl_handler.h index 4743fffb9a0..e955707f5c3 100644 --- a/sql/rpl_handler.h +++ b/sql/rpl_handler.h @@ -124,7 +124,7 @@ public: inited= FALSE; if (my_rwlock_init(&lock, NULL)) return; - init_sql_alloc(&memroot, 1024, 0); + init_sql_alloc(&memroot, 1024, 0, 0); inited= TRUE; } ~Delegate() diff --git a/sql/rpl_mi.cc b/sql/rpl_mi.cc index fc13fb2c762..73a2e26faba 100644 --- a/sql/rpl_mi.cc +++ b/sql/rpl_mi.cc @@ -61,7 +61,7 @@ Master_info::Master_info(LEX_STRING *connection_name_arg, my_casedn_str(system_charset_info, cmp_connection_name.str); } - my_init_dynamic_array(&ignore_server_ids, sizeof(::server_id), 16, 16); + my_init_dynamic_array(&ignore_server_ids, sizeof(::server_id), 16, 16, 0); bzero((char*) &file, sizeof(file)); mysql_mutex_init(key_master_info_run_lock, &run_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(key_master_info_data_lock, &data_lock, MY_MUTEX_INIT_FAST); diff --git a/sql/rpl_tblmap.cc b/sql/rpl_tblmap.cc index b7ac1b2d091..92d8ca228b0 100644 --- a/sql/rpl_tblmap.cc +++ b/sql/rpl_tblmap.cc @@ -46,7 +46,7 @@ table_mapping::table_mapping() offsetof(entry,table_id),sizeof(ulong), 0,0,0); /* We don't preallocate any block, this is consistent with m_free=0 above */ - init_alloc_root(&m_mem_root, TABLE_ID_HASH_SIZE*sizeof(entry), 0); + init_alloc_root(&m_mem_root, TABLE_ID_HASH_SIZE*sizeof(entry), 0, 0); DBUG_VOID_RETURN; } diff --git a/sql/rpl_utility.cc b/sql/rpl_utility.cc index 069fac1c3ec..321aead841e 100644 --- a/sql/rpl_utility.cc +++ b/sql/rpl_utility.cc @@ -1117,7 +1117,7 @@ bool event_checksum_test(uchar *event_buf, ulong event_len, uint8 alg) Deferred_log_events::Deferred_log_events(Relay_log_info *rli) : last_added(NULL) { - my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16); + my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16, 0); } Deferred_log_events::~Deferred_log_events() diff --git a/sql/slave.cc b/sql/slave.cc index 1db0261c73e..9e552e64a9e 100644 --- a/sql/slave.cc +++ b/sql/slave.cc @@ -1779,7 +1779,9 @@ past_checksum: } } } +#ifndef DBUG_OFF after_set_capability: +#endif err: if (errmsg) @@ -2426,10 +2428,22 @@ static int init_slave_thread(THD* thd, Master_info *mi, #if !defined(DBUG_OFF) int simulate_error= 0; #endif + DBUG_EXECUTE_IF("simulate_io_slave_error_on_init", + simulate_error|= (1 << SLAVE_THD_IO);); + DBUG_EXECUTE_IF("simulate_sql_slave_error_on_init", + simulate_error|= (1 << SLAVE_THD_SQL);); + /* We must call store_globals() before doing my_net_init() */ + if (init_thr_lock() || thd->store_globals() || + my_net_init(&thd->net, 0, MYF(MY_THREAD_SPECIFIC)) || + IF_DBUG(simulate_error & (1<< thd_type), 0)) + { + thd->cleanup(); + DBUG_RETURN(-1); + } + thd->system_thread = (thd_type == SLAVE_THD_SQL) ? SYSTEM_THREAD_SLAVE_SQL : SYSTEM_THREAD_SLAVE_IO; thd->security_ctx->skip_grants(); - my_net_init(&thd->net, 0); /* Adding MAX_LOG_EVENT_HEADER_LEN to the max_allowed_packet on all slave threads, since a replication event can become this much larger @@ -2446,17 +2460,6 @@ static int init_slave_thread(THD* thd, Master_info *mi, thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; mysql_mutex_unlock(&LOCK_thread_count); - DBUG_EXECUTE_IF("simulate_io_slave_error_on_init", - simulate_error|= (1 << SLAVE_THD_IO);); - DBUG_EXECUTE_IF("simulate_sql_slave_error_on_init", - simulate_error|= (1 << SLAVE_THD_SQL);); - if (init_thr_lock() || thd->store_globals() || - IF_DBUG(simulate_error & (1<< thd_type), 0)) - { - thd->cleanup(); - DBUG_RETURN(-1); - } - if (thd_type == SLAVE_THD_SQL) thd_proc_info(thd, "Waiting for the next event in relay log"); else @@ -3494,8 +3497,6 @@ err_during_init: mi->rli.relay_log.description_event_for_queue= 0; // TODO: make rpl_status part of Master_info change_rpl_status(RPL_ACTIVE_SLAVE,RPL_IDLE_SLAVE); - DBUG_ASSERT(thd->net.buff != 0); - net_end(&thd->net); // destructor will not free it, because net.vio is 0 mysql_mutex_lock(&LOCK_thread_count); THD_CHECK_SENTRY(thd); delete thd; @@ -3901,8 +3902,6 @@ err_during_init: to avoid unneeded position re-init */ thd->temporary_tables = 0; // remove tempation from destructor to close them - DBUG_ASSERT(thd->net.buff != 0); - net_end(&thd->net); // destructor will not free it, because we are weird DBUG_ASSERT(rli->sql_thd == thd); THD_CHECK_SENTRY(thd); rli->sql_thd= 0; diff --git a/sql/sp_head.cc b/sql/sp_head.cc index a24da193c00..1d6aa73fdb0 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -510,7 +510,7 @@ sp_head::operator new(size_t size) throw() MEM_ROOT own_root; sp_head *sp; - init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC); + init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, 0); sp= (sp_head *) alloc_root(&own_root, size); if (sp == NULL) DBUG_RETURN(NULL); @@ -594,7 +594,7 @@ sp_head::init(LEX *lex) types of stored procedures to simplify reset_lex()/restore_lex() code. */ lex->trg_table_fields.empty(); - my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8); + my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8, 0); m_param_begin= NULL; m_param_end= NULL; @@ -1224,7 +1224,7 @@ sp_head::execute(THD *thd, bool merge_da_on_success) Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer; Object_creation_ctx *saved_creation_ctx; Warning_info *saved_warning_info; - Warning_info warning_info(thd->warning_info->warn_id(), false); + Warning_info warning_info(thd->warning_info->warn_id(), false, true); /* Just reporting a stack overrun error @@ -1254,7 +1254,7 @@ sp_head::execute(THD *thd, bool merge_da_on_success) DBUG_RETURN(TRUE); /* init per-instruction memroot */ - init_sql_alloc(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0); + init_sql_alloc(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); DBUG_ASSERT(!(m_flags & IS_INVOKED)); m_flags|= IS_INVOKED; @@ -1711,7 +1711,7 @@ sp_head::execute_trigger(THD *thd, TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a trigger. */ - init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0); + init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); thd->set_n_backup_active_arena(&call_arena, &backup_arena); if (!(nctx= new sp_rcontext(m_pcont, 0, octx)) || @@ -1828,7 +1828,7 @@ sp_head::execute_function(THD *thd, Item **argp, uint argcount, TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a function/trigger. */ - init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0); + init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); thd->set_n_backup_active_arena(&call_arena, &backup_arena); if (!(nctx= new sp_rcontext(m_pcont, return_value_fld, octx)) || diff --git a/sql/sp_pcontext.cc b/sql/sp_pcontext.cc index 4c5087eaf27..cdafc5cd819 100644 --- a/sql/sp_pcontext.cc +++ b/sql/sp_pcontext.cc @@ -61,20 +61,20 @@ sp_pcontext::sp_pcontext() m_label_scope(LABEL_DEFAULT_SCOPE) { (void) my_init_dynamic_array(&m_vars, sizeof(sp_variable_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_case_expr_id_lst, sizeof(int), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_conds, sizeof(sp_cond_type_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_cursors, sizeof(LEX_STRING), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_handlers, sizeof(sp_cond_type_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); m_label.empty(); m_children.empty(); @@ -89,20 +89,20 @@ sp_pcontext::sp_pcontext(sp_pcontext *prev, label_scope_type label_scope) m_label_scope(label_scope) { (void) my_init_dynamic_array(&m_vars, sizeof(sp_variable_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_case_expr_id_lst, sizeof(int), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_conds, sizeof(sp_cond_type_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_cursors, sizeof(LEX_STRING), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); (void) my_init_dynamic_array(&m_handlers, sizeof(sp_cond_type_t *), - PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC); + PCONTEXT_ARRAY_INIT_ALLOC, + PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); m_label.empty(); m_children.empty(); diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 31627189296..9fa908c43e2 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -688,7 +688,7 @@ my_bool acl_init(bool dont_read_acl_tables) return_val= acl_reload(thd); delete thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); DBUG_RETURN(return_val); } @@ -749,13 +749,13 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) acl_cache->clear(1); // Clear locked hostname cache - init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, 0); if (init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0, FALSE)) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST),20,50); + (void) my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST), 20, 50, 0); while (!(read_record_info.read_record(&read_record_info))) { ACL_HOST host; @@ -807,7 +807,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_users,sizeof(ACL_USER),50,100); + (void) my_init_dynamic_array(&acl_users,sizeof(ACL_USER), 50, 100, 0); password_length= table->field[2]->field_length / table->field[2]->charset()->mbmaxlen; if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323) @@ -1009,7 +1009,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB),50,100); + (void) my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB), 50, 100, 0); while (!(read_record_info.read_record(&read_record_info))) { ACL_DB db; @@ -1067,7 +1067,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) freeze_size(&acl_dbs); (void) my_init_dynamic_array(&acl_proxy_users, sizeof(ACL_PROXY_USER), - 50, 100); + 50, 100, 0); if (tables[3].table) { init_read_record(&read_record_info, thd, table= tables[3].table, NULL, 1, @@ -1722,7 +1722,7 @@ static void init_check_host(void) { DBUG_ENTER("init_check_host"); (void) my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip), - acl_users.elements,1); + acl_users.elements, 1, 0); (void) my_hash_init(&acl_check_hosts,system_charset_info, acl_users.elements, 0, 0, (my_hash_get_key) check_get_key, 0, 0); @@ -4121,7 +4121,7 @@ my_bool grant_init() return_val= grant_reload(thd); delete thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); DBUG_RETURN(return_val); } @@ -4412,7 +4412,7 @@ my_bool grant_reload(THD *thd) opertion possible in case of failure. */ old_mem= memex; - init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0, 0); if ((return_val= grant_load(thd, tables))) { // Error. Revert to old hash diff --git a/sql/sql_admin.cc b/sql/sql_admin.cc index e6bbef482a7..ba1ea01efcc 100644 --- a/sql/sql_admin.cc +++ b/sql/sql_admin.cc @@ -398,7 +398,7 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables, because it's already known that the table is badly damaged. */ - Warning_info wi(thd->query_id, false); + Warning_info wi(thd->query_id, false, true); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; diff --git a/sql/sql_analyse.h b/sql/sql_analyse.h index 34c8e2da3d4..8bac29de5a3 100644 --- a/sql/sql_analyse.h +++ b/sql/sql_analyse.h @@ -121,7 +121,8 @@ public: must_be_blob(0), was_zero_fill(0), was_maybe_zerofill(0), can_be_still_num(1) { init_tree(&tree, 0, 0, sizeof(String), (qsort_cmp2) sortcmp2, - 0, (tree_element_free) free_string, NULL); }; + (tree_element_free) free_string, NULL, + MYF(MY_THREAD_SPECIFIC)); }; void add(); void get_opt_type(String*, ha_rows); @@ -162,7 +163,7 @@ public: { bin_size= my_decimal_get_binary_size(a->max_length, a->decimals); init_tree(&tree, 0, 0, bin_size, (qsort_cmp2)compare_decimal2, - 0, 0, (void *)&bin_size); + 0, (void *)&bin_size, MYF(MY_THREAD_SPECIFIC)); }; void add(); @@ -190,7 +191,8 @@ public: field_real(Item* a, analyse* b) :field_info(a,b), min_arg(0), max_arg(0), sum(0), sum_sqr(0), max_notzero_dec_len(0) { init_tree(&tree, 0, 0, sizeof(double), - (qsort_cmp2) compare_double2, 0, NULL, NULL); } + (qsort_cmp2) compare_double2, NULL, NULL, + MYF(MY_THREAD_SPECIFIC)); } void add(); void get_opt_type(String*, ha_rows); @@ -244,7 +246,8 @@ public: field_longlong(Item* a, analyse* b) :field_info(a,b), min_arg(0), max_arg(0), sum(0), sum_sqr(0) { init_tree(&tree, 0, 0, sizeof(longlong), - (qsort_cmp2) compare_longlong2, 0, NULL, NULL); } + (qsort_cmp2) compare_longlong2, NULL, NULL, + MYF(MY_THREAD_SPECIFIC)); } void add(); void get_opt_type(String*, ha_rows); @@ -289,7 +292,8 @@ public: field_ulonglong(Item* a, analyse * b) :field_info(a,b), min_arg(0), max_arg(0), sum(0),sum_sqr(0) { init_tree(&tree, 0, 0, sizeof(ulonglong), - (qsort_cmp2) compare_ulonglong2, 0, NULL, NULL); } + (qsort_cmp2) compare_ulonglong2, NULL, NULL, + MYF(MY_THREAD_SPECIFIC)); } void add(); void get_opt_type(String*, ha_rows); String *get_min_arg(String *s) { s->set(min_arg,my_thd_charset); return s; } diff --git a/sql/sql_array.h b/sql/sql_array.h index 98a4a4815af..18881d2c345 100644 --- a/sql/sql_array.h +++ b/sql/sql_array.h @@ -100,7 +100,8 @@ template class Dynamic_array public: Dynamic_array(uint prealloc=16, uint increment=16) { - my_init_dynamic_array(&array, sizeof(Elem), prealloc, increment); + my_init_dynamic_array(&array, sizeof(Elem), prealloc, increment, + MY_THREAD_SPECIFIC); } Elem& at(int idx) diff --git a/sql/sql_audit.cc b/sql/sql_audit.cc index 131a71c1d6b..4403034bca8 100644 --- a/sql/sql_audit.cc +++ b/sql/sql_audit.cc @@ -156,7 +156,7 @@ static my_bool acquire_plugins(THD *thd, plugin_ref plugin, void *arg) { /* specify some reasonable initialization defaults */ my_init_dynamic_array(&thd->audit_class_plugins, - sizeof(plugin_ref), 16, 16); + sizeof(plugin_ref), 16, 16, 0); } /* lock the plugin and add it to the list */ diff --git a/sql/sql_base.cc b/sql/sql_base.cc index 9f21b7f006b..fd0d0603395 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -4973,7 +4973,7 @@ bool open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags, anything yet, to avoid penalty for statements which don't use views and thus new .FRM format. */ - init_sql_alloc(&new_frm_mem, 8024, 0); + init_sql_alloc(&new_frm_mem, 8024, 0, 0); thd->current_tablenr= 0; restart: @@ -9265,7 +9265,7 @@ my_bool mysql_rm_tmp_tables(void) my_dirend(dirp); } delete thd; - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); DBUG_RETURN(0); } diff --git a/sql/sql_cache.cc b/sql/sql_cache.cc index 191cc4e01c8..ddc75254c9e 100644 --- a/sql/sql_cache.cc +++ b/sql/sql_cache.cc @@ -1035,8 +1035,8 @@ void query_cache_insert(const char *packet, ulong length, /* Current_thd can be NULL when a new connection is immediately ended due to "Too many connections". thd->store_globals() has not been - called at this time and hence my_pthread_setspecific_ptr(THR_THD, - this) has not been called for this thread. + called at this time and hence set_current_thd(this) has not been + called for this thread. */ if (!thd) diff --git a/sql/sql_class.cc b/sql/sql_class.cc index d6a0eaf9b52..1d0d23a2390 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -807,17 +807,28 @@ THD::THD() #if defined(ENABLED_DEBUG_SYNC) debug_sync_control(0), #endif /* defined(ENABLED_DEBUG_SYNC) */ - main_warning_info(0, false) + main_warning_info(0, false, false) { ulong tmp; mdl_context.init(this); + /* + We set THR_THD to temporally point to this THD to register all the + variables that allocates memory for this THD + */ + THD *old_THR_THD= current_thd; + set_current_thd(this); + status_var.memory_used= 0; + + main_warning_info.init(); /* Pass nominal parameters to init_alloc_root only to ensure that the destructor works OK in case of an error. The main_mem_root will be re-initialized in init_for_queries(). */ - init_sql_alloc(&main_mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0); + init_sql_alloc(&main_mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0, + MYF(MY_THREAD_SPECIFIC)); + stmt_arena= this; thread_stack= 0; scheduler= thread_scheduler; // Will be fixed later @@ -874,6 +885,7 @@ THD::THD() mysql_audit_init_thd(this); #endif net.vio=0; + net.buff= 0; client_capabilities= 0; // minimalistic client ull=0; system_thread= NON_SYSTEM_THREAD; @@ -915,7 +927,7 @@ THD::THD() user_connect=(USER_CONN *)0; my_hash_init(&user_vars, system_charset_info, USER_VARS_HASH_SIZE, 0, 0, (my_hash_get_key) get_var_key, - (my_hash_free_key) free_user_var, 0); + (my_hash_free_key) free_user_var, HASH_THREAD_SPECIFIC); sp_proc_cache= NULL; sp_func_cache= NULL; @@ -923,7 +935,7 @@ THD::THD() /* For user vars replication*/ if (opt_bin_log) my_init_dynamic_array(&user_var_events, - sizeof(BINLOG_USER_VAR_EVENT *), 16, 16); + sizeof(BINLOG_USER_VAR_EVENT *), 16, 16, 0); else bzero((char*) &user_var_events, sizeof(user_var_events)); @@ -946,6 +958,8 @@ THD::THD() prepare_derived_at_open= FALSE; create_tmp_table_for_derived= FALSE; save_prep_leaf_list= FALSE; + /* Restore THR_THD */ + set_current_thd(old_THR_THD); } @@ -1214,6 +1228,7 @@ extern "C" THD *_current_thd_noinline(void) void THD::init(void) { + DBUG_ENTER("thd::init"); mysql_mutex_lock(&LOCK_global_system_variables); plugin_thdvar_init(this); /* @@ -1243,7 +1258,7 @@ void THD::init(void) tx_isolation= (enum_tx_isolation) variables.tx_isolation; update_charset(); reset_current_stmt_binlog_format_row(); - bzero((char *) &status_var, sizeof(status_var)); + set_status_var_init(); bzero((char *) &org_status_var, sizeof(org_status_var)); if (variables.sql_log_bin) @@ -1260,6 +1275,7 @@ void THD::init(void) debug_sync_init_thread(this); #endif /* defined(ENABLED_DEBUG_SYNC) */ apc_target.init(&LOCK_thd_data); + DBUG_VOID_RETURN; } @@ -1433,8 +1449,16 @@ void THD::cleanup(void) THD::~THD() { + THD *orig_thd= current_thd; THD_CHECK_SENTRY(this); DBUG_ENTER("~THD()"); + + /* + In error cases, thd may not be current thd. We have to fix this so + that memory allocation counting is done correctly + */ + set_current_thd(this); + /* Ensure that no one is using THD */ mysql_mutex_lock(&LOCK_thd_data); mysys_var=0; // Safety (shouldn't be needed) @@ -1443,10 +1467,8 @@ THD::~THD() /* Close connection */ #ifndef EMBEDDED_LIBRARY if (net.vio) - { vio_delete(net.vio); - net_end(&net); - } + net_end(&net); #endif stmt_map.reset(); /* close all prepared statements */ if (!cleanup_done) @@ -1481,6 +1503,15 @@ THD::~THD() #endif free_root(&main_mem_root, MYF(0)); + main_warning_info.free_memory(); + if (status_var.memory_used != 0) + { + DBUG_PRINT("error", ("memory_used: %lld", status_var.memory_used)); + SAFEMALLOC_REPORT_MEMORY(my_thread_dbug_id()); + DBUG_ASSERT(status_var.memory_used == 0); // Ensure everything is freed + } + + set_current_thd(orig_thd); DBUG_VOID_RETURN; } @@ -1752,7 +1783,7 @@ bool THD::store_globals() */ DBUG_ASSERT(thread_stack); - if (my_pthread_setspecific_ptr(THR_THD, this) || + if (set_current_thd(this) || my_pthread_setspecific_ptr(THR_MALLOC, &mem_root)) return 1; /* @@ -1796,7 +1827,7 @@ void THD::reset_globals() mysql_mutex_unlock(&LOCK_thd_data); /* Undocking the thread specific data. */ - my_pthread_setspecific_ptr(THR_THD, NULL); + set_current_thd(0); my_pthread_setspecific_ptr(THR_MALLOC, NULL); } @@ -3652,7 +3683,8 @@ void thd_increment_net_big_packet_count(ulong length) void THD::set_status_var_init() { - bzero((char*) &status_var, sizeof(status_var)); + bzero((char*) &status_var, offsetof(STATUS_VAR, + last_cleared_system_status_var)); } diff --git a/sql/sql_class.h b/sql/sql_class.h index 9ac70d4bcee..f10b517a606 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -683,6 +683,8 @@ typedef struct system_status_var ulonglong binlog_bytes_written; double last_query_cost; double cpu_time, busy_time; + /* Don't initialize */ + volatile int64 memory_used; /* This shouldn't be accumulated */ } STATUS_VAR; /* @@ -692,6 +694,7 @@ typedef struct system_status_var */ #define last_system_status_var questions +#define last_cleared_system_status_var memory_used void mark_transaction_to_rollback(THD *thd, bool all); @@ -1425,7 +1428,8 @@ public: m_reopen_array(NULL), m_locked_tables_count(0) { - init_sql_alloc(&m_locked_tables_root, MEM_ROOT_BLOCK_SIZE, 0); + init_sql_alloc(&m_locked_tables_root, MEM_ROOT_BLOCK_SIZE, 0, + MY_THREAD_SPECIFIC); } void unlock_locked_tables(THD *thd); ~Locked_tables_list() @@ -1881,7 +1885,8 @@ public: { bzero((char*)this, sizeof(*this)); xid_state.xid.null(); - init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0); + init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0, + MY_THREAD_SPECIFIC); } } transaction; Global_read_lock global_read_lock; diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc index 4e2b5621aca..4bcb62ef764 100644 --- a/sql/sql_delete.cc +++ b/sql/sql_delete.cc @@ -264,7 +264,8 @@ bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds, { DBUG_ASSERT(usable_index == MAX_KEY); table->sort.io_cache= (IO_CACHE *) my_malloc(sizeof(IO_CACHE), - MYF(MY_FAE | MY_ZEROFILL)); + MYF(MY_FAE | MY_ZEROFILL | + MY_THREAD_SPECIFIC)); if (!(sortorder= make_unireg_sortorder(order, &length, NULL)) || (table->sort.found_records= filesort(thd, table, sortorder, length, diff --git a/sql/sql_error.cc b/sql/sql_error.cc index 06da6250e71..23a60267737 100644 --- a/sql/sql_error.cc +++ b/sql/sql_error.cc @@ -457,23 +457,38 @@ Diagnostics_area::disable_status() m_status= DA_DISABLED; } -Warning_info::Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings) +Warning_info::Warning_info(ulonglong warn_id_arg, + bool allow_unlimited_warnings, bool initialize) :m_statement_warn_count(0), m_current_row_for_warning(1), m_warn_id(warn_id_arg), m_allow_unlimited_warnings(allow_unlimited_warnings), + initialized(0), m_read_only(FALSE) { - /* Initialize sub structures */ - init_sql_alloc(&m_warn_root, WARN_ALLOC_BLOCK_SIZE, WARN_ALLOC_PREALLOC_SIZE); m_warn_list.empty(); bzero((char*) m_warn_count, sizeof(m_warn_count)); + if (initialize) + init(); } +void Warning_info::init() +{ + /* Initialize sub structures */ + init_sql_alloc(&m_warn_root, WARN_ALLOC_BLOCK_SIZE, + WARN_ALLOC_PREALLOC_SIZE, MYF(MY_THREAD_SPECIFIC)); + initialized= 1; +} + +void Warning_info::free_memory() +{ + if (initialized) + free_root(&m_warn_root,MYF(0)); +} Warning_info::~Warning_info() { - free_root(&m_warn_root,MYF(0)); + free_memory(); } @@ -484,7 +499,7 @@ Warning_info::~Warning_info() void Warning_info::clear_warning_info(ulonglong warn_id_arg) { m_warn_id= warn_id_arg; - free_root(&m_warn_root, MYF(0)); + free_memory(); bzero((char*) m_warn_count, sizeof(m_warn_count)); m_warn_list.empty(); m_statement_warn_count= 0; diff --git a/sql/sql_error.h b/sql/sql_error.h index 00ade934226..17ec3aa7b56 100644 --- a/sql/sql_error.h +++ b/sql/sql_error.h @@ -355,15 +355,21 @@ class Warning_info /** Indicates if push_warning() allows unlimited number of warnings. */ bool m_allow_unlimited_warnings; + bool initialized; /* Set to 1 if init() has been called */ private: Warning_info(const Warning_info &rhs); /* Not implemented */ Warning_info& operator=(const Warning_info &rhs); /* Not implemented */ public: - Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings); + Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings, + bool initialize); ~Warning_info(); + /* Allocate memory for structures */ + void init(); + void free_memory(); + /** Reset the warning information. Clear all warnings, the number of warnings, reset current row counter diff --git a/sql/sql_handler.cc b/sql/sql_handler.cc index d03b38171fc..c4055a9221f 100644 --- a/sql/sql_handler.cc +++ b/sql/sql_handler.cc @@ -323,7 +323,7 @@ bool mysql_ha_open(THD *thd, TABLE_LIST *tables, SQL_HANDLER *reopen) /* copy data to sql_handler */ if (!(sql_handler= new SQL_HANDLER(thd))) goto err; - init_alloc_root(&sql_handler->mem_root, 1024, 0); + init_alloc_root(&sql_handler->mem_root, 1024, 0, MYF(MY_THREAD_SPECIFIC)); sql_handler->db.length= strlen(tables->db); sql_handler->table_name.length= strlen(tables->table_name); diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index 61a7a56c413..c0eabd3a2f2 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2481,7 +2481,9 @@ int write_delayed(THD *thd, TABLE *table, enum_duplicates duplic, goto err; } - if (!(row->record= (char*) my_malloc(table->s->reclength, MYF(MY_WME)))) + /* This can't be THREAD_SPECIFIC as it's freed in delayed thread */ + if (!(row->record= (char*) my_malloc(table->s->reclength, + MYF(MY_WME)))) goto err; memcpy(row->record, table->record[0], table->s->reclength); row->start_time= thd->start_time; @@ -2898,24 +2900,28 @@ pthread_handler_t handle_delayed_insert(void *arg) DBUG_LEAVE; } - di->table=0; - thd->killed= KILL_CONNECTION; // If error - mysql_mutex_unlock(&di->mutex); + { + DBUG_ENTER("handle_delayed_insert-cleanup"); + di->table=0; + thd->killed= KILL_CONNECTION; // If error + mysql_mutex_unlock(&di->mutex); - close_thread_tables(thd); // Free the table - thd->mdl_context.release_transactional_locks(); - mysql_cond_broadcast(&di->cond_client); // Safety + close_thread_tables(thd); // Free the table + thd->mdl_context.release_transactional_locks(); + mysql_cond_broadcast(&di->cond_client); // Safety - mysql_mutex_lock(&LOCK_delayed_create); // Because of delayed_get_table - mysql_mutex_lock(&LOCK_delayed_insert); - /* - di should be unlinked from the thread handler list and have no active - clients - */ - delete di; - mysql_mutex_unlock(&LOCK_delayed_insert); - mysql_mutex_unlock(&LOCK_delayed_create); + mysql_mutex_lock(&LOCK_delayed_create); // Because of delayed_get_table + mysql_mutex_lock(&LOCK_delayed_insert); + /* + di should be unlinked from the thread handler list and have no active + clients + */ + delete di; + mysql_mutex_unlock(&LOCK_delayed_insert); + mysql_mutex_unlock(&LOCK_delayed_create); + DBUG_LEAVE; + } my_thread_end(); pthread_exit(0); diff --git a/sql/sql_join_cache.cc b/sql/sql_join_cache.cc index 4626f30df28..fde9f70fa79 100644 --- a/sql/sql_join_cache.cc +++ b/sql/sql_join_cache.cc @@ -934,7 +934,7 @@ int JOIN_CACHE::alloc_buffer() { ulong next_buff_size; - if ((buff= (uchar*) my_malloc(buff_size, MYF(0)))) + if ((buff= (uchar*) my_malloc(buff_size, MYF(MY_THREAD_SPECIFIC)))) break; next_buff_size= buff_size > buff_size_decr ? buff_size-buff_size_decr : 0; @@ -1012,7 +1012,7 @@ int JOIN_CACHE::realloc_buffer() { int rc; free(); - rc= test(!(buff= (uchar*) my_malloc(buff_size, MYF(0)))); + rc= test(!(buff= (uchar*) my_malloc(buff_size, MYF(MY_THREAD_SPECIFIC)))); reset(TRUE); return rc; } @@ -2801,7 +2801,7 @@ int JOIN_CACHE_HASHED::realloc_buffer() { int rc; free(); - rc= test(!(buff= (uchar*) my_malloc(buff_size, MYF(0)))); + rc= test(!(buff= (uchar*) my_malloc(buff_size, MYF(MY_THREAD_SPECIFIC)))); init_hash_table(); reset(TRUE); return rc; diff --git a/sql/sql_lex.cc b/sql/sql_lex.cc index fb4d4defe9c..93e3eb51518 100644 --- a/sql/sql_lex.cc +++ b/sql/sql_lex.cc @@ -2552,7 +2552,7 @@ LEX::LEX() my_init_dynamic_array2(&plugins, sizeof(plugin_ref), plugins_static_buffer, INITIAL_LEX_PLUGIN_LIST_SIZE, - INITIAL_LEX_PLUGIN_LIST_SIZE); + INITIAL_LEX_PLUGIN_LIST_SIZE, 0); reset_query_tables_list(TRUE); mi.init(); } diff --git a/sql/sql_lex.h b/sql/sql_lex.h index 492909ee3d5..e1c0940c461 100644 --- a/sql/sql_lex.h +++ b/sql/sql_lex.h @@ -305,7 +305,7 @@ struct LEX_MASTER_INFO { bzero(this, sizeof(*this)); my_init_dynamic_array(&repl_ignore_server_ids, - sizeof(::server_id), 0, 16); + sizeof(::server_id), 0, 16, 0); } void reset() { diff --git a/sql/sql_load.cc b/sql/sql_load.cc index 4fdabef37ed..7d030329419 100644 --- a/sql/sql_load.cc +++ b/sql/sql_load.cc @@ -1371,7 +1371,7 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs, set_if_bigger(length,line_start.length()); stack=stack_pos=(int*) sql_alloc(sizeof(int)*length); - if (!(buffer=(uchar*) my_malloc(buff_length+1,MYF(0)))) + if (!(buffer=(uchar*) my_malloc(buff_length+1,MYF(MY_THREAD_SPECIFIC)))) error=1; /* purecov: inspected */ else { @@ -1379,7 +1379,7 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs, if (init_io_cache(&cache,(get_it_from_net) ? -1 : file, 0, (get_it_from_net) ? READ_NET : (is_fifo ? READ_FIFO : READ_CACHE),0L,1, - MYF(MY_WME))) + MYF(MY_WME | MY_THREAD_SPECIFIC))) { my_free(buffer); /* purecov: inspected */ buffer= NULL; @@ -1605,7 +1605,7 @@ int READ_INFO::read_field() ** We come here if buffer is too small. Enlarge it and continue */ if (!(new_buffer=(uchar*) my_realloc((char*) buffer,buff_length+1+IO_SIZE, - MYF(MY_WME)))) + MYF(MY_WME | MY_THREAD_SPECIFIC)))) return (error=1); to=new_buffer + (to-buffer); buffer=new_buffer; diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index 472273a0a33..2d3d91ff9d8 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -642,8 +642,6 @@ void do_handle_bootstrap(THD *thd) handle_bootstrap_impl(thd); end: - net_end(&thd->net); - thd->cleanup(); delete thd; #ifndef EMBEDDED_LIBRARY @@ -1291,10 +1289,10 @@ bool dispatch_command(enum enum_server_command command, THD *thd, and flushes tables. */ bool res; - my_pthread_setspecific_ptr(THR_THD, NULL); + set_current_thd(0); res= reload_acl_and_cache(NULL, options | REFRESH_FAST, NULL, ¬_used); - my_pthread_setspecific_ptr(THR_THD, thd); + set_current_thd(thd); if (res) break; } @@ -1465,6 +1463,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd, thd_proc_info(thd, "cleaning up"); thd->reset_query(); + thd->examined_row_count= 0; // For processlist thd->command=COM_SLEEP; dec_thread_running(); thd_proc_info(thd, 0); @@ -4794,7 +4793,8 @@ static bool execute_show_status(THD *thd, TABLE_LIST *all_tables) mysql_mutex_lock(&LOCK_status); add_diff_to_status(&global_status_var, &thd->status_var, &old_status_var); - thd->status_var= old_status_var; + memcpy(&thd->status_var, &old_status_var, + offsetof(STATUS_VAR, last_cleared_system_status_var)); mysql_mutex_unlock(&LOCK_status); return res; } @@ -6843,7 +6843,7 @@ static uint kill_threads_for_user(THD *thd, LEX_USER *user, mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(ER_KILL_DENIED_ERROR); } - if (!threads_to_kill.push_back(tmp, tmp->mem_root)) + if (!threads_to_kill.push_back(tmp, thd->mem_root)) mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete } } diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index 45e8adf1f5f..e24b43c0cf6 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -1114,7 +1114,7 @@ static bool plugin_add(MEM_ROOT *tmp_root, plugin_array_version++; if (my_hash_insert(&plugin_hash[plugin->type], (uchar*)tmp_plugin_ptr)) tmp_plugin_ptr->state= PLUGIN_IS_FREED; - init_alloc_root(&tmp_plugin_ptr->mem_root, 4096, 4096); + init_alloc_root(&tmp_plugin_ptr->mem_root, 4096, 4096, 0); if (name->str) DBUG_RETURN(FALSE); // all done @@ -1507,8 +1507,8 @@ int plugin_init(int *argc, char **argv, int flags) init_plugin_psi_keys(); #endif - init_alloc_root(&plugin_mem_root, 4096, 4096); - init_alloc_root(&tmp_root, 4096, 4096); + init_alloc_root(&plugin_mem_root, 4096, 4096, 0); + init_alloc_root(&tmp_root, 4096, 4096, 0); if (my_hash_init(&bookmark_hash, &my_charset_bin, 16, 0, 0, get_bookmark_hash_key, NULL, HASH_UNIQUE)) @@ -1518,9 +1518,9 @@ int plugin_init(int *argc, char **argv, int flags) mysql_mutex_init(key_LOCK_plugin, &LOCK_plugin, MY_MUTEX_INIT_FAST); if (my_init_dynamic_array(&plugin_dl_array, - sizeof(struct st_plugin_dl *),16,16) || + sizeof(struct st_plugin_dl *),16,16,0) || my_init_dynamic_array(&plugin_array, - sizeof(struct st_plugin_int *),16,16)) + sizeof(struct st_plugin_int *),16,16,0)) goto err; for (i= 0; i < MYSQL_MAX_PLUGIN_TYPE_NUM; i++) @@ -1716,12 +1716,11 @@ static bool register_builtin(struct st_maria_plugin *plugin, */ static void plugin_load(MEM_ROOT *tmp_root, int *argc, char **argv) { - THD thd; TABLE_LIST tables; TABLE *table; READ_RECORD read_record_info; int error; - THD *new_thd= &thd; + THD *new_thd= new THD; bool result; #ifdef EMBEDDED_LIBRARY No_such_table_error_handler error_handler; @@ -1732,7 +1731,7 @@ static void plugin_load(MEM_ROOT *tmp_root, int *argc, char **argv) new_thd->store_globals(); new_thd->db= my_strdup("mysql", MYF(0)); new_thd->db_length= 5; - bzero((char*) &thd.net, sizeof(thd.net)); + bzero((char*) &new_thd->net, sizeof(new_thd->net)); tables.init_one_table("mysql", 5, "plugin", 6, "plugin", TL_READ); #ifdef EMBEDDED_LIBRARY @@ -1799,7 +1798,8 @@ static void plugin_load(MEM_ROOT *tmp_root, int *argc, char **argv) close_mysql_tables(new_thd); end: /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + delete new_thd; + set_current_thd(0); DBUG_VOID_RETURN; } diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc index 96b7d825bd3..e2398536783 100644 --- a/sql/sql_prepare.cc +++ b/sql/sql_prepare.cc @@ -2963,7 +2963,7 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length) param= stmt->param_array[param_number]; Diagnostics_area new_stmt_da, *save_stmt_da= thd->stmt_da; - Warning_info new_warnning_info(thd->query_id, false); + Warning_info new_warnning_info(thd->query_id, false, true); Warning_info *save_warinig_info= thd->warning_info; thd->stmt_da= &new_stmt_da; @@ -3141,7 +3141,7 @@ Prepared_statement::Prepared_statement(THD *thd_arg) flags((uint) IS_IN_USE) { init_sql_alloc(&main_mem_root, thd_arg->variables.query_alloc_block_size, - thd_arg->variables.query_prealloc_size); + thd_arg->variables.query_prealloc_size, MYF(MY_THREAD_SPECIFIC)); *last_error= '\0'; } @@ -4031,7 +4031,7 @@ Ed_result_set::Ed_result_set(List *rows_arg, */ Ed_connection::Ed_connection(THD *thd) - :m_warning_info(thd->query_id, false), + :m_warning_info(thd->query_id, false, true), m_thd(thd), m_rsets(0), m_current_rset(0) @@ -4455,7 +4455,7 @@ bool Protocol_local::send_result_set_metadata(List *columns, uint) { DBUG_ASSERT(m_rset == 0 && !alloc_root_inited(&m_rset_root)); - init_sql_alloc(&m_rset_root, MEM_ROOT_BLOCK_SIZE, 0); + init_sql_alloc(&m_rset_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (! (m_rset= new (&m_rset_root) List)) return TRUE; diff --git a/sql/sql_reload.cc b/sql/sql_reload.cc index 99fe9267589..2720dc7cd74 100644 --- a/sql/sql_reload.cc +++ b/sql/sql_reload.cc @@ -97,7 +97,7 @@ bool reload_acl_and_cache(THD *thd, unsigned long options, { delete tmp_thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); thd= 0; } reset_mqh((LEX_USER *)NULL, TRUE); diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 4ef4311a68a..63718dc9d55 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -4947,7 +4947,8 @@ update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab, /* set a barrier for the array of SARGABLE_PARAM */ (*sargables)[0].field= 0; - if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64)) + if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64, + MYF(MY_THREAD_SPECIFIC))) return TRUE; if (cond) @@ -14362,7 +14363,7 @@ create_tmp_table(THD *thd, TMP_TABLE_PARAM *param, List &fields, if (param->precomputed_group_by) copy_func_count+= param->sum_func_count; - init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (!multi_alloc_root(&own_root, &table, sizeof(*table), @@ -19171,7 +19172,8 @@ create_sort_index(THD *thd, JOIN *join, ORDER *order, goto err; /* purecov: inspected */ table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), - MYF(MY_WME | MY_ZEROFILL)); + MYF(MY_WME | MY_ZEROFILL| + MY_THREAD_SPECIFIC)); table->status=0; // May be wrong if quick_select // If table has a range, move it to select @@ -22418,6 +22420,7 @@ static void print_join(THD *thd, List_iterator_fast ti(*tables); TABLE_LIST **table; uint non_const_tables= 0; + DBUG_ENTER("print_join"); for (TABLE_LIST *t= ti++; t ; t= ti++) { @@ -22431,13 +22434,13 @@ static void print_join(THD *thd, if (!non_const_tables) { str->append(STRING_WITH_LEN("dual")); - return; // all tables were optimized away + DBUG_VOID_RETURN; // all tables were optimized away } ti.rewind(); if (!(table= (TABLE_LIST **)thd->alloc(sizeof(TABLE_LIST*) * non_const_tables))) - return; // out of memory + DBUG_VOID_RETURN; // out of memory TABLE_LIST *tmp, **t= table + (non_const_tables - 1); while ((tmp= ti++)) @@ -22476,6 +22479,7 @@ static void print_join(THD *thd, } print_table_array(thd, eliminated_tables, str, table, table + non_const_tables, query_type); + DBUG_VOID_RETURN; } /** @@ -22984,7 +22988,8 @@ JOIN::reoptimize(Item *added_where, table_map join_tables, reset_query_plan(); if (!keyuse.buffer && - my_init_dynamic_array(&keyuse, sizeof(KEYUSE), 20, 64)) + my_init_dynamic_array(&keyuse, sizeof(KEYUSE), 20, 64, + MYF(MY_THREAD_SPECIFIC))) { delete_dynamic(&added_keyuse); return REOPT_ERROR; diff --git a/sql/sql_servers.cc b/sql/sql_servers.cc index dce679a883f..63f3e6c9d63 100644 --- a/sql/sql_servers.cc +++ b/sql/sql_servers.cc @@ -158,7 +158,7 @@ bool servers_init(bool dont_read_servers_table) } /* Initialize the mem root for data */ - init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (dont_read_servers_table) goto end; @@ -178,7 +178,7 @@ bool servers_init(bool dont_read_servers_table) return_val= servers_reload(thd); delete thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); end: DBUG_RETURN(return_val); @@ -209,7 +209,7 @@ static bool servers_load(THD *thd, TABLE_LIST *tables) my_hash_reset(&servers_cache); free_root(&mem, MYF(0)); - init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, 0); if (init_read_record(&read_record_info,thd,table=tables[0].table,NULL,1,0, FALSE)) diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 5d57edc53ae..f9458fa8588 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -458,7 +458,7 @@ bool ignore_db_dirs_init() { return my_init_dynamic_array(&ignore_db_dirs_array, sizeof(LEX_STRING *), - 0, 0); + 0, 0, 0); } @@ -737,7 +737,8 @@ find_files(THD *thd, List *files, const char *db, bzero((char*) &table_list,sizeof(table_list)); - if (!(dirp = my_dir(path,MYF(dir ? MY_WANT_STAT : 0)))) + if (!(dirp = my_dir(path,MYF((dir ? MY_WANT_STAT : 0) | + MY_THREAD_SPECIFIC)))) { if (my_errno == ENOENT) my_error(ER_BAD_DB_ERROR, MYF(ME_BELL+ME_WAITTANG), db); @@ -2334,11 +2335,14 @@ void Show_explain_request::call_in_target_thread() target_thd->query_length(), target_thd->query_charset()); + DBUG_ASSERT(current_thd == target_thd); + set_current_thd(request_thd); if (target_thd->lex->unit.print_explain(explain_buf, 0 /* explain flags*/, &printed_anything)) { failed_to_produce= TRUE; } + set_current_thd(target_thd); if (!printed_anything) failed_to_produce= TRUE; @@ -2349,10 +2353,20 @@ void Show_explain_request::call_in_target_thread() int select_result_explain_buffer::send_data(List &items) { + int res; + THD *cur_thd= current_thd; + DBUG_ENTER("select_result_explain_buffer::send_data"); + + /* + Switch to the recieveing thread, so that we correctly count memory used + by it. This is needed as it's the receiving thread that will free the + memory. + */ + set_current_thd(thd); fill_record(thd, dst_table, dst_table->field, items, TRUE, FALSE); - if ((dst_table->file->ha_write_tmp_row(dst_table->record[0]))) - return 1; - return 0; + res= dst_table->file->ha_write_tmp_row(dst_table->record[0]); + set_current_thd(cur_thd); + DBUG_RETURN(test(res)); } @@ -2578,6 +2592,18 @@ int fill_schema_processlist(THD* thd, TABLE_LIST* tables, COND* cond) } mysql_mutex_unlock(&tmp->LOCK_thd_data); + /* + This may become negative if we free a memory allocated by another + thread in this thread. However it's better that we notice it eventually + than hide it. + */ + table->field[12]->store((longlong) (tmp->status_var.memory_used + + sizeof(THD)), + FALSE); + table->field[12]->set_notnull(); + table->field[13]->store((longlong) tmp->examined_row_count, TRUE); + table->field[13]->set_notnull(); + if (schema_table_store_record(thd, table)) { mysql_mutex_unlock(&LOCK_thread_count); @@ -2650,7 +2676,7 @@ int add_status_vars(SHOW_VAR *list) if (status_vars_inited) mysql_mutex_lock(&LOCK_status); if (!all_status_vars.buffer && // array is not allocated yet - do it now - my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20)) + my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20, 0)) { res= 1; goto err; @@ -2999,7 +3025,8 @@ static int aggregate_user_stats(HASH *all_user_stats, HASH *agg_user_stats) { // First entry for this role. if (!(agg_user= (USER_STATS*) my_malloc(sizeof(USER_STATS), - MYF(MY_WME | MY_ZEROFILL)))) + MYF(MY_WME | MY_ZEROFILL| + MY_THREAD_SPECIFIC)))) { sql_print_error("Malloc in aggregate_user_stats failed"); DBUG_RETURN(1); @@ -4372,7 +4399,7 @@ static int fill_schema_table_from_frm(THD *thd, TABLE_LIST *tables, if (schema_table->i_s_requested_object & OPEN_TRIGGER_ONLY) { - init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); if (!Table_triggers_list::check_n_load(thd, db_name->str, table_name->str, &tbl, 1)) { @@ -7878,7 +7905,7 @@ static bool do_fill_table(THD *thd, // Warning_info, so "useful warnings" get rejected. In order to avoid // that problem we create a Warning_info instance, which is capable of // storing "unlimited" number of warnings. - Warning_info wi(thd->query_id, true); + Warning_info wi(thd->query_id, true, true); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; @@ -8612,6 +8639,8 @@ ST_FIELD_INFO processlist_fields_info[]= {"MAX_STAGE", 2, MYSQL_TYPE_TINY, 0, 0, "Max_stage", SKIP_OPEN_TABLE}, {"PROGRESS", 703, MYSQL_TYPE_DECIMAL, 0, 0, "Progress", SKIP_OPEN_TABLE}, + {"MEMORY_USED", 7, MYSQL_TYPE_LONG, 0, 0, "Memory_used", SKIP_OPEN_TABLE}, + {"EXAMINED_ROWS", 7, MYSQL_TYPE_LONG, 0, 0, "Examined_rows", SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; @@ -8941,7 +8970,7 @@ int initialize_schema_table(st_plugin_int *plugin) DBUG_ENTER("initialize_schema_table"); if (!(schema_table= (ST_SCHEMA_TABLE *)my_malloc(sizeof(ST_SCHEMA_TABLE), - MYF(MY_WME | MY_ZEROFILL)))) + MYF(MY_WME | MY_ZEROFILL)))) DBUG_RETURN(1); /* Historical Requirement */ plugin->data= schema_table; // shortcut for the future diff --git a/sql/sql_statistics.cc b/sql/sql_statistics.cc index 70ba6897333..687fdf26228 100644 --- a/sql/sql_statistics.cc +++ b/sql/sql_statistics.cc @@ -1387,7 +1387,8 @@ public: is_single_comp_pk= FALSE; uint pk= table->s->primary_key; - if (table->key_info - key_info == pk && table->key_info[pk].key_parts == 1) + if ((uint) (table->key_info - key_info) == pk && + table->key_info[pk].key_parts == 1) { prefixes= 1; is_single_comp_pk= TRUE; diff --git a/sql/sql_string.cc b/sql/sql_string.cc index 126139cd219..9d11677666f 100644 --- a/sql/sql_string.cc +++ b/sql/sql_string.cc @@ -42,7 +42,9 @@ bool String::real_alloc(uint32 length) if (Alloced_length < arg_length) { free(); - if (!(Ptr=(char*) my_malloc(arg_length,MYF(MY_WME)))) + if (!(Ptr=(char*) my_malloc(arg_length,MYF(MY_WME | + (thread_specific ? + MY_THREAD_SPECIFIC : 0))))) return TRUE; Alloced_length=arg_length; alloced=1; @@ -90,10 +92,16 @@ bool String::realloc_raw(uint32 alloc_length) return TRUE; /* Overflow */ if (alloced) { - if (!(new_ptr= (char*) my_realloc(Ptr,len,MYF(MY_WME)))) + if (!(new_ptr= (char*) my_realloc(Ptr,len, + MYF(MY_WME | + (thread_specific ? + MY_THREAD_SPECIFIC : 0))))) return TRUE; // Signal error } - else if ((new_ptr= (char*) my_malloc(len,MYF(MY_WME)))) + else if ((new_ptr= (char*) my_malloc(len, + MYF(MY_WME | + (thread_specific ? + MY_THREAD_SPECIFIC : 0))))) { if (str_length > len - 1) str_length= 0; diff --git a/sql/sql_string.h b/sql/sql_string.h index 2966fc2a920..58cda343dac 100644 --- a/sql/sql_string.h +++ b/sql/sql_string.h @@ -56,23 +56,26 @@ class String { char *Ptr; uint32 str_length,Alloced_length, extra_alloc; - bool alloced; + bool alloced,thread_specific; CHARSET_INFO *str_charset; public: String() { - Ptr=0; str_length=Alloced_length=extra_alloc=0; alloced=0; + Ptr=0; str_length=Alloced_length=extra_alloc=0; + alloced= thread_specific= 0; str_charset= &my_charset_bin; } String(uint32 length_arg) { - alloced=0; Alloced_length= extra_alloc= 0; (void) real_alloc(length_arg); + alloced= thread_specific= 0; + Alloced_length= extra_alloc= 0; (void) real_alloc(length_arg); str_charset= &my_charset_bin; } String(const char *str, CHARSET_INFO *cs) { Ptr=(char*) str; str_length= (uint32) strlen(str); - Alloced_length= extra_alloc= 0; alloced=0; + Alloced_length= extra_alloc= 0; + alloced= thread_specific= 0; str_charset=cs; } /* @@ -82,18 +85,21 @@ public: */ String(const char *str,uint32 len, CHARSET_INFO *cs) { - Ptr=(char*) str; str_length=len; Alloced_length= extra_alloc=0; alloced=0; + Ptr=(char*) str; str_length=len; Alloced_length= extra_alloc=0; + alloced= thread_specific= 0; str_charset=cs; } String(char *str,uint32 len, CHARSET_INFO *cs) { - Ptr=(char*) str; Alloced_length=str_length=len; extra_alloc= 0; alloced=0; + Ptr=(char*) str; Alloced_length=str_length=len; extra_alloc= 0; + alloced= thread_specific= 0; str_charset=cs; } String(const String &str) { Ptr=str.Ptr ; str_length=str.str_length ; - Alloced_length=str.Alloced_length; extra_alloc= 0; alloced=0; + Alloced_length=str.Alloced_length; extra_alloc= 0; + alloced= thread_specific= 0; str_charset=str.str_charset; } static void *operator new(size_t size, MEM_ROOT *mem_root) throw () @@ -108,6 +114,12 @@ public: { /* never called */ } ~String() { free(); } + /* Mark variable thread specific it it's not allocated already */ + inline void set_thread_specific() + { + if (!alloced) + thread_specific= 1; + } inline void set_charset(CHARSET_INFO *charset_arg) { str_charset= charset_arg; } inline CHARSET_INFO *charset() const { return str_charset; } @@ -332,6 +344,7 @@ public: Ptr=s.Ptr ; str_length=s.str_length ; Alloced_length=s.Alloced_length; extra_alloc= s.extra_alloc; alloced= s.alloced; + thread_specific= s.thread_specific; s.alloced= 0; } bool append(const String &s); diff --git a/sql/sql_table.cc b/sql/sql_table.cc index 57d0bf375da..d0a4aedfa4f 100644 --- a/sql/sql_table.cc +++ b/sql/sql_table.cc @@ -961,7 +961,7 @@ static int execute_ddl_log_action(THD *thd, DDL_LOG_ENTRY *ddl_log_entry) ddl_log_entry->handler_name)); handler_name.str= (char*)ddl_log_entry->handler_name; handler_name.length= strlen(ddl_log_entry->handler_name); - init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (!strcmp(ddl_log_entry->handler_name, reg_ext)) frm_action= TRUE; else @@ -1521,7 +1521,7 @@ void execute_ddl_log_recovery() global_ddl_log.recovery_phase= FALSE; delete thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); DBUG_VOID_RETURN; } @@ -5380,7 +5380,7 @@ mysql_compare_tables(TABLE *table, if (table->s->tmp_table == NO_TMP_TABLE) { (void) delete_statistics_for_index(thd, table, table_key, FALSE); - if (table_key - table->key_info == table->s->primary_key) + if ((uint) (table_key - table->key_info) == table->s->primary_key) { KEY *tab_key_info= table->key_info; for (uint j=0; j < table->s->keys; j++, tab_key_info++) @@ -7542,7 +7542,8 @@ copy_data_between_tables(THD *thd, TABLE *from,TABLE *to, else { from->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), - MYF(MY_FAE | MY_ZEROFILL)); + MYF(MY_FAE | MY_ZEROFILL | + MY_THREAD_SPECIFIC)); bzero((char *) &tables, sizeof(tables)); tables.table= from; tables.alias= tables.table_name= from->s->table_name.str; diff --git a/sql/sql_test.cc b/sql/sql_test.cc index 25ab84fe4db..5b3286d77b0 100644 --- a/sql/sql_test.cc +++ b/sql/sql_test.cc @@ -484,7 +484,9 @@ static void display_table_locks(void) void *saved_base; DYNAMIC_ARRAY saved_table_locks; - (void) my_init_dynamic_array(&saved_table_locks,sizeof(TABLE_LOCK_INFO), cached_open_tables() + 20,50); + (void) my_init_dynamic_array(&saved_table_locks,sizeof(TABLE_LOCK_INFO), + cached_open_tables() + 20, 50, + MYF(MY_THREAD_SPECIFIC)); mysql_mutex_lock(&THR_LOCK_lock); for (list= thr_lock_thread_list; list; list= list_rest(list)) { diff --git a/sql/sql_trigger.cc b/sql/sql_trigger.cc index aff00f9fcf4..fa509835dae 100644 --- a/sql/sql_trigger.cc +++ b/sql/sql_trigger.cc @@ -1779,7 +1779,7 @@ bool Table_triggers_list::drop_all_triggers(THD *thd, char *db, char *name) DBUG_ENTER("drop_all_triggers"); bzero(&table, sizeof(table)); - init_sql_alloc(&table.mem_root, 8192, 0); + init_sql_alloc(&table.mem_root, 8192, 0, 0); if (Table_triggers_list::check_n_load(thd, db, name, &table, 1)) { @@ -1999,7 +1999,7 @@ bool Table_triggers_list::change_table_name(THD *thd, const char *db, DBUG_ENTER("change_table_name"); bzero(&table, sizeof(table)); - init_sql_alloc(&table.mem_root, 8192, 0); + init_sql_alloc(&table.mem_root, 8192, 0, 0); /* This method interfaces the mysql server code protected by diff --git a/sql/sql_udf.cc b/sql/sql_udf.cc index 9069d876609..9832f240fb5 100644 --- a/sql/sql_udf.cc +++ b/sql/sql_udf.cc @@ -151,7 +151,7 @@ void udf_init() mysql_rwlock_init(key_rwlock_THR_LOCK_udf, &THR_LOCK_udf); - init_sql_alloc(&mem, UDF_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem, UDF_ALLOC_BLOCK_SIZE, 0, 0); THD *new_thd = new THD; if (!new_thd || my_hash_init(&udf_hash,system_charset_info,32,0,0,get_hash_key, NULL, 0)) @@ -258,7 +258,7 @@ end: close_mysql_tables(new_thd); delete new_thd; /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); DBUG_VOID_RETURN; } diff --git a/sql/sql_update.cc b/sql/sql_update.cc index e320c1a3b86..8a0d95722e8 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -492,7 +492,8 @@ int mysql_update(THD *thd, ha_rows found_rows; table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE), - MYF(MY_FAE | MY_ZEROFILL)); + MYF(MY_FAE | MY_ZEROFILL | + MY_THREAD_SPECIFIC)); if (!(sortorder=make_unireg_sortorder(order, &length, NULL)) || (table->sort.found_records= filesort(thd, table, sortorder, length, select, limit, diff --git a/sql/table.cc b/sql/table.cc index 6eafdc916f9..6fc6bd44b22 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -307,7 +307,7 @@ TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, path_length= build_table_filename(path, sizeof(path) - 1, table_list->db, table_list->table_name, "", 0); - init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); if (multi_alloc_root(&mem_root, &share, sizeof(*share), &key_buff, key_length, @@ -340,7 +340,7 @@ TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, share->free_tables.empty(); share->m_flush_tickets.empty(); - init_sql_alloc(&share->stats_cb.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&share->stats_cb.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root)); mysql_mutex_init(key_TABLE_SHARE_LOCK_ha_data, @@ -381,7 +381,12 @@ void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key, DBUG_PRINT("enter", ("table: '%s'.'%s'", key, table_name)); bzero((char*) share, sizeof(*share)); - init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + /* + This can't be MY_THREAD_SPECIFIC for slaves as they are freed + during cleanup() from Relay_log_info::close_temporary_tables() + */ + init_sql_alloc(&share->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, + MYF(thd->slave_thread ? 0 : MY_THREAD_SPECIFIC)); share->table_category= TABLE_CATEGORY_TEMPORARY; share->tmp_table= INTERNAL_TMP_TABLE; share->db.str= (char*) key; @@ -2341,6 +2346,8 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, DBUG_ENTER("open_table_from_share"); DBUG_PRINT("enter",("name: '%s.%s' form: 0x%lx", share->db.str, share->table_name.str, (long) outparam)); + LINT_INIT(dfield_ptr); + LINT_INIT(vfield_ptr); thd->lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_VIEW; // not a view @@ -2351,7 +2358,7 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, outparam->db_stat= db_stat; outparam->write_row_record= NULL; - init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0); + init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); if (outparam->alias.copy(alias, strlen(alias), table_alias_charset)) goto err; diff --git a/sql/thr_malloc.cc b/sql/thr_malloc.cc index cedcbefc26f..8c7db0673ac 100644 --- a/sql/thr_malloc.cc +++ b/sql/thr_malloc.cc @@ -61,9 +61,10 @@ extern "C" { } } -void init_sql_alloc(MEM_ROOT *mem_root, uint block_size, uint pre_alloc) +void init_sql_alloc(MEM_ROOT *mem_root, uint block_size, uint pre_alloc, + myf my_flags) { - init_alloc_root(mem_root, block_size, pre_alloc); + init_alloc_root(mem_root, block_size, pre_alloc, my_flags); mem_root->error_handler=sql_alloc_error_handler; } diff --git a/sql/thr_malloc.h b/sql/thr_malloc.h index 81b7d3cc238..0b17c5cdaf1 100644 --- a/sql/thr_malloc.h +++ b/sql/thr_malloc.h @@ -20,7 +20,8 @@ typedef struct st_mem_root MEM_ROOT; -void init_sql_alloc(MEM_ROOT *root, uint block_size, uint pre_alloc_size); +void init_sql_alloc(MEM_ROOT *root, uint block_size, uint pre_alloc_size, + myf my_flags); void *sql_alloc(size_t); void *sql_calloc(size_t); char *sql_strdup(const char *str); diff --git a/sql/tztime.cc b/sql/tztime.cc index ba24cab9ca7..525fc96241c 100644 --- a/sql/tztime.cc +++ b/sql/tztime.cc @@ -1637,7 +1637,7 @@ my_tz_init(THD *org_thd, const char *default_tzname, my_bool bootstrap) my_hash_free(&tz_names); goto end; } - init_sql_alloc(&tz_storage, 32 * 1024, 0); + init_sql_alloc(&tz_storage, 32 * 1024, 0, 0); mysql_mutex_init(key_tz_LOCK, &tz_LOCK, MY_MUTEX_INIT_FAST); tz_inited= 1; @@ -1803,7 +1803,7 @@ end: else { /* Remember that we don't have a THD */ - my_pthread_setspecific_ptr(THR_THD, 0); + set_current_thd(0); my_pthread_setspecific_ptr(THR_MALLOC, 0); } @@ -2541,7 +2541,7 @@ scan_tz_dir(char * name_end) } else if (MY_S_ISREG(cur_dir->dir_entry[i].mystat->st_mode)) { - init_alloc_root(&tz_storage, 32768, 0); + init_alloc_root(&tz_storage, 32768, 0, MYF(MY_THREAD_SPECIFIC)); if (!tz_load(fullname, &tz_info, &tz_storage)) print_tz_as_sql(root_name_end + 1, &tz_info); else @@ -2599,7 +2599,7 @@ main(int argc, char **argv) } else { - init_alloc_root(&tz_storage, 32768, 0); + init_alloc_root(&tz_storage, 32768, 0, 0); if (strcmp(argv[1], "--leap") == 0) { diff --git a/sql/uniques.cc b/sql/uniques.cc index c246cd637bd..22f098f8f9a 100644 --- a/sql/uniques.cc +++ b/sql/uniques.cc @@ -84,10 +84,11 @@ Unique::Unique(qsort_cmp2 comp_func, void * comp_func_fixed_arg, if (min_dupl_count_arg) full_size+= sizeof(element_count); my_b_clear(&file); - init_tree(&tree, (ulong) (max_in_memory_size / 16), 0, size, comp_func, 0, - NULL, comp_func_fixed_arg); + init_tree(&tree, (ulong) (max_in_memory_size / 16), 0, size, comp_func, + NULL, comp_func_fixed_arg, MYF(MY_THREAD_SPECIFIC)); /* If the following fail's the next add will also fail */ - my_init_dynamic_array(&file_ptrs, sizeof(BUFFPEK), 16, 16); + my_init_dynamic_array(&file_ptrs, sizeof(BUFFPEK), 16, 16, + MYF(MY_THREAD_SPECIFIC)); /* If you change the following, change it in get_max_elements function, too. */ @@ -602,7 +603,8 @@ bool Unique::walk(tree_walk_action action, void *walk_action_arg) return 1; if (flush_io_cache(&file) || reinit_io_cache(&file, READ_CACHE, 0L, 0, 0)) return 1; - if (!(merge_buffer= (uchar *) my_malloc((ulong) max_in_memory_size, MYF(0)))) + if (!(merge_buffer= (uchar *) my_malloc((ulong) max_in_memory_size, + MYF(MY_THREAD_SPECIFIC)))) return 1; res= merge_walk(merge_buffer, (ulong) max_in_memory_size, size, (BUFFPEK *) file_ptrs.buffer, @@ -625,7 +627,7 @@ bool Unique::get(TABLE *table) { /* Whole tree is in memory; Don't use disk if you don't need to */ if ((record_pointers=table->sort.record_pointers= (uchar*) - my_malloc(size * tree.elements_in_tree, MYF(0)))) + my_malloc(size * tree.elements_in_tree, MYF(MY_THREAD_SPECIFIC)))) { tree_walk_action action= min_dupl_count ? (tree_walk_action) unique_intersect_write_to_ptrs : @@ -650,7 +652,8 @@ bool Unique::get(TABLE *table) /* Open cached file if it isn't open */ outfile=table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE), - MYF(MY_ZEROFILL)); + MYF(MY_ZEROFILL | + MY_THREAD_SPECIFIC)); if (!outfile || (! my_b_inited(outfile) && @@ -673,7 +676,7 @@ bool Unique::get(TABLE *table) if (!(sort_buffer=(uchar*) my_malloc((sort_param.max_keys_per_buffer+1) * sort_param.sort_length, - MYF(0)))) + MYF(MY_THREAD_SPECIFIC)))) return 1; sort_param.unique_buff= sort_buffer+(sort_param.max_keys_per_buffer * sort_param.sort_length); diff --git a/sql/unireg.cc b/sql/unireg.cc index edcfe9eb934..20d101be1a3 100644 --- a/sql/unireg.cc +++ b/sql/unireg.cc @@ -282,7 +282,7 @@ bool mysql_create_frm(THD *thd, const char *file_name, } key_buff_length= uint4korr(fileinfo+47); - keybuff=(uchar*) my_malloc(key_buff_length, MYF(0)); + keybuff=(uchar*) my_malloc(key_buff_length, MYF(MY_THREAD_SPECIFIC)); key_info_length= pack_keys(keybuff, keys, key_info, data_offset); /* @@ -534,7 +534,7 @@ static uchar *pack_screens(List &create_fields, while ((field=it++)) length+=(uint) strlen(field->field_name)+1+TE_INFO_LENGTH+cols/2; - if (!(info=(uchar*) my_malloc(length,MYF(MY_WME)))) + if (!(info=(uchar*) my_malloc(length,MYF(MY_WME | MY_THREAD_SPECIFIC)))) DBUG_RETURN(0); start_screen=0; @@ -1108,7 +1108,9 @@ static bool make_empty_rec(THD *thd, File file,enum legacy_db_type table_type, bzero((char*) &share, sizeof(share)); table.s= &share; - if (!(buff=(uchar*) my_malloc((size_t) reclength,MYF(MY_WME | MY_ZEROFILL)))) + if (!(buff=(uchar*) my_malloc((size_t) reclength, + MYF(MY_WME | MY_ZEROFILL | + MY_THREAD_SPECIFIC)))) { DBUG_RETURN(1); } -- cgit v1.2.1 From 682da0aa750c059a4f81fadcdf42c9211602eda7 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 23 Jan 2013 16:18:09 +0100 Subject: cleanup: use MYF() for mysys flags --- sql/event_data_objects.cc | 2 +- sql/ha_ndbcluster.cc | 2 +- sql/ha_ndbcluster_binlog.cc | 2 +- sql/ha_partition.cc | 6 +++--- sql/log.cc | 2 +- sql/mysqld.cc | 10 +++++----- sql/rpl_filter.cc | 2 +- sql/rpl_handler.cc | 2 +- sql/rpl_handler.h | 2 +- sql/rpl_mi.cc | 2 +- sql/rpl_tblmap.cc | 2 +- sql/rpl_utility.cc | 2 +- sql/sp_head.cc | 10 +++++----- sql/sp_pcontext.cc | 20 ++++++++++---------- sql/sql_acl.cc | 14 +++++++------- sql/sql_array.h | 2 +- sql/sql_audit.cc | 2 +- sql/sql_base.cc | 2 +- sql/sql_class.cc | 2 +- sql/sql_class.h | 4 ++-- sql/sql_lex.h | 2 +- sql/sql_plugin.cc | 10 +++++----- sql/sql_servers.cc | 2 +- sql/sql_show.cc | 6 +++--- sql/sql_trigger.cc | 4 ++-- sql/sql_udf.cc | 2 +- sql/table.cc | 6 +++--- sql/tztime.cc | 6 +++--- 28 files changed, 65 insertions(+), 65 deletions(-) (limited to 'sql') diff --git a/sql/event_data_objects.cc b/sql/event_data_objects.cc index a5dac4c154b..14b1003d308 100644 --- a/sql/event_data_objects.cc +++ b/sql/event_data_objects.cc @@ -209,7 +209,7 @@ Event_basic::Event_basic() { DBUG_ENTER("Event_basic::Event_basic"); /* init memory root */ - init_sql_alloc(&mem_root, 256, 512, 0); + init_sql_alloc(&mem_root, 256, 512, MYF(0)); dbname.str= name.str= NULL; dbname.length= name.length= 0; time_zone= NULL; diff --git a/sql/ha_ndbcluster.cc b/sql/ha_ndbcluster.cc index 44d384e7f2d..6fc30fa4fa0 100644 --- a/sql/ha_ndbcluster.cc +++ b/sql/ha_ndbcluster.cc @@ -8649,7 +8649,7 @@ NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table, MEM_ROOT **root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC); MEM_ROOT *old_root= *root_ptr; - init_sql_alloc(&share->mem_root, 1024, 0, 0); + init_sql_alloc(&share->mem_root, 1024, 0, MYF(0)); *root_ptr= &share->mem_root; // remember to reset before return share->state= NSS_INITIAL; /* enough space for key, db, and table_name */ diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc index e7582d695ce..2b72ffef9bf 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -3964,7 +3964,7 @@ restart: my_pthread_getspecific_ptr(MEM_ROOT**, THR_MALLOC); MEM_ROOT *old_root= *root_ptr; MEM_ROOT mem_root; - init_sql_alloc(&mem_root, 4096, 0, 0); + init_sql_alloc(&mem_root, 4096, 0, MYF(0)); List post_epoch_log_list; List post_epoch_unlock_list; *root_ptr= &mem_root; diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index e28c461f4ce..9a9f0b537f7 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -168,7 +168,7 @@ ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share) :handler(hton, share) { DBUG_ENTER("ha_partition::ha_partition(table)"); - init_alloc_root(&m_mem_root, 512, 512, 0); + init_alloc_root(&m_mem_root, 512, 512, MYF(0)); init_handler_variables(); DBUG_VOID_RETURN; } @@ -190,7 +190,7 @@ ha_partition::ha_partition(handlerton *hton, partition_info *part_info) { DBUG_ENTER("ha_partition::ha_partition(part_info)"); DBUG_ASSERT(part_info); - init_alloc_root(&m_mem_root, 512, 512, 0); + init_alloc_root(&m_mem_root, 512, 512, MYF(0)); init_handler_variables(); m_part_info= part_info; m_create_handler= TRUE; @@ -217,7 +217,7 @@ ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share, :handler(hton, share) { DBUG_ENTER("ha_partition::ha_partition(clone)"); - init_alloc_root(&m_mem_root, 512, 512, 0); + init_alloc_root(&m_mem_root, 512, 512, MYF(0)); init_handler_variables(); m_part_info= part_info_arg; m_create_handler= TRUE; diff --git a/sql/log.cc b/sql/log.cc index c6d91b1f67e..9d476e2a262 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -8311,7 +8311,7 @@ int TC_LOG_BINLOG::recover(LOG_INFO *linfo, const char *last_log_name, sizeof(my_xid), 0, 0, MYF(0))) goto err1; - init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE, 0); + init_alloc_root(&mem_root, TC_LOG_PAGE_SIZE, TC_LOG_PAGE_SIZE, MYF(0)); fdle->flags&= ~LOG_EVENT_BINLOG_IN_USE_F; // abort on the first error diff --git a/sql/mysqld.cc b/sql/mysqld.cc index ca68f8c9ae2..b2c8a842283 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -1121,7 +1121,7 @@ private: void Buffered_logs::init() { - init_alloc_root(&m_root, 1024, 0, 0); + init_alloc_root(&m_root, 1024, 0, MYF(0)); } void Buffered_logs::cleanup() @@ -4761,7 +4761,7 @@ int mysqld_main(int argc, char **argv) my_getopt_skip_unknown= TRUE; /* prepare all_early_options array */ - my_init_dynamic_array(&all_early_options, sizeof(my_option), 100, 25, 0); + my_init_dynamic_array(&all_early_options, sizeof(my_option), 100, 25, MYF(0)); sys_var_add_options(&all_early_options, sys_var::PARSE_EARLY); add_terminator(&all_early_options); @@ -5355,7 +5355,7 @@ static void bootstrap(MYSQL_FILE *file) THD *thd= new THD; thd->bootstrap=1; - my_net_init(&thd->net,(st_vio*) 0, 0); + my_net_init(&thd->net,(st_vio*) 0, MYF(0)); thd->max_client_packet_length= thd->net.max_packet; thd->security_ctx->master_access= ~(ulong)0; thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; @@ -7249,7 +7249,7 @@ static int option_cmp(my_option *a, my_option *b) static void print_help() { MEM_ROOT mem_root; - init_alloc_root(&mem_root, 4096, 4096, 0); + init_alloc_root(&mem_root, 4096, 4096, MYF(0)); pop_dynamic(&all_options); sys_var_add_options(&all_options, sys_var::PARSE_EARLY); @@ -7941,7 +7941,7 @@ static int get_options(int *argc_ptr, char ***argv_ptr) /* prepare all_options array */ my_init_dynamic_array(&all_options, sizeof(my_option), array_elements(my_long_options), - array_elements(my_long_options)/4, 0); + array_elements(my_long_options)/4, MYF(0)); for (my_option *opt= my_long_options; opt < my_long_options + array_elements(my_long_options) - 1; opt++) diff --git a/sql/rpl_filter.cc b/sql/rpl_filter.cc index b44c3c7504c..f2bd036896d 100644 --- a/sql/rpl_filter.cc +++ b/sql/rpl_filter.cc @@ -573,7 +573,7 @@ void Rpl_filter::init_table_rule_array(DYNAMIC_ARRAY* a, bool* a_inited) { my_init_dynamic_array(a, sizeof(TABLE_RULE_ENT*), TABLE_RULE_ARR_SIZE, - TABLE_RULE_ARR_SIZE, 0); + TABLE_RULE_ARR_SIZE, MYF(0)); *a_inited = 1; } diff --git a/sql/rpl_handler.cc b/sql/rpl_handler.cc index 07eeef57842..258dae0edb2 100644 --- a/sql/rpl_handler.cc +++ b/sql/rpl_handler.cc @@ -189,7 +189,7 @@ void delegates_destroy() DYNAMIC_ARRAY *plugins= &s.plugins; \ plugin_ref *plugins_buffer= s.plugins_buffer; \ my_init_dynamic_array2(plugins, sizeof(plugin_ref), \ - plugins_buffer, 8, 8, 0); \ + plugins_buffer, 8, 8, MYF(0)); \ read_lock(); \ Observer_info_iterator iter= observer_info_iter(); \ Observer_info *info= iter++; \ diff --git a/sql/rpl_handler.h b/sql/rpl_handler.h index e955707f5c3..e028fb49808 100644 --- a/sql/rpl_handler.h +++ b/sql/rpl_handler.h @@ -124,7 +124,7 @@ public: inited= FALSE; if (my_rwlock_init(&lock, NULL)) return; - init_sql_alloc(&memroot, 1024, 0, 0); + init_sql_alloc(&memroot, 1024, 0, MYF(0)); inited= TRUE; } ~Delegate() diff --git a/sql/rpl_mi.cc b/sql/rpl_mi.cc index 73a2e26faba..5348a94b35b 100644 --- a/sql/rpl_mi.cc +++ b/sql/rpl_mi.cc @@ -61,7 +61,7 @@ Master_info::Master_info(LEX_STRING *connection_name_arg, my_casedn_str(system_charset_info, cmp_connection_name.str); } - my_init_dynamic_array(&ignore_server_ids, sizeof(::server_id), 16, 16, 0); + my_init_dynamic_array(&ignore_server_ids, sizeof(::server_id), 16, 16, MYF(0)); bzero((char*) &file, sizeof(file)); mysql_mutex_init(key_master_info_run_lock, &run_lock, MY_MUTEX_INIT_FAST); mysql_mutex_init(key_master_info_data_lock, &data_lock, MY_MUTEX_INIT_FAST); diff --git a/sql/rpl_tblmap.cc b/sql/rpl_tblmap.cc index 92d8ca228b0..7b55911d887 100644 --- a/sql/rpl_tblmap.cc +++ b/sql/rpl_tblmap.cc @@ -46,7 +46,7 @@ table_mapping::table_mapping() offsetof(entry,table_id),sizeof(ulong), 0,0,0); /* We don't preallocate any block, this is consistent with m_free=0 above */ - init_alloc_root(&m_mem_root, TABLE_ID_HASH_SIZE*sizeof(entry), 0, 0); + init_alloc_root(&m_mem_root, TABLE_ID_HASH_SIZE*sizeof(entry), 0, MYF(0)); DBUG_VOID_RETURN; } diff --git a/sql/rpl_utility.cc b/sql/rpl_utility.cc index 321aead841e..1b9e744bcc1 100644 --- a/sql/rpl_utility.cc +++ b/sql/rpl_utility.cc @@ -1117,7 +1117,7 @@ bool event_checksum_test(uchar *event_buf, ulong event_len, uint8 alg) Deferred_log_events::Deferred_log_events(Relay_log_info *rli) : last_added(NULL) { - my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16, 0); + my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16, MYF(0)); } Deferred_log_events::~Deferred_log_events() diff --git a/sql/sp_head.cc b/sql/sp_head.cc index 1d6aa73fdb0..57e7877cc34 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -510,7 +510,7 @@ sp_head::operator new(size_t size) throw() MEM_ROOT own_root; sp_head *sp; - init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, 0); + init_sql_alloc(&own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, MYF(0)); sp= (sp_head *) alloc_root(&own_root, size); if (sp == NULL) DBUG_RETURN(NULL); @@ -594,7 +594,7 @@ sp_head::init(LEX *lex) types of stored procedures to simplify reset_lex()/restore_lex() code. */ lex->trg_table_fields.empty(); - my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8, 0); + my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8, MYF(0)); m_param_begin= NULL; m_param_end= NULL; @@ -1254,7 +1254,7 @@ sp_head::execute(THD *thd, bool merge_da_on_success) DBUG_RETURN(TRUE); /* init per-instruction memroot */ - init_sql_alloc(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); + init_sql_alloc(&execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(0)); DBUG_ASSERT(!(m_flags & IS_INVOKED)); m_flags|= IS_INVOKED; @@ -1711,7 +1711,7 @@ sp_head::execute_trigger(THD *thd, TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a trigger. */ - init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); + init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(0)); thd->set_n_backup_active_arena(&call_arena, &backup_arena); if (!(nctx= new sp_rcontext(m_pcont, 0, octx)) || @@ -1828,7 +1828,7 @@ sp_head::execute_function(THD *thd, Item **argp, uint argcount, TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a function/trigger. */ - init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, 0); + init_sql_alloc(&call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(0)); thd->set_n_backup_active_arena(&call_arena, &backup_arena); if (!(nctx= new sp_rcontext(m_pcont, return_value_fld, octx)) || diff --git a/sql/sp_pcontext.cc b/sql/sp_pcontext.cc index cdafc5cd819..f11daeecb7b 100644 --- a/sql/sp_pcontext.cc +++ b/sql/sp_pcontext.cc @@ -62,19 +62,19 @@ sp_pcontext::sp_pcontext() { (void) my_init_dynamic_array(&m_vars, sizeof(sp_variable_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_case_expr_id_lst, sizeof(int), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_conds, sizeof(sp_cond_type_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_cursors, sizeof(LEX_STRING), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_handlers, sizeof(sp_cond_type_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); m_label.empty(); m_children.empty(); @@ -90,19 +90,19 @@ sp_pcontext::sp_pcontext(sp_pcontext *prev, label_scope_type label_scope) { (void) my_init_dynamic_array(&m_vars, sizeof(sp_variable_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_case_expr_id_lst, sizeof(int), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_conds, sizeof(sp_cond_type_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_cursors, sizeof(LEX_STRING), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); (void) my_init_dynamic_array(&m_handlers, sizeof(sp_cond_type_t *), PCONTEXT_ARRAY_INIT_ALLOC, - PCONTEXT_ARRAY_INCREMENT_ALLOC, 0); + PCONTEXT_ARRAY_INCREMENT_ALLOC, MYF(0)); m_label.empty(); m_children.empty(); diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 9fa908c43e2..2d1493b17de 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -749,13 +749,13 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) acl_cache->clear(1); // Clear locked hostname cache - init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, MYF(0)); if (init_read_record(&read_record_info,thd,table= tables[0].table,NULL,1,0, FALSE)) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST), 20, 50, 0); + (void) my_init_dynamic_array(&acl_hosts,sizeof(ACL_HOST), 20, 50, MYF(0)); while (!(read_record_info.read_record(&read_record_info))) { ACL_HOST host; @@ -807,7 +807,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_users,sizeof(ACL_USER), 50, 100, 0); + (void) my_init_dynamic_array(&acl_users,sizeof(ACL_USER), 50, 100, MYF(0)); password_length= table->field[2]->field_length / table->field[2]->charset()->mbmaxlen; if (password_length < SCRAMBLED_PASSWORD_CHAR_LENGTH_323) @@ -1009,7 +1009,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) goto end; table->use_all_columns(); - (void) my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB), 50, 100, 0); + (void) my_init_dynamic_array(&acl_dbs,sizeof(ACL_DB), 50, 100, MYF(0)); while (!(read_record_info.read_record(&read_record_info))) { ACL_DB db; @@ -1067,7 +1067,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) freeze_size(&acl_dbs); (void) my_init_dynamic_array(&acl_proxy_users, sizeof(ACL_PROXY_USER), - 50, 100, 0); + 50, 100, MYF(0)); if (tables[3].table) { init_read_record(&read_record_info, thd, table= tables[3].table, NULL, 1, @@ -1722,7 +1722,7 @@ static void init_check_host(void) { DBUG_ENTER("init_check_host"); (void) my_init_dynamic_array(&acl_wild_hosts,sizeof(struct acl_host_and_ip), - acl_users.elements, 1, 0); + acl_users.elements, 1, MYF(0)); (void) my_hash_init(&acl_check_hosts,system_charset_info, acl_users.elements, 0, 0, (my_hash_get_key) check_get_key, 0, 0); @@ -4412,7 +4412,7 @@ my_bool grant_reload(THD *thd) opertion possible in case of failure. */ old_mem= memex; - init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&memex, ACL_ALLOC_BLOCK_SIZE, 0, MYF(0)); if ((return_val= grant_load(thd, tables))) { // Error. Revert to old hash diff --git a/sql/sql_array.h b/sql/sql_array.h index 18881d2c345..f07126bc0ef 100644 --- a/sql/sql_array.h +++ b/sql/sql_array.h @@ -101,7 +101,7 @@ public: Dynamic_array(uint prealloc=16, uint increment=16) { my_init_dynamic_array(&array, sizeof(Elem), prealloc, increment, - MY_THREAD_SPECIFIC); + MYF(MY_THREAD_SPECIFIC)); } Elem& at(int idx) diff --git a/sql/sql_audit.cc b/sql/sql_audit.cc index 4403034bca8..f1f991242e7 100644 --- a/sql/sql_audit.cc +++ b/sql/sql_audit.cc @@ -156,7 +156,7 @@ static my_bool acquire_plugins(THD *thd, plugin_ref plugin, void *arg) { /* specify some reasonable initialization defaults */ my_init_dynamic_array(&thd->audit_class_plugins, - sizeof(plugin_ref), 16, 16, 0); + sizeof(plugin_ref), 16, 16, MYF(0)); } /* lock the plugin and add it to the list */ diff --git a/sql/sql_base.cc b/sql/sql_base.cc index fd0d0603395..58b13d4cd8a 100644 --- a/sql/sql_base.cc +++ b/sql/sql_base.cc @@ -4973,7 +4973,7 @@ bool open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags, anything yet, to avoid penalty for statements which don't use views and thus new .FRM format. */ - init_sql_alloc(&new_frm_mem, 8024, 0, 0); + init_sql_alloc(&new_frm_mem, 8024, 0, MYF(0)); thd->current_tablenr= 0; restart: diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 1d0d23a2390..44102aaf3bc 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -935,7 +935,7 @@ THD::THD() /* For user vars replication*/ if (opt_bin_log) my_init_dynamic_array(&user_var_events, - sizeof(BINLOG_USER_VAR_EVENT *), 16, 16, 0); + sizeof(BINLOG_USER_VAR_EVENT *), 16, 16, MYF(0)); else bzero((char*) &user_var_events, sizeof(user_var_events)); diff --git a/sql/sql_class.h b/sql/sql_class.h index f10b517a606..9d00d3ff905 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -1429,7 +1429,7 @@ public: m_locked_tables_count(0) { init_sql_alloc(&m_locked_tables_root, MEM_ROOT_BLOCK_SIZE, 0, - MY_THREAD_SPECIFIC); + MYF(MY_THREAD_SPECIFIC)); } void unlock_locked_tables(THD *thd); ~Locked_tables_list() @@ -1886,7 +1886,7 @@ public: bzero((char*)this, sizeof(*this)); xid_state.xid.null(); init_sql_alloc(&mem_root, ALLOC_ROOT_MIN_BLOCK_SIZE, 0, - MY_THREAD_SPECIFIC); + MYF(MY_THREAD_SPECIFIC)); } } transaction; Global_read_lock global_read_lock; diff --git a/sql/sql_lex.h b/sql/sql_lex.h index e1c0940c461..be7cdd8ca1d 100644 --- a/sql/sql_lex.h +++ b/sql/sql_lex.h @@ -305,7 +305,7 @@ struct LEX_MASTER_INFO { bzero(this, sizeof(*this)); my_init_dynamic_array(&repl_ignore_server_ids, - sizeof(::server_id), 0, 16, 0); + sizeof(::server_id), 0, 16, MYF(0)); } void reset() { diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index e24b43c0cf6..d1c12ee4f83 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -1114,7 +1114,7 @@ static bool plugin_add(MEM_ROOT *tmp_root, plugin_array_version++; if (my_hash_insert(&plugin_hash[plugin->type], (uchar*)tmp_plugin_ptr)) tmp_plugin_ptr->state= PLUGIN_IS_FREED; - init_alloc_root(&tmp_plugin_ptr->mem_root, 4096, 4096, 0); + init_alloc_root(&tmp_plugin_ptr->mem_root, 4096, 4096, MYF(0)); if (name->str) DBUG_RETURN(FALSE); // all done @@ -1507,8 +1507,8 @@ int plugin_init(int *argc, char **argv, int flags) init_plugin_psi_keys(); #endif - init_alloc_root(&plugin_mem_root, 4096, 4096, 0); - init_alloc_root(&tmp_root, 4096, 4096, 0); + init_alloc_root(&plugin_mem_root, 4096, 4096, MYF(0)); + init_alloc_root(&tmp_root, 4096, 4096, MYF(0)); if (my_hash_init(&bookmark_hash, &my_charset_bin, 16, 0, 0, get_bookmark_hash_key, NULL, HASH_UNIQUE)) @@ -1518,9 +1518,9 @@ int plugin_init(int *argc, char **argv, int flags) mysql_mutex_init(key_LOCK_plugin, &LOCK_plugin, MY_MUTEX_INIT_FAST); if (my_init_dynamic_array(&plugin_dl_array, - sizeof(struct st_plugin_dl *),16,16,0) || + sizeof(struct st_plugin_dl *), 16, 16, MYF(0)) || my_init_dynamic_array(&plugin_array, - sizeof(struct st_plugin_int *),16,16,0)) + sizeof(struct st_plugin_int *), 16, 16, MYF(0))) goto err; for (i= 0; i < MYSQL_MAX_PLUGIN_TYPE_NUM; i++) diff --git a/sql/sql_servers.cc b/sql/sql_servers.cc index 63f3e6c9d63..b5b7f9866c5 100644 --- a/sql/sql_servers.cc +++ b/sql/sql_servers.cc @@ -209,7 +209,7 @@ static bool servers_load(THD *thd, TABLE_LIST *tables) my_hash_reset(&servers_cache); free_root(&mem, MYF(0)); - init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&mem, ACL_ALLOC_BLOCK_SIZE, 0, MYF(0)); if (init_read_record(&read_record_info,thd,table=tables[0].table,NULL,1,0, FALSE)) diff --git a/sql/sql_show.cc b/sql/sql_show.cc index f9458fa8588..5a414ad7b48 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -458,7 +458,7 @@ bool ignore_db_dirs_init() { return my_init_dynamic_array(&ignore_db_dirs_array, sizeof(LEX_STRING *), - 0, 0, 0); + 0, 0, MYF(0)); } @@ -2676,7 +2676,7 @@ int add_status_vars(SHOW_VAR *list) if (status_vars_inited) mysql_mutex_lock(&LOCK_status); if (!all_status_vars.buffer && // array is not allocated yet - do it now - my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20, 0)) + my_init_dynamic_array(&all_status_vars, sizeof(SHOW_VAR), 200, 20, MYF(0))) { res= 1; goto err; @@ -4399,7 +4399,7 @@ static int fill_schema_table_from_frm(THD *thd, TABLE_LIST *tables, if (schema_table->i_s_requested_object & OPEN_TRIGGER_ONLY) { - init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&tbl.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(0)); if (!Table_triggers_list::check_n_load(thd, db_name->str, table_name->str, &tbl, 1)) { diff --git a/sql/sql_trigger.cc b/sql/sql_trigger.cc index fa509835dae..d7d902bc6b0 100644 --- a/sql/sql_trigger.cc +++ b/sql/sql_trigger.cc @@ -1779,7 +1779,7 @@ bool Table_triggers_list::drop_all_triggers(THD *thd, char *db, char *name) DBUG_ENTER("drop_all_triggers"); bzero(&table, sizeof(table)); - init_sql_alloc(&table.mem_root, 8192, 0, 0); + init_sql_alloc(&table.mem_root, 8192, 0, MYF(0)); if (Table_triggers_list::check_n_load(thd, db, name, &table, 1)) { @@ -1999,7 +1999,7 @@ bool Table_triggers_list::change_table_name(THD *thd, const char *db, DBUG_ENTER("change_table_name"); bzero(&table, sizeof(table)); - init_sql_alloc(&table.mem_root, 8192, 0, 0); + init_sql_alloc(&table.mem_root, 8192, 0, MYF(0)); /* This method interfaces the mysql server code protected by diff --git a/sql/sql_udf.cc b/sql/sql_udf.cc index 9832f240fb5..c792dca873c 100644 --- a/sql/sql_udf.cc +++ b/sql/sql_udf.cc @@ -151,7 +151,7 @@ void udf_init() mysql_rwlock_init(key_rwlock_THR_LOCK_udf, &THR_LOCK_udf); - init_sql_alloc(&mem, UDF_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&mem, UDF_ALLOC_BLOCK_SIZE, 0, MYF(0)); THD *new_thd = new THD; if (!new_thd || my_hash_init(&udf_hash,system_charset_info,32,0,0,get_hash_key, NULL, 0)) diff --git a/sql/table.cc b/sql/table.cc index 6fc6bd44b22..3755f0d25ff 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -307,7 +307,7 @@ TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, path_length= build_table_filename(path, sizeof(path) - 1, table_list->db, table_list->table_name, "", 0); - init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(0)); if (multi_alloc_root(&mem_root, &share, sizeof(*share), &key_buff, key_length, @@ -340,7 +340,7 @@ TABLE_SHARE *alloc_table_share(TABLE_LIST *table_list, char *key, share->free_tables.empty(); share->m_flush_tickets.empty(); - init_sql_alloc(&share->stats_cb.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&share->stats_cb.mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(0)); memcpy((char*) &share->mem_root, (char*) &mem_root, sizeof(mem_root)); mysql_mutex_init(key_TABLE_SHARE_LOCK_ha_data, @@ -2358,7 +2358,7 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, outparam->db_stat= db_stat; outparam->write_row_record= NULL; - init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, 0); + init_sql_alloc(&outparam->mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(0)); if (outparam->alias.copy(alias, strlen(alias), table_alias_charset)) goto err; diff --git a/sql/tztime.cc b/sql/tztime.cc index 525fc96241c..ad5deea7b25 100644 --- a/sql/tztime.cc +++ b/sql/tztime.cc @@ -1637,7 +1637,7 @@ my_tz_init(THD *org_thd, const char *default_tzname, my_bool bootstrap) my_hash_free(&tz_names); goto end; } - init_sql_alloc(&tz_storage, 32 * 1024, 0, 0); + init_sql_alloc(&tz_storage, 32 * 1024, 0, MYF(0)); mysql_mutex_init(key_tz_LOCK, &tz_LOCK, MY_MUTEX_INIT_FAST); tz_inited= 1; @@ -2599,7 +2599,7 @@ main(int argc, char **argv) } else { - init_alloc_root(&tz_storage, 32768, 0, 0); + init_alloc_root(&tz_storage, 32768, 0, MYF(0)); if (strcmp(argv[1], "--leap") == 0) { @@ -2676,7 +2676,7 @@ main(int argc, char **argv) MY_INIT(argv[0]); - init_alloc_root(&tz_storage, 32768, 0); + init_alloc_root(&tz_storage, 32768, MYF(0)); /* let us set some well known timezone */ setenv("TZ", "MET", 1); -- cgit v1.2.1 From 52051882002c1b88a427d50fb343a9ed3614ffe0 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 23 Jan 2013 16:19:37 +0100 Subject: cleanup: * remove unused mysql_option * don't allocate 5GB of memory in the mtr tests * restore the behavior in dynamic_column_offset_byte(), put the ifdef correctly * prefer __attribute__((unused)) to #ifdef * prefer UNINIT_VAR to LINT_INIT * make most Warning_info users blissfully unaware of the postponed initialization * use my_offsetof instead of offsetof where the compiler thinks the latter is incorrect --- sql/slave.cc | 4 +--- sql/sp_head.cc | 2 +- sql/sql_admin.cc | 2 +- sql/sql_error.h | 2 +- sql/sql_prepare.cc | 2 +- sql/sql_show.cc | 2 +- sql/sys_vars.cc | 4 ++-- sql/table.cc | 4 +--- 8 files changed, 9 insertions(+), 13 deletions(-) (limited to 'sql') diff --git a/sql/slave.cc b/sql/slave.cc index 9e552e64a9e..da10169d97b 100644 --- a/sql/slave.cc +++ b/sql/slave.cc @@ -2425,9 +2425,7 @@ static int init_slave_thread(THD* thd, Master_info *mi, SLAVE_THD_TYPE thd_type) { DBUG_ENTER("init_slave_thread"); -#if !defined(DBUG_OFF) - int simulate_error= 0; -#endif + int simulate_error __attribute__((unused))= 0; DBUG_EXECUTE_IF("simulate_io_slave_error_on_init", simulate_error|= (1 << SLAVE_THD_IO);); DBUG_EXECUTE_IF("simulate_sql_slave_error_on_init", diff --git a/sql/sp_head.cc b/sql/sp_head.cc index 57e7877cc34..0dec9b5f145 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -1224,7 +1224,7 @@ sp_head::execute(THD *thd, bool merge_da_on_success) Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer; Object_creation_ctx *saved_creation_ctx; Warning_info *saved_warning_info; - Warning_info warning_info(thd->warning_info->warn_id(), false, true); + Warning_info warning_info(thd->warning_info->warn_id(), false); /* Just reporting a stack overrun error diff --git a/sql/sql_admin.cc b/sql/sql_admin.cc index ba1ea01efcc..e6bbef482a7 100644 --- a/sql/sql_admin.cc +++ b/sql/sql_admin.cc @@ -398,7 +398,7 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables, because it's already known that the table is badly damaged. */ - Warning_info wi(thd->query_id, false, true); + Warning_info wi(thd->query_id, false); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; diff --git a/sql/sql_error.h b/sql/sql_error.h index 17ec3aa7b56..f018387eb3b 100644 --- a/sql/sql_error.h +++ b/sql/sql_error.h @@ -363,7 +363,7 @@ private: public: Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings, - bool initialize); + bool initialize=true); ~Warning_info(); /* Allocate memory for structures */ diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc index e2398536783..71b4a0cf817 100644 --- a/sql/sql_prepare.cc +++ b/sql/sql_prepare.cc @@ -2963,7 +2963,7 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length) param= stmt->param_array[param_number]; Diagnostics_area new_stmt_da, *save_stmt_da= thd->stmt_da; - Warning_info new_warnning_info(thd->query_id, false, true); + Warning_info new_warnning_info(thd->query_id, false); Warning_info *save_warinig_info= thd->warning_info; thd->stmt_da= &new_stmt_da; diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 5a414ad7b48..33e31913e41 100644 --- a/sql/sql_show.cc +++ b/sql/sql_show.cc @@ -7905,7 +7905,7 @@ static bool do_fill_table(THD *thd, // Warning_info, so "useful warnings" get rejected. In order to avoid // that problem we create a Warning_info instance, which is capable of // storing "unlimited" number of warnings. - Warning_info wi(thd->query_id, true, true); + Warning_info wi(thd->query_id, true); Warning_info *wi_saved= thd->warning_info; thd->warning_info= &wi; diff --git a/sql/sys_vars.cc b/sql/sys_vars.cc index d55daa2cb28..d0b39f2b9b0 100644 --- a/sql/sys_vars.cc +++ b/sql/sys_vars.cc @@ -3422,7 +3422,7 @@ Sys_slave_skip_counter("sql_slave_skip_counter", "Skip the next N events from the master log", SESSION_VAR(slave_skip_counter), NO_CMD_LINE, - offsetof(Master_info, rli.slave_skip_counter), + my_offsetof(Master_info, rli.slave_skip_counter), VALID_RANGE(0, UINT_MAX), DEFAULT(0), BLOCK_SIZE(1), ON_UPDATE(update_slave_skip_counter)); @@ -3441,7 +3441,7 @@ Sys_max_relay_log_size( "max_relay_log_size", "set to max_binlog_size", SESSION_VAR(max_relay_log_size), CMD_LINE(REQUIRED_ARG), - offsetof(Master_info, rli.max_relay_log_size), + my_offsetof(Master_info, rli.max_relay_log_size), VALID_RANGE(0, 1024L*1024*1024), DEFAULT(0), BLOCK_SIZE(IO_SIZE), ON_UPDATE(update_max_relay_log_size)); diff --git a/sql/table.cc b/sql/table.cc index 3755f0d25ff..117345ad25d 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -2341,13 +2341,11 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias, uint records, i, bitmap_size; bool error_reported= FALSE; uchar *record, *bitmaps; - Field **field_ptr, **vfield_ptr, **dfield_ptr; + Field **field_ptr, **UNINIT_VAR(vfield_ptr), **UNINIT_VAR(dfield_ptr); uint8 save_context_analysis_only= thd->lex->context_analysis_only; DBUG_ENTER("open_table_from_share"); DBUG_PRINT("enter",("name: '%s.%s' form: 0x%lx", share->db.str, share->table_name.str, (long) outparam)); - LINT_INIT(dfield_ptr); - LINT_INIT(vfield_ptr); thd->lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_VIEW; // not a view -- cgit v1.2.1 From c71fad9983b4a3c6e0d9e9eca02dadfd923ddbbb Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 23 Jan 2013 16:20:39 +0100 Subject: cleanup: * don't use 'myf flags', when 'my_bool is_thread_specific' is meant * call set_malloc_size_cb() for embedded too * warn in safemalloc if the memory is freed by a wrong thread sql/mysqld.cc: move set_malloc_size_cb() to a function that is also called for embedded sql/mysqld.h: gdb-friendly, one can put breakpoint on a function, but not on a macro sql/sql_class.cc: initialize thread_id earlier --- sql/mysqld.cc | 64 ++++++++++++++++++++++++++++---------------------------- sql/mysqld.h | 5 ++++- sql/sql_class.cc | 2 +- 3 files changed, 37 insertions(+), 34 deletions(-) (limited to 'sql') diff --git a/sql/mysqld.cc b/sql/mysqld.cc index b2c8a842283..93e5fc5864b 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -3454,6 +3454,36 @@ extern "C" my_thread_id mariadb_dbug_id() } #endif /* SAFEMALLOC */ +/* Thread Mem Usage By P.Linux */ +extern "C" { +static void my_malloc_size_cb_func(long long size, my_bool is_thread_specific) +{ + /* If thread specific memory */ + if (is_thread_specific) + { + THD *thd= current_thd; + if (mysqld_server_initialized || thd) + { + /* + THD may not be set if we are called from my_net_init() before THD + thread has started. + However, this should never happen, so better to assert and + fix this. + */ + DBUG_ASSERT(thd); + if (thd) + { + DBUG_PRINT("info", ("memory_used: %lld size: %lld", + (longlong) thd->status_var.memory_used, size)); + thd->status_var.memory_used+= size; + DBUG_ASSERT((longlong) thd->status_var.memory_used >= 0); + } + } + } + my_atomic_add64(&global_status_var.memory_used, size); +} +} + /* Init common variables @@ -3464,6 +3494,8 @@ static int init_common_variables() umask(((~my_umask) & 0666)); my_decimal_set_zero(&decimal_zero); // set decimal_zero constant; + set_malloc_size_cb(my_malloc_size_cb_func); + tzset(); // Set tzname sf_leaking_memory= 0; // no memory leaks from now on @@ -4675,36 +4707,6 @@ static void test_lc_time_sz() #endif//DBUG_OFF -/* Thread Mem Usage By P.Linux */ -extern "C" -void my_malloc_size_cb_func(long long size, myf my_flags) -{ - /* If thread specific memory */ - if (my_flags) - { - THD *thd= current_thd; - if (mysqld_server_initialized || thd) - { - /* - THD may not be set if we are called from my_net_init() before THD - thread has started. - However, this should never happen, so better to assert and - fix this. - */ - DBUG_ASSERT(thd); - if (thd) - { - DBUG_PRINT("info", ("memory_used: %lld size: %lld", - (longlong) thd->status_var.memory_used, size)); - thd->status_var.memory_used+= size; - DBUG_ASSERT((longlong) thd->status_var.memory_used >= 0); - } - } - } - my_atomic_add64(&global_status_var.memory_used, size); -} - - #ifdef __WIN__ int win_main(int argc, char **argv) #else @@ -4717,7 +4719,6 @@ int mysqld_main(int argc, char **argv) */ my_progname= argv[0]; sf_leaking_memory= 1; // no safemalloc memory leak reports if we exit early - set_malloc_size_cb(my_malloc_size_cb_func); mysqld_server_started= mysqld_server_initialized= 0; #ifdef HAVE_NPTL @@ -5246,7 +5247,6 @@ int mysqld_main(int argc, char **argv) /* Must be initialized early for comparison of service name */ system_charset_info= &my_charset_utf8_general_ci; - set_malloc_size_cb(my_malloc_size_cb_func); if (my_init()) { diff --git a/sql/mysqld.h b/sql/mysqld.h index e9c4f713182..520fa03bdbf 100644 --- a/sql/mysqld.h +++ b/sql/mysqld.h @@ -534,7 +534,10 @@ inline THD *_current_thd(void) } #endif #define current_thd _current_thd() -#define set_current_thd(X) my_pthread_setspecific_ptr(THR_THD, (X)) +inline int set_current_thd(THD *thd) +{ + return my_pthread_setspecific_ptr(THR_THD, thd); +} /* @todo remove, make it static in ha_maria.cc diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 44102aaf3bc..47c104c2a65 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -793,6 +793,7 @@ THD::THD() accessed_rows_and_keys(0), warning_info(&main_warning_info), stmt_da(&main_da), + thread_id(0), global_disable_checkpoint(0), is_fatal_error(0), transaction_rollback_request(0), @@ -867,7 +868,6 @@ THD::THD() connection_name.length= 0; bzero(&variables, sizeof(variables)); - thread_id= 0; one_shot_set= 0; file_id = 0; query_id= 0; -- cgit v1.2.1 From 6ac52386bbecb90dd4ceb7bd2737ef5eb7abb1ad Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 23 Jan 2013 16:24:04 +0100 Subject: fix the failing federated.federated_innodb test: update all start_bulk_insert() methods to the new signature. --- sql/sql_insert.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'sql') diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index c0eabd3a2f2..cb887d88f56 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -1,5 +1,6 @@ /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. + Copyright (c) 2009, 2013, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by -- cgit v1.2.1 From 259a9404f349406b053f4a271ef8a356dc0f2d3a Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Thu, 24 Jan 2013 17:24:21 +0100 Subject: workaround for incorrectly (?) generated code on gcc 4.2.4-1ubuntu4 with -fPIE (which is added automatically because of DEB_BUILD_HARDENING=1) --- sql/mysqld.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/mysqld.cc b/sql/mysqld.cc index 93e5fc5864b..0704a016fed 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -3480,7 +3480,9 @@ static void my_malloc_size_cb_func(long long size, my_bool is_thread_specific) } } } - my_atomic_add64(&global_status_var.memory_used, size); + // workaround for gcc 4.2.4-1ubuntu4 -fPIE (from DEB_BUILD_HARDENING=1) + int64 volatile * volatile ptr=&global_status_var.memory_used; + my_atomic_add64(ptr, size); } } -- cgit v1.2.1 From bfc71e63a77972fa4ab934855b6ab712bea323a1 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 25 Jan 2013 00:17:39 +0100 Subject: MDEV-3915 COM_CHANGE_USER allows fast password brute-forcing allow only three failed change_user per connection. successful change_user do NOT reset the counter tests/mysql_client_test.c: make --error to work for --change_user errors --- sql/sql_class.cc | 1 + sql/sql_class.h | 1 + sql/sql_parse.cc | 17 ++++++++++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_class.cc b/sql/sql_class.cc index b7a37ae3f69..d44d28eaae2 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -675,6 +675,7 @@ THD::THD() stmt_depends_on_first_successful_insert_id_in_prev_stmt(FALSE), examined_row_count(0), global_read_lock(0), + failed_com_change_user(0), is_fatal_error(0), transaction_rollback_request(0), is_fatal_sub_stmt_error(0), diff --git a/sql/sql_class.h b/sql/sql_class.h index 6b277add4a5..d55200efea4 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -1865,6 +1865,7 @@ public: bool no_errors, password; bool extra_port; /* If extra connection */ + uint8 failed_com_change_user; /** Set to TRUE if execution of the current compound statement can not continue. In particular, disables activation of diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index be0e2db43c6..0c47b7a8bb3 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -1144,6 +1144,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd, uint save_db_length= thd->db_length; char *save_db= thd->db; + int rc; USER_CONN *save_user_connect= thd->user_connect; Security_context save_security_ctx= *thd->security_ctx; CHARSET_INFO *save_character_set_client= @@ -1157,7 +1158,19 @@ bool dispatch_command(enum enum_server_command command, THD *thd, thd->security_ctx->user= 0; thd->user_connect= 0; - if (acl_authenticate(thd, 0, packet_length)) + /* + to limit COM_CHANGE_USER ability to brute-force passwords, + we only allow three unsuccessful COM_CHANGE_USER per connection. + */ + if (thd->failed_com_change_user >= 3) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + rc= 1; + } + else + rc= acl_authenticate(thd, 0, packet_length); + + if (rc) { /* Free user if allocated by acl_authenticate */ x_free(thd->security_ctx->user); @@ -1170,6 +1183,8 @@ bool dispatch_command(enum enum_server_command command, THD *thd, thd->variables.collation_connection= save_collation_connection; thd->variables.character_set_results= save_character_set_results; thd->update_charset(); + thd->failed_com_change_user++; + my_sleep(1000000); } else { -- cgit v1.2.1 From 82c022f2d54813bc0d4b77d23b714c0806b42f73 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 25 Jan 2013 00:20:53 +0100 Subject: report "using password: YES/NO" correctly for the COM_CHANGE_USER failures --- sql/sql_acl.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 1005f5d8688..547572c5db6 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -7471,6 +7471,7 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length) } #ifndef NO_EMBEDDED_ACCESS_CHECKS + thd->password= passwd_len > 0; if (find_mpvio_user(mpvio, sctx)) return 1; -- cgit v1.2.1 From fa7d0c4fdf85c501ebb3a135d31814161e6bc9e4 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 25 Jan 2013 09:41:26 +0100 Subject: MDEV-3909 remote user enumeration instead of returning Access denied on the incorrect user name, emulate the complete failed logic procedure, possibly with the change plugin packet. --- sql/sql_acl.cc | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) (limited to 'sql') diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc index 547572c5db6..29922aa5321 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -7056,6 +7056,7 @@ struct MPVIO_EXT : public MYSQL_PLUGIN_VIO } cached_server_packet; int packets_read, packets_written; ///< counters for send/received packets uint connect_errors; ///< if there were connect errors for this host + bool make_it_fail; /** when plugin returns a failure this tells us what really happened */ enum { SUCCESS, FAILURE, RESTART } status; }; @@ -7322,14 +7323,14 @@ static bool send_plugin_request_packet(MPVIO_EXT *mpvio, /** Finds acl entry in user database for authentication purposes. - Finds a user and copies it into mpvio. Reports an authentication - failure if a user is not found. + Finds a user and copies it into mpvio. Creates a fake user + if no matching user account is found. @note find_acl_user is not the same, because it doesn't take into account the case when user is not empty, but acl_user->user is empty @retval 0 found - @retval 1 not found + @retval 1 error */ static bool find_mpvio_user(MPVIO_EXT *mpvio, Security_context *sctx) @@ -7351,8 +7352,27 @@ static bool find_mpvio_user(MPVIO_EXT *mpvio, Security_context *sctx) if (!mpvio->acl_user) { - login_failed_error(mpvio->thd); - return 1; + /* + A matching user was not found. Fake it. Take any user, make the + authentication fail later. + This way we get a realistically looking failure, with occasional + "change auth plugin" requests even for nonexistent users. The ratio + of "change auth plugin" request will be the same for real and + nonexistent users. + Note, that we cannot pick any user at random, it must always be + the same user account for the incoming sctx->user name. + */ + ulong nr1=1, nr2=4; + CHARSET_INFO *cs= &my_charset_latin1; + cs->coll->hash_sort(cs, (uchar*) sctx->user, strlen(sctx->user), &nr1, &nr2); + + pthread_mutex_lock(&acl_cache->lock); + uint i= nr1 % acl_users.elements; + ACL_USER *acl_user_tmp= dynamic_element(&acl_users, i, ACL_USER*); + mpvio->acl_user= acl_user_tmp->copy(mpvio->thd->mem_root); + pthread_mutex_unlock(&acl_cache->lock); + + mpvio->make_it_fail= true; } /* user account requires non-default plugin and the client is too old */ @@ -7763,8 +7783,8 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio, mpvio->cached_server_packet.pkt_len)) return packet_error; - passwd_len= my_net_read(&mpvio->thd->net); - passwd = (char*)mpvio->thd->net.read_pos; + passwd_len= my_net_read(&thd->net); + passwd= (char*)thd->net.read_pos; } *buff= (uchar*)passwd; @@ -7868,6 +7888,10 @@ static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf) *buf= (uchar*)mpvio->cached_client_reply.pkt; mpvio->cached_client_reply.pkt= 0; mpvio->packets_read++; + + if (mpvio->make_it_fail) + goto err; + return (int)mpvio->cached_client_reply.pkt_len; } /* @@ -7901,13 +7925,19 @@ static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf) else *buf = mpvio->thd->net.read_pos; + if (mpvio->make_it_fail) + goto err; + return (int)pkt_len; err: if (mpvio->status == MPVIO_EXT::FAILURE && !mpvio->thd->is_error()) { inc_host_errors(&mpvio->thd->net.vio->remote.sin_addr); - my_error(ER_HANDSHAKE_ERROR, MYF(0)); + if (mpvio->make_it_fail) + login_failed_error(mpvio->thd); + else + my_error(ER_HANDSHAKE_ERROR, MYF(0)); } return -1; } @@ -8116,6 +8146,7 @@ bool acl_authenticate(THD *thd, uint connect_errors, mpvio.thd= thd; mpvio.connect_errors= connect_errors; mpvio.status= MPVIO_EXT::FAILURE; + mpvio.make_it_fail= false; if (command == COM_CHANGE_USER) { -- cgit v1.2.1 From 326d2d56fe74c5affdcf7c6459c93c3b1dc37dd1 Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 25 Jan 2013 12:26:35 +0100 Subject: MDEV-759 lp:998340 - Valgrind complains on simple selects containing expression DAY(FROM_UNIXTIME(-1)) check item->null_value before using the result of item->val_int() --- sql/item_strfunc.cc | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'sql') diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 4225687724f..9cc77849094 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -1167,7 +1167,7 @@ void Item_str_func::left_right_max_length() if (args[1]->const_item()) { int length=(int) args[1]->val_int()*collation.collation->mbmaxlen; - if (length <= 0) + if (args[1]->null_value || length <= 0) max_length=0; else set_if_smaller(max_length,(uint) length); @@ -1270,7 +1270,9 @@ void Item_func_substr::fix_length_and_dec() if (args[1]->const_item()) { int32 start= (int32) args[1]->val_int(); - if (start < 0) + if (args[1]->null_value) + max_length= 0; + else if (start < 0) max_length= ((uint)(-start) > max_length) ? 0 : (uint)(-start); else max_length-= min((uint)(start - 1), max_length); @@ -1278,7 +1280,7 @@ void Item_func_substr::fix_length_and_dec() if (arg_count == 3 && args[2]->const_item()) { int32 length= (int32) args[2]->val_int(); - if (length <= 0) + if (args[2]->null_value || length <= 0) max_length=0; /* purecov: inspected */ else set_if_smaller(max_length,(uint) length); @@ -2411,7 +2413,9 @@ void Item_func_repeat::fix_length_and_dec() /* Assumes that the maximum length of a String is < INT_MAX32. */ /* Set here so that rest of code sees out-of-bound value as such. */ - if (count > INT_MAX32) + if (args[1]->null_value) + count= 0; + else if (count > INT_MAX32) count= INT_MAX32; ulonglong max_result_length= (ulonglong) args[0]->max_length * count; @@ -2499,7 +2503,9 @@ void Item_func_rpad::fix_length_and_dec() /* Assumes that the maximum length of a String is < INT_MAX32. */ /* Set here so that rest of code sees out-of-bound value as such. */ - if (temp > INT_MAX32) + if (args[1]->null_value) + temp= 0; + else if (temp > INT_MAX32) temp = INT_MAX32; length= temp * collation.collation->mbmaxlen; @@ -2616,7 +2622,9 @@ void Item_func_lpad::fix_length_and_dec() /* Assumes that the maximum length of a String is < INT_MAX32. */ /* Set here so that rest of code sees out-of-bound value as such. */ - if (temp > INT_MAX32) + if (args[1]->null_value) + temp= 0; + else if (temp > INT_MAX32) temp= INT_MAX32; length= temp * collation.collation->mbmaxlen; -- cgit v1.2.1 From 7f208d3c356e559d3be15f161df8a0adbfa2dd1c Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Fri, 25 Jan 2013 14:29:46 +0100 Subject: MDEV-729 lp:998028 - Server crashes on normal shutdown in closefrm after executing a query from MyISAM table don't write a key value into the record buffer - a key length can be larger then the record length. --- sql/opt_range.cc | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'sql') diff --git a/sql/opt_range.cc b/sql/opt_range.cc index a42a03f4c86..14c2eeddb9f 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -10815,9 +10815,10 @@ int QUICK_GROUP_MIN_MAX_SELECT::next_min() */ if (min_max_arg_part && min_max_arg_part->field->is_null()) { + uchar *tmp_key_buff= (uchar*)my_alloca(index_info->key_length); /* Find the first subsequent record without NULL in the MIN/MAX field. */ - key_copy(tmp_record, record, index_info, 0); - result= file->index_read_map(record, tmp_record, + key_copy(tmp_key_buff, record, index_info, 0); + result= file->index_read_map(record, tmp_key_buff, make_keypart_map(real_key_parts), HA_READ_AFTER_KEY); /* @@ -10833,10 +10834,11 @@ int QUICK_GROUP_MIN_MAX_SELECT::next_min() if (!result) { if (key_cmp(index_info->key_part, group_prefix, real_prefix_len)) - key_restore(record, tmp_record, index_info, 0); + key_restore(record, tmp_key_buff, index_info, 0); } else if (result == HA_ERR_KEY_NOT_FOUND || result == HA_ERR_END_OF_FILE) result= 0; /* There is a result in any case. */ + my_afree(tmp_key_buff); } } -- cgit v1.2.1 From 298008dc4fbf4c5cc98d86115218bf89611ff7ea Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 25 Jan 2013 16:56:57 +0200 Subject: The problem was that expression with field after transformation (on the first execution) reached by fix_fields() (via reference) before row which it belongs to (on the second execution) and fix_field for row did not follow usual protocol for Items with argument (first check that the item fixed then call fix_fields). Item_row::fix_field fixed. --- sql/item_row.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/item_row.cc b/sql/item_row.cc index 72bae6f0900..d9d3e359338 100644 --- a/sql/item_row.cc +++ b/sql/item_row.cc @@ -68,7 +68,8 @@ bool Item_row::fix_fields(THD *thd, Item **ref) Item **arg, **arg_end; for (arg= items, arg_end= items+arg_count; arg != arg_end ; arg++) { - if ((*arg)->fix_fields(thd, arg)) + if (!(*arg)->fixed && + (*arg)->fix_fields(thd, arg)) return TRUE; // we can't assign 'item' before, because fix_fields() can change arg Item *item= *arg; -- cgit v1.2.1 From ea1d5943c5aa4e66fa3f36333043dc6fed0a9d60 Mon Sep 17 00:00:00 2001 From: Michael Widenius Date: Fri, 25 Jan 2013 21:40:42 +0200 Subject: Fixed MDEV-3890: Server crash inserting record on a temporary table after truncating it The problem was that a temporary table was re-created as a non-temporary table. mysql-test/suite/maria/truncate.result: Added test cases mysql-test/suite/maria/truncate.test: Added test cases sql/sql_truncate.cc: Mark that table to be created is a temporary table storage/maria/ha_maria.cc: Ensure that temporary tables are not transactional. --- sql/sql_truncate.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'sql') diff --git a/sql/sql_truncate.cc b/sql/sql_truncate.cc index 979dde30ceb..4b77344c042 100644 --- a/sql/sql_truncate.cc +++ b/sql/sql_truncate.cc @@ -263,6 +263,7 @@ static bool recreate_temporary_table(THD *thd, TABLE *table) DBUG_ENTER("recreate_temporary_table"); memset(&create_info, 0, sizeof(create_info)); + create_info.options|= HA_LEX_CREATE_TMP_TABLE; table->file->info(HA_STATUS_AUTO | HA_STATUS_NO_LOCK); -- cgit v1.2.1 From 0791692bdc311f39181b9df236981a2cb439638e Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Sat, 26 Jan 2013 22:33:18 +0100 Subject: MDEV-3875 Wrong result (missing row) on a DISTINCT query with the same subquery in the SELECT list and GROUP BY fix remove_dup_with_hash_index() and remove_dup_with_compare() to take NULLs into account --- sql/field.cc | 15 +++++++++ sql/field.h | 1 + sql/filesort.cc | 25 +++++--------- sql/sql_select.cc | 97 +++++++++++++++++++++++-------------------------------- 4 files changed, 65 insertions(+), 73 deletions(-) (limited to 'sql') diff --git a/sql/field.cc b/sql/field.cc index 9b0f6a7dfcd..fa098bef72c 100644 --- a/sql/field.cc +++ b/sql/field.cc @@ -1062,6 +1062,21 @@ bool Field::type_can_have_key_part(enum enum_field_types type) } +void Field::make_sort_key(uchar *buff,uint length) +{ + if (maybe_null()) + { + if (is_null()) + { + bzero(buff, length + 1); + return; + } + *buff++= 1; + } + sort_string(buff, length); +} + + /** Numeric fields base class constructor. */ diff --git a/sql/field.h b/sql/field.h index 208f1e381f5..115a9519b7b 100644 --- a/sql/field.h +++ b/sql/field.h @@ -386,6 +386,7 @@ public: return bytes; } + void make_sort_key(uchar *buff, uint length); virtual void make_field(Send_field *); virtual void sort_string(uchar *buff,uint length)=0; virtual bool optimize_range(uint idx, uint part); diff --git a/sql/filesort.cc b/sql/filesort.cc index a4d4ec1b37f..703264b7ef5 100644 --- a/sql/filesort.cc +++ b/sql/filesort.cc @@ -783,21 +783,9 @@ static void make_sortkey(register SORTPARAM *param, bool maybe_null=0; if ((field=sort_field->field)) { // Field - if (field->maybe_null()) - { - if (field->is_null()) - { - if (sort_field->reverse) - bfill(to,sort_field->length+1,(char) 255); - else - bzero((char*) to,sort_field->length+1); - to+= sort_field->length+1; - continue; - } - else - *to++=1; - } - field->sort_string(to, sort_field->length); + field->make_sort_key(to, sort_field->length); + if ((maybe_null = field->maybe_null())) + to++; } else { // Item @@ -949,8 +937,11 @@ static void make_sortkey(register SORTPARAM *param, } if (sort_field->reverse) { /* Revers key */ - if (maybe_null) - to[-1]= ~to[-1]; + if (maybe_null && (to[-1]= !to[-1])) + { + to+= sort_field->length; // don't waste the time reversing all 0's + continue; + } length=sort_field->length; while (length--) { diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 0897aa287db..5aa8c0479cf 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -204,7 +204,7 @@ static int create_sort_index(THD *thd, JOIN *join, ORDER *order, static int remove_duplicates(JOIN *join,TABLE *entry,List &fields, Item *having); static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field, - ulong offset,Item *having); + Item *having); static int remove_dup_with_hash_index(THD *thd,TABLE *table, uint field_count, Field **first_field, ulong key_length,Item *having); @@ -18891,19 +18891,24 @@ static bool fix_having(JOIN *join, Item **having) #endif -/***************************************************************************** - Remove duplicates from tmp table - This should be recoded to add a unique index to the table and remove - duplicates - Table is a locked single thread table - fields is the number of fields to check (from the end) -*****************************************************************************/ +/** + Compare fields from table->record[0] and table->record[1], + possibly skipping few first fields. + + @param table + @param ptr field to start the comparison from, + somewhere in the table->field[] array + @retval 1 different + @retval 0 identical +*/ static bool compare_record(TABLE *table, Field **ptr) { for (; *ptr ; ptr++) { - if ((*ptr)->cmp_offset(table->s->rec_buff_length)) + Field *f= *ptr; + if (f->is_null() != f->is_null(table->s->rec_buff_length) || + (!f->is_null() && f->cmp_offset(table->s->rec_buff_length))) return 1; } return 0; @@ -18931,15 +18936,15 @@ static void free_blobs(Field **ptr) static int -remove_duplicates(JOIN *join, TABLE *entry,List &fields, Item *having) +remove_duplicates(JOIN *join, TABLE *table, List &fields, Item *having) { int error; - ulong reclength,offset; + ulong keylength= 0; uint field_count; THD *thd= join->thd; DBUG_ENTER("remove_duplicates"); - entry->reginfo.lock_type=TL_WRITE; + table->reginfo.lock_type=TL_WRITE; /* Calculate how many saved fields there is in list */ field_count=0; @@ -18956,24 +18961,21 @@ remove_duplicates(JOIN *join, TABLE *entry,List &fields, Item *having) join->unit->select_limit_cnt= 1; // Only send first row DBUG_RETURN(0); } - Field **first_field=entry->field+entry->s->fields - field_count; - offset= (field_count ? - entry->field[entry->s->fields - field_count]-> - offset(entry->record[0]) : 0); - reclength=entry->s->reclength-offset; - - free_io_cache(entry); // Safety - entry->file->info(HA_STATUS_VARIABLE); - if (entry->s->db_type() == heap_hton || - (!entry->s->blob_fields && - ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records < + + Field **first_field=table->field+table->s->fields - field_count; + for (Field **ptr=first_field; *ptr; ptr++) + keylength+= (*ptr)->sort_length() + (*ptr)->maybe_null(); + + free_io_cache(table); // Safety + table->file->info(HA_STATUS_VARIABLE); + if (table->s->db_type() == heap_hton || + (!table->s->blob_fields && + ((ALIGN_SIZE(keylength) + HASH_OVERHEAD) * table->file->stats.records < thd->variables.sortbuff_size))) - error=remove_dup_with_hash_index(join->thd, entry, - field_count, first_field, - reclength, having); + error=remove_dup_with_hash_index(join->thd, table, field_count, first_field, + keylength, having); else - error=remove_dup_with_compare(join->thd, entry, first_field, offset, - having); + error=remove_dup_with_compare(join->thd, table, first_field, having); free_blobs(first_field); DBUG_RETURN(error); @@ -18981,18 +18983,13 @@ remove_duplicates(JOIN *join, TABLE *entry,List &fields, Item *having) static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field, - ulong offset, Item *having) + Item *having) { handler *file=table->file; - char *org_record,*new_record; - uchar *record; + uchar *record=table->record[0]; int error; - ulong reclength= table->s->reclength-offset; DBUG_ENTER("remove_dup_with_compare"); - org_record=(char*) (record=table->record[0])+offset; - new_record=(char*) table->record[1]+offset; - if (file->ha_rnd_init_with_error(1)) DBUG_RETURN(1); @@ -19029,7 +19026,7 @@ static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field, error=0; goto err; } - memcpy(new_record,org_record,reclength); + store_record(table,record[1]); /* Read through rest of file and mark duplicated rows deleted */ bool found=0; @@ -19088,8 +19085,9 @@ static int remove_dup_with_hash_index(THD *thd, TABLE *table, int error; handler *file= table->file; ulong extra_length= ALIGN_SIZE(key_length)-key_length; - uint *field_lengths,*field_length; + uint *field_lengths, *field_length; HASH hash; + Field **ptr; DBUG_ENTER("remove_dup_with_hash_index"); if (!my_multi_malloc(MYF(MY_WME), @@ -19101,21 +19099,8 @@ static int remove_dup_with_hash_index(THD *thd, TABLE *table, NullS)) DBUG_RETURN(1); - { - Field **ptr; - ulong total_length= 0; - for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++) - { - uint length= (*ptr)->sort_length(); - (*field_length++)= length; - total_length+= length; - } - DBUG_PRINT("info",("field_count: %u key_length: %lu total_length: %lu", - field_count, key_length, total_length)); - DBUG_ASSERT(total_length <= key_length); - key_length= total_length; - extra_length= ALIGN_SIZE(key_length)-key_length; - } + for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++) + (*field_length++)= (*ptr)->sort_length(); if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, key_length, (hash_get_key) 0, 0, 0)) @@ -19155,13 +19140,13 @@ static int remove_dup_with_hash_index(THD *thd, TABLE *table, /* copy fields to key buffer */ org_key_pos= key_pos; field_length=field_lengths; - for (Field **ptr= first_field ; *ptr ; ptr++) + for (ptr= first_field ; *ptr ; ptr++) { - (*ptr)->sort_string(key_pos,*field_length); - key_pos+= *field_length++; + (*ptr)->make_sort_key(key_pos, *field_length); + key_pos+= (*ptr)->maybe_null() + *field_length++; } /* Check if it exists before */ - if (hash_search(&hash, org_key_pos, key_length)) + if (my_hash_search(&hash, org_key_pos, key_length)) { /* Duplicated found ; Remove the row */ if ((error= file->ha_delete_row(record))) -- cgit v1.2.1 From 5138bf4238d4a8850ee364a3adf10dc2687af67c Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Mon, 28 Jan 2013 09:10:01 +0100 Subject: compilation error with -Wuninitialized -Werror --- sql/sql_insert.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'sql') diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc index f9179843810..53948f11923 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -2084,7 +2084,7 @@ TABLE *Delayed_insert::get_local_table(THD* client_thd) { my_ptrdiff_t adjust_ptrs; Field **field,**org_field, *found_next_number_field; - Field **vfield; + Field **UNINIT_VAR(vfield); TABLE *copy; TABLE_SHARE *share; uchar *bitmap; -- cgit v1.2.1 From f65e5841d7c6ff0e7470d01fab27fd6b42c64c9f Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 28 Jan 2013 15:13:39 +0200 Subject: Fix for MDEV-3948, and backport of the following collection of fixes and backports from MariaDB 10.0. The bug in mdev-3948 was an instance of the problem fixed by Sergey's patch in 10.0 - namely that the range optimizer could change table->[read | write]_set, and not restore it. revno: 3471 committer: Sergey Petrunya branch nick: 10.0-serg-fix-imerge timestamp: Sat 2012-11-03 12:24:36 +0400 message: # MDEV-3817: Wrong result with index_merge+index_merge_intersection, InnoDB table, join, AND and OR conditions Reconcile the fixes from: # # guilhem.bichot@oracle.com-20110805143029-ywrzuz15uzgontr0 # Fix for BUG#12698916 - "JOIN QUERY GIVES WRONG RESULT AT 2ND EXEC. OR # AFTER FLUSH TABLES [-INT VS NULL]" # # guilhem.bichot@oracle.com-20111209150650-tzx3ldzxe1yfwji6 # Fix for BUG#12912171 - ASSERTION FAILED: QUICK->HEAD->READ_SET == SAVE_READ_SET # and # and related fixes from: BUG#1006164, MDEV-376: Now, ROR-merged QUICK_RANGE_SELECT objects make no assumptions about the values of table->read_set and table->write_set. Each QUICK_ROR_SELECT has (and had before) its own column bitmap, but now, all QUICK_ROR_SELECT's functions that care: reset(), init_ror_merged_scan(), and get_next() will set table->read_set when invoked and restore it back to what it was before the call before they return. This allows to avoid the mess when somebody else modifies table->read_set for some reason. --- sql/opt_range.cc | 44 +++++++++++++++++++++++++++++++++----------- sql/opt_range.h | 2 +- sql/sql_update.cc | 14 ++++++++++---- 3 files changed, 44 insertions(+), 16 deletions(-) (limited to 'sql') diff --git a/sql/opt_range.cc b/sql/opt_range.cc index 8f094c47f67..cb25ca7760e 100644 --- a/sql/opt_range.cc +++ b/sql/opt_range.cc @@ -1789,8 +1789,6 @@ QUICK_RANGE_SELECT::QUICK_RANGE_SELECT(THD *thd, TABLE *table, uint key_nr, bzero((char*) &alloc,sizeof(alloc)); file= head->file; record= head->record[0]; - save_read_set= head->read_set; - save_write_set= head->write_set; /* Allocate a bitmap for used columns (Q: why not on MEM_ROOT?) */ if (!(bitmap= (my_bitmap_map*) my_malloc(head->s->column_bitmap_size, @@ -1860,7 +1858,6 @@ QUICK_RANGE_SELECT::~QUICK_RANGE_SELECT() free_root(&alloc,MYF(0)); my_free(column_bitmap.bitmap); } - head->column_bitmaps_set(save_read_set, save_write_set); my_free(mrr_buf_desc); DBUG_VOID_RETURN; } @@ -2004,6 +2001,8 @@ int QUICK_RANGE_SELECT::init_ror_merged_scan(bool reuse_handler) handler *save_file= file, *org_file; my_bool org_key_read; THD *thd= head->in_use; + MY_BITMAP * const save_read_set= head->read_set; + MY_BITMAP * const save_write_set= head->write_set; DBUG_ENTER("QUICK_RANGE_SELECT::init_ror_merged_scan"); in_ror_merged_scan= 1; @@ -2054,6 +2053,7 @@ int QUICK_RANGE_SELECT::init_ror_merged_scan(bool reuse_handler) last_rowid= file->ref; end: + DBUG_ASSERT(head->read_set == &column_bitmap); /* We are only going to read key fields and call position() on 'file' The following sets head->tmp_set to only use this key and then updates @@ -2067,7 +2067,8 @@ end: if (!head->no_keyread) { doing_key_read= 1; - head->mark_columns_used_by_index(index); + head->mark_columns_used_by_index_no_reset(index, head->read_set); + head->enable_keyread(); } head->prepare_for_position(); @@ -2089,8 +2090,9 @@ end: head->file= org_file; head->key_read= org_key_read; - bitmap_copy(&column_bitmap, head->read_set); - head->column_bitmaps_set(&column_bitmap, &column_bitmap); + + /* Restore head->read_set (and write_set) to what they had before the call */ + head->column_bitmaps_set(save_read_set, save_write_set); if (reset()) { @@ -2148,9 +2150,19 @@ int QUICK_ROR_INTERSECT_SELECT::init_ror_merged_scan(bool reuse_handler) while ((cur= quick_it++)) { quick= cur->quick; +#ifndef DBUG_OFF + const MY_BITMAP * const save_read_set= quick->head->read_set; + const MY_BITMAP * const save_write_set= quick->head->write_set; +#endif if (quick->init_ror_merged_scan(FALSE)) DBUG_RETURN(1); quick->file->extra(HA_EXTRA_KEYREAD_PRESERVE_FIELDS); + + // Sets are shared by all members of "quick_selects" so must not change +#ifndef DBUG_OFF + DBUG_ASSERT(quick->head->read_set == save_read_set); + DBUG_ASSERT(quick->head->write_set == save_write_set); +#endif /* All merged scans share the same record buffer in intersection. */ quick->record= head->record[0]; } @@ -10978,9 +10990,15 @@ int QUICK_RANGE_SELECT::reset() uchar *mrange_buff; int error; HANDLER_BUFFER empty_buf; + MY_BITMAP * const save_read_set= head->read_set; + MY_BITMAP * const save_write_set= head->write_set; DBUG_ENTER("QUICK_RANGE_SELECT::reset"); last_range= NULL; cur_range= (QUICK_RANGE**) ranges.buffer; + RANGE_SEQ_IF seq_funcs= {NULL, quick_range_seq_init, quick_range_seq_next, 0, 0}; + + if (in_ror_merged_scan) + head->column_bitmaps_set_no_signal(&column_bitmap, &column_bitmap); if (file->inited == handler::RND) { @@ -10991,15 +11009,12 @@ int QUICK_RANGE_SELECT::reset() if (file->inited == handler::NONE) { - if (in_ror_merged_scan) - head->column_bitmaps_set_no_signal(&column_bitmap, &column_bitmap); - DBUG_EXECUTE_IF("bug14365043_2", DBUG_SET("+d,ha_index_init_fail");); if ((error= file->ha_index_init(index,1))) { file->print_error(error, MYF(0)); - DBUG_RETURN(error); + goto err; } } @@ -11035,10 +11050,14 @@ int QUICK_RANGE_SELECT::reset() if (!mrr_buf_desc) empty_buf.buffer= empty_buf.buffer_end= empty_buf.end_of_used_area= NULL; - RANGE_SEQ_IF seq_funcs= {NULL, quick_range_seq_init, quick_range_seq_next, 0, 0}; error= file->multi_range_read_init(&seq_funcs, (void*)this, ranges.elements, mrr_flags, mrr_buf_desc? mrr_buf_desc: &empty_buf); +err: + /* Restore bitmaps set on entry */ + if (in_ror_merged_scan) + head->column_bitmaps_set_no_signal(save_read_set, save_write_set); + DBUG_RETURN(error); } @@ -11061,6 +11080,9 @@ int QUICK_RANGE_SELECT::reset() int QUICK_RANGE_SELECT::get_next() { range_id_t dummy; + MY_BITMAP * const save_read_set= head->read_set; + MY_BITMAP * const save_write_set= head->write_set; + DBUG_ENTER("QUICK_RANGE_SELECT::get_next"); if (in_ror_merged_scan) { diff --git a/sql/opt_range.h b/sql/opt_range.h index efb45f96345..c59b2a7eb02 100644 --- a/sql/opt_range.h +++ b/sql/opt_range.h @@ -430,7 +430,7 @@ protected: /* Members to deal with case when this quick select is a ROR-merged scan */ bool in_ror_merged_scan; - MY_BITMAP column_bitmap, *save_read_set, *save_write_set; + MY_BITMAP column_bitmap; bool free_file; /* TRUE <=> this->file is "owned" by this quick select */ /* Range pointers to be used when not using MRR interface */ diff --git a/sql/sql_update.cc b/sql/sql_update.cc index 5836f7bf5dc..f59dfb3bc93 100644 --- a/sql/sql_update.cc +++ b/sql/sql_update.cc @@ -480,12 +480,15 @@ int mysql_update(THD *thd, We can't update table directly; We must first search after all matching rows before updating the table! */ + + // Verify that table->restore_column_maps_after_mark_index() will work + DBUG_ASSERT(table->read_set == &table->def_read_set); + DBUG_ASSERT(table->write_set == &table->def_write_set); + if (used_index < MAX_KEY && old_covering_keys.is_set(used_index)) table->add_read_columns_used_by_index(used_index); else - { table->use_all_columns(); - } /* note: We avoid sorting if we sort on the used index */ if (order && (need_sort || used_key_is_modified)) @@ -619,8 +622,11 @@ int mysql_update(THD *thd, if (error >= 0) goto err; } - if (table->key_read) - table->restore_column_maps_after_mark_index(); + /* + This restore bitmaps, works for add_read_columns_used_by_index() and + use_all_columns(): + */ + table->restore_column_maps_after_mark_index(); } if (ignore) -- cgit v1.2.1 From ea5632e9d767f1c4d07cb2dae74ec79bec843b7d Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 30 Jan 2013 15:11:36 +0100 Subject: MDEV-3984: Double free of Master_info * when CHANGE MASTER fails. When CHANGE MASTER fails, it may or may not have already added the Master_info * to the index. Implement logic that properly handles removal and freeing in both cases. --- sql/sql_parse.cc | 15 ++++++++++----- sql/sql_repl.cc | 8 +++++++- sql/sql_repl.h | 2 +- 3 files changed, 18 insertions(+), 7 deletions(-) (limited to 'sql') diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index b125047cb98..0abb249d97b 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -2393,6 +2393,7 @@ case SQLCOM_PREPARE: LEX_MASTER_INFO *lex_mi= &thd->lex->mi; Master_info *mi; bool new_master= 0; + bool master_info_added; if (check_global_access(thd, SUPER_ACL)) goto error; @@ -2415,15 +2416,19 @@ case SQLCOM_PREPARE: new_master= 1; } - res= change_master(thd, mi); + res= change_master(thd, mi, &master_info_added); if (res && new_master) { /* - The new master was added by change_master(). Remove it as it didn't - work. + If the new master was added by change_master(), remove it as it didn't + work (this will free mi as well). + + If new master was not added, we still need to free mi. */ - master_info_index->remove_master_info(&lex_mi->connection_name); - delete mi; + if (master_info_added) + master_info_index->remove_master_info(&lex_mi->connection_name); + else + delete mi; } mysql_mutex_unlock(&LOCK_active_mi); diff --git a/sql/sql_repl.cc b/sql/sql_repl.cc index 5b2e498cb00..6b8d0f5153f 100644 --- a/sql/sql_repl.cc +++ b/sql/sql_repl.cc @@ -1677,10 +1677,14 @@ static bool get_string_parameter(char *to, const char *from, size_t length, @param mi Pointer to Master_info object belonging to the slave's IO thread. + @param master_info_added Out parameter saying if the Master_info *mi was + added to the global list of masters. This is useful in error conditions + to know if caller should free Master_info *mi. + @retval FALSE success @retval TRUE error */ -bool change_master(THD* thd, Master_info* mi) +bool change_master(THD* thd, Master_info* mi, bool *master_info_added) { int thread_mask; const char* errmsg= 0; @@ -1695,6 +1699,7 @@ bool change_master(THD* thd, Master_info* mi) LEX_MASTER_INFO* lex_mi= &thd->lex->mi; DBUG_ENTER("change_master"); + *master_info_added= false; /* We need to check if there is an empty master_host. Otherwise change master succeeds, a master.info file is created containing @@ -1743,6 +1748,7 @@ bool change_master(THD* thd, Master_info* mi) ret= TRUE; goto err; } + *master_info_added= true; } if (global_system_variables.log_warnings > 1) sql_print_information("Master: '%.*s' Master_info_file: '%s' " diff --git a/sql/sql_repl.h b/sql/sql_repl.h index c5a0b31388e..9ca7e6b00b1 100644 --- a/sql/sql_repl.h +++ b/sql/sql_repl.h @@ -41,7 +41,7 @@ extern my_bool opt_sporadic_binlog_dump_fail; int start_slave(THD* thd, Master_info* mi, bool net_report); int stop_slave(THD* thd, Master_info* mi, bool net_report); -bool change_master(THD* thd, Master_info* mi); +bool change_master(THD* thd, Master_info* mi, bool *master_info_added); bool mysql_show_binlog_events(THD* thd); int reset_slave(THD *thd, Master_info* mi); int reset_master(THD* thd); -- cgit v1.2.1 From 5267af5e9e5e601d4f4b1ef40730da1e36d38d9d Mon Sep 17 00:00:00 2001 From: Sergei Golubchik Date: Wed, 30 Jan 2013 22:33:25 +0100 Subject: don't disable the cassandra engine by default --- sql/sql_plugin.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'sql') diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc index 38d8dcf7994..1c47991f474 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -175,8 +175,7 @@ static struct /* we disable few other plugins by default */ { "ndbcluster", PLUGIN_OFF }, { "feedback", PLUGIN_OFF }, - { "pbxt", PLUGIN_OFF }, - { "cassandra", PLUGIN_OFF } + { "pbxt", PLUGIN_OFF } }; /* support for Services */ -- cgit v1.2.1