23
23
@defgroup Query_Optimizer Query Optimizer
26
#include <drizzled/server_includes.h>
27
#include <drizzled/sql_select.h>
28
#include "sj_tmp_table.h"
30
#include <mysys/my_bit.h>
31
#include <drizzled/drizzled_error_messages.h>
32
#include <libdrizzle/gettext.h>
26
#include "drizzled/server_includes.h"
27
#include "drizzled/sql_select.h"
28
#include "drizzled/sj_tmp_table.h"
29
#include "drizzled/table_map_iterator.h"
31
#include "mysys/my_bit.h"
32
#include "drizzled/error.h"
33
#include "drizzled/gettext.h"
34
#include "drizzled/util/test.h"
35
#include "drizzled/name_resolution_context_state.h"
36
#include "drizzled/nested_join.h"
37
#include "drizzled/probes.h"
38
#include "drizzled/show.h"
39
#include "drizzled/item/cache.h"
40
#include "drizzled/item/cmpfunc.h"
41
#include "drizzled/item/copy_string.h"
42
#include "drizzled/item/uint.h"
43
#include "drizzled/cached_item.h"
44
#include "drizzled/sql_base.h"
45
#include "drizzled/field/blob.h"
46
#include "drizzled/check_stack_overrun.h"
47
#include "drizzled/lock.h"
48
#include "drizzled/item/outer_ref.h"
49
#include "drizzled/index_hint.h"
34
56
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
35
57
"MAYBE_REF","ALL","range","index",
42
64
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
43
65
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
44
66
DYNAMIC_ARRAY *keyuse);
45
static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
67
static bool update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,
46
68
JOIN_TAB *join_tab,
47
69
uint32_t tables, COND *conds,
48
70
COND_EQUAL *cond_equal,
49
table_map table_map, SELECT_LEX *select_lex,
71
table_map table_map, Select_Lex *select_lex,
50
72
st_sargable_param **sargables);
51
73
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
52
74
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
88
110
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
89
111
static void update_depend_map(JOIN *join);
90
112
static void update_depend_map(JOIN *join, order_st *order);
91
static order_st *remove_const(JOIN *join,order_st *first_order,COND *cond,
92
bool change_list, bool *simple_order);
113
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond,
114
bool change_list, bool *simple_order);
93
115
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
94
116
List<Item> &fields, bool send_row,
95
117
uint64_t select_options, const char *info,
97
static COND *build_equal_items(THD *thd, COND *cond,
119
static COND *build_equal_items(Session *session, COND *cond,
98
120
COND_EQUAL *inherited,
99
121
List<TableList> *join_list,
100
122
COND_EQUAL **cond_equal_ref);
167
189
bool (*find_func) (Field *, void *), void *data);
168
190
static bool find_field_in_item_list (Field *field, void *data);
169
191
static bool find_field_in_order_list (Field *field, void *data);
170
static int create_sort_index(THD *thd, JOIN *join, order_st *order,
192
static int create_sort_index(Session *session, JOIN *join, order_st *order,
171
193
ha_rows filesort_limit, ha_rows select_limit,
172
194
bool is_order_by);
173
195
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
175
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
176
ulong offset,Item *having);
177
static int remove_dup_with_hash_index(THD *thd,Table *table,
197
static int remove_dup_with_compare(Session *session, Table *entry, Field **field,
198
uint32_t offset, Item *having);
199
static int remove_dup_with_hash_index(Session *session,Table *table,
178
200
uint32_t field_count, Field **first_field,
180
ulong key_length,Item *having);
181
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count);
182
static ulong used_blob_length(CACHE_FIELD **ptr);
201
uint32_t key_length, Item *having);
202
static int join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count);
203
static uint32_t used_blob_length(CACHE_FIELD **ptr);
183
204
static bool store_record_in_cache(JOIN_CACHE *cache);
184
205
static void reset_cache_read(JOIN_CACHE *cache);
185
206
static void reset_cache_write(JOIN_CACHE *cache);
186
207
static void read_cached_record(JOIN_TAB *tab);
187
208
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
188
static order_st *create_distinct_group(THD *thd, Item **ref_pointer_array,
209
static order_st *create_distinct_group(Session *session, Item **ref_pointer_array,
189
210
order_st *order, List<Item> &fields,
190
211
List<Item> &all_fields,
191
212
bool *all_order_by_fields_used);
195
216
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
196
217
static bool alloc_group_fields(JOIN *join,order_st *group);
197
218
// Create list for using with tempory table
198
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
219
static bool change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
199
220
List<Item> &new_list1,
200
221
List<Item> &new_list2,
201
222
uint32_t elements, List<Item> &items);
202
223
// Create list for using with tempory table
203
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
224
static bool change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
204
225
List<Item> &new_list1,
205
226
List<Item> &new_list2,
206
227
uint32_t elements, List<Item> &items);
207
228
static void init_tmptable_sum_functions(Item_sum **func);
208
229
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
209
230
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
210
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
211
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
231
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab);
232
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr);
212
233
static bool init_sum_functions(Item_sum **func, Item_sum **end);
213
234
static bool update_sum_func(Item_sum **func);
214
235
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
236
263
This handles SELECT with and without UNION.
239
bool handle_select(THD *thd, LEX *lex, select_result *result,
240
ulong setup_tables_done_option)
266
bool handle_select(Session *session, LEX *lex, select_result *result,
267
uint64_t setup_tables_done_option)
243
register SELECT_LEX *select_lex = &lex->select_lex;
270
register Select_Lex *select_lex = &lex->select_lex;
244
271
DRIZZLE_SELECT_START();
246
if (select_lex->master_unit()->is_union() ||
273
if (select_lex->master_unit()->is_union() ||
247
274
select_lex->master_unit()->fake_select_lex)
248
res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option);
275
res= mysql_union(session, lex, result, &lex->unit, setup_tables_done_option);
251
SELECT_LEX_UNIT *unit= &lex->unit;
278
Select_Lex_Unit *unit= &lex->unit;
252
279
unit->set_limit(unit->global_parameters);
280
session->session_marker= 0;
255
282
'options' of mysql_select will be set in JOIN, as far as JOIN for
256
every PS/SP execution new, we will not need reset this flag if
283
every PS/SP execution new, we will not need reset this flag if
257
284
setup_tables_done_option changed for next rexecution
259
res= mysql_select(thd, &select_lex->ref_pointer_array,
286
res= mysql_select(session, &select_lex->ref_pointer_array,
260
287
(TableList*) select_lex->table_list.first,
261
288
select_lex->with_wild, select_lex->item_list,
262
289
select_lex->where,
382
408
ref->outer_ref= new_ref;
383
409
ref->ref= &ref->outer_ref;
385
if (!ref->fixed && ref->fix_fields(thd, 0))
411
if (!ref->fixed && ref->fix_fields(session, 0))
387
thd->used_tables|= item->used_tables();
413
session->used_tables|= item->used_tables();
392
#define MAGIC_IN_WHERE_TOP_LEVEL 10
394
419
Function to setup clauses without sum functions.
396
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
400
List<Item> &all_fields,
403
order_st *group, bool *hidden_group_fields)
421
inline int setup_without_group(Session *session, Item **ref_pointer_array,
425
List<Item> &all_fields,
428
order_st *group, bool *hidden_group_fields)
406
nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
408
thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
409
res= setup_conds(thd, tables, leaves, conds);
411
thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
412
res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
431
nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
433
session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
434
res= setup_conds(session, tables, leaves, conds);
436
session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
437
res= res || setup_order(session, ref_pointer_array, tables, fields, all_fields,
414
thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
415
res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
439
session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
440
res= res || setup_group(session, ref_pointer_array, tables, fields, all_fields,
416
441
group, hidden_group_fields);
417
thd->lex->allow_sum_func= save_allow_sum_func;
442
session->lex->allow_sum_func= save_allow_sum_func;
452
477
order= order_init;
453
478
group_list= group_init;
454
479
having= having_init;
455
proc_param= proc_param_init;
456
480
tables_list= tables_init;
457
481
select_lex= select_lex_arg;
458
482
select_lex->join= this;
459
483
join_list= &select_lex->top_join_list;
460
484
union_part= unit_arg->is_union();
462
thd->lex->current_select->is_item_list_lookup= 1;
486
session->lex->current_select->is_item_list_lookup= 1;
464
488
If we have already executed SELECT, then it have not sense to prevent
465
489
its table from update (see unique_table())
467
if (thd->derived_tables_processing)
491
if (session->derived_tables_processing)
468
492
select_lex->exclude_from_table_unique_test= true;
470
494
/* Check that all tables, fields, conds and order are ok */
472
496
if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
473
setup_tables_and_check_access(thd, &select_lex->context, join_list,
497
setup_tables_and_check_access(session, &select_lex->context, join_list,
474
498
tables_list, &select_lex->leaf_tables,
478
502
TableList *table_ptr;
479
503
for (table_ptr= select_lex->leaf_tables;
481
505
table_ptr= table_ptr->next_leaf)
484
if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
485
select_lex->setup_ref_array(thd, og_num) ||
486
setup_fields(thd, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
508
if (setup_wild(session, tables_list, fields_list, &all_fields, wild_num) ||
509
select_lex->setup_ref_array(session, og_num) ||
510
setup_fields(session, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
487
511
&all_fields, 1) ||
488
setup_without_group(thd, (*rref_pointer_array), tables_list,
512
setup_without_group(session, (*rref_pointer_array), tables_list,
489
513
select_lex->leaf_tables, fields_list,
490
514
all_fields, &conds, order, group_list,
491
515
&hidden_group_fields))
492
516
return(-1); /* purecov: inspected */
494
518
ref_pointer_array= *rref_pointer_array;
498
nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
499
thd->where="having clause";
500
thd->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
522
nesting_map save_allow_sum_func= session->lex->allow_sum_func;
523
session->where="having clause";
524
session->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
501
525
select_lex->having_fix_field= 1;
502
526
bool having_fix_rc= (!having->fixed &&
503
(having->fix_fields(thd, &having) ||
527
(having->fix_fields(session, &having) ||
504
528
having->check_cols(1)));
505
529
select_lex->having_fix_field= 0;
506
if (having_fix_rc || thd->is_error())
530
if (having_fix_rc || session->is_error())
507
531
return(-1); /* purecov: inspected */
508
thd->lex->allow_sum_func= save_allow_sum_func;
532
session->lex->allow_sum_func= save_allow_sum_func;
533
557
5. Subquery predicate is at the AND-top-level of ON/WHERE clause
534
558
6. No execution method was already chosen (by a prepared statement).
536
(*). We are not in a subquery of a single table UPDATE/DELETE that
560
(*). We are not in a subquery of a single table UPDATE/DELETE that
537
561
doesn't have a JOIN (TODO: We should handle this at some
538
562
point by switching to multi-table UPDATE/DELETE)
540
564
(**). We're not in a confluent table-less subquery, like
543
567
if (in_subs && // 1
544
568
!select_lex->master_unit()->first_select()->next_select() && // 2
545
569
!select_lex->group_list.elements && !order && // 3
546
570
!having && !select_lex->with_sum_func && // 4
547
thd->thd_marker && // 5
571
session->session_marker && // 5
548
572
select_lex->outer_select()->join && // (*)
549
select_lex->master_unit()->first_select()->leaf_tables && // (**)
573
select_lex->master_unit()->first_select()->leaf_tables && // (**)
551
575
in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED) // 6
554
578
if (!in_subs->left_expr->fixed &&
555
in_subs->left_expr->fix_fields(thd, &in_subs->left_expr))
579
in_subs->left_expr->fix_fields(session, &in_subs->left_expr))
636
660
Item *item= *ord->item;
637
661
if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
638
item->split_sum_func(thd, ref_pointer_array, all_fields);
662
item->split_sum_func(session, ref_pointer_array, all_fields);
642
666
if (having && having->with_sum_func)
643
having->split_sum_func2(thd, ref_pointer_array, all_fields,
667
having->split_sum_func(session, ref_pointer_array, all_fields,
645
669
if (select_lex->inner_sum_func_list)
647
671
Item_sum *end=select_lex->inner_sum_func_list;
648
Item_sum *item_sum= end;
672
Item_sum *item_sum= end;
651
675
item_sum= item_sum->next;
652
item_sum->split_sum_func2(thd, ref_pointer_array,
653
all_fields, item_sum->ref_by, false);
676
item_sum->split_sum_func(session, ref_pointer_array,
677
all_fields, item_sum->ref_by, false);
654
678
} while (item_sum != end);
657
681
if (select_lex->inner_refs_list.elements &&
658
fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array))
682
fix_inner_refs(session, all_fields, select_lex, ref_pointer_array))
662
Check if there are references to un-aggregated columns when computing
686
Check if there are references to un-aggregated columns when computing
663
687
aggregate functions with implicit grouping (there is no GROUP BY).
665
689
MODE_ONLY_FULL_GROUP_BY is enabled here by default
1363
1387
!(select_options & SELECT_DESCRIBE) &&
1365
1389
!(conds->used_tables() & RAND_TABLE_BIT) ||
1366
select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
1390
select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
1368
1392
zero_result_cause= "no matching row in const table";
1372
if (!(thd->options & OPTION_BIG_SELECTS) &&
1373
best_read > (double) thd->variables.max_join_size &&
1396
if (!(session->options & OPTION_BIG_SELECTS) &&
1397
best_read > (double) session->variables.max_join_size &&
1374
1398
!(select_options & SELECT_DESCRIBE))
1375
1399
{ /* purecov: inspected */
1376
1400
my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
1380
if (const_tables && !thd->locked_tables &&
1404
if (const_tables && !session->locked_tables &&
1381
1405
!(select_options & SELECT_NO_UNLOCK))
1382
mysql_unlock_some_tables(thd, table, const_tables);
1406
mysql_unlock_some_tables(session, table, const_tables);
1383
1407
if (!conds && outer_join)
1385
1409
/* Handle the case where we have an OUTER JOIN without a WHERE */
1538
1562
JOIN_TAB *tab= &join_tab[const_tables];
1539
1563
bool all_order_fields_used;
1541
skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
1565
skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
1542
1566
&tab->table->keys_in_use_for_order_by);
1543
if ((group_list=create_distinct_group(thd, select_lex->ref_pointer_array,
1567
if ((group_list=create_distinct_group(session, select_lex->ref_pointer_array,
1544
1568
order, fields_list, all_fields,
1545
1569
&all_order_fields_used)))
1547
1571
bool skip_group= (skip_sort_order &&
1548
test_if_skip_sort_order(tab, group_list, select_limit, 1,
1572
test_if_skip_sort_order(tab, group_list, select_limit, 1,
1549
1573
&tab->table->keys_in_use_for_group_by) != 0);
1550
1574
count_field_types(select_lex, &tmp_table_param, all_fields, 0);
1551
1575
if ((skip_group && all_order_fields_used) ||
1827
1851
- We are using DISTINCT without resolving the distinct as a GROUP BY
1828
1852
on all columns.
1830
1854
If having is not handled here, it will be checked before the row
1831
1855
is sent to the client.
1834
1858
(sort_and_group || (exec_tmp_table1->distinct && !group_list)))
1835
1859
having= tmp_having;
1837
1861
/* if group or order on first table, sort first */
1838
1862
if (group_list && simple_group)
1840
thd_proc_info(thd, "Sorting for group");
1841
if (create_sort_index(thd, this, group_list,
1864
session->set_proc_info("Sorting for group");
1865
if (create_sort_index(session, this, group_list,
1842
1866
HA_POS_ERROR, HA_POS_ERROR, false) ||
1843
1867
alloc_group_fields(this, group_list) ||
1844
1868
make_sum_func_list(all_fields, fields_list, 1) ||
1845
setup_sum_funcs(thd, sum_funcs))
1869
setup_sum_funcs(session, sum_funcs))
2006
2030
the query. It's never shown in EXPLAIN!
2009
When can we have here thd->net.report_error not zero?
2033
When can we have here session->net.report_error not zero?
2014
2037
List<Item> *columns_list= &fields_list;
2017
thd_proc_info(thd, "executing");
2040
session->set_proc_info("executing");
2019
(void) result->prepare2(); // Currently, this cannot fail.
2021
2043
if (!tables_list && (tables || !select_lex->with_sum_func))
2022
{ // Only test of functions
2045
/* Only test of functions */
2023
2046
if (select_options & SELECT_DESCRIBE)
2024
select_describe(this, false, false, false,
2025
(zero_result_cause?zero_result_cause:"No tables used"));
2047
select_describe(this, false, false, false, (zero_result_cause?zero_result_cause:"No tables used"));
2028
result->send_fields(*columns_list,
2029
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2050
result->send_fields(*columns_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2031
2052
We have to test for 'conds' here as the WHERE may not be constant
2032
2053
even if we don't have any tables for prepared statements or if
2089
2108
if (!order && !no_order && (!skip_sort_order || !need_tmp))
2092
Reset 'order' to 'group_list' and reinit variables describing
2110
/* Reset 'order' to 'group_list' and reinit variables describing 'order' */
2095
2111
order= group_list;
2096
2112
simple_order= simple_group;
2097
2113
skip_sort_order= 0;
2100
(order != group_list || !(select_options & SELECT_BIG_RESULT)) &&
2101
(const_tables == tables ||
2102
((simple_order || skip_sort_order) &&
2103
test_if_skip_sort_order(&join_tab[const_tables], order,
2105
&join_tab[const_tables].table->
2106
keys_in_use_for_query))))
2115
if (order && (order != group_list || !(select_options & SELECT_BIG_RESULT)))
2117
if (const_tables == tables
2118
|| ((simple_order || skip_sort_order)
2119
&& test_if_skip_sort_order(&join_tab[const_tables], order, select_limit, 0, &join_tab[const_tables].table->keys_in_use_for_query)))
2108
2122
having= tmp_having;
2109
select_describe(this, need_tmp,
2110
order != 0 && !skip_sort_order,
2112
!tables ? "No tables used" : NULL);
2123
select_describe(this, need_tmp, order != 0 && !skip_sort_order, select_distinct, !tables ? "No tables used" : NULL);
2161
2171
items1= items0 + all_fields.elements;
2162
2172
if (sort_and_group || curr_tmp_table->group)
2164
if (change_to_use_tmp_fields(thd, items1,
2165
tmp_fields_list1, tmp_all_fields1,
2166
fields_list.elements, all_fields))
2174
if (change_to_use_tmp_fields(session, items1,
2175
tmp_fields_list1, tmp_all_fields1,
2176
fields_list.elements, all_fields))
2171
if (change_refs_to_tmp_fields(thd, items1,
2172
tmp_fields_list1, tmp_all_fields1,
2173
fields_list.elements, all_fields))
2181
if (change_refs_to_tmp_fields(session, items1,
2182
tmp_fields_list1, tmp_all_fields1,
2183
fields_list.elements, all_fields))
2176
2186
curr_join->tmp_all_fields1= tmp_all_fields1;
2177
2187
curr_join->tmp_fields_list1= tmp_fields_list1;
2180
2190
curr_all_fields= &tmp_all_fields1;
2181
2191
curr_fields_list= &tmp_fields_list1;
2182
2192
curr_join->set_items_ref_array(items1);
2184
2194
if (sort_and_group || curr_tmp_table->group)
2186
curr_join->tmp_table_param.field_count+=
2187
curr_join->tmp_table_param.sum_func_count+
2188
curr_join->tmp_table_param.func_count;
2189
curr_join->tmp_table_param.sum_func_count=
2190
curr_join->tmp_table_param.func_count= 0;
2196
curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count
2197
+ curr_join->tmp_table_param.func_count;
2198
curr_join->tmp_table_param.sum_func_count= 0;
2199
curr_join->tmp_table_param.func_count= 0;
2194
curr_join->tmp_table_param.field_count+=
2195
curr_join->tmp_table_param.func_count;
2203
curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.func_count;
2196
2204
curr_join->tmp_table_param.func_count= 0;
2199
2207
if (curr_tmp_table->group)
2200
2208
{ // Already grouped
2201
2209
if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
2202
curr_join->order= curr_join->group_list; /* order by group */
2210
curr_join->order= curr_join->group_list; /* order by group */
2203
2211
curr_join->group_list= 0;
2207
2215
If we have different sort & group then we must sort the data by group
2208
2216
and copy it to another tmp table
2211
2219
like SEC_TO_TIME(SUM(...)).
2214
if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
2222
if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct))
2223
|| (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
2215
2224
{ /* Must copy to another table */
2216
2225
/* Free first data from old join */
2217
2226
curr_join->join_free();
2218
2227
if (make_simple_join(curr_join, curr_tmp_table))
2220
2229
calc_group_buffer(curr_join, group_list);
2221
2230
count_field_types(select_lex, &curr_join->tmp_table_param,
2222
2231
curr_join->tmp_all_fields1,
2223
2232
curr_join->select_distinct && !curr_join->group_list);
2224
curr_join->tmp_table_param.hidden_field_count=
2225
(curr_join->tmp_all_fields1.elements-
2226
curr_join->tmp_fields_list1.elements);
2233
curr_join->tmp_table_param.hidden_field_count= curr_join->tmp_all_fields1.elements
2234
- curr_join->tmp_fields_list1.elements;
2229
2236
if (exec_tmp_table2)
2230
curr_tmp_table= exec_tmp_table2;
2237
curr_tmp_table= exec_tmp_table2;
2233
/* group data to new table */
2240
/* group data to new table */
2236
2243
If the access method is loose index scan then all MIN/MAX
2240
2247
if (curr_join->join_tab->is_using_loose_index_scan())
2241
2248
curr_join->tmp_table_param.precomputed_group_by= true;
2243
if (!(curr_tmp_table=
2244
exec_tmp_table2= create_tmp_table(thd,
2245
&curr_join->tmp_table_param,
2248
curr_join->select_distinct &&
2249
!curr_join->group_list,
2250
1, curr_join->select_options,
2254
curr_join->exec_tmp_table2= exec_tmp_table2;
2250
if (!(curr_tmp_table=
2251
exec_tmp_table2= create_tmp_table(session,
2252
&curr_join->tmp_table_param,
2255
curr_join->select_distinct &&
2256
!curr_join->group_list,
2257
1, curr_join->select_options,
2261
curr_join->exec_tmp_table2= exec_tmp_table2;
2256
2263
if (curr_join->group_list)
2258
thd_proc_info(thd, "Creating sort index");
2259
if (curr_join->join_tab == join_tab && save_join_tab())
2263
if (create_sort_index(thd, curr_join, curr_join->group_list,
2264
HA_POS_ERROR, HA_POS_ERROR, false) ||
2265
make_group_fields(this, curr_join))
2265
session->set_proc_info("Creating sort index");
2266
if (curr_join->join_tab == join_tab && save_join_tab())
2270
if (create_sort_index(session, curr_join, curr_join->group_list,
2271
HA_POS_ERROR, HA_POS_ERROR, false) ||
2272
make_group_fields(this, curr_join))
2269
2276
sortorder= curr_join->sortorder;
2272
thd_proc_info(thd, "Copying to group table");
2279
session->set_proc_info("Copying to group table");
2274
2281
if (curr_join != this)
2278
curr_join->sum_funcs= sum_funcs2;
2279
curr_join->sum_funcs_end= sum_funcs_end2;
2283
curr_join->alloc_func_list();
2284
sum_funcs2= curr_join->sum_funcs;
2285
sum_funcs_end2= curr_join->sum_funcs_end;
2285
curr_join->sum_funcs= sum_funcs2;
2286
curr_join->sum_funcs_end= sum_funcs_end2;
2290
curr_join->alloc_func_list();
2291
sum_funcs2= curr_join->sum_funcs;
2292
sum_funcs_end2= curr_join->sum_funcs_end;
2288
if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2295
if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, 1, true))
2291
2297
curr_join->group_list= 0;
2292
if (!curr_join->sort_and_group &&
2293
curr_join->const_tables != curr_join->tables)
2299
if (!curr_join->sort_and_group && (curr_join->const_tables != curr_join->tables))
2294
2300
curr_join->join_tab[curr_join->const_tables].sorted= 0;
2295
if (setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2296
(tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2302
if (setup_sum_funcs(curr_join->session, curr_join->sum_funcs)
2303
|| (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2301
2308
end_read_record(&curr_join->join_tab->read_record);
2302
2309
curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
2303
2310
curr_join->join_tab[0].table= 0; // Table is freed
2305
2312
// No sum funcs anymore
2308
items2= items1 + all_fields.elements;
2309
if (change_to_use_tmp_fields(thd, items2,
2310
tmp_fields_list2, tmp_all_fields2,
2311
fields_list.elements, tmp_all_fields1))
2313
curr_join->tmp_fields_list2= tmp_fields_list2;
2314
curr_join->tmp_all_fields2= tmp_all_fields2;
2315
items2= items1 + all_fields.elements;
2316
if (change_to_use_tmp_fields(session, items2,
2317
tmp_fields_list2, tmp_all_fields2,
2318
fields_list.elements, tmp_all_fields1))
2320
curr_join->tmp_fields_list2= tmp_fields_list2;
2321
curr_join->tmp_all_fields2= tmp_all_fields2;
2316
2323
curr_fields_list= &curr_join->tmp_fields_list2;
2317
2324
curr_all_fields= &curr_join->tmp_all_fields2;
2318
2325
curr_join->set_items_ref_array(items2);
2319
curr_join->tmp_table_param.field_count+=
2320
curr_join->tmp_table_param.sum_func_count;
2326
curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count;
2321
2327
curr_join->tmp_table_param.sum_func_count= 0;
2323
2329
if (curr_tmp_table->distinct)
2324
2330
curr_join->select_distinct=0; /* Each row is unique */
2326
2332
curr_join->join_free(); /* Free quick selects */
2327
2333
if (curr_join->select_distinct && ! curr_join->group_list)
2329
thd_proc_info(thd, "Removing duplicates");
2335
session->set_proc_info("Removing duplicates");
2330
2336
if (curr_join->tmp_having)
2331
curr_join->tmp_having->update_used_tables();
2337
curr_join->tmp_having->update_used_tables();
2332
2339
if (remove_duplicates(curr_join, curr_tmp_table,
2333
2340
*curr_fields_list, curr_join->tmp_having))
2335
2343
curr_join->tmp_having=0;
2336
2344
curr_join->select_distinct=0;
2339
2347
if (make_simple_join(curr_join, curr_tmp_table))
2341
2349
calc_group_buffer(curr_join, curr_join->group_list);
2342
count_field_types(select_lex, &curr_join->tmp_table_param,
2343
*curr_all_fields, 0);
2350
count_field_types(select_lex, &curr_join->tmp_table_param, *curr_all_fields, 0);
2347
2354
if (curr_join->group || curr_join->tmp_table_param.sum_func_count)
2349
2356
if (make_group_fields(this, curr_join))
2356
init_items_ref_array();
2362
init_items_ref_array();
2357
2363
items3= ref_pointer_array + (all_fields.elements*4);
2358
setup_copy_fields(thd, &curr_join->tmp_table_param,
2364
setup_copy_fields(session, &curr_join->tmp_table_param,
2359
2365
items3, tmp_fields_list3, tmp_all_fields3,
2360
2366
curr_fields_list->elements, *curr_all_fields);
2361
2367
tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
2362
2368
tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
2363
tmp_table_param.save_copy_field_end=
2364
curr_join->tmp_table_param.copy_field_end;
2369
tmp_table_param.save_copy_field_end= curr_join->tmp_table_param.copy_field_end;
2365
2370
curr_join->tmp_all_fields3= tmp_all_fields3;
2366
2371
curr_join->tmp_fields_list3= tmp_fields_list3;
2370
2375
curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
2371
2376
curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
2372
curr_join->tmp_table_param.copy_field_end=
2373
tmp_table_param.save_copy_field_end;
2377
curr_join->tmp_table_param.copy_field_end= tmp_table_param.save_copy_field_end;
2375
2379
curr_fields_list= &tmp_fields_list3;
2376
2380
curr_all_fields= &tmp_all_fields3;
2377
2381
curr_join->set_items_ref_array(items3);
2379
2383
if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2381
setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2382
thd->is_fatal_error)
2385
setup_sum_funcs(curr_join->session, curr_join->sum_funcs) ||
2386
session->is_fatal_error)
2385
2389
if (curr_join->group_list || curr_join->order)
2387
thd_proc_info(thd, "Sorting result");
2391
session->set_proc_info("Sorting result");
2388
2392
/* If we have already done the group, add HAVING to sorted table */
2389
if (curr_join->tmp_having && ! curr_join->group_list &&
2390
! curr_join->sort_and_group)
2393
if (curr_join->tmp_having && ! curr_join->group_list && ! curr_join->sort_and_group)
2392
2395
// Some tables may have been const
2393
2396
curr_join->tmp_having->update_used_tables();
2395
2398
table_map used_tables= (curr_join->const_table_map |
2396
2399
curr_table->table->map);
2398
Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
2401
Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having, used_tables, used_tables, 0);
2401
2402
if (sort_table_cond)
2403
if (!curr_table->select)
2404
if (!(curr_table->select= new SQL_SELECT))
2406
if (!curr_table->select->cond)
2407
curr_table->select->cond= sort_table_cond;
2408
else // This should never happen
2410
if (!(curr_table->select->cond=
2411
new Item_cond_and(curr_table->select->cond,
2415
Item_cond_and do not need fix_fields for execution, its parameters
2416
are fixed or do not need fix_fields, too
2418
curr_table->select->cond->quick_fix_field();
2420
curr_table->select_cond= curr_table->select->cond;
2421
curr_table->select_cond->top_level_item();
2422
curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2404
if (!curr_table->select)
2405
if (!(curr_table->select= new SQL_SELECT))
2407
if (!curr_table->select->cond)
2408
curr_table->select->cond= sort_table_cond;
2409
else // This should never happen
2411
if (!(curr_table->select->cond=
2412
new Item_cond_and(curr_table->select->cond,
2416
Item_cond_and do not need fix_fields for execution, its parameters
2417
are fixed or do not need fix_fields, too
2419
curr_table->select->cond->quick_fix_field();
2421
curr_table->select_cond= curr_table->select->cond;
2422
curr_table->select_cond->top_level_item();
2423
curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2429
curr_join->select_limit= HA_POS_ERROR;
2430
curr_join->select_limit= HA_POS_ERROR;
2433
We can abort sorting after thd->select_limit rows if we there is no
2434
WHERE clause for any tables after the sorted one.
2436
JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
2437
JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
2438
for (; curr_table < end_table ; curr_table++)
2441
table->keyuse is set in the case there was an original WHERE clause
2442
on the table that was optimized away.
2444
if (curr_table->select_cond ||
2445
(curr_table->keyuse && !curr_table->first_inner))
2447
/* We have to sort all rows */
2448
curr_join->select_limit= HA_POS_ERROR;
2434
We can abort sorting after session->select_limit rows if we there is no
2435
WHERE clause for any tables after the sorted one.
2437
JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
2438
JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
2439
for (; curr_table < end_table ; curr_table++)
2442
table->keyuse is set in the case there was an original WHERE clause
2443
on the table that was optimized away.
2445
if (curr_table->select_cond ||
2446
(curr_table->keyuse && !curr_table->first_inner))
2448
/* We have to sort all rows */
2449
curr_join->select_limit= HA_POS_ERROR;
2453
2454
if (curr_join->join_tab == join_tab && save_join_tab())
2458
Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
2459
chose FILESORT to be faster than INDEX SCAN or there is no
2460
suitable index present.
2461
Note, that create_sort_index calls test_if_skip_sort_order and may
2462
finally replace sorting with index scan if there is a LIMIT clause in
2463
the query. XXX: it's never shown in EXPLAIN!
2464
OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
2457
Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
2458
chose FILESORT to be faster than INDEX SCAN or there is no
2459
suitable index present.
2460
Note, that create_sort_index calls test_if_skip_sort_order and may
2461
finally replace sorting with index scan if there is a LIMIT clause in
2462
the query. XXX: it's never shown in EXPLAIN!
2463
OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
2466
if (create_sort_index(thd, curr_join,
2467
curr_join->group_list ?
2465
if (create_sort_index(session, curr_join,
2466
curr_join->group_list ?
2468
2467
curr_join->group_list : curr_join->order,
2469
2468
curr_join->select_limit,
2470
2469
(select_options & OPTION_FOUND_ROWS ?
2471
2470
HA_POS_ERROR : unit->select_limit_cnt),
2472
2471
curr_join->group_list ? true : false))
2474
2474
sortorder= curr_join->sortorder;
2475
2475
if (curr_join->const_tables != curr_join->tables &&
2476
2476
!curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
2487
/* XXX: When can we have here thd->is_error() not zero? */
2488
if (thd->is_error())
2487
/* XXX: When can we have here session->is_error() not zero? */
2488
if (session->is_error())
2490
error= thd->is_error();
2490
error= session->is_error();
2493
2493
curr_join->having= curr_join->tmp_having;
2494
2494
curr_join->fields= curr_fields_list;
2497
thd_proc_info(thd, "Sending data");
2498
result->send_fields(*curr_fields_list,
2499
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2500
error= do_select(curr_join, curr_fields_list, NULL);
2501
thd->limit_found_rows= curr_join->send_records;
2496
session->set_proc_info("Sending data");
2497
result->send_fields(*curr_fields_list,
2498
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2499
error= do_select(curr_join, curr_fields_list, NULL);
2500
session->limit_found_rows= curr_join->send_records;
2504
2502
/* Accumulate the counts from all join iterations of all join parts. */
2505
thd->examined_row_count+= curr_join->examined_rows;
2503
session->examined_row_count+= curr_join->examined_rows;
2508
2506
With EXPLAIN EXTENDED we have to restore original ref_array
2509
2507
for a derived table which is always materialized.
2510
2508
Otherwise we would not be able to print the query correctly.
2513
(thd->lex->describe & DESCRIBE_EXTENDED) &&
2514
select_lex->linkage == DERIVED_TABLE_TYPE)
2510
if (items0 && (session->lex->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
2515
2511
set_items_ref_array(items0);
2525
2520
Return error that hold JOIN.
2531
2524
select_lex->join= 0;
2649
if (!(join= new JOIN(thd, fields, select_options, result)))
2638
if (!(join= new JOIN(session, fields, select_options, result)))
2651
thd_proc_info(thd, "init");
2652
thd->used_tables=0; // Updated by setup_fields
2640
session->set_proc_info("init");
2641
session->used_tables=0; // Updated by setup_fields
2653
2642
if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2654
conds, og_num, order, group, having, proc_param,
2643
conds, og_num, order, group, having,
2655
2644
select_lex, unit)) == true)
2661
/* dump_TableList_graph(select_lex, select_lex->leaf_tables); */
2662
2650
if (join->flatten_subqueries())
2667
/* dump_TableList_struct(select_lex, select_lex->leaf_tables); */
2669
2656
if ((err= join->optimize()))
2674
if (thd->lex->describe & DESCRIBE_EXTENDED)
2661
if (session->lex->describe & DESCRIBE_EXTENDED)
2676
2663
join->conds_history= join->conds;
2677
2664
join->having_history= (join->having?join->having:join->tmp_having);
2680
if (thd->is_error())
2667
if (session->is_error())
2685
if (thd->lex->describe & DESCRIBE_EXTENDED)
2672
if (session->lex->describe & DESCRIBE_EXTENDED)
2687
2674
select_lex->where= join->conds_history;
2688
2675
select_lex->having= join->having_history;
2942
2929
tl->table->tablenr= table_no;
2943
2930
tl->table->map= ((table_map)1) << table_no;
2944
SELECT_LEX *old_sl= tl->select_lex;
2945
tl->select_lex= parent_join->select_lex;
2931
Select_Lex *old_sl= tl->select_lex;
2932
tl->select_lex= parent_join->select_lex;
2946
2933
for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
2947
2934
emb->select_lex= parent_join->select_lex;
2949
2936
parent_join->tables += subq_lex->join->tables;
2952
2939
Put the subquery's WHERE into semi-join's sj_on_expr
2953
2940
Add the subquery-induced equalities too.
2955
SELECT_LEX *save_lex= thd->lex->current_select;
2956
thd->lex->current_select=subq_lex;
2942
Select_Lex *save_lex= session->lex->current_select;
2943
session->lex->current_select=subq_lex;
2957
2944
if (!subq_pred->left_expr->fixed &&
2958
subq_pred->left_expr->fix_fields(thd, &subq_pred->left_expr))
2945
subq_pred->left_expr->fix_fields(session, &subq_pred->left_expr))
2960
thd->lex->current_select=save_lex;
2947
session->lex->current_select=save_lex;
2962
2949
sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
2963
2950
sj_nest->nested_join->sj_depends_on= subq_pred->used_tables() |
3062
3049
/* 1. Fix children subqueries */
3063
for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
3050
for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
3064
3051
in_subq != in_subq_end; in_subq++)
3066
3053
JOIN *child_join= (*in_subq)->unit->first_select()->join;
3067
3054
child_join->outer_tables = child_join->tables;
3068
3055
if (child_join->flatten_subqueries())
3070
(*in_subq)->sj_convert_priority=
3057
(*in_subq)->sj_convert_priority=
3071
3058
(*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
3074
//dump_TableList_struct(select_lex, select_lex->leaf_tables);
3076
2. Pick which subqueries to convert:
3077
sort the subquery array
3078
- prefer correlated subqueries over uncorrelated;
3079
- prefer subqueries that have greater number of outer tables;
3081
sj_subselects.sort(subq_sj_candidate_cmp);
3082
// #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
3083
/* Replace all subqueries to be flattened with Item_int(1) */
3084
for (in_subq= sj_subselects.front();
3085
in_subq != in_subq_end &&
3086
tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3061
bool outer_join_disable_semi_join= false;
3063
* Temporary measure: disable semi-joins when they are together with outer
3066
* @see LP Bug #314911
3068
for (TableList *tbl= select_lex->leaf_tables; tbl; tbl=tbl->next_leaf)
3089
if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
3070
TableList *embedding= tbl->embedding;
3071
if (tbl->on_expr || (tbl->embedding && !(embedding->sj_on_expr &&
3072
!embedding->embedding)))
3074
in_subq= sj_subselects.front();
3075
outer_join_disable_semi_join= true;
3093
for (in_subq= sj_subselects.front();
3094
in_subq != in_subq_end &&
3095
tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3079
if (! outer_join_disable_semi_join)
3098
if (convert_subq_to_sj(this, *in_subq))
3082
2. Pick which subqueries to convert:
3083
sort the subquery array
3084
- prefer correlated subqueries over uncorrelated;
3085
- prefer subqueries that have greater number of outer tables;
3087
sj_subselects.sort(subq_sj_candidate_cmp);
3088
// #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
3089
/* Replace all subqueries to be flattened with Item_int(1) */
3090
for (in_subq= sj_subselects.front();
3091
in_subq != in_subq_end &&
3092
tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3095
if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
3099
for (in_subq= sj_subselects.front();
3100
in_subq != in_subq_end &&
3101
tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3104
if (convert_subq_to_sj(this, *in_subq))
3102
3109
/* 3. Finalize those we didn't convert */
3359
3364
*****************************************************************************/
3362
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
3367
static ha_rows get_quick_record_count(Session *session, SQL_SELECT *select,
3364
3369
const key_map *keys,ha_rows limit)
3367
if (check_stack_overrun(thd, STACK_MIN_SIZE, NULL))
3372
if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
3368
3373
return(0); // Fatal error flag is set
3371
3376
select->head=table;
3372
3377
table->reginfo.impossible_range=0;
3373
if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
3378
if ((error= select->test_quick_select(session, *(key_map *)keys,(table_map) 0,
3374
3379
limit, 0, false)) == 1)
3375
3380
return(select->quick->records);
3376
3381
if (error == -1)
3586
3591
table=s->table;
3589
3594
If equi-join condition by a key is null rejecting and after a
3590
3595
substitution of a const table the key value happens to be null
3591
3596
then we can state that there are no matches for this equi-join.
3593
3598
if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
3596
3601
When performing an outer join operation if there are no matching rows
3597
3602
for the single row of the outer table all the inner tables are to be
3598
3603
null complemented and thus considered as constant tables.
3599
Here we apply this consideration to the case of outer join operations
3604
Here we apply this consideration to the case of outer join operations
3600
3605
with a single inner table only because the case with nested tables
3601
3606
would require a more thorough analysis.
3602
3607
TODO. Apply single row substitution to null complemented inner tables
3603
for nested outer join operations.
3608
for nested outer join operations.
3605
3610
while (keyuse->table == table)
3607
3612
if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
3608
3613
keyuse->val->is_null() && keyuse->null_rejecting)
3610
3615
s->type= JT_CONST;
3611
mark_as_null_row(table);
3616
table->mark_as_null_row();
3612
3617
found_const_table_map|= table->map;
3613
3618
join->const_table_map|= table->map;
3614
3619
set_position(join,const_count++,s,(KEYUSE*) 0);
3771
records= get_quick_record_count(join->thd, select, s->table,
3776
records= get_quick_record_count(join->session, select, s->table,
3772
3777
&s->const_keys, join->row_limit);
3773
3778
s->quick=select->quick;
3774
3779
s->needed_reg=select->needed_reg;
3775
3780
select->quick=0;
3776
3781
if (records == 0 && s->table->reginfo.impossible_range)
3779
Impossible WHERE or ON expression
3780
In case of ON, we mark that the we match one empty NULL row.
3781
In case of WHERE, don't set found_const_table_map to get the
3782
caller to abort with a zero row result.
3784
join->const_table_map|= s->table->map;
3785
set_position(join,const_count++,s,(KEYUSE*) 0);
3787
if (*s->on_expr_ref)
3789
/* Generate empty row */
3790
s->info= "Impossible ON condition";
3791
found_const_table_map|= s->table->map;
3793
mark_as_null_row(s->table); // All fields are NULL
3784
Impossible WHERE or ON expression
3785
In case of ON, we mark that the we match one empty NULL row.
3786
In case of WHERE, don't set found_const_table_map to get the
3787
caller to abort with a zero row result.
3789
join->const_table_map|= s->table->map;
3790
set_position(join,const_count++,s,(KEYUSE*) 0);
3792
if (*s->on_expr_ref)
3794
/* Generate empty row */
3795
s->info= "Impossible ON condition";
3796
found_const_table_map|= s->table->map;
3798
s->table->mark_as_null_row(); // All fields are NULL
3796
3801
if (records != HA_POS_ERROR)
3798
s->found_records=records;
3799
s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
3803
s->found_records=records;
3804
s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
4567
update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
4568
uint32_t tables, COND *cond,
4569
COND_EQUAL *cond_equal __attribute__((unused)),
4570
table_map normal_tables, SELECT_LEX *select_lex,
4572
update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
4573
uint32_t tables, COND *cond, COND_EQUAL *,
4574
table_map normal_tables, Select_Lex *select_lex,
4571
4575
SARGABLE_PARAM **sargables)
4573
4577
uint and_level,i,found_eq_constant;
4574
4578
KEY_FIELD *key_fields, *end, *field;
4576
4580
uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
4579
We use the same piece of memory to store both KEY_FIELD
4583
We use the same piece of memory to store both KEY_FIELD
4580
4584
and SARGABLE_PARAM structure.
4581
4585
KEY_FIELD values are placed at the beginning this memory
4582
4586
while SARGABLE_PARAM values are put at the end.
4583
4587
All predicates that are used to fill arrays of KEY_FIELD
4584
4588
and SARGABLE_PARAM structures have at most 2 arguments
4585
except BETWEEN predicates that have 3 arguments and
4589
except BETWEEN predicates that have 3 arguments and
4587
This any predicate if it's not BETWEEN/IN can be used
4591
This any predicate if it's not BETWEEN/IN can be used
4588
4592
directly to fill at most 2 array elements, either of KEY_FIELD
4589
4593
or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
4590
4594
can be filled as this predicate is considered as
4593
4597
it is considered as sargable only for its first argument.
4594
4598
Multiple equality can add elements that are filled after
4595
4599
substitution of field arguments by equal fields. There
4596
can be not more than select_lex->max_equal_elems such
4600
can be not more than select_lex->max_equal_elems such
4599
4603
sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
4600
(((thd->lex->current_select->cond_count+1)*2 +
4601
thd->lex->current_select->between_count)*m+1);
4602
if (!(key_fields=(KEY_FIELD*) thd->alloc(sz)))
4604
(((session->lex->current_select->cond_count+1)*2 +
4605
session->lex->current_select->between_count)*m+1);
4606
if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
4603
4607
return true; /* purecov: inspected */
4605
4609
field= end= key_fields;
4606
*sargables= (SARGABLE_PARAM *) key_fields +
4610
*sargables= (SARGABLE_PARAM *) key_fields +
4607
4611
(sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
4608
4612
/* set a barrier for the array of SARGABLE_PARAM */
4609
(*sargables)[0].field= 0;
4613
(*sargables)[0].field= 0;
4611
4615
if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
5110
5114
ReuseRangeEstimateForRef-1:
5111
5115
We get here if we've found a ref(const) (c_i are constants):
5112
5116
"(keypart1=c1) AND ... AND (keypartN=cN)" [ref_const_cond]
5114
If range optimizer was able to construct a "range"
5118
If range optimizer was able to construct a "range"
5115
5119
access on this index, then its condition "quick_cond" was
5116
5120
eqivalent to ref_const_cond (*), and we can re-use E(#rows)
5117
5121
from the range optimizer.
5119
Proof of (*): By properties of range and ref optimizers
5120
quick_cond will be equal or tighther than ref_const_cond.
5121
ref_const_cond already covers "smallest" possible interval -
5122
a singlepoint interval over all keyparts. Therefore,
5123
quick_cond is equivalent to ref_const_cond (if it was an
5123
Proof of (*): By properties of range and ref optimizers
5124
quick_cond will be equal or tighther than ref_const_cond.
5125
ref_const_cond already covers "smallest" possible interval -
5126
a singlepoint interval over all keyparts. Therefore,
5127
quick_cond is equivalent to ref_const_cond (if it was an
5124
5128
empty interval we wouldn't have got here).
5126
if (table->quick_keys.is_set(key))
5130
if (table->quick_keys.test(key))
5127
5131
records= (double) table->quick_rows[key];
5189
5193
ReuseRangeEstimateForRef-3:
5190
5194
We're now considering a ref[or_null] access via
5191
(t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR
5192
(same-as-above but with one cond replaced
5195
(t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR
5196
(same-as-above but with one cond replaced
5193
5197
with "t.keypart_i IS NULL")] (**)
5195
5199
Try re-using E(#rows) from "range" optimizer:
5196
5200
We can do so if "range" optimizer used the same intervals as
5197
in (**). The intervals used by range optimizer may be not
5201
in (**). The intervals used by range optimizer may be not
5198
5202
available at this point (as "range" access might have choosen to
5199
5203
create quick select over another index), so we can't compare
5200
5204
them to (**). We'll make indirect judgements instead.
5201
5205
The sufficient conditions for re-use are:
5202
5206
(C1) All e_i in (**) are constants, i.e. found_ref==false. (if
5203
5207
this is not satisfied we have no way to know which ranges
5204
will be actually scanned by 'ref' until we execute the
5208
will be actually scanned by 'ref' until we execute the
5206
5210
(C2) max #key parts in 'range' access == K == max_key_part (this
5207
5211
is apparently a necessary requirement)
5209
We also have a property that "range optimizer produces equal or
5213
We also have a property that "range optimizer produces equal or
5210
5214
tighter set of scan intervals than ref(const) optimizer". Each
5211
of the intervals in (**) are "tightest possible" intervals when
5212
one limits itself to using keyparts 1..K (which we do in #2).
5215
of the intervals in (**) are "tightest possible" intervals when
5216
one limits itself to using keyparts 1..K (which we do in #2).
5213
5217
From here it follows that range access used either one, or
5214
5218
both of the (I1) and (I2) intervals:
5216
(t.keypart1=c1 AND ... AND t.keypartK=eK) (I1)
5217
(same-as-above but with one cond replaced
5220
(t.keypart1=c1 AND ... AND t.keypartK=eK) (I1)
5221
(same-as-above but with one cond replaced
5218
5222
with "t.keypart_i IS NULL") (I2)
5220
5224
The remaining part is to exclude the situation where range
6042
6044
for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
6044
6046
table_map real_table_bit= s->table->map;
6045
if ((remaining_tables & real_table_bit) &&
6046
!(remaining_tables & s->dependent) &&
6047
if ((remaining_tables & real_table_bit) &&
6048
!(remaining_tables & s->dependent) &&
6047
6049
(!idx || !check_interleaving_with_nj(join->positions[idx-1].table, s)))
6049
6051
double current_record_count, current_read_time;
6050
6052
advance_sj_state(remaining_tables, s);
6053
psergey-insideout-todo:
6054
when best_access_path() detects it could do an InsideOut scan or
6055
some other scan, have it return an insideout scan and a flag that
6056
requests to "fork" this loop iteration. (Q: how does that behave
6055
psergey-insideout-todo:
6056
when best_access_path() detects it could do an InsideOut scan or
6057
some other scan, have it return an insideout scan and a flag that
6058
requests to "fork" this loop iteration. (Q: how does that behave
6057
6059
when the depth is insufficient??)
6059
6061
/* Find the best access method from 's' to the current partial plan */
6060
best_access_path(join, s, thd, remaining_tables, idx,
6062
best_access_path(join, s, session, remaining_tables, idx,
6061
6063
record_count, read_time);
6062
6064
/* Compute the cost of extending the plan with 's' */
6063
6065
current_record_count= record_count * join->positions[idx].records_read;
6308
6308
and a join order:
6309
6309
t1, ref access on t1.key=c1
6310
t2, ref access on t2.key=c2
6311
t3, ref access on t3.key=t1.field
6310
t2, ref access on t2.key=c2
6311
t3, ref access on t3.key=t1.field
6313
6313
For t1: n_ref_scans = 1, n_distinct_ref_scans = 1
6314
6314
For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1
6315
6315
For t3: n_ref_scans = records_read(t1)*records_read(t2)
6316
6316
n_distinct_ref_scans = #records_read(t1)
6318
6318
The reason for having this function (at least the latest version of it)
6319
is that we need to account for buffering in join execution.
6319
is that we need to account for buffering in join execution.
6321
6321
An edge-case example: if we have a non-first table in join accessed via
6322
6322
ref(const) or ref(param) where there is a small number of different
6323
6323
values of param, then the access will likely hit the disk cache and will
6324
6324
not require any disk seeks.
6326
6326
The proper solution would be to assume an LRU disk cache of some size,
6327
6327
calculate probability of cache hits, etc. For now we just count
6328
6328
identical ref accesses as one.
6331
6331
Expected number of row combinations
6492
6492
uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
6493
6493
j->ref.items[i]=keyuse->val; // Save for cond removal
6494
6494
j->ref.cond_guards[i]= keyuse->cond_guard;
6495
if (keyuse->null_rejecting)
6495
if (keyuse->null_rejecting)
6496
6496
j->ref.null_rejecting |= 1 << i;
6497
6497
keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
6498
6498
if (!keyuse->used_tables &&
6499
6499
!(join->select_options & SELECT_DESCRIBE))
6500
6500
{ // Compare against constant
6501
store_key_item tmp(thd, keyinfo->key_part[i].field,
6501
store_key_item tmp(session, keyinfo->key_part[i].field,
6502
6502
key_buff + maybe_null,
6503
6503
maybe_null ? key_buff : 0,
6504
6504
keyinfo->key_part[i].length, keyuse->val);
6505
if (thd->is_fatal_error)
6505
if (session->is_fatal_error)
6510
*ref_key++= get_store_key(thd,
6510
*ref_key++= get_store_key(session,
6511
6511
keyuse,join->const_table_map,
6512
6512
&keyinfo->key_part[i],
6513
6513
key_buff, maybe_null);
6597
6597
Table *table= field->table;
6598
THD *thd= table->in_use;
6599
ha_rows cuted_fields=thd->cuted_fields;
6598
Session *session= table->in_use;
6599
ha_rows cuted_fields=session->cuted_fields;
6602
6602
we should restore old value of count_cuted_fields because
6603
store_val_in_field can be called from mysql_insert
6603
store_val_in_field can be called from mysql_insert
6604
6604
with select_insert, which make count_cuted_fields= 1
6606
enum_check_fields old_count_cuted_fields= thd->count_cuted_fields;
6607
thd->count_cuted_fields= check_flag;
6606
enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
6607
session->count_cuted_fields= check_flag;
6608
6608
error= item->save_in_field(field, 1);
6609
thd->count_cuted_fields= old_count_cuted_fields;
6610
return error || cuted_fields != thd->cuted_fields;
6609
session->count_cuted_fields= old_count_cuted_fields;
6610
return error || cuted_fields != session->cuted_fields;
7307
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno,
7306
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno,
7308
7307
bool other_tbls_ok)
7310
7309
if (item->const_item())
7314
Don't push down the triggered conditions. Nested outer joins execution
7313
Don't push down the triggered conditions. Nested outer joins execution
7315
7314
code may need to evaluate a condition several times (both triggered and
7316
7315
untriggered), and there is no way to put thi
7317
7316
TODO: Consider cloning the triggered condition and using the copies for:
7318
7317
1. push the first copy down, to have most restrictive index condition
7320
2. Put the second copy into tab->select_cond.
7319
2. Put the second copy into tab->select_cond.
7322
if (item->type() == Item::FUNC_ITEM &&
7321
if (item->type() == Item::FUNC_ITEM &&
7323
7322
((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
7787
7786
if (tab->select && tab->select->quick)
7789
7788
if (statistics)
7790
status_var_increment(join->thd->status_var.select_full_range_join_count);
7789
status_var_increment(join->session->status_var.select_full_range_join_count);
7794
join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
7793
join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
7795
7794
if (statistics)
7796
status_var_increment(join->thd->status_var.select_full_join_count);
7795
status_var_increment(join->session->status_var.select_full_join_count);
7799
7798
if (!table->no_keyread)
7801
7800
if (tab->select && tab->select->quick &&
7802
7801
tab->select->quick->index != MAX_KEY && //not index_merge
7803
table->covering_keys.is_set(tab->select->quick->index))
7802
table->covering_keys.test(tab->select->quick->index))
7805
7804
table->key_read=1;
7806
7805
table->file->extra(HA_EXTRA_KEYREAD);
7808
else if (!table->covering_keys.is_clear_all() &&
7807
else if (!table->covering_keys.none() &&
7809
7808
!(tab->select && tab->select->quick))
7810
7809
{ // Only read index tree
7811
7810
if (!tab->insideout_match_tab)
8537
8521
bool left_copyfl, right_copyfl;
8538
8522
Item_equal *left_item_equal=
8539
8523
find_item_equal(cond_equal, left_field, &left_copyfl);
8540
Item_equal *right_item_equal=
8524
Item_equal *right_item_equal=
8541
8525
find_item_equal(cond_equal, right_field, &right_copyfl);
8543
8527
/* As (NULL=NULL) != true we can't just remove the predicate f=f */
8544
8528
if (left_field->eq(right_field)) /* f = f */
8545
return (!(left_field->maybe_null() && !left_item_equal));
8529
return (!(left_field->maybe_null() && !left_item_equal));
8547
8531
if (left_item_equal && left_item_equal == right_item_equal)
8550
8534
The equality predicate is inference of one of the existing
8551
8535
multiple equalities, i.e the condition is already covered
8552
8536
by upper level equalities
8557
bool copy_item_name= test(item && item->name >= subq_sj_cond_name &&
8541
bool copy_item_name= test(item && item->name >= subq_sj_cond_name &&
8558
8542
item->name < subq_sj_cond_name + 64);
8559
8543
/* Copy the found multiple equalities at the current level if needed */
8560
8544
if (left_copyfl)
8787
8771
if (left_item->type() == Item::ROW_ITEM &&
8788
8772
right_item->type() == Item::ROW_ITEM)
8790
thd->lex->current_select->cond_count--;
8791
return check_row_equality(thd,
8774
session->lex->current_select->cond_count--;
8775
return check_row_equality(session,
8792
8776
(Item_row *) left_item,
8793
8777
(Item_row *) right_item,
8794
8778
cond_equal, eq_list);
8797
8781
return check_simple_equality(left_item, right_item, item, cond_equal);
8804
8788
Replace all equality predicates in a condition by multiple equality items.
8806
8790
At each 'and' level the function detects items for equality predicates
8807
8791
and replaced them by a set of multiple equality items of class Item_equal,
8808
taking into account inherited equalities from upper levels.
8792
taking into account inherited equalities from upper levels.
8809
8793
If an equality predicate is used not in a conjunction it's just
8810
8794
replaced by a multiple equality predicate.
8811
8795
For each 'and' level the function set a pointer to the inherited
8812
8796
multiple equalities in the cond_equal field of the associated
8813
object of the type Item_cond_and.
8797
object of the type Item_cond_and.
8814
8798
The function also traverses the cond tree and and for each field reference
8815
8799
sets a pointer to the multiple equality item containing the field, if there
8816
8800
is any. If this multiple equality equates fields to a constant the
8817
function replaces the field reference by the constant in the cases
8801
function replaces the field reference by the constant in the cases
8818
8802
when the field is not of a string type or when the field reference is
8819
8803
just an argument of a comparison predicate.
8820
The function also determines the maximum number of members in
8804
The function also determines the maximum number of members in
8821
8805
equality lists of each Item_cond_and object assigning it to
8822
thd->lex->current_select->max_equal_elems.
8806
session->lex->current_select->max_equal_elems.
8825
8809
Multiple equality predicate =(f1,..fn) is equivalent to the conjuction of
8842
8826
The function performs the substitution in a recursive descent by
8843
8827
the condtion tree, passing to the next AND level a chain of multiple
8844
8828
equality predicates which have been built at the upper levels.
8845
The Item_equal items built at the level are attached to other
8829
The Item_equal items built at the level are attached to other
8846
8830
non-equality conjucts as a sublist. The pointer to the inherited
8847
8831
multiple equalities is saved in the and condition object (Item_cond_and).
8848
This chain allows us for any field reference occurence easyly to find a
8832
This chain allows us for any field reference occurence easyly to find a
8849
8833
multiple equality that must be held for this occurence.
8850
8834
For each AND level we do the following:
8851
8835
- scan it for all equality predicate (=) items
8852
8836
- join them into disjoint Item_equal() groups
8853
- process the included OR conditions recursively to do the same for
8837
- process the included OR conditions recursively to do the same for
8856
8840
We need to do things in this order as lower AND levels need to know about
8857
8841
all possible Item_equal objects in upper levels.
8859
@param thd thread handle
8843
@param session thread handle
8860
8844
@param cond condition(expression) where to make replacement
8861
8845
@param inherited path to all inherited multiple equality items
8983
8967
item_equal->fix_length_and_dec();
8984
8968
item_equal->update_used_tables();
8985
set_if_bigger(thd->lex->current_select->max_equal_elems,
8986
item_equal->members());
8969
set_if_bigger(session->lex->current_select->max_equal_elems,
8970
item_equal->members());
8988
8972
and_cond->cond_equal= cond_equal;
8989
8973
args->concat((List<Item> *)&cond_equal.current_level);
8991
8975
return and_cond;
8995
8979
For each field reference in cond, not from equal item predicates,
8996
8980
set a pointer to the multiple equality it belongs to (if there is any)
8997
8981
as soon the field is not of a string type or the field reference is
8998
an argument of a comparison predicate.
8982
an argument of a comparison predicate.
9000
8984
unsigned char *is_subst_valid= (unsigned char *) 1;
9001
8985
cond= cond->compile(&Item::subst_argument_checker,
9003
8987
&Item::equal_fields_propagator,
9004
8988
(unsigned char *) inherited);
9005
8989
cond->update_used_tables();
9425
9409
Field *field= item_field->field;
9426
9410
JOIN_TAB *stat= field->table->reginfo.join_tab;
9427
9411
key_map possible_keys= field->key_start;
9428
possible_keys.intersect(field->table->keys_in_use_for_query);
9429
stat[0].const_keys.merge(possible_keys);
9412
possible_keys&= field->table->keys_in_use_for_query;
9413
stat[0].const_keys|= possible_keys;
9432
For each field in the multiple equality (for which we know that it
9433
is a constant) we have to find its corresponding key part, and set
9416
For each field in the multiple equality (for which we know that it
9417
is a constant) we have to find its corresponding key part, and set
9434
9418
that key part in const_key_parts.
9436
if (!possible_keys.is_clear_all())
9420
if (possible_keys.any())
9438
Table *tab= field->table;
9422
Table *field_tab= field->table;
9440
for (use= stat->keyuse; use && use->table == tab; use++)
9441
if (possible_keys.is_set(use->key) &&
9442
tab->key_info[use->key].key_part[use->keypart].field ==
9424
for (use= stat->keyuse; use && use->table == field_tab; use++)
9425
if (possible_keys.test(use->key) &&
9426
field_tab->key_info[use->key].key_part[use->keypart].field ==
9444
tab->const_key_parts[use->key]|= use->keypart_map;
9428
field_tab->const_key_parts[use->key]|= use->keypart_map;
9608
9592
if (right_const)
9610
resolve_const_item(thd, &args[1], args[0]);
9594
resolve_const_item(session, &args[1], args[0]);
9611
9595
func->update_used_tables();
9612
change_cond_ref_to_const(thd, save_list, and_father, and_father,
9596
change_cond_ref_to_const(session, save_list, and_father, and_father,
9613
9597
args[0], args[1]);
9615
9599
else if (left_const)
9617
resolve_const_item(thd, &args[0], args[1]);
9601
resolve_const_item(session, &args[0], args[1]);
9618
9602
func->update_used_tables();
9619
change_cond_ref_to_const(thd, save_list, and_father, and_father,
9603
change_cond_ref_to_const(session, save_list, and_father, and_father,
9620
9604
args[1], args[0]);
9767
9751
if ((nested_join= table->nested_join))
9770
9754
If the element of join_list is a nested join apply
9771
9755
the procedure to its nested join list first.
9773
9757
if (table->on_expr)
9775
9759
Item *expr= table->on_expr;
9777
If an on expression E is attached to the table,
9761
If an on expression E is attached to the table,
9778
9762
check all null rejected predicates in this expression.
9779
9763
If such a predicate over an attribute belonging to
9780
9764
an inner table of an embedded outer join is found,
9781
9765
the outer join is converted to an inner join and
9782
the corresponding on expression is added to E.
9766
the corresponding on expression is added to E.
9784
9768
expr= simplify_joins(join, &nested_join->join_list,
9785
9769
expr, false, in_sj || table->sj_on_expr);
10003
9987
Check interleaving with an inner tables of an outer join for
10004
9988
extension table.
10006
Check if table next_tab can be added to current partial join order, and
9990
Check if table next_tab can be added to current partial join order, and
10007
9991
if yes, record that it has been added.
10009
9993
The function assumes that both current partial join order and its
10010
9994
extension with next_tab are valid wrt table dependencies.
10014
9998
LIMITATIONS ON JOIN order_st
10015
9999
The nested [outer] joins executioner algorithm imposes these limitations
10016
10000
on join order:
10017
1. "Outer tables first" - any "outer" table must be before any
10001
1. "Outer tables first" - any "outer" table must be before any
10018
10002
corresponding "inner" table.
10019
10003
2. "No interleaving" - tables inside a nested join must form a continuous
10020
sequence in join order (i.e. the sequence must not be interrupted by
10004
sequence in join order (i.e. the sequence must not be interrupted by
10021
10005
tables that are outside of this nested join).
10023
10007
#1 is checked elsewhere, this function checks #2 provided that #1 has
10024
10008
been already checked.
10026
10010
WHY NEED NON-INTERLEAVING
10027
Consider an example:
10011
Consider an example:
10029
10013
select * from t0 join t1 left join (t2 join t3) on cond1
10048
10032
The limitations on join order can be rephrased as follows: for valid
10049
10033
join order one must be able to:
10050
10034
1. write down the used tables in the join order on one line.
10051
2. for each nested join, put one '(' and one ')' on the said line
10035
2. for each nested join, put one '(' and one ')' on the said line
10052
10036
3. write "LEFT JOIN" and "ON (...)" where appropriate
10053
10037
4. get a query equivalent to the query we're trying to execute.
10055
10039
Calls to check_interleaving_with_nj() are equivalent to writing the
10056
above described line from left to right.
10057
A single check_interleaving_with_nj(A,B) call is equivalent to writing
10040
above described line from left to right.
10041
A single check_interleaving_with_nj(A,B) call is equivalent to writing
10058
10042
table B and appropriate brackets on condition that table A and
10059
10043
appropriate brackets is the last what was written. Graphically the
10060
10044
transition is as follows:
10209
10193
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
10210
10194
Item::cond_result *cond_value)
10212
THD *thd= join->thd;
10196
Session *session= join->session;
10215
10199
*cond_value= Item::COND_TRUE;
10219
10203
Build all multiple equality predicates and eliminate equality
10220
10204
predicates that can be inferred from these multiple equalities.
10221
10205
For each reference of a field included into a multiple equality
10222
10206
that occurs in a function set a pointer to the multiple equality
10223
10207
predicate. Substitute a constant instead of this field if the
10224
10208
multiple equality contains a constant.
10226
conds= build_equal_items(join->thd, conds, NULL, join_list,
10210
conds= build_equal_items(join->session, conds, NULL, join_list,
10227
10211
&join->cond_equal);
10229
10213
/* change field = field to field = const for each found field = const */
10230
propagate_cond_constants(thd, (I_List<COND_CMP> *) 0, conds, conds);
10214
propagate_cond_constants(session, (I_List<COND_CMP> *) 0, conds, conds);
10232
10216
Remove all instances of item == item
10233
10217
Remove all and-levels where CONST item != CONST item
10235
conds= remove_eq_conds(thd, conds, cond_value) ;
10219
conds= remove_eq_conds(session, conds, cond_value) ;
10237
10221
return(conds);
10253
remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value)
10237
remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
10255
10239
if (cond->type() == Item::COND_ITEM)
10257
bool and_level= ((Item_cond*) cond)->functype()
10258
== Item_func::COND_AND_FUNC;
10241
bool and_level= (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC);
10259
10243
List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10260
10244
Item::cond_result tmp_cond_value;
10261
bool should_fix_fields=0;
10245
bool should_fix_fields= false;
10263
*cond_value=Item::COND_UNDEF;
10247
*cond_value= Item::COND_UNDEF;
10265
while ((item=li++))
10249
while ((item= li++))
10267
Item *new_item=remove_eq_conds(thd, item, &tmp_cond_value);
10251
Item *new_item= remove_eq_conds(session, item, &tmp_cond_value);
10270
10254
else if (item != new_item)
10272
li.replace(new_item);
10273
should_fix_fields=1;
10256
li.replace(new_item);
10257
should_fix_fields= true;
10275
10259
if (*cond_value == Item::COND_UNDEF)
10276
*cond_value=tmp_cond_value;
10277
switch (tmp_cond_value) {
10278
case Item::COND_OK: // Not true or false
10279
if (and_level || *cond_value == Item::COND_FALSE)
10280
*cond_value=tmp_cond_value;
10282
case Item::COND_FALSE:
10285
*cond_value=tmp_cond_value;
10286
return (COND*) 0; // Always false
10289
case Item::COND_TRUE:
10292
*cond_value= tmp_cond_value;
10293
return (COND*) 0; // Always true
10296
case Item::COND_UNDEF: // Impossible
10297
break; /* purecov: deadcode */
10260
*cond_value= tmp_cond_value;
10262
switch (tmp_cond_value)
10264
case Item::COND_OK: /* Not true or false */
10265
if (and_level || (*cond_value == Item::COND_FALSE))
10266
*cond_value= tmp_cond_value;
10268
case Item::COND_FALSE:
10271
*cond_value= tmp_cond_value;
10272
return (COND *) NULL; /* Always false */
10275
case Item::COND_TRUE:
10278
*cond_value= tmp_cond_value;
10279
return (COND *) NULL; /* Always true */
10282
case Item::COND_UNDEF: /* Impossible */
10283
break; /* purecov: deadcode */
10300
10287
if (should_fix_fields)
10301
10288
cond->update_used_tables();
10303
if (!((Item_cond*) cond)->argument_list()->elements ||
10304
*cond_value != Item::COND_OK)
10290
if (! ((Item_cond*) cond)->argument_list()->elements || *cond_value != Item::COND_OK)
10291
return (COND*) NULL;
10306
10293
if (((Item_cond*) cond)->argument_list()->elements == 1)
10295
/* Argument list contains only one element, so reduce it so a single item, then remove list */
10308
10296
item= ((Item_cond*) cond)->argument_list()->head();
10309
10297
((Item_cond*) cond)->argument_list()->empty();
10313
else if (cond->type() == Item::FUNC_ITEM &&
10314
((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
10301
else if (cond->type() == Item::FUNC_ITEM && ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
10317
10304
Handles this special case for some ODBC applications:
10323
10310
SELECT * from table_name where auto_increment_column = LAST_INSERT_ID
10326
Item_func_isnull *func=(Item_func_isnull*) cond;
10313
Item_func_isnull *func= (Item_func_isnull*) cond;
10327
10314
Item **args= func->arguments();
10328
10315
if (args[0]->type() == Item::FIELD_ITEM)
10330
Field *field=((Item_field*) args[0])->field;
10331
if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null &&
10332
(thd->options & OPTION_AUTO_IS_NULL) &&
10333
(thd->first_successful_insert_id_in_prev_stmt > 0 &&
10334
thd->substitute_null_with_insert_id))
10317
Field *field= ((Item_field*) args[0])->field;
10318
if (field->flags & AUTO_INCREMENT_FLAG
10319
&& ! field->table->maybe_null
10320
&& session->options & OPTION_AUTO_IS_NULL
10322
session->first_successful_insert_id_in_prev_stmt > 0
10323
&& session->substitute_null_with_insert_id
10337
if ((new_cond= new Item_func_eq(args[0],
10338
new Item_int("last_insert_id()",
10339
thd->read_first_successful_insert_id_in_prev_stmt(),
10340
MY_INT64_NUM_DECIMAL_DIGITS))))
10328
if ((new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()",
10329
session->read_first_successful_insert_id_in_prev_stmt(),
10330
MY_INT64_NUM_DECIMAL_DIGITS))))
10344
10334
Item_func_eq can't be fixed after creation so we do not check
10345
10335
cond->fixed, also it do not need tables so we use 0 as second
10348
cond->fix_fields(thd, &cond);
10338
cond->fix_fields(session, &cond);
10351
10341
IS NULL should be mapped to LAST_INSERT_ID only for first row, so
10352
10342
clear for next row
10354
thd->substitute_null_with_insert_id= false;
10344
session->substitute_null_with_insert_id= false;
10356
10347
/* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
10357
else if (((field->type() == DRIZZLE_TYPE_NEWDATE) ||
10358
(field->type() == DRIZZLE_TYPE_DATETIME)) &&
10359
(field->flags & NOT_NULL_FLAG) &&
10360
!field->table->maybe_null)
10349
((field->type() == DRIZZLE_TYPE_DATE) || (field->type() == DRIZZLE_TYPE_DATETIME))
10350
&& (field->flags & NOT_NULL_FLAG)
10351
&& ! field->table->maybe_null)
10363
if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
10354
if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
10367
10358
Item_func_eq can't be fixed after creation so we do not check
10368
10359
cond->fixed, also it do not need tables so we use 0 as second
10371
cond->fix_fields(thd, &cond);
10362
cond->fix_fields(session, &cond);
10365
#endif /* NOTDEFINED */
10375
10367
if (cond->const_item())
10377
10369
*cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10370
return (COND *) NULL;
10381
10373
else if (cond->const_item() && !cond->is_expensive())
10393
10385
*cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10386
return (COND *) NULL;
10396
10388
else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
10397
{ // boolan compare function
10390
/* boolan compare function */
10398
10391
Item *left_item= ((Item_func*) cond)->arguments()[0];
10399
10392
Item *right_item= ((Item_func*) cond)->arguments()[1];
10400
10393
if (left_item->eq(right_item,1))
10402
if (!left_item->maybe_null ||
10403
((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
10404
return (COND*) 0; // Compare of identical items
10395
if (!left_item->maybe_null || ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
10396
return (COND*) NULL; /* Comparison of identical items */
10407
*cond_value=Item::COND_OK;
10408
return cond; // Point at next and level
10399
*cond_value= Item::COND_OK;
10400
return cond; /* Point at next and return into recursion */
10412
10404
Check if equality can be used in removing components of GROUP BY/DISTINCT
10415
10407
test_if_equality_guarantees_uniqueness()
10416
10408
l the left comparison argument (a field if any)
10417
10409
r the right comparison argument (a const of any)
10420
Checks if an equality predicate can be used to take away
10421
DISTINCT/GROUP BY because it is known to be true for exactly one
10412
Checks if an equality predicate can be used to take away
10413
DISTINCT/GROUP BY because it is known to be true for exactly one
10422
10414
distinct value (e.g. <expr> == <const>).
10423
Arguments must be of the same type because e.g.
10424
<string_field> = <int_const> may match more than 1 distinct value from
10426
We must take into consideration and the optimization done for various
10415
Arguments must be of the same type because e.g.
10416
<string_field> = <int_const> may match more than 1 distinct value from
10418
We must take into consideration and the optimization done for various
10427
10419
string constants when compared to dates etc (see Item_int_with_ref) as
10428
10420
well as the collation of the arguments.
10431
10423
true can be used
10432
10424
false cannot be used
12031
12027
enum_nested_loop_state
12032
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12033
bool end_of_records)
12028
end_write(JOIN *join, JOIN_TAB *,
12029
bool end_of_records)
12035
12031
Table *table=join->tmp_table;
12037
if (join->thd->killed) // Aborted by user
12033
if (join->session->killed) // Aborted by user
12039
join->thd->send_kill_message();
12035
join->session->send_kill_message();
12040
12036
return(NESTED_LOOP_KILLED); /* purecov: inspected */
12042
12038
if (!end_of_records)
12044
12040
copy_fields(&join->tmp_table_param);
12045
12041
copy_funcs(join->tmp_table_param.items_to_copy);
12046
#ifdef TO_BE_DELETED
12047
if (!table->uniques) // If not unique handling
12049
/* Copy null values from group to row */
12051
for (group=table->group ; group ; group=group->next)
12053
Item *item= *group->item;
12054
if (item->maybe_null)
12056
Field *field=item->get_tmp_table_field();
12057
field->ptr[-1]= (unsigned char) (field->is_null() ? 1 : 0);
12062
12042
if (!join->having || join->having->val_int())
12344
12324
@note Because of current requirements for semijoin flattening, we do not
12345
12325
need to recurse here, hence this function will only examine the top-level
12346
AND conditions. (see JOIN::prepare, comment above the line
12326
AND conditions. (see JOIN::prepare, comment above the line
12347
12327
'if (do_materialize)'
12349
12329
@param join The top-level query.
12350
12330
@param old_cond The expression to be replaced.
12351
12331
@param new_cond The expression to be substituted.
12352
@param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for
12332
@param do_fix_fields If true, Item::fix_fields(Session*, Item**) is called for
12353
12333
the new expression.
12354
12334
@return <code>true</code> if there was an error, <code>false</code> if
12357
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
12337
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
12358
12338
Item *new_cond, bool do_fix_fields)
12360
12340
if (join->conds == old_cond) {
12361
12341
join->conds= new_cond;
12362
12342
if (do_fix_fields)
12363
new_cond->fix_fields(join->thd, &join->conds);
12343
new_cond->fix_fields(join->session, &join->conds);
12364
12344
return false;
12367
12347
if (join->conds->type() == Item::COND_ITEM) {
12368
12348
List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
12370
12350
while ((item= li++))
12371
if (item == old_cond)
12351
if (item == old_cond)
12373
12353
li.replace(new_cond);
12374
12354
if (do_fix_fields)
12375
new_cond->fix_fields(join->thd, li.ref());
12355
new_cond->fix_fields(join->session, li.ref());
12376
12356
return false;
12952
12932
if (tab->ref.key >= 0)
12955
We'll use ref access method on key new_ref_key. In general case
12935
We'll use ref access method on key new_ref_key. In general case
12956
12936
the index search tuple for new_ref_key will be different (e.g.
12957
12937
when one index is defined as (part1, part2, ...) and another as
12958
(part1, part2(N), ...) and the WHERE clause contains
12959
"part1 = const1 AND part2=const2".
12938
(part1, part2(N), ...) and the WHERE clause contains
12939
"part1 = const1 AND part2=const2".
12960
12940
So we build tab->ref from scratch here.
12962
12942
KEYUSE *keyuse= tab->keyuse;
12963
12943
while (keyuse->key != new_ref_key && keyuse->table == tab->table)
12966
if (create_ref_for_key(tab->join, tab, keyuse,
12946
if (create_ref_for_key(tab->join, tab, keyuse,
12967
12947
tab->join->const_table_map))
13056
13036
for (nr=0; nr < table->s->keys ; nr++)
13058
13038
int direction;
13059
if (keys.is_set(nr) &&
13039
if (keys.test(nr) &&
13060
13040
(direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
13062
bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13042
bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13065
13045
Don't use an index scan with order_st BY without limit.
13066
13046
For GROUP BY without limit always use index scan
13067
if there is a suitable index.
13047
if there is a suitable index.
13068
13048
Why we hold to this asymmetry hardly can be explained
13069
13049
rationally. It's easy to demonstrate that using
13070
13050
temporary table + filesort could be cheaper for grouping
13073
13053
if (is_covering ||
13074
select_limit != HA_POS_ERROR ||
13054
select_limit != HA_POS_ERROR ||
13075
13055
(ref_key < 0 && (group || table->force_index)))
13077
13057
double rec_per_key;
13078
13058
double index_scan_time;
13079
13059
KEY *keyinfo= tab->table->key_info+nr;
13153
13133
best_key_parts= keyinfo->key_parts;
13154
13134
best_records= quick_records;
13155
13135
is_best_covering= is_covering;
13156
best_key_direction= direction;
13136
best_key_direction= direction;
13162
13142
if (best_key >= 0)
13164
13144
bool quick_created= false;
13165
if (table->quick_keys.is_set(best_key) && best_key != ref_key)
13145
if (table->quick_keys.test(best_key) && best_key != ref_key)
13168
map.clear_all(); // Force the creation of quick select
13169
map.set_bit(best_key); // only best_key.
13171
select->test_quick_select(join->thd, map, 0,
13148
test_map.reset(); // Force the creation of quick select
13149
test_map.set(best_key); // only best_key.
13151
select->test_quick_select(join->session, test_map, 0,
13172
13152
join->select_options & OPTION_FOUND_ROWS ?
13173
13153
HA_POS_ERROR :
13174
13154
join->unit->select_limit_cnt,
13334
13314
is going to be used as it is applied now only for one table queries
13335
13315
with covering indexes.
13337
if ((order != join->group_list ||
13317
if ((order != join->group_list ||
13338
13318
!(join->select_options & SELECT_BIG_RESULT) ||
13339
13319
(select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
13340
test_if_skip_sort_order(tab,order,select_limit,0,
13320
test_if_skip_sort_order(tab,order,select_limit,0,
13341
13321
is_order_by ? &table->keys_in_use_for_order_by :
13342
13322
&table->keys_in_use_for_group_by))
13344
13324
for (order_st *ord= join->order; ord; ord= ord->next)
13346
if (!(join->sortorder=
13326
if (!(join->sortorder=
13347
13327
make_unireg_sortorder(order, &length, join->sortorder)))
13348
13328
goto err; /* purecov: inspected */
13350
table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE),
13351
MYF(MY_WME | MY_ZEROFILL));
13330
table->sort.io_cache= new IO_CACHE;
13331
memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
13352
13332
table->status=0; // May be wrong if quick_select
13354
13334
// If table has a range, move it to select
13455
13435
field_count++;
13458
if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having)
13438
if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having)
13459
13439
{ // only const items with no OPTION_FOUND_ROWS
13460
13440
join->unit->select_limit_cnt= 1; // Only send first row
13463
13443
Field **first_field=entry->field+entry->s->fields - field_count;
13464
offset= (field_count ?
13444
offset= (field_count ?
13465
13445
entry->field[entry->s->fields - field_count]->
13466
13446
offset(entry->record[0]) : 0);
13467
reclength=entry->s->reclength-offset;
13447
reclength= entry->s->reclength-offset;
13469
13449
free_io_cache(entry); // Safety
13470
13450
entry->file->info(HA_STATUS_VARIABLE);
13471
if (entry->s->db_type() == heap_hton ||
13451
if (entry->s->db_type() == heap_engine ||
13472
13452
(!entry->s->blob_fields &&
13473
13453
((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
13474
thd->variables.sortbuff_size)))
13475
error=remove_dup_with_hash_index(join->thd, entry,
13454
session->variables.sortbuff_size)))
13455
error= remove_dup_with_hash_index(join->session, entry,
13476
13456
field_count, first_field,
13477
13457
reclength, having);
13479
error=remove_dup_with_compare(join->thd, entry, first_field, offset,
13459
error= remove_dup_with_compare(join->session, entry, first_field, offset,
13482
13462
free_blobs(first_field);
13575
13555
Note that this will not work on tables with blobs!
13578
static int remove_dup_with_hash_index(THD *thd, Table *table,
13558
static int remove_dup_with_hash_index(Session *session, Table *table,
13579
13559
uint32_t field_count,
13580
13560
Field **first_field,
13561
uint32_t key_length,
13582
13562
Item *having)
13584
13564
unsigned char *key_buffer, *key_pos, *record=table->record[0];
13586
13566
handler *file= table->file;
13587
ulong extra_length= ALIGN_SIZE(key_length)-key_length;
13567
uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
13588
13568
uint32_t *field_lengths,*field_length;
13591
13571
if (!my_multi_malloc(MYF(MY_WME),
13593
(uint) ((key_length + extra_length) *
13573
(uint32_t) ((key_length + extra_length) *
13594
13574
(long) file->stats.records),
13595
13575
&field_lengths,
13596
(uint) (field_count*sizeof(*field_lengths)),
13576
(uint32_t) (field_count*sizeof(*field_lengths)),
13602
ulong total_length= 0;
13582
uint32_t total_length= 0;
13603
13583
for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
13605
13585
uint32_t length= (*ptr)->sort_length();
14767
14744
if (!(pos= new Item_copy_string(pos)))
14770
Item_copy_string::copy for function can call
14747
Item_copy_string::copy for function can call
14771
14748
Item_copy_string::val_int for blob via Item_ref.
14772
14749
But if Item_copy_string::copy for blob isn't called before,
14773
14750
it's value will be wrong
14774
so let's insert Item_copy_string for blobs in the beginning of
14751
so let's insert Item_copy_string for blobs in the beginning of
14776
(to see full test case look at having.test, BUG #4358)
14753
(to see full test case look at having.test, BUG #4358)
14778
14755
if (param->copy_funcs.push_front(pos))
14784
set up save buffer and change result_field to point at
14761
set up save buffer and change result_field to point at
14787
14764
field= item->field;
14788
item->result_field=field->new_field(thd->mem_root,field->table, 1);
14765
item->result_field=field->new_field(session->mem_root,field->table, 1);
14790
14767
We need to allocate one extra byte for null handling and
14791
14768
another extra byte to not get warnings from purify in
16040
16015
if (tab->use_quick == 2)
16042
/* 4 bits per 1 hex digit + terminating '\0' */
16043
char buf[MAX_KEY / 4 + 1];
16018
* To print out the bitset in tab->keys, we go through
16019
* it 32 bits at a time. We need to do this to ensure
16020
* that the to_ulong() method will not throw an
16021
* out_of_range exception at runtime which would happen
16022
* if the bitset we were working with was larger than 64
16023
* bits on a 64-bit platform (for example).
16029
for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
16031
bitset<32> tmp(str, pos, 32);
16033
s << uppercase << hex << tmp.to_ulong();
16044
16035
extra.append(STRING_WITH_LEN("; Range checked for each "
16045
16036
"record (index map: 0x"));
16046
extra.append(tab->keys.print(buf));
16037
extra.append(s.str().c_str());
16047
16038
extra.append(')');
16049
16040
else if (tab->select->cond)
16051
16042
const COND *pushed_cond= tab->table->file->pushed_cond;
16053
if (thd->variables.engine_condition_pushdown && pushed_cond)
16044
if (session->variables.engine_condition_pushdown && pushed_cond)
16055
16046
extra.append(STRING_WITH_LEN("; Using where with pushed "
16056
16047
"condition"));
16057
if (thd->lex->describe & DESCRIBE_EXTENDED)
16048
if (session->lex->describe & DESCRIBE_EXTENDED)
16059
16050
extra.append(STRING_WITH_LEN(": "));
16060
16051
((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
16167
16158
join->error= 1;
16170
for (SELECT_LEX_UNIT *unit= join->select_lex->first_inner_unit();
16161
for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
16172
16163
unit= unit->next_unit())
16174
if (mysql_explain_union(thd, unit, result))
16165
if (mysql_explain_union(session, unit, result))
16181
bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result)
16172
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
16184
SELECT_LEX *first= unit->first_select();
16175
Select_Lex *first= unit->first_select();
16186
for (SELECT_LEX *sl= first;
16177
for (Select_Lex *sl= first;
16188
16179
sl= sl->next_select())
16190
16181
// drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
16191
16182
uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
16192
sl->type= (((&thd->lex->select_lex)==sl)?
16193
(sl->first_inner_unit() || sl->next_select() ?
16183
sl->type= (((&session->lex->select_lex)==sl)?
16184
(sl->first_inner_unit() || sl->next_select() ?
16194
16185
"PRIMARY" : "SIMPLE"):
16195
16186
((sl == first)?
16196
16187
((sl->linkage == DERIVED_TABLE_TYPE) ?
16210
16201
unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
16211
16202
unit->fake_select_lex->type= "UNION RESULT";
16212
16203
unit->fake_select_lex->options|= SELECT_DESCRIBE;
16213
if (!(res= unit->prepare(thd, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
16204
if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
16214
16205
res= unit->exec();
16215
16206
res|= unit->cleanup();
16219
thd->lex->current_select= first;
16210
session->lex->current_select= first;
16220
16211
unit->set_limit(unit->global_parameters);
16221
res= mysql_select(thd, &first->ref_pointer_array,
16212
res= mysql_select(session, &first->ref_pointer_array,
16222
16213
(TableList*) first->table_list.first,
16223
16214
first->with_wild, first->item_list,
16224
16215
first->where,
16227
16218
(order_st*) first->order_list.first,
16228
16219
(order_st*) first->group_list.first,
16229
16220
first->having,
16230
(order_st*) thd->lex->proc_list.first,
16231
first->options | thd->options | SELECT_DESCRIBE,
16221
first->options | session->options | SELECT_DESCRIBE,
16232
16222
result, unit, first);
16234
return(res || thd->is_error());
16224
return(res || session->is_error());
16238
static void print_table_array(THD *thd, String *str, TableList **table,
16228
static void print_table_array(Session *session, String *str, TableList **table,
16239
16229
TableList **end)
16241
(*table)->print(thd, str, QT_ORDINARY);
16231
(*table)->print(session, str, QT_ORDINARY);
16243
16233
for (TableList **tbl= table + 1; tbl < end; tbl++)
16269
16259
Print joins from the FROM clause.
16270
@param thd thread handler
16260
@param session thread handler
16271
16261
@param str string where table should be printed
16272
16262
@param tables list of tables in join
16273
16263
@query_type type of the query is being generated
16276
static void print_join(THD *thd,
16278
List<TableList> *tables,
16279
enum_query_type query_type __attribute__((unused)))
16266
static void print_join(Session *session, String *str,
16267
List<TableList> *tables, enum_query_type)
16281
16269
/* List is reversed => we should reverse it before using */
16282
16270
List_iterator_fast<TableList> ti(*tables);
16283
TableList **table= (TableList **)thd->alloc(sizeof(TableList*) *
16271
TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
16284
16272
tables->elements);
16285
16273
if (table == 0)
16286
16274
return; // out of memory
16288
16276
for (TableList **t= table + (tables->elements - 1); t >= table; t--)
16292
16280
If the first table is a semi-join nest, swap it with something that is
16293
16281
not a semi-join nest.
16309
16297
assert(tables->elements >= 1);
16310
print_table_array(thd, str, table, table + tables->elements);
16315
@brief Print an index hint
16317
@details Prints out the USE|FORCE|IGNORE index hint.
16319
@param thd the current thread
16320
@param[out] str appends the index hint here
16321
@param hint what the hint is (as string : "USE INDEX"|
16322
"FORCE INDEX"|"IGNORE INDEX")
16323
@param hint_length the length of the string in 'hint'
16324
@param indexes a list of index names for the hint
16328
Index_hint::print(THD *thd, String *str)
16332
case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
16333
case INDEX_HINT_USE: str->append(STRING_WITH_LEN("USE INDEX")); break;
16334
case INDEX_HINT_FORCE: str->append(STRING_WITH_LEN("FORCE INDEX")); break;
16336
str->append (STRING_WITH_LEN(" ("));
16337
if (key_name.length)
16339
if (thd && !my_strnncoll(system_charset_info,
16340
(const unsigned char *)key_name.str, key_name.length,
16341
(const unsigned char *)primary_key_name,
16342
strlen(primary_key_name)))
16343
str->append(primary_key_name);
16345
append_identifier(thd, str, key_name.str, key_name.length);
16298
print_table_array(session, str, table, table + tables->elements);
16352
16302
Print table as it should be in join list.
16354
16304
@param str string where table should be printed
16357
void TableList::print(THD *thd, String *str, enum_query_type query_type)
16306
void TableList::print(Session *session, String *str, enum_query_type query_type)
16359
16308
if (nested_join)
16361
16310
str->append('(');
16362
print_join(thd, str, &nested_join->join_list, query_type);
16311
print_join(session, str, &nested_join->join_list, query_type);
16363
16312
str->append(')');
16378
16327
// A normal table
16380
append_identifier(thd, str, db, db_length);
16329
str->append_identifier(db, db_length);
16381
16330
str->append('.');
16383
16332
if (schema_table)
16385
append_identifier(thd, str, schema_table_name,
16386
strlen(schema_table_name));
16334
str->append_identifier(schema_table_name, strlen(schema_table_name));
16387
16335
cmp_name= schema_table_name;
16391
append_identifier(thd, str, table_name, table_name_length);
16339
str->append_identifier(table_name, table_name_length);
16392
16340
cmp_name= table_name;
16395
16343
if (my_strcasecmp(table_alias_charset, cmp_name, alias))
16397
char t_alias_buff[MAX_ALIAS_NAME];
16398
const char *t_alias= alias;
16401
if (lower_case_table_names== 1)
16346
if (alias && alias[0])
16403
if (alias && alias[0])
16405
my_stpcpy(t_alias_buff, alias);
16406
my_casedn_str(files_charset_info, t_alias_buff);
16407
t_alias= t_alias_buff;
16350
string t_alias(alias);
16351
if (lower_case_table_names== 1)
16352
transform(t_alias.begin(), t_alias.end(),
16353
t_alias.begin(), ::tolower);
16355
str->append_identifier(t_alias.c_str(), t_alias.length());
16411
append_identifier(thd, str, t_alias, strlen(t_alias));
16414
16360
if (index_hints)
16419
16365
while ((hint= it++))
16421
16367
str->append (STRING_WITH_LEN(" "));
16422
hint->print (thd, str);
16368
hint->print (session, str);
16429
void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
16375
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
16431
/* QQ: thd may not be set for sub queries, but this should be fixed */
16377
/* QQ: session may not be set for sub queries, but this should be fixed */
16379
session= current_session;
16435
16381
str->append(STRING_WITH_LEN("select "));
16437
16383
/* First add options */
16438
16384
if (options & SELECT_STRAIGHT_JOIN)
16439
16385
str->append(STRING_WITH_LEN("straight_join "));
16440
if ((thd->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
16441
(this == &thd->lex->select_lex))
16386
if ((session->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
16387
(this == &session->lex->select_lex))
16442
16388
str->append(STRING_WITH_LEN("high_priority "));
16443
16389
if (options & SELECT_DISTINCT)
16444
16390
str->append(STRING_WITH_LEN("distinct "));