45
42
#include "drizzled/join_cache.h"
46
43
#include "drizzled/show.h"
47
44
#include "drizzled/field/blob.h"
48
#include "drizzled/optimizer/position.h"
49
#include "drizzled/optimizer/sargable_param.h"
50
#include "drizzled/optimizer/key_use.h"
51
#include "drizzled/optimizer/range.h"
52
#include "drizzled/optimizer/sum.h"
53
#include "drizzled/optimizer/explain_plan.h"
54
#include "drizzled/optimizer/access_method_factory.h"
55
#include "drizzled/optimizer/access_method.h"
56
#include "drizzled/records.h"
57
#include "drizzled/probes.h"
58
#include "drizzled/internal/my_bit.h"
59
#include "drizzled/internal/my_sys.h"
60
#include "drizzled/internal/iocache.h"
45
#include "mysys/my_bit.h"
62
47
#include <algorithm>
64
49
using namespace std;
69
extern plugin::StorageEngine *heap_engine;
70
extern std::bitset<12> test_flags;
72
51
/** Declarations of static functions used in this source file. */
73
static bool make_group_fields(Join *main_join, Join *curr_join);
74
static void calc_group_buffer(Join *join, Order *group);
75
static bool alloc_group_fields(Join *join, Order *group);
76
static uint32_t cache_record_length(Join *join, uint32_t index);
77
static double prev_record_reads(Join *join, uint32_t idx, table_map found_ref);
78
static bool get_best_combination(Join *join);
79
static void set_position(Join *join,
82
optimizer::KeyUse *key);
83
static bool choose_plan(Join *join,table_map join_tables);
84
static void best_access_path(Join *join, JoinTable *s,
52
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
53
static void calc_group_buffer(JOIN *join,order_st *group);
54
static bool alloc_group_fields(JOIN *join,order_st *group);
56
TODO: 'find_best' is here only temporarily until 'greedy_search' is
59
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index, double record_count,double read_time);
60
static uint32_t cache_record_length(JOIN *join, uint32_t index);
61
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
62
static bool get_best_combination(JOIN *join);
63
static void set_position(JOIN *join,uint32_t index,JoinTable *table,KeyUse *key);
64
static bool choose_plan(JOIN *join,table_map join_tables);
65
static void best_access_path(JOIN *join, JoinTable *s,
86
67
table_map remaining_tables,
88
69
double record_count,
90
static void optimize_straight_join(Join *join, table_map join_tables);
91
static bool greedy_search(Join *join, table_map remaining_tables, uint32_t depth, uint32_t prune_level);
92
static bool best_extension_by_limited_search(Join *join,
71
static void optimize_straight_join(JOIN *join, table_map join_tables);
72
static bool greedy_search(JOIN *join, table_map remaining_tables, uint32_t depth, uint32_t prune_level);
73
static bool best_extension_by_limited_search(JOIN *join,
93
74
table_map remaining_tables,
95
76
double record_count,
98
79
uint32_t prune_level);
99
static uint32_t determine_search_depth(Join* join);
100
static bool make_simple_join(Join *join,Table *tmp_table);
101
static void make_outerjoin_info(Join *join);
102
static bool make_join_select(Join *join, optimizer::SqlSelect *select,COND *item);
103
static bool make_join_readinfo(Join *join);
104
static void update_depend_map(Join *join);
105
static void update_depend_map(Join *join, Order *order);
106
static Order *remove_constants(Join *join,Order *first_order,COND *cond, bool change_list, bool *simple_order);
107
static int return_zero_rows(Join *join,
80
static uint32_t determine_search_depth(JOIN* join);
81
static bool make_simple_join(JOIN *join,Table *tmp_table);
82
static void make_outerjoin_info(JOIN *join);
83
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
84
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
85
static void update_depend_map(JOIN *join);
86
static void update_depend_map(JOIN *join, order_st *order);
87
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond, bool change_list, bool *simple_order);
88
static int return_zero_rows(JOIN *join,
108
89
select_result *res,
109
90
TableList *tables,
110
91
List<Item> &fields,
2894
2848
We can't copy all data as the key may have different format
2895
2849
as the row data (for example as with VARCHAR keys)
2897
KeyPartInfo *key_part;
2851
KEY_PART_INFO *key_part;
2898
2852
for (group=table->group,key_part=table->key_info[0].key_part;
2900
2854
group=group->next,key_part++)
2902
2856
if (key_part->null_bit)
2903
memcpy(table->getInsertRecord()+key_part->offset, group->buff, 1);
2857
memcpy(table->record[0]+key_part->offset, group->buff, 1);
2905
2859
init_tmptable_sum_functions(join->sum_funcs);
2906
if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
2907
return NESTED_LOOP_ERROR;
2908
if ((error=table->cursor->insertRecord(table->getInsertRecord())))
2860
copy_funcs(join->tmp_table_param.items_to_copy);
2861
if ((error=table->file->ha_write_row(table->record[0])))
2910
my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
2911
return NESTED_LOOP_ERROR; // Table is_full error
2863
if (create_myisam_from_heap(join->session, table,
2864
join->tmp_table_param.start_recinfo,
2865
&join->tmp_table_param.recinfo,
2867
return NESTED_LOOP_ERROR; // Not a table_is_full error
2868
/* Change method to update rows */
2869
table->file->ha_index_init(0, 0);
2870
join->join_tab[join->tables-1].next_select= end_unique_update;
2913
2872
join->send_records++;
2914
2873
return NESTED_LOOP_OK;
2917
2876
/** Like end_update, but this is done with unique constraints instead of keys. */
2918
enum_nested_loop_state end_unique_update(Join *join, JoinTable *, bool end_of_records)
2877
enum_nested_loop_state end_unique_update(JOIN *join, JoinTable *, bool end_of_records)
2920
2879
Table *table= join->tmp_table;
2923
2882
if (end_of_records)
2924
2883
return NESTED_LOOP_OK;
2925
if (join->session->getKilled()) // Aborted by user
2884
if (join->session->killed) // Aborted by user
2927
2886
join->session->send_kill_message();
2928
return NESTED_LOOP_KILLED;
2887
return NESTED_LOOP_KILLED; /* purecov: inspected */
2931
2890
init_tmptable_sum_functions(join->sum_funcs);
2932
2891
copy_fields(&join->tmp_table_param); // Groups are copied twice.
2933
if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
2934
return NESTED_LOOP_ERROR;
2892
copy_funcs(join->tmp_table_param.items_to_copy);
2936
if (!(error= table->cursor->insertRecord(table->getInsertRecord())))
2894
if (!(error= table->file->ha_write_row(table->record[0])))
2937
2895
join->send_records++; // New group
2940
if ((int) table->get_dup_key(error) < 0)
2898
if ((int) table->file->get_dup_key(error) < 0)
2942
table->print_error(error,MYF(0));
2943
return NESTED_LOOP_ERROR;
2900
table->file->print_error(error,MYF(0)); /* purecov: inspected */
2901
return NESTED_LOOP_ERROR; /* purecov: inspected */
2945
if (table->cursor->rnd_pos(table->getUpdateRecord(),table->cursor->dup_ref))
2903
if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
2947
table->print_error(error,MYF(0));
2948
return NESTED_LOOP_ERROR;
2905
table->file->print_error(error,MYF(0)); /* purecov: inspected */
2906
return NESTED_LOOP_ERROR; /* purecov: inspected */
2950
2908
table->restoreRecord();
2951
2909
update_tmptable_sum_func(join->sum_funcs,table);
2952
if ((error= table->cursor->updateRecord(table->getUpdateRecord(),
2953
table->getInsertRecord())))
2910
if ((error= table->file->ha_update_row(table->record[1],
2955
table->print_error(error,MYF(0));
2956
return NESTED_LOOP_ERROR;
2913
table->file->print_error(error,MYF(0)); /* purecov: inspected */
2914
return NESTED_LOOP_ERROR; /* purecov: inspected */
2959
2917
return NESTED_LOOP_OK;
3094
static uint32_t cache_record_length(Join *join,uint32_t idx)
3047
- TODO: this function is here only temporarily until 'greedy_search' is
3048
tested and accepted.
3054
static bool find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count, double read_time)
3056
Session *session= join->session;
3057
if (session->killed)
3061
read_time+=record_count/(double) TIME_FOR_COMPARE;
3062
if (join->sort_by_table &&
3063
join->sort_by_table !=
3064
join->positions[join->const_tables].table->table)
3065
read_time+=record_count; // We have to make a temp table
3066
if (read_time < join->best_read)
3068
memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
3069
join->best_read= read_time - 0.001;
3073
if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
3074
return(false); /* Found better before */
3077
double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
3078
for (JoinTable **pos=join->best_ref+idx ; (s=*pos) ; pos++)
3080
table_map real_table_bit=s->table->map;
3081
if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent) &&
3082
(!idx|| !check_interleaving_with_nj(join->positions[idx-1].table, s)))
3084
double records, best;
3085
best_access_path(join, s, session, rest_tables, idx, record_count,
3087
records= join->positions[idx].records_read;
3088
best= join->positions[idx].read_time;
3090
Go to the next level only if there hasn't been a better key on
3091
this level! This will cut down the search for a lot simple cases!
3093
double current_record_count=record_count*records;
3094
double current_read_time=read_time+best;
3095
if (best_record_count > current_record_count ||
3096
best_read_time > current_read_time ||
3097
(idx == join->const_tables && s->table == join->sort_by_table))
3099
if (best_record_count >= current_record_count &&
3100
best_read_time >= current_read_time &&
3101
(!(s->key_dependent & rest_tables) || records < 2.0))
3103
best_record_count=current_record_count;
3104
best_read_time=current_read_time;
3106
std::swap(join->best_ref[idx], *pos);
3107
if (find_best(join,rest_tables & ~real_table_bit,idx+1,
3108
current_record_count,current_read_time))
3110
std::swap(join->best_ref[idx], *pos);
3112
restore_prev_nj_state(s);
3113
if (join->select_options & SELECT_STRAIGHT_JOIN)
3114
break; // Don't test all combinations
3120
static uint32_t cache_record_length(JOIN *join,uint32_t idx)
3096
3122
uint32_t length=0;
3097
3123
JoinTable **pos,**end;
3413
3445
if 1. expression doesn't refer to forward tables
3414
3446
2. we won't get two ref-or-null's
3416
if (! (remaining_tables & keyuse->getUsedTables()) &&
3417
! (ref_or_null_part && (keyuse->getOptimizeFlags() &
3418
KEY_OPTIMIZE_REF_OR_NULL)))
3448
if (!(remaining_tables & keyuse->used_tables) &&
3449
!(ref_or_null_part && (keyuse->optimize &
3450
KEY_OPTIMIZE_REF_OR_NULL)))
3420
found_part|= keyuse->getKeypartMap();
3421
if (! (keyuse->getUsedTables() & ~join->const_table_map))
3422
const_part|= keyuse->getKeypartMap();
3452
found_part|= keyuse->keypart_map;
3453
if (!(keyuse->used_tables & ~join->const_table_map))
3454
const_part|= keyuse->keypart_map;
3424
3456
double tmp2= prev_record_reads(join, idx, (found_ref |
3425
keyuse->getUsedTables()));
3457
keyuse->used_tables));
3426
3458
if (tmp2 < best_prev_record_reads)
3428
best_part_found_ref= keyuse->getUsedTables() & ~join->const_table_map;
3460
best_part_found_ref= keyuse->used_tables & ~join->const_table_map;
3429
3461
best_prev_record_reads= tmp2;
3431
if (rec > keyuse->getTableRows())
3432
rec= keyuse->getTableRows();
3463
if (rec > keyuse->ref_table_rows)
3464
rec= keyuse->ref_table_rows;
3434
3466
If there is one 'key_column IS NULL' expression, we can
3435
3467
use this ref_or_null optimisation of this field
3437
if (keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)
3438
ref_or_null_part|= keyuse->getKeypartMap();
3469
if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)
3470
ref_or_null_part |= keyuse->keypart_map;
3442
} while (keyuse->getTable() == table && keyuse->getKey() == key &&
3443
keyuse->getKeypart() == keypart);
3444
found_ref|= best_part_found_ref;
3445
} while (keyuse->getTable() == table && keyuse->getKey() == key);
3474
} while (keyuse->table == table && keyuse->key == key &&
3475
keyuse->keypart == keypart);
3476
found_ref|= best_part_found_ref;
3477
} while (keyuse->table == table && keyuse->key == key);
3448
3480
Assume that that each key matches a proportional part of table.
4523
4536
if (join->tables > 1)
4524
4537
cond->update_used_tables(); // Tablenr may have changed
4525
4538
if (join->const_tables == join->tables &&
4526
session->lex->current_select->master_unit() ==
4527
&session->lex->unit) // not upper level SELECT
4539
session->lex->current_select->master_unit() ==
4540
&session->lex->unit) // not upper level SELECT
4528
4541
join->const_table_map|=RAND_TABLE_BIT;
4529
4542
{ // Check const tables
4530
4543
COND *const_cond=
4531
make_cond_for_table(cond,
4532
join->const_table_map,
4544
make_cond_for_table(cond,
4545
join->const_table_map,
4534
4547
for (JoinTable *tab= join->join_tab+join->const_tables;
4535
tab < join->join_tab+join->tables ; tab++)
4548
tab < join->join_tab+join->tables ; tab++)
4537
4550
if (*tab->on_expr_ref)
4539
4552
JoinTable *cond_tab= tab->first_inner;
4540
4553
COND *tmp= make_cond_for_table(*tab->on_expr_ref,
4541
join->const_table_map,
4554
join->const_table_map,
4545
4558
tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
4548
4561
tmp->quick_fix_field();
4549
4562
cond_tab->select_cond= !cond_tab->select_cond ? tmp :
4550
new Item_cond_and(cond_tab->select_cond,
4552
if (! cond_tab->select_cond)
4563
new Item_cond_and(cond_tab->select_cond,
4565
if (!cond_tab->select_cond)
4554
4567
cond_tab->select_cond->quick_fix_field();
4557
if (const_cond && ! const_cond->val_int())
4570
if (const_cond && !const_cond->val_int())
4559
return 1; // Impossible const condition
4572
return(1); // Impossible const condition
4563
4576
used_tables=((select->const_tables=join->const_table_map) |
4564
OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
4577
OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
4565
4578
for (uint32_t i=join->const_tables ; i < join->tables ; i++)
4567
4580
JoinTable *tab=join->join_tab+i;
4569
first_inner is the X in queries like:
4570
SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
4582
first_inner is the X in queries like:
4583
SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
4572
4585
JoinTable *first_inner_tab= tab->first_inner;
4573
4586
table_map current_map= tab->table->map;
4574
4587
bool use_quick_range=0;
4578
Following force including random expression in last table condition.
4579
It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
4591
Following force including random expression in last table condition.
4592
It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
4581
4594
if (i == join->tables-1)
4582
current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
4595
current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
4583
4596
used_tables|=current_map;
4585
if (tab->type == AM_REF && tab->quick &&
4586
(uint32_t) tab->ref.key == tab->quick->index &&
4587
tab->ref.key_length < tab->quick->max_used_key_length)
4598
if (tab->type == JT_REF && tab->quick &&
4599
(uint32_t) tab->ref.key == tab->quick->index &&
4600
tab->ref.key_length < tab->quick->max_used_key_length)
4589
/* Range uses longer key; Use this instead of ref on key */
4602
/* Range uses longer key; Use this instead of ref on key */
4593
4606
tab->ref.key= -1;
4594
tab->ref.key_parts= 0; // Don't use ref key.
4595
cur_pos= join->getPosFromOptimalPlan(i);
4596
cur_pos.setFanout(rows2double(tab->quick->records));
4607
tab->ref.key_parts=0; // Don't use ref key.
4608
join->best_positions[i].records_read= rows2double(tab->quick->records);
4598
We will use join cache here : prevent sorting of the first
4599
table only and sort at the end.
4610
We will use join cache here : prevent sorting of the first
4611
table only and sort at the end.
4601
4613
if (i != join->const_tables && join->tables > join->const_tables + 1)
4602
4614
join->full_join= 1;
4607
4619
tmp= make_cond_for_table(cond,used_tables,current_map, 0);
4608
4620
if (cond && !tmp && tab->quick)
4609
4621
{ // Outer join
4610
if (tab->type != AM_ALL)
4622
if (tab->type != JT_ALL)
4613
Don't use the quick method
4614
We come here in the case where we have 'key=constant' and
4615
the test is removed by make_cond_for_table()
4625
Don't use the quick method
4626
We come here in the case where we have 'key=constant' and
4627
the test is removed by make_cond_for_table()
4617
4629
delete tab->quick;
4623
Hack to handle the case where we only refer to a table
4624
in the ON part of an OUTER JOIN. In this case we want the code
4625
below to check if we should use 'quick' instead.
4635
Hack to handle the case where we only refer to a table
4636
in the ON part of an OUTER JOIN. In this case we want the code
4637
below to check if we should use 'quick' instead.
4627
4639
tmp= new Item_int((int64_t) 1,1); // Always true
4631
if (tmp || !cond || tab->type == AM_REF || tab->type == AM_REF_OR_NULL ||
4632
tab->type == AM_EQ_REF)
4643
if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
4644
tab->type == JT_EQ_REF)
4634
optimizer::SqlSelect *sel= tab->select= ((optimizer::SqlSelect*)
4635
session->memdup((unsigned char*) select,
4638
return 1; // End of memory
4646
SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
4647
session->memdup((unsigned char*) select,
4650
return(1); // End of memory
4640
If tab is an inner table of an outer join operation,
4641
add a match guard to the pushed down predicate.
4642
The guard will turn the predicate on only after
4643
the first match for outer tables is encountered.
4652
If tab is an inner table of an outer join operation,
4653
add a match guard to the pushed down predicate.
4654
The guard will turn the predicate on only after
4655
the first match for outer tables is encountered.
4645
4657
if (cond && tmp)
4648
Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
4649
a cond, so neutralize the hack above.
4651
if (! (tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
4660
Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
4661
a cond, so neutralize the hack above.
4663
if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
4653
4665
tab->select_cond=sel->cond=tmp;
4666
/* Push condition to storage engine if this is enabled
4667
and the condition is not guarded */
4668
tab->table->file->pushed_cond= NULL;
4669
if (session->variables.engine_condition_pushdown)
4672
make_cond_for_table(tmp, current_map, current_map, 0);
4675
/* Push condition to handler */
4676
if (!tab->table->file->cond_push(push_cond))
4677
tab->table->file->pushed_cond= push_cond;
4656
4682
tab->select_cond= sel->cond= NULL;
4658
sel->head=tab->table;
4661
/* Use quick key read if it's a constant and it's not used
4663
if (tab->needed_reg.none() && tab->type != AM_EQ_REF
4664
&& (tab->type != AM_REF || (uint32_t) tab->ref.key == tab->quick->index))
4666
sel->quick=tab->quick; // Use value from get_quick_...
4667
sel->quick_keys.reset();
4668
sel->needed_reg.reset();
4676
uint32_t ref_key= static_cast<uint32_t>(sel->head->reginfo.join_tab->ref.key + 1);
4677
if (i == join->const_tables && ref_key)
4679
if (tab->const_keys.any() &&
4680
tab->table->reginfo.impossible_range)
4683
else if (tab->type == AM_ALL && ! use_quick_range)
4685
if (tab->const_keys.any() &&
4686
tab->table->reginfo.impossible_range)
4687
return 1; // Impossible range
4689
We plan to scan all rows.
4690
Check again if we should use an index.
4691
We could have used an column from a previous table in
4692
the index if we are using limit and this is the first table
4695
cur_pos= join->getPosFromOptimalPlan(i);
4696
if ((cond && (! ((tab->keys & tab->const_keys) == tab->keys) && i > 0)) ||
4697
(! tab->const_keys.none() && (i == join->const_tables) &&
4698
(join->unit->select_limit_cnt < cur_pos.getFanout()) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
4700
/* Join with outer join condition */
4701
COND *orig_cond= sel->cond;
4702
sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
4705
We can't call sel->cond->fix_fields,
4706
as it will break tab->on_expr if it's AND condition
4707
(fix_fields currently removes extra AND/OR levels).
4708
Yet attributes of the just built condition are not needed.
4709
Thus we call sel->cond->quick_fix_field for safety.
4711
if (sel->cond && ! sel->cond->fixed)
4712
sel->cond->quick_fix_field();
4714
if (sel->test_quick_select(session, tab->keys,
4715
used_tables & ~ current_map,
4716
(join->select_options &
4719
join->unit->select_limit_cnt), 0,
4684
sel->head=tab->table;
4687
/* Use quick key read if it's a constant and it's not used
4689
if (tab->needed_reg.none() && tab->type != JT_EQ_REF
4690
&& (tab->type != JT_REF || (uint32_t) tab->ref.key == tab->quick->index))
4692
sel->quick=tab->quick; // Use value from get_quick_...
4693
sel->quick_keys.reset();
4694
sel->needed_reg.reset();
4702
uint32_t ref_key=(uint32_t) sel->head->reginfo.join_tab->ref.key+1;
4703
if (i == join->const_tables && ref_key)
4705
if (tab->const_keys.any() &&
4706
tab->table->reginfo.impossible_range)
4709
else if (tab->type == JT_ALL && ! use_quick_range)
4711
if (tab->const_keys.any() &&
4712
tab->table->reginfo.impossible_range)
4713
return(1); // Impossible range
4715
We plan to scan all rows.
4716
Check again if we should use an index.
4717
We could have used an column from a previous table in
4718
the index if we are using limit and this is the first table
4721
if ((cond && (!((tab->keys & tab->const_keys) == tab->keys) && i > 0)) ||
4722
(!tab->const_keys.none() && (i == join->const_tables) && (join->unit->select_limit_cnt < join->best_positions[i].records_read) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
4724
/* Join with outer join condition */
4725
COND *orig_cond=sel->cond;
4726
sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
4729
We can't call sel->cond->fix_fields,
4730
as it will break tab->on_expr if it's AND condition
4731
(fix_fields currently removes extra AND/OR levels).
4732
Yet attributes of the just built condition are not needed.
4733
Thus we call sel->cond->quick_fix_field for safety.
4735
if (sel->cond && !sel->cond->fixed)
4736
sel->cond->quick_fix_field();
4738
if (sel->test_quick_select(session, tab->keys,
4739
used_tables & ~ current_map,
4740
(join->select_options &
4743
join->unit->select_limit_cnt), 0,
4723
Before reporting "Impossible WHERE" for the whole query
4724
we have to check isn't it only "impossible ON" instead
4747
Before reporting "Impossible WHERE" for the whole query
4748
we have to check isn't it only "impossible ON" instead
4726
4750
sel->cond=orig_cond;
4727
if (! *tab->on_expr_ref ||
4751
if (!*tab->on_expr_ref ||
4728
4752
sel->test_quick_select(session, tab->keys,
4729
used_tables & ~ current_map,
4730
(join->select_options &
4733
join->unit->select_limit_cnt),0,
4735
return 1; // Impossible WHERE
4753
used_tables & ~ current_map,
4754
(join->select_options &
4757
join->unit->select_limit_cnt),0,
4759
return(1); // Impossible WHERE
4738
sel->cond=orig_cond;
4762
sel->cond=orig_cond;
4740
/* Fix for EXPLAIN */
4743
cur_pos= join->getPosFromOptimalPlan(i);
4744
cur_pos.setFanout(static_cast<double>(sel->quick->records));
4749
sel->needed_reg= tab->needed_reg;
4750
sel->quick_keys.reset();
4764
/* Fix for EXPLAIN */
4766
join->best_positions[i].records_read= (double)sel->quick->records;
4770
sel->needed_reg=tab->needed_reg;
4771
sel->quick_keys.reset();
4752
4773
if (!((tab->checked_keys & sel->quick_keys) == sel->quick_keys) ||
4753
4774
!((tab->checked_keys & sel->needed_reg) == sel->needed_reg))
4755
tab->keys= sel->quick_keys;
4776
tab->keys= sel->quick_keys;
4756
4777
tab->keys|= sel->needed_reg;
4757
tab->use_quick= (!sel->needed_reg.none() &&
4758
(select->quick_keys.none() ||
4760
(select->quick->records >= 100L)))) ?
4762
sel->read_tables= used_tables & ~current_map;
4764
if (i != join->const_tables && tab->use_quick != 2)
4765
{ /* Read with cache */
4778
tab->use_quick= (!sel->needed_reg.none() &&
4779
(select->quick_keys.none() ||
4781
(select->quick->records >= 100L)))) ?
4783
sel->read_tables= used_tables & ~current_map;
4785
if (i != join->const_tables && tab->use_quick != 2)
4786
{ /* Read with cache */
4767
4788
(tmp=make_cond_for_table(cond,
4768
join->const_table_map |
4772
tab->cache.select= (optimizer::SqlSelect*)
4773
session->memdup((unsigned char*) sel, sizeof(optimizer::SqlSelect));
4774
tab->cache.select->cond= tmp;
4775
tab->cache.select->read_tables= join->const_table_map;
4789
join->const_table_map |
4793
tab->cache.select=(SQL_SELECT*)
4794
session->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
4795
tab->cache.select->cond=tmp;
4796
tab->cache.select->read_tables=join->const_table_map;
4782
Push down conditions from all on expressions.
4783
Each of these conditions are guarded by a variable
4784
that turns if off just before null complemented row for
4785
outer joins is formed. Thus, the condition from an
4786
'on expression' are guaranteed not to be checked for
4787
the null complemented row.
4803
Push down conditions from all on expressions.
4804
Each of these conditions are guarded by a variable
4805
that turns if off just before null complemented row for
4806
outer joins is formed. Thus, the condition from an
4807
'on expression' are guaranteed not to be checked for
4808
the null complemented row.
4790
4811
/* First push down constant conditions from on expressions */
4791
4812
for (JoinTable *join_tab= join->join_tab+join->const_tables;
4792
join_tab < join->join_tab+join->tables ; join_tab++)
4813
join_tab < join->join_tab+join->tables ; join_tab++)
4794
4815
if (*join_tab->on_expr_ref)
4796
4817
JoinTable *cond_tab= join_tab->first_inner;
4797
4818
tmp= make_cond_for_table(*join_tab->on_expr_ref,
4798
join->const_table_map,
4819
join->const_table_map,
4802
4823
tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
4805
4826
tmp->quick_fix_field();
4806
4827
cond_tab->select_cond= !cond_tab->select_cond ? tmp :
4807
new Item_cond_and(cond_tab->select_cond,tmp);
4808
if (! cond_tab->select_cond)
4828
new Item_cond_and(cond_tab->select_cond,tmp);
4829
if (!cond_tab->select_cond)
4810
4831
cond_tab->select_cond->quick_fix_field();
4887
4908
true - Out of memory
4889
static bool make_join_readinfo(Join *join)
4910
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
4913
bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
4893
for (uint32_t i= join->const_tables ; i < join->tables ; i++)
4916
for (i=join->const_tables ; i < join->tables ; i++)
4895
4918
JoinTable *tab=join->join_tab+i;
4896
4919
Table *table=tab->table;
4920
bool using_join_cache;
4897
4921
tab->read_record.table= table;
4898
tab->read_record.cursor= table->cursor;
4922
tab->read_record.file=table->file;
4899
4923
tab->next_select=sub_select; /* normal select */
4901
4925
TODO: don't always instruct first table's ref/range access method to
4902
4926
produce sorted output.
4904
4928
tab->sorted= sorted;
4905
sorted= false; // only first must be sorted
4929
sorted= 0; // only first must be sorted
4907
4930
if (tab->insideout_match_tab)
4909
if (! (tab->insideout_buf= (unsigned char*) join->session->alloc(tab->table->key_info
4932
if (!(tab->insideout_buf= (unsigned char*)join->session->alloc(tab->table->key_info
4915
optimizer::AccessMethodFactory &factory= optimizer::AccessMethodFactory::singleton();
4916
boost::shared_ptr<optimizer::AccessMethod> access_method(factory.createAccessMethod(tab->type));
4918
if (! access_method)
4922
* Is abort() the correct thing to call here? I call this here because it was what was called in
4923
* the default case for the switch statement that used to be here.
4937
switch (tab->type) {
4938
case JT_SYSTEM: // Only happens with left join
4939
table->status=STATUS_NO_RECORD;
4940
tab->read_first_record= join_read_system;
4941
tab->read_record.read_record= join_no_more_records;
4943
case JT_CONST: // Only happens with left join
4944
table->status=STATUS_NO_RECORD;
4945
tab->read_first_record= join_read_const;
4946
tab->read_record.read_record= join_no_more_records;
4947
if (table->covering_keys.test(tab->ref.key) &&
4951
table->file->extra(HA_EXTRA_KEYREAD);
4955
table->status=STATUS_NO_RECORD;
4958
delete tab->select->quick;
4959
tab->select->quick=0;
4963
tab->read_first_record= join_read_key;
4964
tab->read_record.read_record= join_no_more_records;
4965
if (table->covering_keys.test(tab->ref.key) && !table->no_keyread)
4968
table->file->extra(HA_EXTRA_KEYREAD);
4971
push_index_cond(tab, tab->ref.key, true);
4973
case JT_REF_OR_NULL:
4975
table->status=STATUS_NO_RECORD;
4978
delete tab->select->quick;
4979
tab->select->quick=0;
4983
if (table->covering_keys.test(tab->ref.key) && !table->no_keyread)
4986
table->file->extra(HA_EXTRA_KEYREAD);
4989
push_index_cond(tab, tab->ref.key, true);
4990
if (tab->type == JT_REF)
4992
tab->read_first_record= join_read_always_key;
4993
tab->read_record.read_record= tab->insideout_match_tab?
4994
join_read_next_same_diff : join_read_next_same;
4998
tab->read_first_record= join_read_always_key_or_null;
4999
tab->read_record.read_record= join_read_next_same_or_null;
5004
If previous table use cache
5005
If the incoming data set is already sorted don't use cache.
5007
table->status=STATUS_NO_RECORD;
5008
using_join_cache= false;
5009
if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
5010
tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
5011
!tab->insideout_match_tab)
5013
if ((options & SELECT_DESCRIBE) ||
5014
!join_init_cache(join->session,join->join_tab+join->const_tables,
5015
i-join->const_tables))
5017
using_join_cache= true;
5018
tab[-1].next_select=sub_select_cache; /* Patch previous */
5021
/* These init changes read_record */
5022
if (tab->use_quick == 2)
5024
join->session->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
5025
tab->read_first_record= join_init_quick_read_record;
5027
status_var_increment(join->session->status_var.select_range_check_count);
5031
tab->read_first_record= join_init_read_record;
5032
if (i == join->const_tables)
5034
if (tab->select && tab->select->quick)
5037
status_var_increment(join->session->status_var.select_range_count);
5041
join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
5043
status_var_increment(join->session->status_var.select_scan_count);
5048
if (tab->select && tab->select->quick)
5051
status_var_increment(join->session->status_var.select_full_range_join_count);
5055
join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
5057
status_var_increment(join->session->status_var.select_full_join_count);
5060
if (!table->no_keyread)
5062
if (tab->select && tab->select->quick &&
5063
tab->select->quick->index != MAX_KEY && //not index_merge
5064
table->covering_keys.test(tab->select->quick->index))
5067
table->file->extra(HA_EXTRA_KEYREAD);
5069
else if (!table->covering_keys.none() &&
5070
!(tab->select && tab->select->quick))
5071
{ // Only read index tree
5072
if (!tab->insideout_match_tab)
5075
See bug #26447: "Using the clustered index for a table scan
5076
is always faster than using a secondary index".
5078
if (table->s->primary_key != MAX_KEY &&
5079
table->file->primary_key_is_clustered())
5080
tab->index= table->s->primary_key;
5082
tab->index= table->find_shortest_key(&table->covering_keys);
5084
tab->read_first_record= join_read_first;
5085
tab->type=JT_NEXT; // Read with index_first / index_next
5088
if (tab->select && tab->select->quick &&
5089
tab->select->quick->index != MAX_KEY && ! tab->table->key_read)
5090
push_index_cond(tab, tab->select->quick->index, !using_join_cache);
5094
break; /* purecov: deadcode */
5097
abort(); /* purecov: deadcode */
4928
access_method->getStats(table, tab);
4931
join->join_tab[join->tables-1].next_select= NULL; /* Set by do_select */
5100
join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
4936
5104
/** Update the dependency map for the tables. */
4937
static void update_depend_map(Join *join)
5105
static void update_depend_map(JOIN *join)
4939
5107
JoinTable *join_tab=join->join_tab, *end=join_tab+join->tables;
5520
5666
s->needed_reg.reset();
5521
5667
table_vector[i]=s->table=table=tables->table;
5522
5668
table->pos_in_table_list= tables;
5523
assert(table->cursor);
5524
error= table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
5669
error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
5527
table->print_error(error, MYF(0));
5672
table->file->print_error(error, MYF(0));
5530
5675
table->quick_keys.reset();
5531
5676
table->reginfo.join_tab=s;
5532
5677
table->reginfo.not_exists_optimize=0;
5533
5678
memset(table->const_key_parts, 0,
5534
sizeof(key_part_map)*table->getShare()->sizeKeys());
5679
sizeof(key_part_map)*table->s->keys);
5535
5680
all_table_map|= table->map;
5537
5682
s->info=0; // For describe
5539
s->dependent= tables->getDepTables();
5684
s->dependent= tables->dep_tables;
5540
5685
s->key_dependent= 0;
5541
table->quick_condition_rows= table->cursor->stats.records;
5686
if (tables->schema_table)
5687
table->file->stats.records= 2;
5688
table->quick_condition_rows= table->file->stats.records;
5543
5690
s->on_expr_ref= &tables->on_expr;
5544
5691
if (*s->on_expr_ref)
5546
5693
/* s is the only inner table of an outer join */
5547
if (!table->cursor->stats.records && !embedding)
5694
if (!table->file->stats.records && !embedding)
5548
5695
{ // Empty table
5549
5696
s->dependent= 0; // Ignore LEFT JOIN depend.
5550
set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
5697
set_position(join,const_count++,s,(KeyUse*) 0);
5553
5700
outer_join|= table->map;
5554
s->embedding_map.reset();
5555
for (;embedding; embedding= embedding->getEmbedding())
5556
s->embedding_map|= embedding->getNestedJoin()->nj_map;
5701
s->embedding_map= 0;
5702
for (;embedding; embedding= embedding->embedding)
5703
s->embedding_map|= embedding->nested_join->nj_map;
5559
if (embedding && !(false && ! embedding->getEmbedding()))
5706
if (embedding && !(false && ! embedding->embedding))
5561
5708
/* s belongs to a nested join, maybe to several embedded joins */
5562
s->embedding_map.reset();
5709
s->embedding_map= 0;
5565
nested_join_st *nested_join= embedding->getNestedJoin();
5566
s->embedding_map|= nested_join->nj_map;
5567
s->dependent|= embedding->getDepTables();
5568
embedding= embedding->getEmbedding();
5712
nested_join_st *nested_join= embedding->nested_join;
5713
s->embedding_map|=nested_join->nj_map;
5714
s->dependent|= embedding->dep_tables;
5715
embedding= embedding->embedding;
5569
5716
outer_join|= nested_join->used_tables;
5571
5718
while (embedding);
5574
if ((table->cursor->stats.records <= 1) && !s->dependent &&
5575
(table->cursor->getEngine()->check_flag(HTON_BIT_STATS_RECORDS_IS_EXACT)) &&
5721
if ((table->file->stats.records <= 1) && !s->dependent &&
5722
(table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
5576
5723
!join->no_const_tables)
5578
set_position(join, const_count++, s, (optimizer::KeyUse*) 0);
5725
set_position(join,const_count++,s,(KeyUse*) 0);
5581
5728
stat_vector[i]=0;
6026
6162
Nested joins perspective: Remove the last table from the join order.
6028
The algorithm is the reciprocal of check_interleaving_with_nj(), hence
6029
parent join nest nodes are updated only when the last table in its child
6030
node is removed. The ASCII graphic below will clarify.
6032
%A table nesting such as <tt> t1 x [ ( t2 x t3 ) x ( t4 x t5 ) ] </tt>is
6033
represented by the below join nest tree.
6041
t1 x [ (t2 x t3) x (t4 x t5) ]
6044
At the point in time when check_interleaving_with_nj() adds the table t5 to
6045
the query execution plan, QEP, it also directs the node named NJ2 to mark
6046
the table as covered. NJ2 does so by incrementing its @c counter
6047
member. Since all of NJ2's tables are now covered by the QEP, the algorithm
6048
proceeds up the tree to NJ1, incrementing its counter as well. All join
6049
nests are now completely covered by the QEP.
6051
restore_prev_nj_state() does the above in reverse. As seen above, the node
6052
NJ1 contains the nodes t2, t3, and NJ2. Its counter being equal to 3 means
6053
that the plan covers t2, t3, and NJ2, @e and that the sub-plan (t4 x t5)
6054
completely covers NJ2. The removal of t5 from the partial plan will first
6055
decrement NJ2's counter to 1. It will then detect that NJ2 went from being
6056
completely to partially covered, and hence the algorithm must continue
6057
upwards to NJ1 and decrement its counter to 2. %A subsequent removal of t4
6058
will however not influence NJ1 since it did not un-cover the last table in
6062
restore_prev_nj_state()
6063
last join table to remove, it is assumed to be the last in current
6068
6164
Remove the last table from the partial join order and update the nested
6069
joins counters and join->cur_embedding_map. It is ok to call this
6070
function for the first table in join order (for which
6165
joins counters and join->cur_embedding_map. It is ok to call this
6166
function for the first table in join order (for which
6071
6167
check_interleaving_with_nj has not been called)
6073
6169
@param last join table to remove, it is assumed to be the last in current
6074
6170
partial join order.
6077
6172
static void restore_prev_nj_state(JoinTable *last)
6079
TableList *last_emb= last->table->pos_in_table_list->getEmbedding();
6080
Join *join= last->join;
6081
for (;last_emb != NULL; last_emb= last_emb->getEmbedding())
6083
nested_join_st *nest= last_emb->getNestedJoin();
6085
bool was_fully_covered= nest->is_fully_covered();
6087
if (--nest->counter_ == 0)
6088
join->cur_embedding_map&= ~nest->nj_map;
6090
if (!was_fully_covered)
6174
TableList *last_emb= last->table->pos_in_table_list->embedding;
6175
JOIN *join= last->join;
6178
if (last_emb->on_expr)
6180
if (!(--last_emb->nested_join->counter_))
6181
join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
6182
else if (last_emb->nested_join->join_list.elements-1 ==
6183
last_emb->nested_join->counter_)
6184
join->cur_embedding_map|= last_emb->nested_join->nj_map;
6188
last_emb= last_emb->embedding;
6193
Determine if the set is already ordered for order_st BY, so it can
6194
disable join cache because it will change the ordering of the results.
6195
Code handles sort table that is at any location (not only first after
6196
the const tables) despite the fact that it's currently prohibited.
6197
We must disable join cache if the first non-const table alone is
6198
ordered. If there is a temp table the ordering is done as a last
6199
operation and doesn't prevent join cache usage.
6201
static uint32_t make_join_orderinfo(JOIN *join)
6205
return join->tables;
6207
for (i=join->const_tables ; i < join->tables ; i++)
6209
JoinTable *tab= join->join_tab+i;
6210
Table *table= tab->table;
6211
if ((table == join->sort_by_table &&
6212
(!join->order || join->skip_sort_order)) ||
6213
(join->sort_by_table == (Table *) 1 && i != join->const_tables))
6093
join->cur_embedding_map|= nest->nj_map;