~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Monty Taylor
  • Date: 2009-04-25 20:45:19 UTC
  • mto: (997.2.5 mordred)
  • mto: This revision was merged to the branch mainline in revision 1003.
  • Revision ID: mordred@inaugust.com-20090425204519-lgrl7mz2r66v0jby
Blackhole.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
  @brief
20
20
  mysql_select and join optimization
21
21
 
 
22
 
22
23
  @defgroup Query_Optimizer  Query Optimizer
23
24
  @{
24
25
*/
25
 
#include "config.h"
26
 
 
27
 
#include <string>
28
 
#include <iostream>
29
 
#include <algorithm>
30
 
#include <vector>
31
 
 
32
 
#include "drizzled/sql_select.h" /* include join.h */
33
 
 
 
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"
 
30
 
 
31
#include "mysys/my_bit.h"
34
32
#include "drizzled/error.h"
35
33
#include "drizzled/gettext.h"
36
34
#include "drizzled/util/test.h"
49
47
#include "drizzled/lock.h"
50
48
#include "drizzled/item/outer_ref.h"
51
49
#include "drizzled/index_hint.h"
52
 
#include "drizzled/memory/multi_malloc.h"
53
 
#include "drizzled/records.h"
54
 
#include "drizzled/internal/iocache.h"
55
50
 
56
 
#include "drizzled/sql_union.h"
57
 
#include "drizzled/optimizer/key_field.h"
58
 
#include "drizzled/optimizer/position.h"
59
 
#include "drizzled/optimizer/sargable_param.h"
60
 
#include "drizzled/optimizer/key_use.h"
61
 
#include "drizzled/optimizer/range.h"
62
 
#include "drizzled/optimizer/quick_range_select.h"
63
 
#include "drizzled/optimizer/quick_ror_intersect_select.h"
 
51
#include <string>
 
52
#include <bitset>
64
53
 
65
54
using namespace std;
66
55
 
67
 
namespace drizzled
68
 
{
69
 
 
70
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
 
56
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
 
57
                              "MAYBE_REF","ALL","range","index",
 
58
                              "ref_or_null","unique_subquery","index_subquery",
 
59
                              "index_merge"
 
60
};
 
61
 
 
62
struct st_sargable_param;
 
63
 
 
64
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
 
65
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
 
66
                                 DYNAMIC_ARRAY *keyuse);
 
67
static bool update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,
 
68
                                JOIN_TAB *join_tab,
 
69
                                uint32_t tables, COND *conds,
 
70
                                COND_EQUAL *cond_equal,
 
71
                                table_map table_map, Select_Lex *select_lex,
 
72
                                st_sargable_param **sargables);
 
73
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
 
74
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
 
75
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
76
                               table_map used_tables);
 
77
static bool choose_plan(JOIN *join,table_map join_tables);
 
78
 
 
79
static void best_access_path(JOIN *join, JOIN_TAB *s, Session *session,
 
80
                             table_map remaining_tables, uint32_t idx,
 
81
                             double record_count, double read_time);
 
82
static void optimize_straight_join(JOIN *join, table_map join_tables);
 
83
static bool greedy_search(JOIN *join, table_map remaining_tables,
 
84
                             uint32_t depth, uint32_t prune_level);
 
85
static bool best_extension_by_limited_search(JOIN *join,
 
86
                                             table_map remaining_tables,
 
87
                                             uint32_t idx, double record_count,
 
88
                                             double read_time, uint32_t depth,
 
89
                                             uint32_t prune_level);
 
90
static uint32_t determine_search_depth(JOIN* join);
 
91
extern "C" int join_tab_cmp(const void* ptr1, const void* ptr2);
 
92
extern "C" int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
 
93
/*
 
94
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
 
95
  tested and approved.
 
96
*/
 
97
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index,
 
98
                      double record_count,double read_time);
 
99
static uint32_t cache_record_length(JOIN *join,uint32_t index);
 
100
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
 
101
static bool get_best_combination(JOIN *join);
 
102
static store_key *get_store_key(Session *session,
 
103
                                KEYUSE *keyuse, table_map used_tables,
 
104
                                KEY_PART_INFO *key_part, unsigned char *key_buff,
 
105
                                uint32_t maybe_null);
 
106
static bool make_simple_join(JOIN *join,Table *tmp_table);
 
107
static void make_outerjoin_info(JOIN *join);
 
108
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
 
109
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
 
110
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
 
111
static void update_depend_map(JOIN *join);
 
112
static void update_depend_map(JOIN *join, order_st *order);
 
113
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond,
 
114
                                  bool change_list, bool *simple_order);
 
115
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
 
116
                            List<Item> &fields, bool send_row,
 
117
                            uint64_t select_options, const char *info,
 
118
                            Item *having);
71
119
static COND *build_equal_items(Session *session, COND *cond,
72
120
                               COND_EQUAL *inherited,
73
121
                               List<TableList> *join_list,
74
122
                               COND_EQUAL **cond_equal_ref);
75
 
 
 
123
static COND* substitute_for_best_equal_field(COND *cond,
 
124
                                             COND_EQUAL *cond_equal,
 
125
                                             void *table_join_idx);
 
126
static COND *simplify_joins(JOIN *join, List<TableList> *join_list,
 
127
                            COND *conds, bool top, bool in_sj);
 
128
static bool check_interleaving_with_nj(JOIN_TAB *last, JOIN_TAB *next);
 
129
static void restore_prev_nj_state(JOIN_TAB *last);
 
130
static void reset_nj_counters(List<TableList> *join_list);
 
131
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
 
132
                                          uint32_t first_unused);
 
133
 
 
134
static
 
135
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab);
 
136
static void restore_prev_sj_state(const table_map remaining_tables,
 
137
                                  const JOIN_TAB *tab);
 
138
 
 
139
static COND *optimize_cond(JOIN *join, COND *conds,
 
140
                           List<TableList> *join_list,
 
141
                           Item::cond_result *cond_value);
 
142
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
 
143
static int do_select(JOIN *join,List<Item> *fields,Table *tmp_table);
 
144
 
 
145
static enum_nested_loop_state
 
146
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
 
147
                     int error);
 
148
static enum_nested_loop_state
 
149
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab);
 
150
static enum_nested_loop_state
 
151
flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last);
 
152
static enum_nested_loop_state
 
153
end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
154
static enum_nested_loop_state
 
155
end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
156
static enum_nested_loop_state
 
157
end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
158
static enum_nested_loop_state
 
159
end_unique_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
160
 
 
161
static int join_read_const_table(JOIN_TAB *tab, POSITION *pos);
 
162
static int join_read_system(JOIN_TAB *tab);
 
163
static int join_read_const(JOIN_TAB *tab);
 
164
static int join_read_key(JOIN_TAB *tab);
 
165
static int join_read_always_key(JOIN_TAB *tab);
 
166
static int join_read_last_key(JOIN_TAB *tab);
 
167
static int join_no_more_records(READ_RECORD *info);
 
168
static int join_read_next(READ_RECORD *info);
 
169
static int join_read_next_different(READ_RECORD *info);
 
170
static int join_init_quick_read_record(JOIN_TAB *tab);
 
171
static int test_if_quick_select(JOIN_TAB *tab);
 
172
static int join_init_read_record(JOIN_TAB *tab);
 
173
static int join_read_first(JOIN_TAB *tab);
 
174
static int join_read_next_same(READ_RECORD *info);
 
175
static int join_read_next_same_diff(READ_RECORD *info);
 
176
static int join_read_last(JOIN_TAB *tab);
 
177
static int join_read_prev_same(READ_RECORD *info);
 
178
static int join_read_prev(READ_RECORD *info);
 
179
int join_read_always_key_or_null(JOIN_TAB *tab);
 
180
int join_read_next_same_or_null(READ_RECORD *info);
 
181
static COND *make_cond_for_table(COND *cond,table_map table,
 
182
                                 table_map used_table,
 
183
                                 bool exclude_expensive_cond);
76
184
static Item* part_of_refkey(Table *form,Field *field);
77
 
static bool cmp_buffer_with_ref(JoinTable *tab);
78
 
static void change_cond_ref_to_const(Session *session,
79
 
                                     vector<COND_CMP>& save_list,
80
 
                                     Item *and_father,
81
 
                                     Item *cond,
82
 
                                     Item *field,
83
 
                                     Item *value);
84
 
static bool copy_blobs(Field **ptr);
 
185
static bool test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,
 
186
                                    ha_rows select_limit, bool no_changes,
 
187
                                    const key_map *map);
 
188
static bool list_contains_unique_index(Table *table,
 
189
                          bool (*find_func) (Field *, void *), void *data);
 
190
static bool find_field_in_item_list (Field *field, void *data);
 
191
static bool find_field_in_order_list (Field *field, void *data);
 
192
static int create_sort_index(Session *session, JOIN *join, order_st *order,
 
193
                             ha_rows filesort_limit, ha_rows select_limit,
 
194
                             bool is_order_by);
 
195
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
 
196
                             Item *having);
 
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,
 
200
                                      uint32_t field_count, Field **first_field,
 
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);
 
204
static bool store_record_in_cache(JOIN_CACHE *cache);
 
205
static void reset_cache_read(JOIN_CACHE *cache);
 
206
static void reset_cache_write(JOIN_CACHE *cache);
 
207
static void read_cached_record(JOIN_TAB *tab);
 
208
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
 
209
static order_st *create_distinct_group(Session *session, Item **ref_pointer_array,
 
210
                                    order_st *order, List<Item> &fields,
 
211
                                    List<Item> &all_fields,
 
212
                                    bool *all_order_by_fields_used);
 
213
static bool test_if_subpart(order_st *a,order_st *b);
 
214
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
 
215
static void calc_group_buffer(JOIN *join,order_st *group);
 
216
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
 
217
static bool alloc_group_fields(JOIN *join,order_st *group);
 
218
// Create list for using with tempory table
 
219
static bool change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
 
220
                                     List<Item> &new_list1,
 
221
                                     List<Item> &new_list2,
 
222
                                     uint32_t elements, List<Item> &items);
 
223
// Create list for using with tempory table
 
224
static bool change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
 
225
                                      List<Item> &new_list1,
 
226
                                      List<Item> &new_list2,
 
227
                                      uint32_t elements, List<Item> &items);
 
228
static void init_tmptable_sum_functions(Item_sum **func);
 
229
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
 
230
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
 
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);
 
233
static bool init_sum_functions(Item_sum **func, Item_sum **end);
 
234
static bool update_sum_func(Item_sum **func);
 
235
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
 
236
                            bool distinct, const char *message=NULL);
 
237
static Item *remove_additional_cond(Item* conds);
 
238
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
 
239
static bool test_if_ref(Item_field *left_item,Item *right_item);
 
240
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
 
241
                                       Item *new_cond, bool fix_fields);
85
242
 
86
243
static bool eval_const_cond(COND *cond)
87
244
{
88
245
    return ((Item_func*) cond)->val_int() ? true : false;
89
246
}
90
247
 
 
248
 
91
249
/*
92
250
  This is used to mark equalities that were made from i-th IN-equality.
93
251
  We limit semi-join InsideOut optimization to handling max 64 inequalities,
96
254
const char *subq_sj_cond_name=
97
255
  "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
98
256
 
99
 
static bool copy_blobs(Field **ptr)
 
257
static bool bitmap_covers(const table_map x, const table_map y)
100
258
{
101
 
  for (; *ptr ; ptr++)
102
 
  {
103
 
    if ((*ptr)->flags & BLOB_FLAG)
104
 
      if (((Field_blob *) (*ptr))->copy())
105
 
        return 1;                               // Error
106
 
  }
107
 
  return 0;
 
259
  return !test(y & ~x);
108
260
}
109
261
 
110
262
/**
111
263
  This handles SELECT with and without UNION.
112
264
*/
 
265
 
113
266
bool handle_select(Session *session, LEX *lex, select_result *result,
114
267
                   uint64_t setup_tables_done_option)
115
268
{
116
269
  bool res;
117
 
  register Select_Lex *select_lex= &lex->select_lex;
118
 
  DRIZZLE_SELECT_START(session->query.c_str());
 
270
  register Select_Lex *select_lex = &lex->select_lex;
 
271
  DRIZZLE_SELECT_START();
119
272
 
120
273
  if (select_lex->master_unit()->is_union() ||
121
274
      select_lex->master_unit()->fake_select_lex)
122
 
    res= drizzle_union(session, lex, result, &lex->unit,
123
 
                       setup_tables_done_option);
 
275
    res= mysql_union(session, lex, result, &lex->unit, setup_tables_done_option);
124
276
  else
125
277
  {
126
278
    Select_Lex_Unit *unit= &lex->unit;
148
300
  if (unlikely(res))
149
301
    result->abort();
150
302
 
151
 
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
152
 
  return res;
 
303
  DRIZZLE_SELECT_END();
 
304
  return(res);
153
305
}
154
306
 
 
307
 
155
308
/*
156
309
  Fix fields referenced from inner selects.
157
310
 
192
345
    true  an error occured
193
346
    false ok
194
347
*/
195
 
bool fix_inner_refs(Session *session, 
196
 
                    List<Item> &all_fields, 
197
 
                    Select_Lex *select, 
198
 
                    Item **ref_pointer_array)
 
348
 
 
349
bool
 
350
fix_inner_refs(Session *session, List<Item> &all_fields, Select_Lex *select,
 
351
                 Item **ref_pointer_array)
199
352
{
200
353
  Item_outer_ref *ref;
201
354
  bool res= false;
262
415
  return res;
263
416
}
264
417
 
 
418
/**
 
419
  Function to setup clauses without sum functions.
 
420
*/
 
421
inline int setup_without_group(Session *session, Item **ref_pointer_array,
 
422
                               TableList *tables,
 
423
                               TableList *leaves,
 
424
                               List<Item> &fields,
 
425
                               List<Item> &all_fields,
 
426
                               COND **conds,
 
427
                               order_st *order,
 
428
                               order_st *group, bool *hidden_group_fields)
 
429
{
 
430
  int res;
 
431
  nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
 
432
 
 
433
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
 
434
  res= setup_conds(session, tables, leaves, conds);
 
435
 
 
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,
 
438
                          order);
 
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,
 
441
                          group, hidden_group_fields);
 
442
  session->lex->allow_sum_func= save_allow_sum_func;
 
443
  return(res);
 
444
}
 
445
 
265
446
/*****************************************************************************
266
447
  Check fields, find best join, do the select and output fields.
267
448
  mysql_select assumes that all tables are already opened
268
449
*****************************************************************************/
269
450
 
 
451
/**
 
452
  Prepare of whole select (including sub queries in future).
 
453
 
 
454
  @todo
 
455
    Add check of calculation of GROUP functions and fields:
 
456
    SELECT COUNT(*)+table.col1 from table1;
 
457
 
 
458
  @retval
 
459
    -1   on error
 
460
  @retval
 
461
    0   on success
 
462
*/
 
463
int
 
464
JOIN::prepare(Item ***rref_pointer_array,
 
465
              TableList *tables_init,
 
466
              uint32_t wild_num, COND *conds_init, uint32_t og_num,
 
467
              order_st *order_init, order_st *group_init,
 
468
              Item *having_init,
 
469
              Select_Lex *select_lex_arg,
 
470
              Select_Lex_Unit *unit_arg)
 
471
{
 
472
  // to prevent double initialization on EXPLAIN
 
473
  if (optimized)
 
474
    return(0);
 
475
 
 
476
  conds= conds_init;
 
477
  order= order_init;
 
478
  group_list= group_init;
 
479
  having= having_init;
 
480
  tables_list= tables_init;
 
481
  select_lex= select_lex_arg;
 
482
  select_lex->join= this;
 
483
  join_list= &select_lex->top_join_list;
 
484
  union_part= unit_arg->is_union();
 
485
 
 
486
  session->lex->current_select->is_item_list_lookup= 1;
 
487
  /*
 
488
    If we have already executed SELECT, then it have not sense to prevent
 
489
    its table from update (see unique_table())
 
490
  */
 
491
  if (session->derived_tables_processing)
 
492
    select_lex->exclude_from_table_unique_test= true;
 
493
 
 
494
  /* Check that all tables, fields, conds and order are ok */
 
495
 
 
496
  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
 
497
      setup_tables_and_check_access(session, &select_lex->context, join_list,
 
498
                                    tables_list, &select_lex->leaf_tables,
 
499
                                    false))
 
500
      return(-1);
 
501
 
 
502
  TableList *table_ptr;
 
503
  for (table_ptr= select_lex->leaf_tables;
 
504
       table_ptr;
 
505
       table_ptr= table_ptr->next_leaf)
 
506
    tables++;
 
507
 
 
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,
 
511
                   &all_fields, 1) ||
 
512
      setup_without_group(session, (*rref_pointer_array), tables_list,
 
513
                          select_lex->leaf_tables, fields_list,
 
514
                          all_fields, &conds, order, group_list,
 
515
                          &hidden_group_fields))
 
516
    return(-1);                         /* purecov: inspected */
 
517
 
 
518
  ref_pointer_array= *rref_pointer_array;
 
519
 
 
520
  if (having)
 
521
  {
 
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;
 
525
    select_lex->having_fix_field= 1;
 
526
    bool having_fix_rc= (!having->fixed &&
 
527
                         (having->fix_fields(session, &having) ||
 
528
                          having->check_cols(1)));
 
529
    select_lex->having_fix_field= 0;
 
530
    if (having_fix_rc || session->is_error())
 
531
      return(-1);                               /* purecov: inspected */
 
532
    session->lex->allow_sum_func= save_allow_sum_func;
 
533
  }
 
534
 
 
535
  {
 
536
    Item_subselect *subselect;
 
537
    Item_in_subselect *in_subs= NULL;
 
538
    /*
 
539
      Are we in a subquery predicate?
 
540
      TODO: the block below will be executed for every PS execution without need.
 
541
    */
 
542
    if ((subselect= select_lex->master_unit()->item))
 
543
    {
 
544
      bool do_semijoin= !test(session->variables.optimizer_switch &
 
545
                              OPTIMIZER_SWITCH_NO_SEMIJOIN);
 
546
      if (subselect->substype() == Item_subselect::IN_SUBS)
 
547
        in_subs= (Item_in_subselect*)subselect;
 
548
 
 
549
      /*
 
550
        Check if we're in subquery that is a candidate for flattening into a
 
551
        semi-join (which is done done in flatten_subqueries()). The
 
552
        requirements are:
 
553
          1. Subquery predicate is an IN/=ANY subq predicate
 
554
          2. Subquery is a single SELECT (not a UNION)
 
555
          3. Subquery does not have GROUP BY or order_st BY
 
556
          4. Subquery does not use aggregate functions or HAVING
 
557
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
 
558
          6. No execution method was already chosen (by a prepared statement).
 
559
 
 
560
          (*). We are not in a subquery of a single table UPDATE/DELETE that
 
561
               doesn't have a JOIN (TODO: We should handle this at some
 
562
               point by switching to multi-table UPDATE/DELETE)
 
563
 
 
564
          (**). We're not in a confluent table-less subquery, like
 
565
                "SELECT 1".
 
566
      */
 
567
      if (in_subs &&                                                    // 1
 
568
          !select_lex->master_unit()->first_select()->next_select() &&  // 2
 
569
          !select_lex->group_list.elements && !order &&                 // 3
 
570
          !having && !select_lex->with_sum_func &&                      // 4
 
571
          session->session_marker &&                                            // 5
 
572
          select_lex->outer_select()->join &&                           // (*)
 
573
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**)
 
574
          do_semijoin &&
 
575
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
 
576
      {
 
577
        {
 
578
          if (!in_subs->left_expr->fixed &&
 
579
               in_subs->left_expr->fix_fields(session, &in_subs->left_expr))
 
580
          {
 
581
            return(-1);
 
582
          }
 
583
          /*
 
584
            Check that the right part of the subselect contains no more than one
 
585
            column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
 
586
          */
 
587
          if (subselect->substype() == Item_subselect::IN_SUBS &&
 
588
             (select_lex->item_list.elements !=
 
589
              ((Item_in_subselect*)subselect)->left_expr->cols()))
 
590
          {
 
591
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
 
592
            return(-1);
 
593
          }
 
594
        }
 
595
 
 
596
        /* Register the subquery for further processing */
 
597
        select_lex->outer_select()->join->sj_subselects.append(session->mem_root, in_subs);
 
598
        in_subs->expr_join_nest= (TableList*)session->session_marker;
 
599
      }
 
600
      else
 
601
      {
 
602
        bool do_materialize= !test(session->variables.optimizer_switch &
 
603
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
 
604
        /*
 
605
          Check if the subquery predicate can be executed via materialization.
 
606
          The required conditions are:
 
607
          1. Subquery predicate is an IN/=ANY subq predicate
 
608
          2. Subquery is a single SELECT (not a UNION)
 
609
          3. Subquery is not a table-less query. In this case there is no
 
610
             point in materializing.
 
611
          4. Subquery predicate is a top-level predicate
 
612
             (this implies it is not negated)
 
613
             TODO: this is a limitation that should be lifeted once we
 
614
             implement correct NULL semantics (WL#3830)
 
615
          5. Subquery is non-correlated
 
616
             TODO:
 
617
             This is an overly restrictive condition. It can be extended to:
 
618
             (Subquery is non-correlated ||
 
619
              Subquery is correlated to any query outer to IN predicate ||
 
620
              (Subquery is correlated to the immediate outer query &&
 
621
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
 
622
               aggregate functions) && subquery predicate is not under "NOT IN"))
 
623
          6. No execution method was already chosen (by a prepared statement).
 
624
 
 
625
          (*) The subquery must be part of a SELECT statement. The current
 
626
               condition also excludes multi-table update statements.
 
627
 
 
628
          We have to determine whether we will perform subquery materialization
 
629
          before calling the IN=>EXISTS transformation, so that we know whether to
 
630
          perform the whole transformation or only that part of it which wraps
 
631
          Item_in_subselect in an Item_in_optimizer.
 
632
        */
 
633
        if (do_materialize &&
 
634
            in_subs  &&                                                   // 1
 
635
            !select_lex->master_unit()->first_select()->next_select() &&  // 2
 
636
            select_lex->master_unit()->first_select()->leaf_tables &&     // 3
 
637
            session->lex->sql_command == SQLCOM_SELECT)                       // *
 
638
        {
 
639
          if (in_subs->is_top_level_item() &&                             // 4
 
640
              !in_subs->is_correlated &&                                  // 5
 
641
              in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED) // 6
 
642
            in_subs->exec_method= Item_in_subselect::MATERIALIZATION;
 
643
        }
 
644
 
 
645
        Item_subselect::trans_res trans_res;
 
646
        if ((trans_res= subselect->select_transformer(this)) !=
 
647
            Item_subselect::RES_OK)
 
648
        {
 
649
          return((trans_res == Item_subselect::RES_ERROR));
 
650
        }
 
651
      }
 
652
    }
 
653
  }
 
654
 
 
655
  if (order)
 
656
  {
 
657
    order_st *ord;
 
658
    for (ord= order; ord; ord= ord->next)
 
659
    {
 
660
      Item *item= *ord->item;
 
661
      if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
 
662
        item->split_sum_func(session, ref_pointer_array, all_fields);
 
663
    }
 
664
  }
 
665
 
 
666
  if (having && having->with_sum_func)
 
667
    having->split_sum_func(session, ref_pointer_array, all_fields,
 
668
                           &having, true);
 
669
  if (select_lex->inner_sum_func_list)
 
670
  {
 
671
    Item_sum *end=select_lex->inner_sum_func_list;
 
672
    Item_sum *item_sum= end;
 
673
    do
 
674
    {
 
675
      item_sum= item_sum->next;
 
676
      item_sum->split_sum_func(session, ref_pointer_array,
 
677
                               all_fields, item_sum->ref_by, false);
 
678
    } while (item_sum != end);
 
679
  }
 
680
 
 
681
  if (select_lex->inner_refs_list.elements &&
 
682
      fix_inner_refs(session, all_fields, select_lex, ref_pointer_array))
 
683
    return(-1);
 
684
 
 
685
  /*
 
686
    Check if there are references to un-aggregated columns when computing
 
687
    aggregate functions with implicit grouping (there is no GROUP BY).
 
688
 
 
689
    MODE_ONLY_FULL_GROUP_BY is enabled here by default
 
690
  */
 
691
  if (!group_list && select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED))
 
692
  {
 
693
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
 
694
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
 
695
    return(-1);
 
696
  }
 
697
  {
 
698
    /* Caclulate the number of groups */
 
699
    send_group_parts= 0;
 
700
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
701
      send_group_parts++;
 
702
  }
 
703
 
 
704
  if (error)
 
705
    goto err;                                   /* purecov: inspected */
 
706
 
 
707
  if (result && result->prepare(fields_list, unit_arg))
 
708
    goto err;                                   /* purecov: inspected */
 
709
 
 
710
  /* Init join struct */
 
711
  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
 
712
  ref_pointer_array_size= all_fields.elements*sizeof(Item*);
 
713
  this->group= group_list != 0;
 
714
  unit= unit_arg;
 
715
 
 
716
#ifdef RESTRICTED_GROUP
 
717
  if (sum_func_count && !group_list && (func_count || field_count))
 
718
  {
 
719
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
 
720
    goto err;
 
721
  }
 
722
#endif
 
723
  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
 
724
    goto err;
 
725
  if (alloc_func_list())
 
726
    goto err;
 
727
 
 
728
  return(0); // All OK
 
729
 
 
730
err:
 
731
  return(-1);                           /* purecov: inspected */
 
732
}
 
733
 
 
734
 
 
735
/*
 
736
  Remove the predicates pushed down into the subquery
 
737
 
 
738
  SYNOPSIS
 
739
    JOIN::remove_subq_pushed_predicates()
 
740
      where   IN  Must be NULL
 
741
              OUT The remaining WHERE condition, or NULL
 
742
 
 
743
  DESCRIPTION
 
744
    Given that this join will be executed using (unique|index)_subquery,
 
745
    without "checking NULL", remove the predicates that were pushed down
 
746
    into the subquery.
 
747
 
 
748
    If the subquery compares scalar values, we can remove the condition that
 
749
    was wrapped into trig_cond (it will be checked when needed by the subquery
 
750
    engine)
 
751
 
 
752
    If the subquery compares row values, we need to keep the wrapped
 
753
    equalities in the WHERE clause: when the left (outer) tuple has both NULL
 
754
    and non-NULL values, we'll do a full table scan and will rely on the
 
755
    equalities corresponding to non-NULL parts of left tuple to filter out
 
756
    non-matching records.
 
757
 
 
758
    TODO: We can remove the equalities that will be guaranteed to be true by the
 
759
    fact that subquery engine will be using index lookup. This must be done only
 
760
    for cases where there are no conversion errors of significance, e.g. 257
 
761
    that is searched in a byte. But this requires homogenization of the return
 
762
    codes of all Field*::store() methods.
 
763
*/
 
764
 
 
765
void JOIN::remove_subq_pushed_predicates(Item **where)
 
766
{
 
767
  if (conds->type() == Item::FUNC_ITEM &&
 
768
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
 
769
      ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
 
770
      ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM &&
 
771
      test_if_ref ((Item_field *)((Item_func *)conds)->arguments()[1],
 
772
                   ((Item_func *)conds)->arguments()[0]))
 
773
  {
 
774
    *where= 0;
 
775
    return;
 
776
  }
 
777
}
 
778
 
 
779
 
270
780
/*
271
781
  Index lookup-based subquery: save some flags for EXPLAIN output
272
782
 
285
795
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
286
796
    and set appropriate flags in join_tab->packed_info.
287
797
*/
288
 
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
 
798
 
 
799
static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
289
800
{
290
801
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
291
 
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
 
802
  if (join_tab->table->covering_keys.is_set(join_tab->ref.key))
292
803
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
293
804
  if (where)
294
805
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
302
813
  }
303
814
}
304
815
 
 
816
 
 
817
 
 
818
 
 
819
/*
 
820
  Check if the table's rowid is included in the temptable
 
821
 
 
822
  SYNOPSIS
 
823
    sj_table_is_included()
 
824
      join      The join
 
825
      join_tab  The table to be checked
 
826
 
 
827
  DESCRIPTION
 
828
    SemiJoinDuplicateElimination: check the table's rowid should be included
 
829
    in the temptable. This is so if
 
830
 
 
831
    1. The table is not embedded within some semi-join nest
 
832
    2. The has been pulled out of a semi-join nest, or
 
833
 
 
834
    3. The table is functionally dependent on some previous table
 
835
 
 
836
    [4. This is also true for constant tables that can't be
 
837
        NULL-complemented but this function is not called for such tables]
 
838
 
 
839
  RETURN
 
840
    true  - Include table's rowid
 
841
    false - Don't
 
842
*/
 
843
 
 
844
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab)
 
845
{
 
846
  if (join_tab->emb_sj_nest)
 
847
    return false;
 
848
 
 
849
  /* Check if this table is functionally dependent on the tables that
 
850
     are within the same outer join nest
 
851
  */
 
852
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
 
853
  if (join_tab->type == JT_EQ_REF)
 
854
  {
 
855
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
 
856
    uint32_t idx;
 
857
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
 
858
    {
 
859
      JOIN_TAB *ref_tab= join->join_tab + idx;
 
860
      if (embedding == ref_tab->table->pos_in_table_list->embedding)
 
861
        return true;
 
862
    }
 
863
    /* Ok, functionally dependent */
 
864
    return false;
 
865
  }
 
866
  /* Not functionally dependent => need to include*/
 
867
  return true;
 
868
}
 
869
 
 
870
 
 
871
/*
 
872
  Setup the strategies to eliminate semi-join duplicates.
 
873
 
 
874
  SYNOPSIS
 
875
    setup_semijoin_dups_elimination()
 
876
      join           Join to process
 
877
      options        Join options (needed to see if join buffering will be
 
878
                     used or not)
 
879
      no_jbuf_after  Another bit of information re where join buffering will
 
880
                     be used.
 
881
 
 
882
  DESCRIPTION
 
883
    Setup the strategies to eliminate semi-join duplicates. ATM there are 3
 
884
    strategies:
 
885
 
 
886
    1. DuplicateWeedout (use of temptable to remove duplicates based on rowids
 
887
                         of row combinations)
 
888
    2. FirstMatch (pick only the 1st matching row combination of inner tables)
 
889
    3. InsideOut (scanning the sj-inner table in a way that groups duplicates
 
890
                  together and picking the 1st one)
 
891
 
 
892
    The join order has "duplicate-generating ranges", and every range is
 
893
    served by one strategy or a combination of FirstMatch with with some
 
894
    other strategy.
 
895
 
 
896
    "Duplicate-generating range" is defined as a range within the join order
 
897
    that contains all of the inner tables of a semi-join. All ranges must be
 
898
    disjoint, if tables of several semi-joins are interleaved, then the ranges
 
899
    are joined together, which is equivalent to converting
 
900
      SELECT ... WHERE oe1 IN (SELECT ie1 ...) AND oe2 IN (SELECT ie2 )
 
901
    to
 
902
      SELECT ... WHERE (oe1, oe2) IN (SELECT ie1, ie2 ... ...)
 
903
    .
 
904
 
 
905
    Applicability conditions are as follows:
 
906
 
 
907
    DuplicateWeedout strategy
 
908
    ~~~~~~~~~~~~~~~~~~~~~~~~~
 
909
 
 
910
      (ot|nt)*  [ it ((it|ot|nt)* (it|ot))]  (nt)*
 
911
      +------+  +=========================+  +---+
 
912
        (1)                 (2)               (3)
 
913
 
 
914
       (1) - Prefix of OuterTables (those that participate in
 
915
             IN-equality and/or are correlated with subquery) and outer
 
916
             Noncorrelated Tables.
 
917
       (2) - The handled range. The range starts with the first sj-inner
 
918
             table, and covers all sj-inner and outer tables
 
919
             Within the range,  Inner, Outer, outer Noncorrelated tables
 
920
             may follow in any order.
 
921
       (3) - The suffix of outer Noncorrelated tables.
 
922
 
 
923
    FirstMatch strategy
 
924
    ~~~~~~~~~~~~~~~~~~~
 
925
 
 
926
      (ot|nt)*  [ it ((it|nt)* it) ]  (nt)*
 
927
      +------+  +==================+  +---+
 
928
        (1)             (2)          (3)
 
929
 
 
930
      (1) - Prefix of outer and non-correlated tables
 
931
      (2) - The handled range, which may contain only inner and
 
932
            non-correlated tables.
 
933
      (3) - The suffix of outer Noncorrelated tables.
 
934
 
 
935
    InsideOut strategy
 
936
    ~~~~~~~~~~~~~~~~~~
 
937
 
 
938
     (ot|ct|nt) [ insideout_tbl (ot|nt|it)* it ]  (ot|nt)*
 
939
     +--------+   +===========+ +=============+   +------+
 
940
        (1)           (2)          (3)              (4)
 
941
 
 
942
      (1) - Prefix that may contain any outer tables. The prefix must contain
 
943
            all the non-trivially correlated outer tables. (non-trivially means
 
944
            that the correlation is not just through the IN-equality).
 
945
 
 
946
      (2) - Inner table for which the InsideOut scan is performed.
 
947
 
 
948
      (3) - The remainder of the duplicate-generating range. It is served by
 
949
            application of FirstMatch strategy, with the exception that
 
950
            outer IN-correlated tables are considered to be non-correlated.
 
951
 
 
952
      (4) - THe suffix of outer and outer non-correlated tables.
 
953
 
 
954
    If several strategies are applicable, their relative priorities are:
 
955
      1. InsideOut
 
956
      2. FirstMatch
 
957
      3. DuplicateWeedout
 
958
 
 
959
    This function walks over the join order and sets up the strategies by
 
960
    setting appropriate members in join_tab structures.
 
961
 
 
962
  RETURN
 
963
    false  OK
 
964
    true   Out of memory error
 
965
*/
 
966
 
 
967
static
 
968
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
969
{
 
970
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
971
  struct {
 
972
    /*
 
973
      0 - invalid (EOF marker),
 
974
      1 - InsideOut,
 
975
      2 - Temptable (maybe confluent),
 
976
      3 - Temptable with join buffering
 
977
    */
 
978
    uint32_t strategy;
 
979
    uint32_t start_idx; /* Left range bound */
 
980
    uint32_t end_idx;   /* Right range bound */
 
981
    /*
 
982
      For Temptable strategy: Bitmap of all outer and correlated tables from
 
983
      all involved join nests.
 
984
    */
 
985
    table_map outer_tables;
 
986
  } dups_ranges [MAX_TABLES];
 
987
 
 
988
  TableList *emb_insideout_nest= NULL;
 
989
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
 
990
                               tables) whose ranges we're in */
 
991
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
 
992
  table_map range_start_map= 0; /* table_map at current range start */
 
993
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
 
994
  int cur_range= 0;
 
995
  uint32_t i;
 
996
 
 
997
  /*
 
998
    First pass: locate the duplicate-generating ranges and pick the strategies.
 
999
  */
 
1000
  for (i=join->const_tables ; i < join->tables ; i++)
 
1001
  {
 
1002
    JOIN_TAB *tab=join->join_tab+i;
 
1003
    Table *table=tab->table;
 
1004
    cur_map |= table->map;
 
1005
 
 
1006
    if (tab->emb_sj_nest) // Encountered an sj-inner table
 
1007
    {
 
1008
      if (!emb_sj_map)
 
1009
      {
 
1010
        dups_ranges[cur_range].start_idx= i;
 
1011
        range_start_map= cur_map & ~table->map;
 
1012
        /*
 
1013
          Remember if this is a possible start of range that is covered by
 
1014
          the InsideOut strategy (the reason that it is not covered could
 
1015
          be that it overlaps with anther semi-join's range. we don't
 
1016
          support InsideOut for joined ranges)
 
1017
        */
 
1018
        if (join->best_positions[i].use_insideout_scan)
 
1019
          emb_insideout_nest= tab->emb_sj_nest;
 
1020
      }
 
1021
 
 
1022
      emb_sj_map |= tab->emb_sj_nest->sj_inner_tables;
 
1023
      emb_outer_tables |= tab->emb_sj_nest->nested_join->sj_depends_on;
 
1024
 
 
1025
      if (tab->emb_sj_nest != emb_insideout_nest)
 
1026
      {
 
1027
        /*
 
1028
          Two different semi-joins interleave. This cannot be handled by
 
1029
          InsideOut strategy.
 
1030
        */
 
1031
        emb_insideout_nest= NULL;
 
1032
      }
 
1033
    }
 
1034
 
 
1035
    if (emb_sj_map) /* We're in duplicate-generating range */
 
1036
    {
 
1037
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
1038
          tab->type == JT_ALL && tab->use_quick != 2 && !tab->first_inner &&
 
1039
          i <= no_jbuf_after && !dealing_with_jbuf)
 
1040
      {
 
1041
        /*
 
1042
          This table uses join buffering, which makes use of FirstMatch or
 
1043
          InsideOut strategies impossible for the current and (we assume)
 
1044
          preceding duplicate-producing ranges.
 
1045
          That is, for the join order:
 
1046
 
 
1047
              x x [ x  x]  x  [x x x]  x  [x x X*  x] x
 
1048
                  |     |     |     |          | \
 
1049
                  +-----+     +-----+          |  join buffering use
 
1050
                     r1          r2         we're here
 
1051
 
 
1052
          we'll have to remove r1 and r2 and use duplicate-elimination
 
1053
          strategy that spans all the tables, starting from the very 1st
 
1054
          one.
 
1055
        */
 
1056
        dealing_with_jbuf= true;
 
1057
        emb_insideout_nest= false;
 
1058
 
 
1059
        /*
 
1060
          Absorb all preceding duplicate-eliminating ranges. Their strategies
 
1061
          do not matter:
 
1062
        */
 
1063
        for (int prev_range= 0; prev_range < cur_range; prev_range++)
 
1064
        {
 
1065
          dups_ranges[cur_range].outer_tables |=
 
1066
            dups_ranges[prev_range].outer_tables;
 
1067
        }
 
1068
        dups_ranges[0].start_idx= 0; /* Will need to start from the 1st table */
 
1069
        dups_ranges[0].outer_tables= dups_ranges[cur_range].outer_tables;
 
1070
        cur_range=  0;
 
1071
      }
 
1072
 
 
1073
      /*
 
1074
        Check if we are at the end of duplicate-producing range. We are if
 
1075
 
 
1076
        1. It's an InsideOut range (which presumes all correlated tables are
 
1077
           in the prefix), and all inner tables are in the join order prefix,
 
1078
           or
 
1079
        2. It's a DuplicateElimination range (possibly covering several
 
1080
           SJ-nests), and all inner, outer, and correlated tables of all
 
1081
           sj-nests are in the join order prefix.
 
1082
      */
 
1083
      bool end_of_range= false;
 
1084
      if (emb_insideout_nest &&
 
1085
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
 
1086
      {
 
1087
        /* Save that this range is handled with InsideOut: */
 
1088
        dups_ranges[cur_range].strategy= 1;
 
1089
        end_of_range= true;
 
1090
      }
 
1091
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
 
1092
      {
 
1093
        /*
 
1094
          This is a complete range to be handled with either DuplicateWeedout
 
1095
          or FirstMatch
 
1096
        */
 
1097
        dups_ranges[cur_range].strategy= dealing_with_jbuf? 3 : 2;
 
1098
        /*
 
1099
          This will hold tables from within the range that need to be put
 
1100
          into the join buffer before we can use the FirstMatch on its tail.
 
1101
        */
 
1102
        dups_ranges[cur_range].outer_tables= emb_outer_tables &
 
1103
                                             ~range_start_map;
 
1104
        end_of_range= true;
 
1105
      }
 
1106
 
 
1107
      if (end_of_range)
 
1108
      {
 
1109
        dups_ranges[cur_range].end_idx= i+1;
 
1110
        emb_sj_map= emb_outer_tables= 0;
 
1111
        emb_insideout_nest= NULL;
 
1112
        dealing_with_jbuf= false;
 
1113
        dups_ranges[++cur_range].strategy= 0;
 
1114
      }
 
1115
    }
 
1116
  }
 
1117
 
 
1118
  Session *session= join->session;
 
1119
  SJ_TMP_TABLE **next_sjtbl_ptr= &join->sj_tmp_tables;
 
1120
  /*
 
1121
    Second pass: setup the chosen strategies
 
1122
  */
 
1123
  for (int j= 0; j < cur_range; j++)
 
1124
  {
 
1125
    JOIN_TAB *tab=join->join_tab + dups_ranges[j].start_idx;
 
1126
    JOIN_TAB *jump_to;
 
1127
    if (dups_ranges[j].strategy == 1)  // InsideOut strategy
 
1128
    {
 
1129
      tab->insideout_match_tab= join->join_tab + dups_ranges[j].end_idx - 1;
 
1130
      jump_to= tab++;
 
1131
    }
 
1132
    else // DuplicateWeedout strategy
 
1133
    {
 
1134
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
 
1135
      table_map weed_cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
1136
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
 
1137
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
 
1138
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
 
1139
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
 
1140
      JOIN_TAB *last_outer_tab= tab - 1;
 
1141
      /*
 
1142
        Walk through the range and remember
 
1143
         - tables that need their rowids to be put into temptable
 
1144
         - the last outer table
 
1145
      */
 
1146
      for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
1147
      {
 
1148
        if (sj_table_is_included(join, tab))
 
1149
        {
 
1150
          last_tab->join_tab= tab;
 
1151
          last_tab->rowid_offset= jt_rowid_offset;
 
1152
          jt_rowid_offset += tab->table->file->ref_length;
 
1153
          if (tab->table->maybe_null)
 
1154
          {
 
1155
            last_tab->null_byte= jt_null_bits / 8;
 
1156
            last_tab->null_bit= jt_null_bits++;
 
1157
          }
 
1158
          last_tab++;
 
1159
          tab->table->prepare_for_position();
 
1160
          tab->rowid_keep_flags= rowid_keep_flags;
 
1161
        }
 
1162
        weed_cur_map |= tab->table->map;
 
1163
        if (!tab->emb_sj_nest && bitmap_covers(weed_cur_map,
 
1164
                                               dups_ranges[j].outer_tables))
 
1165
          last_outer_tab= tab;
 
1166
      }
 
1167
 
 
1168
      if (jt_rowid_offset) /* Temptable has at least one rowid */
 
1169
      {
 
1170
        SJ_TMP_TABLE *sjtbl;
 
1171
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
 
1172
        if (!(sjtbl= (SJ_TMP_TABLE*)session->alloc(sizeof(SJ_TMP_TABLE))) ||
 
1173
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) session->alloc(tabs_size)))
 
1174
          return(true);
 
1175
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
 
1176
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
 
1177
        sjtbl->rowid_len= jt_rowid_offset;
 
1178
        sjtbl->null_bits= jt_null_bits;
 
1179
        sjtbl->null_bytes= (jt_null_bits + 7)/8;
 
1180
 
 
1181
        *next_sjtbl_ptr= sjtbl;
 
1182
        next_sjtbl_ptr= &(sjtbl->next);
 
1183
        sjtbl->next= NULL;
 
1184
 
 
1185
        sjtbl->tmp_table=
 
1186
          create_duplicate_weedout_tmp_table(session,
 
1187
                                             sjtbl->rowid_len +
 
1188
                                             sjtbl->null_bytes,
 
1189
                                             sjtbl);
 
1190
 
 
1191
        join->join_tab[dups_ranges[j].start_idx].flush_weedout_table= sjtbl;
 
1192
        join->join_tab[dups_ranges[j].end_idx - 1].check_weed_out_table= sjtbl;
 
1193
      }
 
1194
      tab= last_outer_tab + 1;
 
1195
      jump_to= last_outer_tab;
 
1196
    }
 
1197
 
 
1198
    /* Create the FirstMatch tail */
 
1199
    for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
1200
    {
 
1201
      if (tab->emb_sj_nest)
 
1202
        tab->do_firstmatch= jump_to;
 
1203
      else
 
1204
        jump_to= tab;
 
1205
    }
 
1206
  }
 
1207
  return(false);
 
1208
}
 
1209
 
 
1210
 
 
1211
static void cleanup_sj_tmp_tables(JOIN *join)
 
1212
{
 
1213
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl;
 
1214
       sj_tbl= sj_tbl->next)
 
1215
  {
 
1216
    if (sj_tbl->tmp_table)
 
1217
    {
 
1218
      sj_tbl->tmp_table->free_tmp_table(join->session);
 
1219
    }
 
1220
  }
 
1221
  join->sj_tmp_tables= NULL;
 
1222
}
 
1223
 
 
1224
uint32_t make_join_orderinfo(JOIN *join);
 
1225
 
 
1226
/**
 
1227
  global select optimisation.
 
1228
 
 
1229
  @note
 
1230
    error code saved in field 'error'
 
1231
 
 
1232
  @retval
 
1233
    0   success
 
1234
  @retval
 
1235
    1   error
 
1236
*/
 
1237
 
 
1238
int
 
1239
JOIN::optimize()
 
1240
{
 
1241
  // to prevent double initialization on EXPLAIN
 
1242
  if (optimized)
 
1243
    return(0);
 
1244
  optimized= 1;
 
1245
 
 
1246
  session->set_proc_info("optimizing");
 
1247
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
 
1248
              unit->select_limit_cnt);
 
1249
  /* select_limit is used to decide if we are likely to scan the whole table */
 
1250
  select_limit= unit->select_limit_cnt;
 
1251
  if (having || (select_options & OPTION_FOUND_ROWS))
 
1252
    select_limit= HA_POS_ERROR;
 
1253
  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
 
1254
  // Ignore errors of execution if option IGNORE present
 
1255
  if (session->lex->ignore)
 
1256
    session->lex->current_select->no_error= 1;
 
1257
 
 
1258
#ifdef HAVE_REF_TO_FIELDS                       // Not done yet
 
1259
  /* Add HAVING to WHERE if possible */
 
1260
  if (having && !group_list && !sum_func_count)
 
1261
  {
 
1262
    if (!conds)
 
1263
    {
 
1264
      conds= having;
 
1265
      having= 0;
 
1266
    }
 
1267
    else if ((conds=new Item_cond_and(conds,having)))
 
1268
    {
 
1269
      /*
 
1270
        Item_cond_and can't be fixed after creation, so we do not check
 
1271
        conds->fixed
 
1272
      */
 
1273
      conds->fix_fields(session, &conds);
 
1274
      conds->change_ref_to_fields(session, tables_list);
 
1275
      conds->top_level_item();
 
1276
      having= 0;
 
1277
    }
 
1278
  }
 
1279
#endif
 
1280
 
 
1281
  /* Convert all outer joins to inner joins if possible */
 
1282
  conds= simplify_joins(this, join_list, conds, true, false);
 
1283
  build_bitmap_for_nested_joins(join_list, 0);
 
1284
 
 
1285
  conds= optimize_cond(this, conds, join_list, &cond_value);
 
1286
  if (session->is_error())
 
1287
  {
 
1288
    error= 1;
 
1289
    return(1);
 
1290
  }
 
1291
 
 
1292
  {
 
1293
    having= optimize_cond(this, having, join_list, &having_value);
 
1294
    if (session->is_error())
 
1295
    {
 
1296
      error= 1;
 
1297
      return(1);
 
1298
    }
 
1299
    if (select_lex->where)
 
1300
      select_lex->cond_value= cond_value;
 
1301
    if (select_lex->having)
 
1302
      select_lex->having_value= having_value;
 
1303
 
 
1304
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE ||
 
1305
        (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
 
1306
    {                                           /* Impossible cond */
 
1307
      zero_result_cause=  having_value == Item::COND_FALSE ?
 
1308
                           "Impossible HAVING" : "Impossible WHERE";
 
1309
      error= 0;
 
1310
      return(0);
 
1311
    }
 
1312
  }
 
1313
 
 
1314
  /* Optimize count(*), cmin() and cmax() */
 
1315
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
 
1316
  {
 
1317
    int res;
 
1318
    /*
 
1319
      opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
 
1320
      to the WHERE conditions,
 
1321
      or 1 if all items were resolved,
 
1322
      or 0, or an error number HA_ERR_...
 
1323
    */
 
1324
    if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
 
1325
    {
 
1326
      if (res == HA_ERR_KEY_NOT_FOUND)
 
1327
      {
 
1328
        zero_result_cause= "No matching min/max row";
 
1329
        error=0;
 
1330
        return(0);
 
1331
      }
 
1332
      if (res > 1)
 
1333
      {
 
1334
        error= res;
 
1335
        return(1);
 
1336
      }
 
1337
      if (res < 0)
 
1338
      {
 
1339
        zero_result_cause= "No matching min/max row";
 
1340
        error=0;
 
1341
        return(0);
 
1342
      }
 
1343
      zero_result_cause= "Select tables optimized away";
 
1344
      tables_list= 0;                           // All tables resolved
 
1345
      /*
 
1346
        Extract all table-independent conditions and replace the WHERE
 
1347
        clause with them. All other conditions were computed by opt_sum_query
 
1348
        and the MIN/MAX/COUNT function(s) have been replaced by constants,
 
1349
        so there is no need to compute the whole WHERE clause again.
 
1350
        Notice that make_cond_for_table() will always succeed to remove all
 
1351
        computed conditions, because opt_sum_query() is applicable only to
 
1352
        conjunctions.
 
1353
        Preserve conditions for EXPLAIN.
 
1354
      */
 
1355
      if (conds && !(session->lex->describe & DESCRIBE_EXTENDED))
 
1356
      {
 
1357
        COND *table_independent_conds=
 
1358
          make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
 
1359
        conds= table_independent_conds;
 
1360
      }
 
1361
    }
 
1362
  }
 
1363
  if (!tables_list)
 
1364
  {
 
1365
    error= 0;
 
1366
    return(0);
 
1367
  }
 
1368
  error= -1;                                    // Error is sent to client
 
1369
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
 
1370
 
 
1371
  /* Calculate how to do the join */
 
1372
  session->set_proc_info("statistics");
 
1373
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
 
1374
      session->is_fatal_error)
 
1375
  {
 
1376
    return(1);
 
1377
  }
 
1378
 
 
1379
  /* Remove distinct if only const tables */
 
1380
  select_distinct= select_distinct && (const_tables != tables);
 
1381
  session->set_proc_info("preparing");
 
1382
  if (result->initialize_tables(this))
 
1383
  {
 
1384
    return(1);                          // error == -1
 
1385
  }
 
1386
  if (const_table_map != found_const_table_map &&
 
1387
      !(select_options & SELECT_DESCRIBE) &&
 
1388
      (!conds ||
 
1389
       !(conds->used_tables() & RAND_TABLE_BIT) ||
 
1390
       select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
 
1391
  {
 
1392
    zero_result_cause= "no matching row in const table";
 
1393
    error= 0;
 
1394
    return(0);
 
1395
  }
 
1396
  if (!(session->options & OPTION_BIG_SELECTS) &&
 
1397
      best_read > (double) session->variables.max_join_size &&
 
1398
      !(select_options & SELECT_DESCRIBE))
 
1399
  {                                             /* purecov: inspected */
 
1400
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
 
1401
    error= -1;
 
1402
    return(1);
 
1403
  }
 
1404
  if (const_tables && !session->locked_tables &&
 
1405
      !(select_options & SELECT_NO_UNLOCK))
 
1406
    mysql_unlock_some_tables(session, table, const_tables);
 
1407
  if (!conds && outer_join)
 
1408
  {
 
1409
    /* Handle the case where we have an OUTER JOIN without a WHERE */
 
1410
    conds=new Item_int((int64_t) 1,1);  // Always true
 
1411
  }
 
1412
  select= make_select(*table, const_table_map,
 
1413
                      const_table_map, conds, 1, &error);
 
1414
  if (error)
 
1415
  {                                             /* purecov: inspected */
 
1416
    error= -1;                                  /* purecov: inspected */
 
1417
    return(1);
 
1418
  }
 
1419
 
 
1420
  reset_nj_counters(join_list);
 
1421
  make_outerjoin_info(this);
 
1422
 
 
1423
  /*
 
1424
    Among the equal fields belonging to the same multiple equality
 
1425
    choose the one that is to be retrieved first and substitute
 
1426
    all references to these in where condition for a reference for
 
1427
    the selected field.
 
1428
  */
 
1429
  if (conds)
 
1430
  {
 
1431
    conds= substitute_for_best_equal_field(conds, cond_equal, map2table);
 
1432
    conds->update_used_tables();
 
1433
  }
 
1434
 
 
1435
  /*
 
1436
    Permorm the the optimization on fields evaluation mentioned above
 
1437
    for all on expressions.
 
1438
  */
 
1439
  for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
 
1440
  {
 
1441
    if (*tab->on_expr_ref)
 
1442
    {
 
1443
      *tab->on_expr_ref= substitute_for_best_equal_field(*tab->on_expr_ref,
 
1444
                                                         tab->cond_equal,
 
1445
                                                         map2table);
 
1446
      (*tab->on_expr_ref)->update_used_tables();
 
1447
    }
 
1448
  }
 
1449
 
 
1450
  if (conds &&!outer_join && const_table_map != found_const_table_map &&
 
1451
      (select_options & SELECT_DESCRIBE) &&
 
1452
      select_lex->master_unit() == &session->lex->unit) // upper level SELECT
 
1453
  {
 
1454
    conds=new Item_int((int64_t) 0,1);  // Always false
 
1455
  }
 
1456
  if (make_join_select(this, select, conds))
 
1457
  {
 
1458
    zero_result_cause=
 
1459
      "Impossible WHERE noticed after reading const tables";
 
1460
    return(0);                          // error == 0
 
1461
  }
 
1462
 
 
1463
  error= -1;                                    /* if goto err */
 
1464
 
 
1465
  /* Optimize distinct away if possible */
 
1466
  {
 
1467
    order_st *org_order= order;
 
1468
    order=remove_constants(this, order,conds,1, &simple_order);
 
1469
    if (session->is_error())
 
1470
    {
 
1471
      error= 1;
 
1472
      return(1);
 
1473
    }
 
1474
 
 
1475
    /*
 
1476
      If we are using order_st BY NULL or order_st BY const_expression,
 
1477
      return result in any order (even if we are using a GROUP BY)
 
1478
    */
 
1479
    if (!order && org_order)
 
1480
      skip_sort_order= 1;
 
1481
  }
 
1482
  /*
 
1483
     Check if we can optimize away GROUP BY/DISTINCT.
 
1484
     We can do that if there are no aggregate functions, the
 
1485
     fields in DISTINCT clause (if present) and/or columns in GROUP BY
 
1486
     (if present) contain direct references to all key parts of
 
1487
     an unique index (in whatever order) and if the key parts of the
 
1488
     unique index cannot contain NULLs.
 
1489
     Note that the unique keys for DISTINCT and GROUP BY should not
 
1490
     be the same (as long as they are unique).
 
1491
 
 
1492
     The FROM clause must contain a single non-constant table.
 
1493
  */
 
1494
  if (tables - const_tables == 1 && (group_list || select_distinct) &&
 
1495
      !tmp_table_param.sum_func_count &&
 
1496
      (!join_tab[const_tables].select ||
 
1497
       !join_tab[const_tables].select->quick ||
 
1498
       join_tab[const_tables].select->quick->get_type() !=
 
1499
       QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
 
1500
  {
 
1501
    if (group_list &&
 
1502
       list_contains_unique_index(join_tab[const_tables].table,
 
1503
                                 find_field_in_order_list,
 
1504
                                 (void *) group_list))
 
1505
    {
 
1506
      /*
 
1507
        We have found that grouping can be removed since groups correspond to
 
1508
        only one row anyway, but we still have to guarantee correct result
 
1509
        order. The line below effectively rewrites the query from GROUP BY
 
1510
        <fields> to order_st BY <fields>. There are two exceptions:
 
1511
        - if skip_sort_order is set (see above), then we can simply skip
 
1512
          GROUP BY;
 
1513
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
 
1514
          with the GROUP BY ones, i.e. either one is a prefix of another.
 
1515
          We only check if the order_st BY is a prefix of GROUP BY. In this case
 
1516
          test_if_subpart() copies the ASC/DESC attributes from the original
 
1517
          order_st BY fields.
 
1518
          If GROUP BY is a prefix of order_st BY, then it is safe to leave
 
1519
          'order' as is.
 
1520
       */
 
1521
      if (!order || test_if_subpart(group_list, order))
 
1522
          order= skip_sort_order ? 0 : group_list;
 
1523
      /*
 
1524
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be
 
1525
        rewritten to IGNORE INDEX FOR order_st BY(fields).
 
1526
      */
 
1527
      join_tab->table->keys_in_use_for_order_by=
 
1528
        join_tab->table->keys_in_use_for_group_by;
 
1529
      group_list= 0;
 
1530
      group= 0;
 
1531
    }
 
1532
    if (select_distinct &&
 
1533
       list_contains_unique_index(join_tab[const_tables].table,
 
1534
                                 find_field_in_item_list,
 
1535
                                 (void *) &fields_list))
 
1536
    {
 
1537
      select_distinct= 0;
 
1538
    }
 
1539
  }
 
1540
  if (group_list || tmp_table_param.sum_func_count)
 
1541
  {
 
1542
    if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
 
1543
      select_distinct=0;
 
1544
  }
 
1545
  else if (select_distinct && tables - const_tables == 1)
 
1546
  {
 
1547
    /*
 
1548
      We are only using one table. In this case we change DISTINCT to a
 
1549
      GROUP BY query if:
 
1550
      - The GROUP BY can be done through indexes (no sort) and the order_st
 
1551
        BY only uses selected fields.
 
1552
        (In this case we can later optimize away GROUP BY and order_st BY)
 
1553
      - We are scanning the whole table without LIMIT
 
1554
        This can happen if:
 
1555
        - We are using CALC_FOUND_ROWS
 
1556
        - We are using an order_st BY that can't be optimized away.
 
1557
 
 
1558
      We don't want to use this optimization when we are using LIMIT
 
1559
      because in this case we can just create a temporary table that
 
1560
      holds LIMIT rows and stop when this table is full.
 
1561
    */
 
1562
    JOIN_TAB *tab= &join_tab[const_tables];
 
1563
    bool all_order_fields_used;
 
1564
    if (order)
 
1565
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
 
1566
        &tab->table->keys_in_use_for_order_by);
 
1567
    if ((group_list=create_distinct_group(session, select_lex->ref_pointer_array,
 
1568
                                          order, fields_list, all_fields,
 
1569
                                          &all_order_fields_used)))
 
1570
    {
 
1571
      bool skip_group= (skip_sort_order &&
 
1572
        test_if_skip_sort_order(tab, group_list, select_limit, 1,
 
1573
                                &tab->table->keys_in_use_for_group_by) != 0);
 
1574
      count_field_types(select_lex, &tmp_table_param, all_fields, 0);
 
1575
      if ((skip_group && all_order_fields_used) ||
 
1576
          select_limit == HA_POS_ERROR ||
 
1577
          (order && !skip_sort_order))
 
1578
      {
 
1579
        /*  Change DISTINCT to GROUP BY */
 
1580
        select_distinct= 0;
 
1581
        no_order= !order;
 
1582
        if (all_order_fields_used)
 
1583
        {
 
1584
          if (order && skip_sort_order)
 
1585
          {
 
1586
            /*
 
1587
              Force MySQL to read the table in sorted order to get result in
 
1588
              order_st BY order.
 
1589
            */
 
1590
            tmp_table_param.quick_group=0;
 
1591
          }
 
1592
          order=0;
 
1593
        }
 
1594
        group=1;                                // For end_write_group
 
1595
      }
 
1596
      else
 
1597
        group_list= 0;
 
1598
    }
 
1599
    else if (session->is_fatal_error)                   // End of memory
 
1600
      return(1);
 
1601
  }
 
1602
  simple_group= 0;
 
1603
  {
 
1604
    order_st *old_group_list;
 
1605
    group_list= remove_constants(this, (old_group_list= group_list), conds,
 
1606
                                 rollup.state == ROLLUP::STATE_NONE,
 
1607
                                 &simple_group);
 
1608
    if (session->is_error())
 
1609
    {
 
1610
      error= 1;
 
1611
      return(1);
 
1612
    }
 
1613
    if (old_group_list && !group_list)
 
1614
      select_distinct= 0;
 
1615
  }
 
1616
  if (!group_list && group)
 
1617
  {
 
1618
    order=0;                                    // The output has only one row
 
1619
    simple_order=1;
 
1620
    select_distinct= 0;                       // No need in distinct for 1 row
 
1621
    group_optimized_away= 1;
 
1622
  }
 
1623
 
 
1624
  calc_group_buffer(this, group_list);
 
1625
  send_group_parts= tmp_table_param.group_parts; /* Save org parts */
 
1626
 
 
1627
  if (test_if_subpart(group_list, order) ||
 
1628
      (!group_list && tmp_table_param.sum_func_count))
 
1629
    order=0;
 
1630
 
 
1631
  // Can't use sort on head table if using row cache
 
1632
  if (full_join)
 
1633
  {
 
1634
    if (group_list)
 
1635
      simple_group=0;
 
1636
    if (order)
 
1637
      simple_order=0;
 
1638
  }
 
1639
 
 
1640
  /*
 
1641
    Check if we need to create a temporary table.
 
1642
    This has to be done if all tables are not already read (const tables)
 
1643
    and one of the following conditions holds:
 
1644
    - We are using DISTINCT (simple distinct's are already optimized away)
 
1645
    - We are using an order_st BY or GROUP BY on fields not in the first table
 
1646
    - We are using different order_st BY and GROUP BY orders
 
1647
    - The user wants us to buffer the result.
 
1648
  */
 
1649
  need_tmp= (const_tables != tables &&
 
1650
             ((select_distinct || !simple_order || !simple_group) ||
 
1651
              (group_list && order) ||
 
1652
              test(select_options & OPTION_BUFFER_RESULT)));
 
1653
 
 
1654
  uint32_t no_jbuf_after= make_join_orderinfo(this);
 
1655
  uint64_t select_opts_for_readinfo=
 
1656
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
 
1657
 
 
1658
  sj_tmp_tables= NULL;
 
1659
  if (!select_lex->sj_nests.is_empty())
 
1660
    setup_semijoin_dups_elimination(this, select_opts_for_readinfo,
 
1661
                                    no_jbuf_after);
 
1662
 
 
1663
  // No cache for MATCH == 'Don't use join buffering when we use MATCH'.
 
1664
  if (make_join_readinfo(this, select_opts_for_readinfo, no_jbuf_after))
 
1665
    return(1);
 
1666
 
 
1667
  /* Create all structures needed for materialized subquery execution. */
 
1668
  if (setup_subquery_materialization())
 
1669
    return(1);
 
1670
 
 
1671
  /*
 
1672
    is this simple IN subquery?
 
1673
  */
 
1674
  if (!group_list && !order &&
 
1675
      unit->item && unit->item->substype() == Item_subselect::IN_SUBS &&
 
1676
      tables == 1 && conds &&
 
1677
      !unit->is_union())
 
1678
  {
 
1679
    if (!having)
 
1680
    {
 
1681
      Item *where= conds;
 
1682
      if (join_tab[0].type == JT_EQ_REF &&
 
1683
          join_tab[0].ref.items[0]->name == in_left_expr_name)
 
1684
      {
 
1685
        remove_subq_pushed_predicates(&where);
 
1686
        save_index_subquery_explain_info(join_tab, where);
 
1687
        join_tab[0].type= JT_UNIQUE_SUBQUERY;
 
1688
        error= 0;
 
1689
        return(unit->item->
 
1690
                    change_engine(new
 
1691
                                  subselect_uniquesubquery_engine(session,
 
1692
                                                                  join_tab,
 
1693
                                                                  unit->item,
 
1694
                                                                  where)));
 
1695
      }
 
1696
      else if (join_tab[0].type == JT_REF &&
 
1697
               join_tab[0].ref.items[0]->name == in_left_expr_name)
 
1698
      {
 
1699
        remove_subq_pushed_predicates(&where);
 
1700
        save_index_subquery_explain_info(join_tab, where);
 
1701
        join_tab[0].type= JT_INDEX_SUBQUERY;
 
1702
        error= 0;
 
1703
        return(unit->item->
 
1704
                    change_engine(new
 
1705
                                  subselect_indexsubquery_engine(session,
 
1706
                                                                 join_tab,
 
1707
                                                                 unit->item,
 
1708
                                                                 where,
 
1709
                                                                 NULL,
 
1710
                                                                 0)));
 
1711
      }
 
1712
    } else if (join_tab[0].type == JT_REF_OR_NULL &&
 
1713
               join_tab[0].ref.items[0]->name == in_left_expr_name &&
 
1714
               having->name == in_having_cond)
 
1715
    {
 
1716
      join_tab[0].type= JT_INDEX_SUBQUERY;
 
1717
      error= 0;
 
1718
      conds= remove_additional_cond(conds);
 
1719
      save_index_subquery_explain_info(join_tab, conds);
 
1720
      return(unit->item->
 
1721
                  change_engine(new subselect_indexsubquery_engine(session,
 
1722
                                                                   join_tab,
 
1723
                                                                   unit->item,
 
1724
                                                                   conds,
 
1725
                                                                   having,
 
1726
                                                                   1)));
 
1727
    }
 
1728
 
 
1729
  }
 
1730
  /*
 
1731
    Need to tell handlers that to play it safe, it should fetch all
 
1732
    columns of the primary key of the tables: this is because MySQL may
 
1733
    build row pointers for the rows, and for all columns of the primary key
 
1734
    the read set has not necessarily been set by the server code.
 
1735
  */
 
1736
  if (need_tmp || select_distinct || group_list || order)
 
1737
  {
 
1738
    for (uint32_t i = const_tables; i < tables; i++)
 
1739
      join_tab[i].table->prepare_for_position();
 
1740
  }
 
1741
 
 
1742
  if (const_tables != tables)
 
1743
  {
 
1744
    /*
 
1745
      Because filesort always does a full table scan or a quick range scan
 
1746
      we must add the removed reference to the select for the table.
 
1747
      We only need to do this when we have a simple_order or simple_group
 
1748
      as in other cases the join is done before the sort.
 
1749
    */
 
1750
    if ((order || group_list) &&
 
1751
        (join_tab[const_tables].type != JT_ALL) &&
 
1752
        (join_tab[const_tables].type != JT_REF_OR_NULL) &&
 
1753
        ((order && simple_order) || (group_list && simple_group)))
 
1754
    {
 
1755
      if (add_ref_to_table_cond(session,&join_tab[const_tables])) {
 
1756
        return(1);
 
1757
      }
 
1758
    }
 
1759
 
 
1760
    if (!(select_options & SELECT_BIG_RESULT) &&
 
1761
        ((group_list &&
 
1762
          (!simple_group ||
 
1763
           !test_if_skip_sort_order(&join_tab[const_tables], group_list,
 
1764
                                    unit->select_limit_cnt, 0,
 
1765
                                    &join_tab[const_tables].table->
 
1766
                                    keys_in_use_for_group_by))) ||
 
1767
         select_distinct) &&
 
1768
        tmp_table_param.quick_group)
 
1769
    {
 
1770
      need_tmp=1; simple_order=simple_group=0;  // Force tmp table without sort
 
1771
    }
 
1772
    if (order)
 
1773
    {
 
1774
      /*
 
1775
        Force using of tmp table if sorting by a SP or UDF function due to
 
1776
        their expensive and probably non-deterministic nature.
 
1777
      */
 
1778
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
1779
      {
 
1780
        Item *item= *tmp_order->item;
 
1781
        if (item->is_expensive())
 
1782
        {
 
1783
          /* Force tmp table without sort */
 
1784
          need_tmp=1; simple_order=simple_group=0;
 
1785
          break;
 
1786
        }
 
1787
      }
 
1788
    }
 
1789
  }
 
1790
 
 
1791
  tmp_having= having;
 
1792
  if (select_options & SELECT_DESCRIBE)
 
1793
  {
 
1794
    error= 0;
 
1795
    return(0);
 
1796
  }
 
1797
  having= 0;
 
1798
 
 
1799
  /*
 
1800
    The loose index scan access method guarantees that all grouping or
 
1801
    duplicate row elimination (for distinct) is already performed
 
1802
    during data retrieval, and that all MIN/MAX functions are already
 
1803
    computed for each group. Thus all MIN/MAX functions should be
 
1804
    treated as regular functions, and there is no need to perform
 
1805
    grouping in the main execution loop.
 
1806
    Notice that currently loose index scan is applicable only for
 
1807
    single table queries, thus it is sufficient to test only the first
 
1808
    join_tab element of the plan for its access method.
 
1809
  */
 
1810
  if (join_tab->is_using_loose_index_scan())
 
1811
    tmp_table_param.precomputed_group_by= true;
 
1812
 
 
1813
  /* Create a tmp table if distinct or if the sort is too complicated */
 
1814
  if (need_tmp)
 
1815
  {
 
1816
    session->set_proc_info("Creating tmp table");
 
1817
 
 
1818
    init_items_ref_array();
 
1819
 
 
1820
    tmp_table_param.hidden_field_count= (all_fields.elements -
 
1821
                                         fields_list.elements);
 
1822
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
 
1823
                                                             (order_st*) 0);
 
1824
    /*
 
1825
      Pushing LIMIT to the temporary table creation is not applicable
 
1826
      when there is order_st BY or GROUP BY or there is no GROUP BY, but
 
1827
      there are aggregate functions, because in all these cases we need
 
1828
      all result rows.
 
1829
    */
 
1830
    ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
 
1831
                             !tmp_group &&
 
1832
                             !session->lex->current_select->with_sum_func) ?
 
1833
                            select_limit : HA_POS_ERROR;
 
1834
 
 
1835
    if (!(exec_tmp_table1=
 
1836
          create_tmp_table(session, &tmp_table_param, all_fields,
 
1837
                           tmp_group,
 
1838
                           group_list ? 0 : select_distinct,
 
1839
                           group_list && simple_group,
 
1840
                           select_options,
 
1841
                           tmp_rows_limit,
 
1842
                           (char *) "")))
 
1843
                {
 
1844
      return(1);
 
1845
    }
 
1846
 
 
1847
    /*
 
1848
      We don't have to store rows in temp table that doesn't match HAVING if:
 
1849
      - we are sorting the table and writing complete group rows to the
 
1850
        temp table.
 
1851
      - We are using DISTINCT without resolving the distinct as a GROUP BY
 
1852
        on all columns.
 
1853
 
 
1854
      If having is not handled here, it will be checked before the row
 
1855
      is sent to the client.
 
1856
    */
 
1857
    if (tmp_having &&
 
1858
        (sort_and_group || (exec_tmp_table1->distinct && !group_list)))
 
1859
      having= tmp_having;
 
1860
 
 
1861
    /* if group or order on first table, sort first */
 
1862
    if (group_list && simple_group)
 
1863
    {
 
1864
      session->set_proc_info("Sorting for group");
 
1865
      if (create_sort_index(session, this, group_list,
 
1866
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
 
1867
          alloc_group_fields(this, group_list) ||
 
1868
          make_sum_func_list(all_fields, fields_list, 1) ||
 
1869
          setup_sum_funcs(session, sum_funcs))
 
1870
      {
 
1871
        return(1);
 
1872
      }
 
1873
      group_list=0;
 
1874
    }
 
1875
    else
 
1876
    {
 
1877
      if (make_sum_func_list(all_fields, fields_list, 0) ||
 
1878
          setup_sum_funcs(session, sum_funcs))
 
1879
      {
 
1880
        return(1);
 
1881
      }
 
1882
 
 
1883
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
 
1884
      {
 
1885
        session->set_proc_info("Sorting for order");
 
1886
        if (create_sort_index(session, this, order,
 
1887
                              HA_POS_ERROR, HA_POS_ERROR, true))
 
1888
        {
 
1889
          return(1);
 
1890
        }
 
1891
        order=0;
 
1892
      }
 
1893
    }
 
1894
 
 
1895
    /*
 
1896
      Optimize distinct when used on some of the tables
 
1897
      SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
 
1898
      In this case we can stop scanning t2 when we have found one t1.a
 
1899
    */
 
1900
 
 
1901
    if (exec_tmp_table1->distinct)
 
1902
    {
 
1903
      table_map used_tables= session->used_tables;
 
1904
      JOIN_TAB *last_join_tab= join_tab+tables-1;
 
1905
      do
 
1906
      {
 
1907
        if (used_tables & last_join_tab->table->map)
 
1908
          break;
 
1909
        last_join_tab->not_used_in_distinct=1;
 
1910
      } while (last_join_tab-- != join_tab);
 
1911
      /* Optimize "select distinct b from t1 order by key_part_1 limit #" */
 
1912
      if (order && skip_sort_order)
 
1913
      {
 
1914
        /* Should always succeed */
 
1915
        if (test_if_skip_sort_order(&join_tab[const_tables],
 
1916
                                    order, unit->select_limit_cnt, 0,
 
1917
                                    &join_tab[const_tables].table->
 
1918
                                      keys_in_use_for_order_by))
 
1919
          order=0;
 
1920
      }
 
1921
    }
 
1922
 
 
1923
    /*
 
1924
      If this join belongs to an uncacheable subquery save
 
1925
      the original join
 
1926
    */
 
1927
    if (select_lex->uncacheable && !is_top_level_join() &&
 
1928
        init_save_join_tab())
 
1929
      return(-1);                         /* purecov: inspected */
 
1930
  }
 
1931
 
 
1932
  error= 0;
 
1933
  return(0);
 
1934
}
 
1935
 
 
1936
 
 
1937
/**
 
1938
  Restore values in temporary join.
 
1939
*/
 
1940
void JOIN::restore_tmp()
 
1941
{
 
1942
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
 
1943
}
 
1944
 
 
1945
 
 
1946
int
 
1947
JOIN::reinit()
 
1948
{
 
1949
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
 
1950
                                    select_lex->offset_limit->val_uint() :
 
1951
                                    0UL);
 
1952
 
 
1953
  first_record= 0;
 
1954
 
 
1955
  if (exec_tmp_table1)
 
1956
  {
 
1957
    exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
 
1958
    exec_tmp_table1->file->ha_delete_all_rows();
 
1959
    free_io_cache(exec_tmp_table1);
 
1960
    filesort_free_buffers(exec_tmp_table1,0);
 
1961
  }
 
1962
  if (exec_tmp_table2)
 
1963
  {
 
1964
    exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
 
1965
    exec_tmp_table2->file->ha_delete_all_rows();
 
1966
    free_io_cache(exec_tmp_table2);
 
1967
    filesort_free_buffers(exec_tmp_table2,0);
 
1968
  }
 
1969
  if (items0)
 
1970
    set_items_ref_array(items0);
 
1971
 
 
1972
  if (join_tab_save)
 
1973
    memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);
 
1974
 
 
1975
  if (tmp_join)
 
1976
    restore_tmp();
 
1977
 
 
1978
  /* Reset of sum functions */
 
1979
  if (sum_funcs)
 
1980
  {
 
1981
    Item_sum *func, **func_ptr= sum_funcs;
 
1982
    while ((func= *(func_ptr++)))
 
1983
      func->clear();
 
1984
  }
 
1985
 
 
1986
  return(0);
 
1987
}
 
1988
 
 
1989
/**
 
1990
   @brief Save the original join layout
 
1991
 
 
1992
   @details Saves the original join layout so it can be reused in
 
1993
   re-execution and for EXPLAIN.
 
1994
 
 
1995
   @return Operation status
 
1996
   @retval 0      success.
 
1997
   @retval 1      error occurred.
 
1998
*/
 
1999
 
 
2000
bool
 
2001
JOIN::init_save_join_tab()
 
2002
{
 
2003
  if (!(tmp_join= (JOIN*)session->alloc(sizeof(JOIN))))
 
2004
    return 1;                                  /* purecov: inspected */
 
2005
  error= 0;                                    // Ensure that tmp_join.error= 0
 
2006
  restore_tmp();
 
2007
  return 0;
 
2008
}
 
2009
 
 
2010
 
 
2011
bool
 
2012
JOIN::save_join_tab()
 
2013
{
 
2014
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
 
2015
  {
 
2016
    if (!(join_tab_save= (JOIN_TAB*)session->memdup((unsigned char*) join_tab,
 
2017
                                                sizeof(JOIN_TAB) * tables)))
 
2018
      return 1;
 
2019
  }
 
2020
  return 0;
 
2021
}
 
2022
 
 
2023
 
 
2024
/**
 
2025
  Exec select.
 
2026
 
 
2027
  @todo
 
2028
    Note, that create_sort_index calls test_if_skip_sort_order and may
 
2029
    finally replace sorting with index scan if there is a LIMIT clause in
 
2030
    the query.  It's never shown in EXPLAIN!
 
2031
 
 
2032
  @todo
 
2033
    When can we have here session->net.report_error not zero?
 
2034
*/
 
2035
void JOIN::exec()
 
2036
{
 
2037
  List<Item> *columns_list= &fields_list;
 
2038
  int      tmp_error;
 
2039
 
 
2040
  session->set_proc_info("executing");
 
2041
  error= 0;
 
2042
 
 
2043
  if (!tables_list && (tables || !select_lex->with_sum_func))
 
2044
  {                                           
 
2045
    /* Only test of functions */
 
2046
    if (select_options & SELECT_DESCRIBE)
 
2047
      select_describe(this, false, false, false, (zero_result_cause?zero_result_cause:"No tables used"));
 
2048
    else
 
2049
    {
 
2050
      result->send_fields(*columns_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
 
2051
      /*
 
2052
        We have to test for 'conds' here as the WHERE may not be constant
 
2053
        even if we don't have any tables for prepared statements or if
 
2054
        conds uses something like 'rand()'.
 
2055
      */
 
2056
      if (cond_value != Item::COND_FALSE &&
 
2057
          (!conds || conds->val_int()) &&
 
2058
          (!having || having->val_int()))
 
2059
      {
 
2060
        if (do_send_rows && result->send_data(fields_list))
 
2061
          error= 1;
 
2062
        else
 
2063
        {
 
2064
          error= (int) result->send_eof();
 
2065
          send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 : session->sent_row_count);
 
2066
        }
 
2067
      }
 
2068
      else
 
2069
      {
 
2070
        error= (int) result->send_eof();
 
2071
        send_records= 0;
 
2072
      }
 
2073
    }
 
2074
    /* Single select (without union) always returns 0 or 1 row */
 
2075
    session->limit_found_rows= send_records;
 
2076
    session->examined_row_count= 0;
 
2077
    return;
 
2078
  }
 
2079
  /*
 
2080
    Don't reset the found rows count if there're no tables as
 
2081
    FOUND_ROWS() may be called. Never reset the examined row count here.
 
2082
    It must be accumulated from all join iterations of all join parts.
 
2083
  */
 
2084
  if (tables)
 
2085
    session->limit_found_rows= 0;
 
2086
 
 
2087
  if (zero_result_cause)
 
2088
  {
 
2089
    (void) return_zero_rows(this, result, select_lex->leaf_tables,
 
2090
                            *columns_list,
 
2091
                            send_row_on_empty_set(),
 
2092
                            select_options,
 
2093
                            zero_result_cause,
 
2094
                            having);
 
2095
    return;
 
2096
  }
 
2097
 
 
2098
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) && get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
 
2099
    return;
 
2100
 
 
2101
  if (select_options & SELECT_DESCRIBE)
 
2102
  {
 
2103
    /*
 
2104
      Check if we managed to optimize order_st BY away and don't use temporary
 
2105
      table to resolve order_st BY: in that case, we only may need to do
 
2106
      filesort for GROUP BY.
 
2107
    */
 
2108
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
 
2109
    {
 
2110
      /* Reset 'order' to 'group_list' and reinit variables describing 'order' */
 
2111
      order= group_list;
 
2112
      simple_order= simple_group;
 
2113
      skip_sort_order= 0;
 
2114
    }
 
2115
    if (order && (order != group_list || !(select_options & SELECT_BIG_RESULT)))
 
2116
    {
 
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)))
 
2120
      order= 0;
 
2121
    }
 
2122
    having= tmp_having;
 
2123
    select_describe(this, need_tmp, order != 0 && !skip_sort_order,  select_distinct, !tables ? "No tables used" : NULL);
 
2124
    return;
 
2125
  }
 
2126
 
 
2127
  JOIN *curr_join= this;
 
2128
  List<Item> *curr_all_fields= &all_fields;
 
2129
  List<Item> *curr_fields_list= &fields_list;
 
2130
  Table *curr_tmp_table= 0;
 
2131
  /*
 
2132
    Initialize examined rows here because the values from all join parts
 
2133
    must be accumulated in examined_row_count. Hence every join
 
2134
    iteration must count from zero.
 
2135
  */
 
2136
  curr_join->examined_rows= 0;
 
2137
 
 
2138
  /* Create a tmp table if distinct or if the sort is too complicated */
 
2139
  if (need_tmp)
 
2140
  {
 
2141
    if (tmp_join)
 
2142
    {
 
2143
      /*
 
2144
        We are in a non cacheable sub query. Get the saved join structure
 
2145
        after optimization.
 
2146
        (curr_join may have been modified during last exection and we need
 
2147
        to reset it)
 
2148
      */
 
2149
      curr_join= tmp_join;
 
2150
    }
 
2151
    curr_tmp_table= exec_tmp_table1;
 
2152
 
 
2153
    /* Copy data to the temporary table */
 
2154
    session->set_proc_info("Copying to tmp table");
 
2155
    if (! curr_join->sort_and_group && curr_join->const_tables != curr_join->tables)
 
2156
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
 
2157
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
 
2158
    {
 
2159
      error= tmp_error;
 
2160
      return;
 
2161
    }
 
2162
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
 
2163
 
 
2164
    if (curr_join->having)
 
2165
      curr_join->having= curr_join->tmp_having= 0; // Allready done
 
2166
 
 
2167
    /* Change sum_fields reference to calculated fields in tmp_table */
 
2168
    curr_join->all_fields= *curr_all_fields;
 
2169
    if (!items1)
 
2170
    {
 
2171
      items1= items0 + all_fields.elements;
 
2172
      if (sort_and_group || curr_tmp_table->group)
 
2173
      {
 
2174
        if (change_to_use_tmp_fields(session, items1,
 
2175
                  tmp_fields_list1, tmp_all_fields1,
 
2176
                  fields_list.elements, all_fields))
 
2177
          return;
 
2178
      }
 
2179
      else
 
2180
      {
 
2181
        if (change_refs_to_tmp_fields(session, items1,
 
2182
                    tmp_fields_list1, tmp_all_fields1,
 
2183
                    fields_list.elements, all_fields))
 
2184
          return;
 
2185
      }
 
2186
      curr_join->tmp_all_fields1= tmp_all_fields1;
 
2187
      curr_join->tmp_fields_list1= tmp_fields_list1;
 
2188
      curr_join->items1= items1;
 
2189
    }
 
2190
    curr_all_fields= &tmp_all_fields1;
 
2191
    curr_fields_list= &tmp_fields_list1;
 
2192
    curr_join->set_items_ref_array(items1);
 
2193
 
 
2194
    if (sort_and_group || curr_tmp_table->group)
 
2195
    {
 
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;
 
2200
    }
 
2201
    else
 
2202
    {
 
2203
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.func_count;
 
2204
      curr_join->tmp_table_param.func_count= 0;
 
2205
    }
 
2206
 
 
2207
    if (curr_tmp_table->group)
 
2208
    {                                           // Already grouped
 
2209
      if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
 
2210
        curr_join->order= curr_join->group_list;  /* order by group */
 
2211
      curr_join->group_list= 0;
 
2212
    }
 
2213
 
 
2214
    /*
 
2215
      If we have different sort & group then we must sort the data by group
 
2216
      and copy it to another tmp table
 
2217
      This code is also used if we are using distinct something
 
2218
      we haven't been able to store in the temporary table yet
 
2219
      like SEC_TO_TIME(SUM(...)).
 
2220
    */
 
2221
 
 
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))
 
2224
    {                                   /* Must copy to another table */
 
2225
      /* Free first data from old join */
 
2226
      curr_join->join_free();
 
2227
      if (make_simple_join(curr_join, curr_tmp_table))
 
2228
        return;
 
2229
      calc_group_buffer(curr_join, group_list);
 
2230
      count_field_types(select_lex, &curr_join->tmp_table_param,
 
2231
                        curr_join->tmp_all_fields1,
 
2232
                        curr_join->select_distinct && !curr_join->group_list);
 
2233
      curr_join->tmp_table_param.hidden_field_count= curr_join->tmp_all_fields1.elements
 
2234
                                                   - curr_join->tmp_fields_list1.elements;
 
2235
 
 
2236
      if (exec_tmp_table2)
 
2237
        curr_tmp_table= exec_tmp_table2;
 
2238
      else
 
2239
      {
 
2240
        /* group data to new table */
 
2241
 
 
2242
        /*
 
2243
          If the access method is loose index scan then all MIN/MAX
 
2244
          functions are precomputed, and should be treated as regular
 
2245
          functions. See extended comment in JOIN::exec.
 
2246
        */
 
2247
        if (curr_join->join_tab->is_using_loose_index_scan())
 
2248
          curr_join->tmp_table_param.precomputed_group_by= true;
 
2249
 
 
2250
        if (!(curr_tmp_table=
 
2251
              exec_tmp_table2= create_tmp_table(session,
 
2252
                                                &curr_join->tmp_table_param,
 
2253
                                                *curr_all_fields,
 
2254
                                                (order_st*) 0,
 
2255
                                                curr_join->select_distinct &&
 
2256
                                                !curr_join->group_list,
 
2257
                                                1, curr_join->select_options,
 
2258
                                                HA_POS_ERROR,
 
2259
                                                (char *) "")))
 
2260
          return;
 
2261
        curr_join->exec_tmp_table2= exec_tmp_table2;
 
2262
      }
 
2263
      if (curr_join->group_list)
 
2264
      {
 
2265
        session->set_proc_info("Creating sort index");
 
2266
        if (curr_join->join_tab == join_tab && save_join_tab())
 
2267
        {
 
2268
          return;
 
2269
        }
 
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))
 
2273
        {
 
2274
          return;
 
2275
        }
 
2276
        sortorder= curr_join->sortorder;
 
2277
      }
 
2278
 
 
2279
      session->set_proc_info("Copying to group table");
 
2280
      tmp_error= -1;
 
2281
      if (curr_join != this)
 
2282
      {
 
2283
        if (sum_funcs2)
 
2284
        {
 
2285
          curr_join->sum_funcs= sum_funcs2;
 
2286
          curr_join->sum_funcs_end= sum_funcs_end2;
 
2287
        }
 
2288
        else
 
2289
        {
 
2290
          curr_join->alloc_func_list();
 
2291
          sum_funcs2= curr_join->sum_funcs;
 
2292
          sum_funcs_end2= curr_join->sum_funcs_end;
 
2293
        }
 
2294
      }
 
2295
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, 1, true))
 
2296
        return;
 
2297
      curr_join->group_list= 0;
 
2298
 
 
2299
      if (!curr_join->sort_and_group && (curr_join->const_tables != curr_join->tables))
 
2300
        curr_join->join_tab[curr_join->const_tables].sorted= 0;
 
2301
      
 
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)))
 
2304
      {
 
2305
        error= tmp_error;
 
2306
        return;
 
2307
      }
 
2308
      end_read_record(&curr_join->join_tab->read_record);
 
2309
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
 
2310
      curr_join->join_tab[0].table= 0;           // Table is freed
 
2311
 
 
2312
      // No sum funcs anymore
 
2313
      if (!items2)
 
2314
      {
 
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))
 
2319
          return;
 
2320
        curr_join->tmp_fields_list2= tmp_fields_list2;
 
2321
        curr_join->tmp_all_fields2= tmp_all_fields2;
 
2322
      }
 
2323
      curr_fields_list= &curr_join->tmp_fields_list2;
 
2324
      curr_all_fields= &curr_join->tmp_all_fields2;
 
2325
      curr_join->set_items_ref_array(items2);
 
2326
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count;
 
2327
      curr_join->tmp_table_param.sum_func_count= 0;
 
2328
    }
 
2329
    if (curr_tmp_table->distinct)
 
2330
      curr_join->select_distinct=0;             /* Each row is unique */
 
2331
 
 
2332
    curr_join->join_free();                     /* Free quick selects */
 
2333
    if (curr_join->select_distinct && ! curr_join->group_list)
 
2334
    {
 
2335
      session->set_proc_info("Removing duplicates");
 
2336
      if (curr_join->tmp_having)
 
2337
        curr_join->tmp_having->update_used_tables();
 
2338
 
 
2339
      if (remove_duplicates(curr_join, curr_tmp_table,
 
2340
                            *curr_fields_list, curr_join->tmp_having))
 
2341
        return;
 
2342
      
 
2343
      curr_join->tmp_having=0;
 
2344
      curr_join->select_distinct=0;
 
2345
    }
 
2346
    curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
 
2347
    if (make_simple_join(curr_join, curr_tmp_table))
 
2348
      return;
 
2349
    calc_group_buffer(curr_join, curr_join->group_list);
 
2350
    count_field_types(select_lex, &curr_join->tmp_table_param, *curr_all_fields, 0);
 
2351
 
 
2352
  }
 
2353
 
 
2354
  if (curr_join->group || curr_join->tmp_table_param.sum_func_count)
 
2355
  {
 
2356
    if (make_group_fields(this, curr_join))
 
2357
      return;
 
2358
 
 
2359
    if (! items3)
 
2360
    {
 
2361
      if (! items0)
 
2362
        init_items_ref_array();
 
2363
      items3= ref_pointer_array + (all_fields.elements*4);
 
2364
      setup_copy_fields(session, &curr_join->tmp_table_param,
 
2365
                        items3, tmp_fields_list3, tmp_all_fields3,
 
2366
                        curr_fields_list->elements, *curr_all_fields);
 
2367
      tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
 
2368
      tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
 
2369
      tmp_table_param.save_copy_field_end= curr_join->tmp_table_param.copy_field_end;
 
2370
      curr_join->tmp_all_fields3= tmp_all_fields3;
 
2371
      curr_join->tmp_fields_list3= tmp_fields_list3;
 
2372
    }
 
2373
    else
 
2374
    {
 
2375
      curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
 
2376
      curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
 
2377
      curr_join->tmp_table_param.copy_field_end= tmp_table_param.save_copy_field_end;
 
2378
    }
 
2379
    curr_fields_list= &tmp_fields_list3;
 
2380
    curr_all_fields= &tmp_all_fields3;
 
2381
    curr_join->set_items_ref_array(items3);
 
2382
 
 
2383
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
 
2384
                                      1, true) ||
 
2385
        setup_sum_funcs(curr_join->session, curr_join->sum_funcs) ||
 
2386
        session->is_fatal_error)
 
2387
      return;
 
2388
  }
 
2389
  if (curr_join->group_list || curr_join->order)
 
2390
  {
 
2391
    session->set_proc_info("Sorting result");
 
2392
    /* If we have already done the group, add HAVING to sorted table */
 
2393
    if (curr_join->tmp_having && ! curr_join->group_list &&     ! curr_join->sort_and_group)
 
2394
    {
 
2395
      // Some tables may have been const
 
2396
      curr_join->tmp_having->update_used_tables();
 
2397
      JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
 
2398
      table_map used_tables= (curr_join->const_table_map |
 
2399
                              curr_table->table->map);
 
2400
 
 
2401
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having, used_tables, used_tables, 0);
 
2402
      if (sort_table_cond)
 
2403
      {
 
2404
        if (!curr_table->select)
 
2405
          if (!(curr_table->select= new SQL_SELECT))
 
2406
            return;
 
2407
        if (!curr_table->select->cond)
 
2408
          curr_table->select->cond= sort_table_cond;
 
2409
        else                                    // This should never happen
 
2410
        {
 
2411
          if (!(curr_table->select->cond=
 
2412
          new Item_cond_and(curr_table->select->cond,
 
2413
                sort_table_cond)))
 
2414
            return;
 
2415
          /*
 
2416
            Item_cond_and do not need fix_fields for execution, its parameters
 
2417
            are fixed or do not need fix_fields, too
 
2418
          */
 
2419
          curr_table->select->cond->quick_fix_field();
 
2420
        }
 
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,
 
2424
                    ~ (table_map) 0,
 
2425
                    ~used_tables, 0);
 
2426
      }
 
2427
    }
 
2428
    {
 
2429
      if (group)
 
2430
        curr_join->select_limit= HA_POS_ERROR;
 
2431
      else
 
2432
      {
 
2433
        /*
 
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.
 
2436
        */
 
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++)
 
2440
        {
 
2441
          /*
 
2442
            table->keyuse is set in the case there was an original WHERE clause
 
2443
            on the table that was optimized away.
 
2444
          */
 
2445
          if (curr_table->select_cond ||
 
2446
              (curr_table->keyuse && !curr_table->first_inner))
 
2447
          {
 
2448
            /* We have to sort all rows */
 
2449
            curr_join->select_limit= HA_POS_ERROR;
 
2450
            break;
 
2451
          }
 
2452
        }
 
2453
      }
 
2454
      if (curr_join->join_tab == join_tab && save_join_tab())
 
2455
        return;
 
2456
      /*
 
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.
 
2464
      */
 
2465
      if (create_sort_index(session, curr_join,
 
2466
                            curr_join->group_list ?
 
2467
                            curr_join->group_list : curr_join->order,
 
2468
                            curr_join->select_limit,
 
2469
                            (select_options & OPTION_FOUND_ROWS ?
 
2470
                             HA_POS_ERROR : unit->select_limit_cnt),
 
2471
                            curr_join->group_list ? true : false))
 
2472
        return;
 
2473
 
 
2474
      sortorder= curr_join->sortorder;
 
2475
      if (curr_join->const_tables != curr_join->tables &&
 
2476
          !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
 
2477
      {
 
2478
        /*
 
2479
          If no IO cache exists for the first table then we are using an
 
2480
          INDEX SCAN and no filesort. Thus we should not remove the sorted
 
2481
          attribute on the INDEX SCAN.
 
2482
        */
 
2483
        skip_sort_order= 1;
 
2484
      }
 
2485
    }
 
2486
  }
 
2487
  /* XXX: When can we have here session->is_error() not zero? */
 
2488
  if (session->is_error())
 
2489
  {
 
2490
    error= session->is_error();
 
2491
    return;
 
2492
  }
 
2493
  curr_join->having= curr_join->tmp_having;
 
2494
  curr_join->fields= curr_fields_list;
 
2495
 
 
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;
 
2501
 
 
2502
  /* Accumulate the counts from all join iterations of all join parts. */
 
2503
  session->examined_row_count+= curr_join->examined_rows;
 
2504
 
 
2505
  /*
 
2506
    With EXPLAIN EXTENDED we have to restore original ref_array
 
2507
    for a derived table which is always materialized.
 
2508
    Otherwise we would not be able to print the query  correctly.
 
2509
  */
 
2510
  if (items0 && (session->lex->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
 
2511
    set_items_ref_array(items0);
 
2512
 
 
2513
  return;
 
2514
}
 
2515
 
 
2516
/**
 
2517
  Clean up join.
 
2518
 
 
2519
  @return
 
2520
    Return error that hold JOIN.
 
2521
*/
 
2522
int JOIN::destroy()
 
2523
{
 
2524
  select_lex->join= 0;
 
2525
 
 
2526
  if (tmp_join)
 
2527
  {
 
2528
    if (join_tab != tmp_join->join_tab)
 
2529
    {
 
2530
      JOIN_TAB *tab, *end;
 
2531
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
 
2532
        tab->cleanup();
 
2533
    }
 
2534
    tmp_join->tmp_join= 0;
 
2535
    tmp_table_param.copy_field=0;
 
2536
    return(tmp_join->destroy());
 
2537
  }
 
2538
  cond_equal= 0;
 
2539
 
 
2540
  cleanup(1);
 
2541
  if (exec_tmp_table1)
 
2542
    exec_tmp_table1->free_tmp_table(session);
 
2543
  if (exec_tmp_table2)
 
2544
    exec_tmp_table2->free_tmp_table(session);
 
2545
  delete select;
 
2546
  delete_dynamic(&keyuse);
 
2547
  return(error);
 
2548
}
 
2549
 
305
2550
/**
306
2551
  An entry point to single-unit select (a select without UNION).
307
2552
 
308
 
  @param session                  thread Cursor
 
2553
  @param session                  thread handler
309
2554
  @param rref_pointer_array   a reference to ref_pointer_array of
310
2555
                              the top-level select_lex for this query
311
2556
  @param tables               list of all tables used in this query.
321
2566
                              for a, b and c in this list.
322
2567
  @param conds                top level item of an expression representing
323
2568
                              WHERE clause of the top level select
324
 
  @param og_num               total number of ORDER BY and GROUP BY clauses
 
2569
  @param og_num               total number of order_st BY and GROUP BY clauses
325
2570
                              arguments
326
 
  @param order                linked list of ORDER BY agruments
 
2571
  @param order                linked list of order_st BY agruments
327
2572
  @param group                linked list of GROUP BY arguments
328
2573
  @param having               top level item of HAVING expression
329
2574
  @param select_options       select options (BIG_RESULT, etc)
344
2589
  @retval
345
2590
    true   an error
346
2591
*/
347
 
bool mysql_select(Session *session,
348
 
                  Item ***rref_pointer_array,
349
 
                  TableList *tables, 
350
 
                  uint32_t wild_num, 
351
 
                  List<Item> &fields,
352
 
                  COND *conds, 
353
 
                  uint32_t og_num,  
354
 
                  order_st *order, 
355
 
                  order_st *group,
356
 
                  Item *having, 
357
 
                  uint64_t select_options,
358
 
                  select_result *result, 
359
 
                  Select_Lex_Unit *unit,
360
 
                  Select_Lex *select_lex)
 
2592
 
 
2593
bool
 
2594
mysql_select(Session *session, Item ***rref_pointer_array,
 
2595
             TableList *tables, uint32_t wild_num, List<Item> &fields,
 
2596
             COND *conds, uint32_t og_num,  order_st *order, order_st *group,
 
2597
             Item *having, uint64_t select_options,
 
2598
             select_result *result, Select_Lex_Unit *unit,
 
2599
             Select_Lex *select_lex)
361
2600
{
362
2601
  bool err;
363
2602
  bool free_join= 1;
372
2611
      creation
373
2612
    */
374
2613
    if (select_lex->linkage != DERIVED_TABLE_TYPE ||
375
 
        (select_options & SELECT_DESCRIBE))
 
2614
        (select_options & SELECT_DESCRIBE))
376
2615
    {
377
2616
      if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
378
2617
      {
379
 
        //here is EXPLAIN of subselect or derived table
380
 
        if (join->change_result(result))
381
 
        {
382
 
          return(true);
383
 
        }
 
2618
        //here is EXPLAIN of subselect or derived table
 
2619
        if (join->change_result(result))
 
2620
        {
 
2621
          return(true);
 
2622
        }
384
2623
      }
385
2624
      else
386
2625
      {
387
2626
        if ((err= join->prepare(rref_pointer_array, tables, wild_num,
388
2627
                               conds, og_num, order, group, having, select_lex, unit)))
389
 
        {
390
 
          goto err;
391
 
        }
 
2628
        {
 
2629
          goto err;
 
2630
        }
392
2631
      }
393
2632
    }
394
2633
    free_join= 0;
397
2636
  else
398
2637
  {
399
2638
    if (!(join= new JOIN(session, fields, select_options, result)))
400
 
      return(true);
 
2639
        return(true);
401
2640
    session->set_proc_info("init");
402
2641
    session->used_tables=0;                         // Updated by setup_fields
403
2642
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
408
2647
    }
409
2648
  }
410
2649
 
411
 
  err= join->optimize();
412
 
  if (err)
413
 
  {
414
 
    goto err; // 1
 
2650
  if (join->flatten_subqueries())
 
2651
  {
 
2652
    err= 1;
 
2653
    goto err;
 
2654
  }
 
2655
 
 
2656
  if ((err= join->optimize()))
 
2657
  {
 
2658
    goto err;                                   // 1
415
2659
  }
416
2660
 
417
2661
  if (session->lex->describe & DESCRIBE_EXTENDED)
441
2685
  return(join->error);
442
2686
}
443
2687
 
444
 
inline Item *and_items(Item* cond, Item *item)
 
2688
 
 
2689
int subq_sj_candidate_cmp(Item_in_subselect* const *el1,
 
2690
                          Item_in_subselect* const *el2)
 
2691
{
 
2692
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
 
2693
         ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
 
2694
}
 
2695
 
 
2696
 
 
2697
inline Item * and_items(Item* cond, Item *item)
445
2698
{
446
2699
  return (cond? (new Item_cond_and(cond, item)) : item);
447
2700
}
448
2701
 
449
 
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
2702
 
 
2703
static TableList *alloc_join_nest(Session *session)
 
2704
{
 
2705
  TableList *tbl;
 
2706
  if (!(tbl= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
 
2707
                                       sizeof(nested_join_st))))
 
2708
    return NULL;
 
2709
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl +
 
2710
                                    ALIGN_SIZE(sizeof(TableList)));
 
2711
  return tbl;
 
2712
}
 
2713
 
 
2714
 
 
2715
void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
450
2716
{
451
2717
  List_iterator<TableList> it(*tlist);
452
2718
  TableList *table;
459
2725
  }
460
2726
}
461
2727
 
 
2728
 
 
2729
/*
 
2730
  Convert a subquery predicate into a TableList semi-join nest
 
2731
 
 
2732
  SYNOPSIS
 
2733
    convert_subq_to_sj()
 
2734
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON
 
2735
                    clause
 
2736
       subq_pred    Subquery predicate to be converted
 
2737
 
 
2738
  DESCRIPTION
 
2739
    Convert a subquery predicate into a TableList semi-join nest. All the
 
2740
    prerequisites are already checked, so the conversion is always successfull.
 
2741
 
 
2742
    Prepared Statements: the transformation is permanent:
 
2743
     - Changes in TableList structures are naturally permanent
 
2744
     - Item tree changes are performed on statement MEM_ROOT:
 
2745
        = we activate statement MEM_ROOT
 
2746
        = this function is called before the first fix_prepare_information
 
2747
          call.
 
2748
 
 
2749
    This is intended because the criteria for subquery-to-sj conversion remain
 
2750
    constant for the lifetime of the Prepared Statement.
 
2751
 
 
2752
  RETURN
 
2753
    false  OK
 
2754
    true   Out of memory error
 
2755
*/
 
2756
 
 
2757
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
 
2758
{
 
2759
  Select_Lex *parent_lex= parent_join->select_lex;
 
2760
  TableList *emb_tbl_nest= NULL;
 
2761
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
 
2762
  Session *session= parent_join->session;
 
2763
 
 
2764
  /*
 
2765
    1. Find out where to put the predicate into.
 
2766
     Note: for "t1 LEFT JOIN t2" this will be t2, a leaf.
 
2767
  */
 
2768
  if ((void*)subq_pred->expr_join_nest != (void*)1)
 
2769
  {
 
2770
    if (subq_pred->expr_join_nest->nested_join)
 
2771
    {
 
2772
      /*
 
2773
        We're dealing with
 
2774
 
 
2775
          ... [LEFT] JOIN  ( ... ) ON (subquery AND whatever) ...
 
2776
 
 
2777
        The sj-nest will be inserted into the brackets nest.
 
2778
      */
 
2779
      emb_tbl_nest=  subq_pred->expr_join_nest;
 
2780
      emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
2781
    }
 
2782
    else if (!subq_pred->expr_join_nest->outer_join)
 
2783
    {
 
2784
      /*
 
2785
        We're dealing with
 
2786
 
 
2787
          ... INNER JOIN tblX ON (subquery AND whatever) ...
 
2788
 
 
2789
        The sj-nest will be tblX's "sibling", i.e. another child of its
 
2790
        parent. This is ok because tblX is joined as an inner join.
 
2791
      */
 
2792
      emb_tbl_nest= subq_pred->expr_join_nest->embedding;
 
2793
      if (emb_tbl_nest)
 
2794
        emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
2795
    }
 
2796
    else if (!subq_pred->expr_join_nest->nested_join)
 
2797
    {
 
2798
      TableList *outer_tbl= subq_pred->expr_join_nest;
 
2799
      TableList *wrap_nest;
 
2800
      /*
 
2801
        We're dealing with
 
2802
 
 
2803
          ... LEFT JOIN tbl ON (on_expr AND subq_pred) ...
 
2804
 
 
2805
        we'll need to convert it into:
 
2806
 
 
2807
          ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
 
2808
                        |                      |
 
2809
                        |<----- wrap_nest ---->|
 
2810
 
 
2811
        Q:  other subqueries may be pointing to this element. What to do?
 
2812
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
 
2813
            But we'll need to fix other pointers.
 
2814
        A2: Another way: have TableList::next_ptr so the following
 
2815
            subqueries know the table has been nested.
 
2816
        A3: changes in the TableList::outer_join will make everything work
 
2817
            automatically.
 
2818
      */
 
2819
      if (!(wrap_nest= alloc_join_nest(parent_join->session)))
 
2820
      {
 
2821
        return(true);
 
2822
      }
 
2823
      wrap_nest->embedding= outer_tbl->embedding;
 
2824
      wrap_nest->join_list= outer_tbl->join_list;
 
2825
      wrap_nest->alias= (char*) "(sj-wrap)";
 
2826
 
 
2827
      wrap_nest->nested_join->join_list.empty();
 
2828
      wrap_nest->nested_join->join_list.push_back(outer_tbl);
 
2829
 
 
2830
      outer_tbl->embedding= wrap_nest;
 
2831
      outer_tbl->join_list= &wrap_nest->nested_join->join_list;
 
2832
 
 
2833
      /*
 
2834
        wrap_nest will take place of outer_tbl, so move the outer join flag
 
2835
        and on_expr
 
2836
      */
 
2837
      wrap_nest->outer_join= outer_tbl->outer_join;
 
2838
      outer_tbl->outer_join= 0;
 
2839
 
 
2840
      wrap_nest->on_expr= outer_tbl->on_expr;
 
2841
      outer_tbl->on_expr= NULL;
 
2842
 
 
2843
      List_iterator<TableList> li(*wrap_nest->join_list);
 
2844
      TableList *tbl;
 
2845
      while ((tbl= li++))
 
2846
      {
 
2847
        if (tbl == outer_tbl)
 
2848
        {
 
2849
          li.replace(wrap_nest);
 
2850
          break;
 
2851
        }
 
2852
      }
 
2853
      /*
 
2854
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the
 
2855
        semi-join nest into it
 
2856
      */
 
2857
      emb_join_list= &wrap_nest->nested_join->join_list;
 
2858
      emb_tbl_nest=  wrap_nest;
 
2859
    }
 
2860
  }
 
2861
 
 
2862
  TableList *sj_nest;
 
2863
  nested_join_st *nested_join;
 
2864
  if (!(sj_nest= alloc_join_nest(parent_join->session)))
 
2865
  {
 
2866
    return(true);
 
2867
  }
 
2868
  nested_join= sj_nest->nested_join;
 
2869
 
 
2870
  sj_nest->join_list= emb_join_list;
 
2871
  sj_nest->embedding= emb_tbl_nest;
 
2872
  sj_nest->alias= (char*) "(sj-nest)";
 
2873
  /* Nests do not participate in those 'chains', so: */
 
2874
  /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
 
2875
  emb_join_list->push_back(sj_nest);
 
2876
 
 
2877
  /*
 
2878
    nested_join->used_tables and nested_join->not_null_tables are
 
2879
    initialized in simplify_joins().
 
2880
  */
 
2881
 
 
2882
  /*
 
2883
    2. Walk through subquery's top list and set 'embedding' to point to the
 
2884
       sj-nest.
 
2885
  */
 
2886
  Select_Lex *subq_lex= subq_pred->unit->first_select();
 
2887
  nested_join->join_list.empty();
 
2888
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
 
2889
  TableList *tl, *last_leaf;
 
2890
  while ((tl= li++))
 
2891
  {
 
2892
    tl->embedding= sj_nest;
 
2893
    tl->join_list= &nested_join->join_list;
 
2894
    nested_join->join_list.push_back(tl);
 
2895
  }
 
2896
 
 
2897
  /*
 
2898
    Reconnect the next_leaf chain.
 
2899
    TODO: Do we have to put subquery's tables at the end of the chain?
 
2900
          Inserting them at the beginning would be a bit faster.
 
2901
    NOTE: We actually insert them at the front! That's because the order is
 
2902
          reversed in this list.
 
2903
  */
 
2904
  for (tl= parent_lex->leaf_tables; tl->next_leaf; tl= tl->next_leaf) {};
 
2905
  tl->next_leaf= subq_lex->leaf_tables;
 
2906
  last_leaf= tl;
 
2907
 
 
2908
  /*
 
2909
    Same as above for next_local chain
 
2910
    (a theory: a next_local chain always starts with ::leaf_tables
 
2911
     because view's tables are inserted after the view)
 
2912
  */
 
2913
  for (tl= parent_lex->leaf_tables; tl->next_local; tl= tl->next_local) {};
 
2914
  tl->next_local= subq_lex->leaf_tables;
 
2915
 
 
2916
  /* A theory: no need to re-connect the next_global chain */
 
2917
 
 
2918
  /* 3. Remove the original subquery predicate from the WHERE/ON */
 
2919
 
 
2920
  // The subqueries were replaced for Item_int(1) earlier
 
2921
  subq_pred->exec_method= Item_in_subselect::SEMI_JOIN; // for subsequent executions
 
2922
  /*TODO: also reset the 'with_subselect' there. */
 
2923
 
 
2924
  /* n. Adjust the parent_join->tables counter */
 
2925
  uint32_t table_no= parent_join->tables;
 
2926
  /* n. Walk through child's tables and adjust table->map */
 
2927
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
 
2928
  {
 
2929
    tl->table->tablenr= table_no;
 
2930
    tl->table->map= ((table_map)1) << table_no;
 
2931
    Select_Lex *old_sl= tl->select_lex;
 
2932
    tl->select_lex= parent_join->select_lex;
 
2933
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
 
2934
      emb->select_lex= parent_join->select_lex;
 
2935
  }
 
2936
  parent_join->tables += subq_lex->join->tables;
 
2937
 
 
2938
  /*
 
2939
    Put the subquery's WHERE into semi-join's sj_on_expr
 
2940
    Add the subquery-induced equalities too.
 
2941
  */
 
2942
  Select_Lex *save_lex= session->lex->current_select;
 
2943
  session->lex->current_select=subq_lex;
 
2944
  if (!subq_pred->left_expr->fixed &&
 
2945
       subq_pred->left_expr->fix_fields(session, &subq_pred->left_expr))
 
2946
    return(true);
 
2947
  session->lex->current_select=save_lex;
 
2948
 
 
2949
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
 
2950
  sj_nest->nested_join->sj_depends_on=  subq_pred->used_tables() |
 
2951
                                        subq_pred->left_expr->used_tables();
 
2952
  sj_nest->sj_on_expr= subq_lex->where;
 
2953
 
 
2954
  /*
 
2955
    Create the IN-equalities and inject them into semi-join's ON expression.
 
2956
    Additionally, for InsideOut strategy
 
2957
     - Record the number of IN-equalities.
 
2958
     - Create list of pointers to (oe1, ..., ieN). We'll need the list to
 
2959
       see which of the expressions are bound and which are not (for those
 
2960
       we'll produce a distinct stream of (ie_i1,...ie_ik).
 
2961
 
 
2962
       (TODO: can we just create a list of pointers and hope the expressions
 
2963
       will not substitute themselves on fix_fields()? or we need to wrap
 
2964
       them into Item_direct_view_refs and store pointers to those. The
 
2965
       pointers to Item_direct_view_refs are guaranteed to be stable as
 
2966
       Item_direct_view_refs doesn't substitute itself with anything in
 
2967
       Item_direct_view_ref::fix_fields.
 
2968
  */
 
2969
  sj_nest->sj_in_exprs= subq_pred->left_expr->cols();
 
2970
  sj_nest->nested_join->sj_outer_expr_list.empty();
 
2971
 
 
2972
  if (subq_pred->left_expr->cols() == 1)
 
2973
  {
 
2974
    nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr);
 
2975
 
 
2976
    Item *item_eq= new Item_func_eq(subq_pred->left_expr,
 
2977
                                    subq_lex->ref_pointer_array[0]);
 
2978
    item_eq->name= (char*)subq_sj_cond_name;
 
2979
    sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
2980
  }
 
2981
  else
 
2982
  {
 
2983
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
 
2984
    {
 
2985
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
 
2986
                                                element_index(i));
 
2987
      Item *item_eq=
 
2988
        new Item_func_eq(subq_pred->left_expr->element_index(i),
 
2989
                         subq_lex->ref_pointer_array[i]);
 
2990
      item_eq->name= (char*)subq_sj_cond_name + (i % 64);
 
2991
      sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
2992
    }
 
2993
  }
 
2994
  /* Fix the created equality and AND */
 
2995
  sj_nest->sj_on_expr->fix_fields(parent_join->session, &sj_nest->sj_on_expr);
 
2996
 
 
2997
  /*
 
2998
    Walk through sj nest's WHERE and ON expressions and call
 
2999
    item->fix_table_changes() for all items.
 
3000
  */
 
3001
  sj_nest->sj_on_expr->fix_after_pullout(parent_lex, &sj_nest->sj_on_expr);
 
3002
  fix_list_after_tbl_changes(parent_lex, &sj_nest->nested_join->join_list);
 
3003
 
 
3004
 
 
3005
  /* Unlink the child select_lex so it doesn't show up in EXPLAIN: */
 
3006
  subq_lex->master_unit()->exclude_level();
 
3007
 
 
3008
  /* Inject sj_on_expr into the parent's WHERE or ON */
 
3009
  if (emb_tbl_nest)
 
3010
  {
 
3011
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr,
 
3012
                                     sj_nest->sj_on_expr);
 
3013
    emb_tbl_nest->on_expr->fix_fields(parent_join->session, &emb_tbl_nest->on_expr);
 
3014
  }
 
3015
  else
 
3016
  {
 
3017
    /* Inject into the WHERE */
 
3018
    parent_join->conds= and_items(parent_join->conds, sj_nest->sj_on_expr);
 
3019
    parent_join->conds->fix_fields(parent_join->session, &parent_join->conds);
 
3020
    parent_join->select_lex->where= parent_join->conds;
 
3021
  }
 
3022
 
 
3023
  return(false);
 
3024
}
 
3025
 
 
3026
 
 
3027
/*
 
3028
  Convert candidate subquery predicates to semi-joins
 
3029
 
 
3030
  SYNOPSIS
 
3031
    JOIN::flatten_subqueries()
 
3032
 
 
3033
  DESCRIPTION
 
3034
    Convert candidate subquery predicates to semi-joins.
 
3035
 
 
3036
  RETURN
 
3037
    false  OK
 
3038
    true   Error
 
3039
*/
 
3040
 
 
3041
bool JOIN::flatten_subqueries()
 
3042
{
 
3043
  Item_in_subselect **in_subq;
 
3044
  Item_in_subselect **in_subq_end;
 
3045
 
 
3046
  if (sj_subselects.elements() == 0)
 
3047
    return(false);
 
3048
 
 
3049
  /* 1. Fix children subqueries */
 
3050
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
 
3051
       in_subq != in_subq_end; in_subq++)
 
3052
  {
 
3053
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
3054
    child_join->outer_tables = child_join->tables;
 
3055
    if (child_join->flatten_subqueries())
 
3056
      return(true);
 
3057
    (*in_subq)->sj_convert_priority=
 
3058
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
 
3059
  }
 
3060
  
 
3061
  bool outer_join_disable_semi_join= false;
 
3062
  /*
 
3063
   * Temporary measure: disable semi-joins when they are together with outer
 
3064
   * joins.
 
3065
   *
 
3066
   * @see LP Bug #314911
 
3067
   */
 
3068
  for (TableList *tbl= select_lex->leaf_tables; tbl; tbl=tbl->next_leaf)
 
3069
  {
 
3070
    TableList *embedding= tbl->embedding;
 
3071
    if (tbl->on_expr || (tbl->embedding && !(embedding->sj_on_expr && 
 
3072
                                            !embedding->embedding)))
 
3073
    {
 
3074
      in_subq= sj_subselects.front();
 
3075
      outer_join_disable_semi_join= true;
 
3076
    }
 
3077
  }
 
3078
 
 
3079
  if (! outer_join_disable_semi_join)
 
3080
  {
 
3081
    /*
 
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;
 
3086
    */
 
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;
 
3093
        in_subq++)
 
3094
    {
 
3095
      if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
 
3096
        return(true);
 
3097
    }
 
3098
 
 
3099
    for (in_subq= sj_subselects.front();
 
3100
        in_subq != in_subq_end &&
 
3101
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
3102
        in_subq++)
 
3103
    {
 
3104
      if (convert_subq_to_sj(this, *in_subq))
 
3105
        return(true);
 
3106
    }
 
3107
  }
 
3108
 
 
3109
  /* 3. Finalize those we didn't convert */
 
3110
  for (; in_subq!= in_subq_end; in_subq++)
 
3111
  {
 
3112
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
3113
    Item_subselect::trans_res res;
 
3114
    (*in_subq)->changed= 0;
 
3115
    (*in_subq)->fixed= 0;
 
3116
    res= (*in_subq)->select_transformer(child_join);
 
3117
    if (res == Item_subselect::RES_ERROR)
 
3118
      return(true);
 
3119
 
 
3120
    (*in_subq)->changed= 1;
 
3121
    (*in_subq)->fixed= 1;
 
3122
 
 
3123
    Item *substitute= (*in_subq)->substitution;
 
3124
    bool do_fix_fields= !(*in_subq)->substitution->fixed;
 
3125
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
 
3126
      return(true);
 
3127
 
 
3128
    //if ((*in_subq)->fix_fields(session, (*in_subq)->ref_ptr))
 
3129
    //  return(true);
 
3130
  }
 
3131
  sj_subselects.clear();
 
3132
  return(false);
 
3133
}
 
3134
 
 
3135
/**
 
3136
  Setup for execution all subqueries of a query, for which the optimizer
 
3137
  chose hash semi-join.
 
3138
 
 
3139
  @details Iterate over all subqueries of the query, and if they are under an
 
3140
  IN predicate, and the optimizer chose to compute it via hash semi-join:
 
3141
  - try to initialize all data structures needed for the materialized execution
 
3142
    of the IN predicate,
 
3143
  - if this fails, then perform the IN=>EXISTS transformation which was
 
3144
    previously blocked during JOIN::prepare.
 
3145
 
 
3146
  This method is part of the "code generation" query processing phase.
 
3147
 
 
3148
  This phase must be called after substitute_for_best_equal_field() because
 
3149
  that function may replace items with other items from a multiple equality,
 
3150
  and we need to reference the correct items in the index access method of the
 
3151
  IN predicate.
 
3152
 
 
3153
  @return Operation status
 
3154
  @retval false     success.
 
3155
  @retval true      error occurred.
 
3156
*/
 
3157
bool JOIN::setup_subquery_materialization()
 
3158
{
 
3159
  for (Select_Lex_Unit *un= select_lex->first_inner_unit(); un;
 
3160
       un= un->next_unit())
 
3161
  {
 
3162
    for (Select_Lex *sl= un->first_select(); sl; sl= sl->next_select())
 
3163
    {
 
3164
      Item_subselect *subquery_predicate= sl->master_unit()->item;
 
3165
      if (subquery_predicate &&
 
3166
          subquery_predicate->substype() == Item_subselect::IN_SUBS)
 
3167
      {
 
3168
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
 
3169
        if (in_subs->exec_method == Item_in_subselect::MATERIALIZATION &&
 
3170
            in_subs->setup_engine())
 
3171
          return true;
 
3172
      }
 
3173
    }
 
3174
  }
 
3175
  return false;
 
3176
}
 
3177
 
 
3178
 
 
3179
/*
 
3180
  Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
3181
 
 
3182
  SYNOPSIS
 
3183
    find_eq_ref_candidate()
 
3184
      table             Table to be checked
 
3185
      sj_inner_tables   Bitmap of inner tables. eq_ref(inner_table) doesn't
 
3186
                        count.
 
3187
 
 
3188
  DESCRIPTION
 
3189
    Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
3190
 
 
3191
  TODO
 
3192
    Check again if it is feasible to factor common parts with constant table
 
3193
    search
 
3194
 
 
3195
  RETURN
 
3196
    true  - There exists an eq_ref(outer-tables) candidate
 
3197
    false - Otherwise
 
3198
*/
 
3199
 
 
3200
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
 
3201
{
 
3202
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
 
3203
  uint32_t key;
 
3204
 
 
3205
  if (keyuse)
 
3206
  {
 
3207
    while (1) /* For each key */
 
3208
    {
 
3209
      key= keyuse->key;
 
3210
      KEY *keyinfo= table->key_info + key;
 
3211
      key_part_map bound_parts= 0;
 
3212
      if ((keyinfo->flags & HA_NOSAME) == HA_NOSAME)
 
3213
      {
 
3214
        do  /* For all equalities on all key parts */
 
3215
        {
 
3216
          /* Check if this is "t.keypart = expr(outer_tables) */
 
3217
          if (!(keyuse->used_tables & sj_inner_tables) &&
 
3218
              !(keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL))
 
3219
          {
 
3220
            bound_parts |= 1 << keyuse->keypart;
 
3221
          }
 
3222
          keyuse++;
 
3223
        } while (keyuse->key == key && keyuse->table == table);
 
3224
 
 
3225
        if (bound_parts == PREV_BITS(uint, keyinfo->key_parts))
 
3226
          return true;
 
3227
        if (keyuse->table != table)
 
3228
          return false;
 
3229
      }
 
3230
      else
 
3231
      {
 
3232
        do
 
3233
        {
 
3234
          keyuse++;
 
3235
          if (keyuse->table != table)
 
3236
            return false;
 
3237
        }
 
3238
        while (keyuse->key == key);
 
3239
      }
 
3240
    }
 
3241
  }
 
3242
  return false;
 
3243
}
 
3244
 
 
3245
 
 
3246
/*
 
3247
  Pull tables out of semi-join nests, if possible
 
3248
 
 
3249
  SYNOPSIS
 
3250
    pull_out_semijoin_tables()
 
3251
      join  The join where to do the semi-join flattening
 
3252
 
 
3253
  DESCRIPTION
 
3254
    Try to pull tables out of semi-join nests.
 
3255
 
 
3256
    PRECONDITIONS
 
3257
    When this function is called, the join may have several semi-join nests
 
3258
    (possibly within different semi-join nests), but it is guaranteed that
 
3259
    one semi-join nest does not contain another.
 
3260
 
 
3261
    ACTION
 
3262
    A table can be pulled out of the semi-join nest if
 
3263
     - It is a constant table
 
3264
     - It is accessed
 
3265
 
 
3266
    POSTCONDITIONS
 
3267
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
 
3268
       tables)
 
3269
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
 
3270
     * Semi-join nests TableList::sj_inner_tables
 
3271
 
 
3272
    This operation is (and should be) performed at each PS execution since
 
3273
    tables may become/cease to be constant across PS reexecutions.
 
3274
 
 
3275
  RETURN
 
3276
    0 - OK
 
3277
    1 - Out of memory error
 
3278
*/
 
3279
 
 
3280
int pull_out_semijoin_tables(JOIN *join)
 
3281
{
 
3282
  TableList *sj_nest;
 
3283
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
 
3284
 
 
3285
  /* Try pulling out of the each of the semi-joins */
 
3286
  while ((sj_nest= sj_list_it++))
 
3287
  {
 
3288
    /* Action #1: Mark the constant tables to be pulled out */
 
3289
    table_map pulled_tables= 0;
 
3290
 
 
3291
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
 
3292
    TableList *tbl;
 
3293
    while ((tbl= child_li++))
 
3294
    {
 
3295
      if (tbl->table)
 
3296
      {
 
3297
        tbl->table->reginfo.join_tab->emb_sj_nest= sj_nest;
 
3298
        if (tbl->table->map & join->const_table_map)
 
3299
        {
 
3300
          pulled_tables |= tbl->table->map;
 
3301
        }
 
3302
      }
 
3303
    }
 
3304
 
 
3305
    /*
 
3306
      Action #2: Find which tables we can pull out based on
 
3307
      update_ref_and_keys() data. Note that pulling one table out can allow
 
3308
      us to pull out some other tables too.
 
3309
    */
 
3310
    bool pulled_a_table;
 
3311
    do
 
3312
    {
 
3313
      pulled_a_table= false;
 
3314
      child_li.rewind();
 
3315
      while ((tbl= child_li++))
 
3316
      {
 
3317
        if (tbl->table && !(pulled_tables & tbl->table->map))
 
3318
        {
 
3319
          if (find_eq_ref_candidate(tbl->table,
 
3320
                                    sj_nest->nested_join->used_tables &
 
3321
                                    ~pulled_tables))
 
3322
          {
 
3323
            pulled_a_table= true;
 
3324
            pulled_tables |= tbl->table->map;
 
3325
          }
 
3326
        }
 
3327
      }
 
3328
    } while (pulled_a_table);
 
3329
 
 
3330
    child_li.rewind();
 
3331
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
 
3332
    {
 
3333
      (sj_nest)->sj_inner_tables= 0;
 
3334
      while ((tbl= child_li++))
 
3335
      {
 
3336
        if (tbl->table)
 
3337
          tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
3338
      }
 
3339
    }
 
3340
    else
 
3341
    {
 
3342
      /* Record the bitmap of inner tables, mark the inner tables */
 
3343
      table_map inner_tables=(sj_nest)->nested_join->used_tables &
 
3344
                             ~pulled_tables;
 
3345
      (sj_nest)->sj_inner_tables= inner_tables;
 
3346
      while ((tbl= child_li++))
 
3347
      {
 
3348
        if (tbl->table)
 
3349
        {
 
3350
          if (inner_tables & tbl->table->map)
 
3351
            tbl->table->reginfo.join_tab->emb_sj_nest= (sj_nest);
 
3352
          else
 
3353
            tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
3354
        }
 
3355
      }
 
3356
    }
 
3357
  }
 
3358
  return(0);
 
3359
}
 
3360
 
462
3361
/*****************************************************************************
463
 
  Create JoinTableS, make a guess about the table types,
 
3362
  Create JOIN_TABS, make a guess about the table types,
464
3363
  Approximate how many records will be used in each table
465
3364
*****************************************************************************/
466
 
ha_rows get_quick_record_count(Session *session, optimizer::SqlSelect *select, Table *table, const key_map *keys,ha_rows limit)
 
3365
 
 
3366
 
 
3367
static ha_rows get_quick_record_count(Session *session, SQL_SELECT *select,
 
3368
                                      Table *table,
 
3369
                                      const key_map *keys,ha_rows limit)
467
3370
{
468
3371
  int error;
469
3372
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
484
3387
  return(HA_POS_ERROR);                 /* This shouldn't happend */
485
3388
}
486
3389
 
 
3390
/*
 
3391
   This structure is used to collect info on potentially sargable
 
3392
   predicates in order to check whether they become sargable after
 
3393
   reading const tables.
 
3394
   We form a bitmap of indexes that can be used for sargable predicates.
 
3395
   Only such indexes are involved in range analysis.
 
3396
*/
 
3397
typedef struct st_sargable_param
 
3398
{
 
3399
  Field *field;              /* field against which to check sargability */
 
3400
  Item **arg_value;          /* values of potential keys for lookups     */
 
3401
  uint32_t num_values;           /* number of values in the above array      */
 
3402
} SARGABLE_PARAM;
 
3403
 
 
3404
/**
 
3405
  Calculate the best possible join and initialize the join structure.
 
3406
 
 
3407
  @retval
 
3408
    0   ok
 
3409
  @retval
 
3410
    1   Fatal error
 
3411
*/
 
3412
 
 
3413
static bool
 
3414
make_join_statistics(JOIN *join, TableList *tables, COND *conds,
 
3415
                     DYNAMIC_ARRAY *keyuse_array)
 
3416
{
 
3417
  int error;
 
3418
  Table *table;
 
3419
  uint32_t i,table_count,const_count,key;
 
3420
  table_map found_const_table_map, all_table_map, found_ref, refs;
 
3421
  key_map const_ref, eq_part;
 
3422
  Table **table_vector;
 
3423
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
 
3424
  KEYUSE *keyuse,*start_keyuse;
 
3425
  table_map outer_join=0;
 
3426
  SARGABLE_PARAM *sargables= 0;
 
3427
  JOIN_TAB *stat_vector[MAX_TABLES+1];
 
3428
 
 
3429
  table_count=join->tables;
 
3430
  stat=(JOIN_TAB*) join->session->calloc(sizeof(JOIN_TAB)*table_count);
 
3431
  stat_ref=(JOIN_TAB**) join->session->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
 
3432
  table_vector=(Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
 
3433
  if (!stat || !stat_ref || !table_vector)
 
3434
    return(1);                          // Eom /* purecov: inspected */
 
3435
 
 
3436
  join->best_ref=stat_vector;
 
3437
 
 
3438
  stat_end=stat+table_count;
 
3439
  found_const_table_map= all_table_map=0;
 
3440
  const_count=0;
 
3441
 
 
3442
  for (s= stat, i= 0;
 
3443
       tables;
 
3444
       s++, tables= tables->next_leaf, i++)
 
3445
  {
 
3446
    TableList *embedding= tables->embedding;
 
3447
    stat_vector[i]=s;
 
3448
    s->keys.init();
 
3449
    s->const_keys.init();
 
3450
    s->checked_keys.init();
 
3451
    s->needed_reg.init();
 
3452
    table_vector[i]=s->table=table=tables->table;
 
3453
    table->pos_in_table_list= tables;
 
3454
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
3455
    if(error)
 
3456
    {
 
3457
        table->file->print_error(error, MYF(0));
 
3458
        return(1);
 
3459
    }
 
3460
    table->quick_keys.clear_all();
 
3461
    table->reginfo.join_tab=s;
 
3462
    table->reginfo.not_exists_optimize=0;
 
3463
    memset(table->const_key_parts, 0,
 
3464
           sizeof(key_part_map)*table->s->keys);
 
3465
    all_table_map|= table->map;
 
3466
    s->join=join;
 
3467
    s->info=0;                                  // For describe
 
3468
 
 
3469
    s->dependent= tables->dep_tables;
 
3470
    s->key_dependent= 0;
 
3471
    if (tables->schema_table)
 
3472
      table->file->stats.records= 2;
 
3473
    table->quick_condition_rows= table->file->stats.records;
 
3474
 
 
3475
    s->on_expr_ref= &tables->on_expr;
 
3476
    if (*s->on_expr_ref)
 
3477
    {
 
3478
      /* s is the only inner table of an outer join */
 
3479
      if (!table->file->stats.records && !embedding)
 
3480
      {                                         // Empty table
 
3481
        s->dependent= 0;                        // Ignore LEFT JOIN depend.
 
3482
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
3483
        continue;
 
3484
      }
 
3485
      outer_join|= table->map;
 
3486
      s->embedding_map= 0;
 
3487
      for (;embedding; embedding= embedding->embedding)
 
3488
        s->embedding_map|= embedding->nested_join->nj_map;
 
3489
      continue;
 
3490
    }
 
3491
    if (embedding && !(embedding->sj_on_expr && ! embedding->embedding))
 
3492
    {
 
3493
      /* s belongs to a nested join, maybe to several embedded joins */
 
3494
      s->embedding_map= 0;
 
3495
      do
 
3496
      {
 
3497
        nested_join_st *nested_join= embedding->nested_join;
 
3498
        s->embedding_map|=nested_join->nj_map;
 
3499
        s->dependent|= embedding->dep_tables;
 
3500
        embedding= embedding->embedding;
 
3501
        outer_join|= nested_join->used_tables;
 
3502
      }
 
3503
      while (embedding);
 
3504
      continue;
 
3505
    }
 
3506
    if ((table->file->stats.records <= 1) &&
 
3507
        !s->dependent &&
 
3508
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
 
3509
    {
 
3510
      set_position(join,const_count++,s,(KEYUSE*) 0);
 
3511
    }
 
3512
  }
 
3513
  stat_vector[i]=0;
 
3514
  join->outer_join=outer_join;
 
3515
 
 
3516
  if (join->outer_join)
 
3517
  {
 
3518
    /*
 
3519
       Build transitive closure for relation 'to be dependent on'.
 
3520
       This will speed up the plan search for many cases with outer joins,
 
3521
       as well as allow us to catch illegal cross references/
 
3522
       Warshall's algorithm is used to build the transitive closure.
 
3523
       As we use bitmaps to represent the relation the complexity
 
3524
       of the algorithm is O((number of tables)^2).
 
3525
    */
 
3526
    for (i= 0, s= stat ; i < table_count ; i++, s++)
 
3527
    {
 
3528
      for (uint32_t j= 0 ; j < table_count ; j++)
 
3529
      {
 
3530
        table= stat[j].table;
 
3531
        if (s->dependent & table->map)
 
3532
          s->dependent |= table->reginfo.join_tab->dependent;
 
3533
      }
 
3534
      if (s->dependent)
 
3535
        s->table->maybe_null= 1;
 
3536
    }
 
3537
    /* Catch illegal cross references for outer joins */
 
3538
    for (i= 0, s= stat ; i < table_count ; i++, s++)
 
3539
    {
 
3540
      if (s->dependent & s->table->map)
 
3541
      {
 
3542
        join->tables=0;                 // Don't use join->table
 
3543
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
 
3544
        return(1);
 
3545
      }
 
3546
      s->key_dependent= s->dependent;
 
3547
    }
 
3548
  }
 
3549
 
 
3550
  if (conds || outer_join)
 
3551
    if (update_ref_and_keys(join->session, keyuse_array, stat, join->tables,
 
3552
                            conds, join->cond_equal,
 
3553
                            ~outer_join, join->select_lex, &sargables))
 
3554
      return(1);
 
3555
 
 
3556
  /* Read tables with 0 or 1 rows (system tables) */
 
3557
  join->const_table_map= 0;
 
3558
 
 
3559
  for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
 
3560
       p_pos < p_end ;
 
3561
       p_pos++)
 
3562
  {
 
3563
    int tmp;
 
3564
    s= p_pos->table;
 
3565
    s->type=JT_SYSTEM;
 
3566
    join->const_table_map|=s->table->map;
 
3567
    if ((tmp=join_read_const_table(s, p_pos)))
 
3568
    {
 
3569
      if (tmp > 0)
 
3570
        return(1);                      // Fatal error
 
3571
    }
 
3572
    else
 
3573
      found_const_table_map|= s->table->map;
 
3574
  }
 
3575
 
 
3576
  /* loop until no more const tables are found */
 
3577
  int ref_changed;
 
3578
  do
 
3579
  {
 
3580
  more_const_tables_found:
 
3581
    ref_changed = 0;
 
3582
    found_ref=0;
 
3583
 
 
3584
    /*
 
3585
      We only have to loop from stat_vector + const_count as
 
3586
      set_position() will move all const_tables first in stat_vector
 
3587
    */
 
3588
 
 
3589
    for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
 
3590
    {
 
3591
      table=s->table;
 
3592
 
 
3593
      /*
 
3594
        If equi-join condition by a key is null rejecting and after a
 
3595
        substitution of a const table the key value happens to be null
 
3596
        then we can state that there are no matches for this equi-join.
 
3597
      */
 
3598
      if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
 
3599
      {
 
3600
        /*
 
3601
          When performing an outer join operation if there are no matching rows
 
3602
          for the single row of the outer table all the inner tables are to be
 
3603
          null complemented and thus considered as constant tables.
 
3604
          Here we apply this consideration to the case of outer join operations
 
3605
          with a single inner table only because the case with nested tables
 
3606
          would require a more thorough analysis.
 
3607
          TODO. Apply single row substitution to null complemented inner tables
 
3608
          for nested outer join operations.
 
3609
        */
 
3610
        while (keyuse->table == table)
 
3611
        {
 
3612
          if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
 
3613
              keyuse->val->is_null() && keyuse->null_rejecting)
 
3614
          {
 
3615
            s->type= JT_CONST;
 
3616
            table->mark_as_null_row();
 
3617
            found_const_table_map|= table->map;
 
3618
            join->const_table_map|= table->map;
 
3619
            set_position(join,const_count++,s,(KEYUSE*) 0);
 
3620
            goto more_const_tables_found;
 
3621
           }
 
3622
          keyuse++;
 
3623
        }
 
3624
      }
 
3625
 
 
3626
      if (s->dependent)                         // If dependent on some table
 
3627
      {
 
3628
        // All dep. must be constants
 
3629
        if (s->dependent & ~(found_const_table_map))
 
3630
          continue;
 
3631
        if (table->file->stats.records <= 1L &&
 
3632
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
3633
            !table->pos_in_table_list->embedding)
 
3634
        {                                       // system table
 
3635
          int tmp= 0;
 
3636
          s->type=JT_SYSTEM;
 
3637
          join->const_table_map|=table->map;
 
3638
          set_position(join,const_count++,s,(KEYUSE*) 0);
 
3639
          if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
 
3640
          {
 
3641
            if (tmp > 0)
 
3642
              return(1);                        // Fatal error
 
3643
          }
 
3644
          else
 
3645
            found_const_table_map|= table->map;
 
3646
          continue;
 
3647
        }
 
3648
      }
 
3649
      /* check if table can be read by key or table only uses const refs */
 
3650
      if ((keyuse=s->keyuse))
 
3651
      {
 
3652
        s->type= JT_REF;
 
3653
        while (keyuse->table == table)
 
3654
        {
 
3655
          start_keyuse=keyuse;
 
3656
          key=keyuse->key;
 
3657
          s->keys.set_bit(key);               // QQ: remove this ?
 
3658
 
 
3659
          refs=0;
 
3660
          const_ref.clear_all();
 
3661
          eq_part.clear_all();
 
3662
          do
 
3663
          {
 
3664
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
 
3665
            {
 
3666
              if (!((~found_const_table_map) & keyuse->used_tables))
 
3667
                const_ref.set_bit(keyuse->keypart);
 
3668
              else
 
3669
                refs|=keyuse->used_tables;
 
3670
              eq_part.set_bit(keyuse->keypart);
 
3671
            }
 
3672
            keyuse++;
 
3673
          } while (keyuse->table == table && keyuse->key == key);
 
3674
 
 
3675
          if (eq_part.is_prefix(table->key_info[key].key_parts) &&
 
3676
              !table->pos_in_table_list->embedding)
 
3677
          {
 
3678
            if ((table->key_info[key].flags & (HA_NOSAME))
 
3679
                 == HA_NOSAME)
 
3680
            {
 
3681
              if (const_ref == eq_part)
 
3682
              {                                 // Found everything for ref.
 
3683
                int tmp;
 
3684
                ref_changed = 1;
 
3685
                s->type= JT_CONST;
 
3686
                join->const_table_map|=table->map;
 
3687
                set_position(join,const_count++,s,start_keyuse);
 
3688
                if (create_ref_for_key(join, s, start_keyuse,
 
3689
                                       found_const_table_map))
 
3690
                  return(1);
 
3691
                if ((tmp=join_read_const_table(s,
 
3692
                                               join->positions+const_count-1)))
 
3693
                {
 
3694
                  if (tmp > 0)
 
3695
                    return(1);                  // Fatal error
 
3696
                }
 
3697
                else
 
3698
                  found_const_table_map|= table->map;
 
3699
                break;
 
3700
              }
 
3701
              else
 
3702
                found_ref|= refs;      // Table is const if all refs are const
 
3703
            }
 
3704
            else if (const_ref == eq_part)
 
3705
              s->const_keys.set_bit(key);
 
3706
          }
 
3707
        }
 
3708
      }
 
3709
    }
 
3710
  } while (join->const_table_map & found_ref && ref_changed);
 
3711
 
 
3712
  /*
 
3713
    Update info on indexes that can be used for search lookups as
 
3714
    reading const tables may has added new sargable predicates.
 
3715
  */
 
3716
  if (const_count && sargables)
 
3717
  {
 
3718
    for( ; sargables->field ; sargables++)
 
3719
    {
 
3720
      Field *field= sargables->field;
 
3721
      JOIN_TAB *join_tab= field->table->reginfo.join_tab;
 
3722
      key_map possible_keys= field->key_start;
 
3723
      possible_keys.intersect(field->table->keys_in_use_for_query);
 
3724
      bool is_const= 1;
 
3725
      for (uint32_t j=0; j < sargables->num_values; j++)
 
3726
        is_const&= sargables->arg_value[j]->const_item();
 
3727
      if (is_const)
 
3728
        join_tab[0].const_keys.merge(possible_keys);
 
3729
    }
 
3730
  }
 
3731
 
 
3732
  if (pull_out_semijoin_tables(join))
 
3733
    return(true);
 
3734
 
 
3735
  /* Calc how many (possible) matched records in each table */
 
3736
 
 
3737
  for (s=stat ; s < stat_end ; s++)
 
3738
  {
 
3739
    if (s->type == JT_SYSTEM || s->type == JT_CONST)
 
3740
    {
 
3741
      /* Only one matching row */
 
3742
      s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
 
3743
      continue;
 
3744
    }
 
3745
    /* Approximate found rows and time to read them */
 
3746
    s->found_records=s->records=s->table->file->stats.records;
 
3747
    s->read_time=(ha_rows) s->table->file->scan_time();
 
3748
 
 
3749
    /*
 
3750
      Set a max range of how many seeks we can expect when using keys
 
3751
      This is can't be to high as otherwise we are likely to use
 
3752
      table scan.
 
3753
    */
 
3754
    s->worst_seeks= cmin((double) s->found_records / 10,
 
3755
                        (double) s->read_time*3);
 
3756
    if (s->worst_seeks < 2.0)                   // Fix for small tables
 
3757
      s->worst_seeks=2.0;
 
3758
 
 
3759
    /*
 
3760
      Add to stat->const_keys those indexes for which all group fields or
 
3761
      all select distinct fields participate in one index.
 
3762
    */
 
3763
    add_group_and_distinct_keys(join, s);
 
3764
 
 
3765
    if (!s->const_keys.is_clear_all() &&
 
3766
        !s->table->pos_in_table_list->embedding)
 
3767
    {
 
3768
      ha_rows records;
 
3769
      SQL_SELECT *select;
 
3770
      select= make_select(s->table, found_const_table_map,
 
3771
                          found_const_table_map,
 
3772
                          *s->on_expr_ref ? *s->on_expr_ref : conds,
 
3773
                          1, &error);
 
3774
      if (!select)
 
3775
        return(1);
 
3776
      records= get_quick_record_count(join->session, select, s->table,
 
3777
                                      &s->const_keys, join->row_limit);
 
3778
      s->quick=select->quick;
 
3779
      s->needed_reg=select->needed_reg;
 
3780
      select->quick=0;
 
3781
      if (records == 0 && s->table->reginfo.impossible_range)
 
3782
      {
 
3783
        /*
 
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.
 
3788
        */
 
3789
        join->const_table_map|= s->table->map;
 
3790
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
3791
        s->type= JT_CONST;
 
3792
        if (*s->on_expr_ref)
 
3793
        {
 
3794
          /* Generate empty row */
 
3795
          s->info= "Impossible ON condition";
 
3796
          found_const_table_map|= s->table->map;
 
3797
          s->type= JT_CONST;
 
3798
          s->table->mark_as_null_row();         // All fields are NULL
 
3799
        }
 
3800
      }
 
3801
      if (records != HA_POS_ERROR)
 
3802
      {
 
3803
        s->found_records=records;
 
3804
        s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
 
3805
      }
 
3806
      delete select;
 
3807
    }
 
3808
  }
 
3809
 
 
3810
  join->join_tab=stat;
 
3811
  join->map2table=stat_ref;
 
3812
  join->table= join->all_tables=table_vector;
 
3813
  join->const_tables=const_count;
 
3814
  join->found_const_table_map=found_const_table_map;
 
3815
 
 
3816
  /* Find an optimal join order of the non-constant tables. */
 
3817
  if (join->const_tables != join->tables)
 
3818
  {
 
3819
    optimize_keyuse(join, keyuse_array);
 
3820
    if (choose_plan(join, all_table_map & ~join->const_table_map))
 
3821
      return(true);
 
3822
  }
 
3823
  else
 
3824
  {
 
3825
    memcpy(join->best_positions, join->positions,
 
3826
           sizeof(POSITION)*join->const_tables);
 
3827
    join->best_read=1.0;
 
3828
  }
 
3829
  /* Generate an execution plan from the found optimal join order. */
 
3830
  return(join->session->killed || get_best_combination(join));
 
3831
}
 
3832
 
 
3833
 
487
3834
/*****************************************************************************
488
3835
  Check with keys are used and with tables references with tables
489
3836
  Updates in stat:
492
3839
          keyuse     Pointer to possible keys
493
3840
*****************************************************************************/
494
3841
 
 
3842
/// Used when finding key fields
 
3843
typedef struct key_field_t {
 
3844
  Field         *field;
 
3845
  Item          *val;                   ///< May be empty if diff constant
 
3846
  uint          level;
 
3847
  uint          optimize; // KEY_OPTIMIZE_*
 
3848
  bool          eq_func;
 
3849
  /**
 
3850
    If true, the condition this struct represents will not be satisfied
 
3851
    when val IS NULL.
 
3852
  */
 
3853
  bool          null_rejecting;
 
3854
  bool          *cond_guard; /* See KEYUSE::cond_guard */
 
3855
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
 
3856
} KEY_FIELD;
 
3857
 
 
3858
/**
 
3859
  Merge new key definitions to old ones, remove those not used in both.
 
3860
 
 
3861
  This is called for OR between different levels.
 
3862
 
 
3863
  To be able to do 'ref_or_null' we merge a comparison of a column
 
3864
  and 'column IS NULL' to one test.  This is useful for sub select queries
 
3865
  that are internally transformed to something like:.
 
3866
 
 
3867
  @code
 
3868
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
 
3869
  @endcode
 
3870
 
 
3871
  KEY_FIELD::null_rejecting is processed as follows: @n
 
3872
  result has null_rejecting=true if it is set for both ORed references.
 
3873
  for example:
 
3874
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
 
3875
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
 
3876
 
 
3877
  @todo
 
3878
    The result of this is that we're missing some 'ref' accesses.
 
3879
    OptimizerTeam: Fix this
 
3880
*/
 
3881
 
 
3882
static KEY_FIELD *
 
3883
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
 
3884
                 uint32_t and_level)
 
3885
{
 
3886
  if (start == new_fields)
 
3887
    return start;                               // Impossible or
 
3888
  if (new_fields == end)
 
3889
    return start;                               // No new fields, skip all
 
3890
 
 
3891
  KEY_FIELD *first_free=new_fields;
 
3892
 
 
3893
  /* Mark all found fields in old array */
 
3894
  for (; new_fields != end ; new_fields++)
 
3895
  {
 
3896
    for (KEY_FIELD *old=start ; old != first_free ; old++)
 
3897
    {
 
3898
      if (old->field == new_fields->field)
 
3899
      {
 
3900
        /*
 
3901
          NOTE: below const_item() call really works as "!used_tables()", i.e.
 
3902
          it can return false where it is feasible to make it return true.
 
3903
 
 
3904
          The cause is as follows: Some of the tables are already known to be
 
3905
          const tables (the detection code is in make_join_statistics(),
 
3906
          above the update_ref_and_keys() call), but we didn't propagate
 
3907
          information about this: Table::const_table is not set to true, and
 
3908
          Item::update_used_tables() hasn't been called for each item.
 
3909
          The result of this is that we're missing some 'ref' accesses.
 
3910
          TODO: OptimizerTeam: Fix this
 
3911
        */
 
3912
        if (!new_fields->val->const_item())
 
3913
        {
 
3914
          /*
 
3915
            If the value matches, we can use the key reference.
 
3916
            If not, we keep it until we have examined all new values
 
3917
          */
 
3918
          if (old->val->eq(new_fields->val, old->field->binary()))
 
3919
          {
 
3920
            old->level= and_level;
 
3921
            old->optimize= ((old->optimize & new_fields->optimize &
 
3922
                             KEY_OPTIMIZE_EXISTS) |
 
3923
                            ((old->optimize | new_fields->optimize) &
 
3924
                             KEY_OPTIMIZE_REF_OR_NULL));
 
3925
            old->null_rejecting= (old->null_rejecting &&
 
3926
                                  new_fields->null_rejecting);
 
3927
          }
 
3928
        }
 
3929
        else if (old->eq_func && new_fields->eq_func &&
 
3930
                 old->val->eq_by_collation(new_fields->val,
 
3931
                                           old->field->binary(),
 
3932
                                           old->field->charset()))
 
3933
 
 
3934
        {
 
3935
          old->level= and_level;
 
3936
          old->optimize= ((old->optimize & new_fields->optimize &
 
3937
                           KEY_OPTIMIZE_EXISTS) |
 
3938
                          ((old->optimize | new_fields->optimize) &
 
3939
                           KEY_OPTIMIZE_REF_OR_NULL));
 
3940
          old->null_rejecting= (old->null_rejecting &&
 
3941
                                new_fields->null_rejecting);
 
3942
        }
 
3943
        else if (old->eq_func && new_fields->eq_func &&
 
3944
                 ((old->val->const_item() && old->val->is_null()) ||
 
3945
                  new_fields->val->is_null()))
 
3946
        {
 
3947
          /* field = expression OR field IS NULL */
 
3948
          old->level= and_level;
 
3949
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
 
3950
          /*
 
3951
            Remember the NOT NULL value unless the value does not depend
 
3952
            on other tables.
 
3953
          */
 
3954
          if (!old->val->used_tables() && old->val->is_null())
 
3955
            old->val= new_fields->val;
 
3956
          /* The referred expression can be NULL: */
 
3957
          old->null_rejecting= 0;
 
3958
        }
 
3959
        else
 
3960
        {
 
3961
          /*
 
3962
            We are comparing two different const.  In this case we can't
 
3963
            use a key-lookup on this so it's better to remove the value
 
3964
            and let the range optimzier handle it
 
3965
          */
 
3966
          if (old == --first_free)              // If last item
 
3967
            break;
 
3968
          *old= *first_free;                    // Remove old value
 
3969
          old--;                                // Retry this value
 
3970
        }
 
3971
      }
 
3972
    }
 
3973
  }
 
3974
  /* Remove all not used items */
 
3975
  for (KEY_FIELD *old=start ; old != first_free ;)
 
3976
  {
 
3977
    if (old->level != and_level)
 
3978
    {                                           // Not used in all levels
 
3979
      if (old == --first_free)
 
3980
        break;
 
3981
      *old= *first_free;                        // Remove old value
 
3982
      continue;
 
3983
    }
 
3984
    old++;
 
3985
  }
 
3986
  return first_free;
 
3987
}
 
3988
 
 
3989
 
 
3990
/**
 
3991
  Add a possible key to array of possible keys if it's usable as a key
 
3992
 
 
3993
    @param key_fields      Pointer to add key, if usable
 
3994
    @param and_level       And level, to be stored in KEY_FIELD
 
3995
    @param cond            Condition predicate
 
3996
    @param field           Field used in comparision
 
3997
    @param eq_func         True if we used =, <=> or IS NULL
 
3998
    @param value           Value used for comparison with field
 
3999
    @param usable_tables   Tables which can be used for key optimization
 
4000
    @param sargables       IN/OUT Array of found sargable candidates
 
4001
 
 
4002
  @note
 
4003
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
 
4004
    table, we store this to be able to do not exists optimization later.
 
4005
 
 
4006
  @returns
 
4007
    *key_fields is incremented if we stored a key in the array
 
4008
*/
 
4009
 
 
4010
static void
 
4011
add_key_field(KEY_FIELD **key_fields,uint32_t and_level, Item_func *cond,
 
4012
              Field *field, bool eq_func, Item **value, uint32_t num_values,
 
4013
              table_map usable_tables, SARGABLE_PARAM **sargables)
 
4014
{
 
4015
  uint32_t exists_optimize= 0;
 
4016
  if (!(field->flags & PART_KEY_FLAG))
 
4017
  {
 
4018
    // Don't remove column IS NULL on a LEFT JOIN table
 
4019
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
4020
        !field->table->maybe_null || field->null_ptr)
 
4021
      return;                                   // Not a key. Skip it
 
4022
    exists_optimize= KEY_OPTIMIZE_EXISTS;
 
4023
    assert(num_values == 1);
 
4024
  }
 
4025
  else
 
4026
  {
 
4027
    table_map used_tables=0;
 
4028
    bool optimizable=0;
 
4029
    for (uint32_t i=0; i<num_values; i++)
 
4030
    {
 
4031
      used_tables|=(value[i])->used_tables();
 
4032
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
 
4033
        optimizable=1;
 
4034
    }
 
4035
    if (!optimizable)
 
4036
      return;
 
4037
    if (!(usable_tables & field->table->map))
 
4038
    {
 
4039
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
4040
          !field->table->maybe_null || field->null_ptr)
 
4041
        return;                                 // Can't use left join optimize
 
4042
      exists_optimize= KEY_OPTIMIZE_EXISTS;
 
4043
    }
 
4044
    else
 
4045
    {
 
4046
      JOIN_TAB *stat=field->table->reginfo.join_tab;
 
4047
      key_map possible_keys=field->key_start;
 
4048
      possible_keys.intersect(field->table->keys_in_use_for_query);
 
4049
      stat[0].keys.merge(possible_keys);             // Add possible keys
 
4050
 
 
4051
      /*
 
4052
        Save the following cases:
 
4053
        Field op constant
 
4054
        Field LIKE constant where constant doesn't start with a wildcard
 
4055
        Field = field2 where field2 is in a different table
 
4056
        Field op formula
 
4057
        Field IS NULL
 
4058
        Field IS NOT NULL
 
4059
         Field BETWEEN ...
 
4060
         Field IN ...
 
4061
      */
 
4062
      stat[0].key_dependent|=used_tables;
 
4063
 
 
4064
      bool is_const=1;
 
4065
      for (uint32_t i=0; i<num_values; i++)
 
4066
      {
 
4067
        if (!(is_const&= value[i]->const_item()))
 
4068
          break;
 
4069
      }
 
4070
      if (is_const)
 
4071
        stat[0].const_keys.merge(possible_keys);
 
4072
      else if (!eq_func)
 
4073
      {
 
4074
        /*
 
4075
          Save info to be able check whether this predicate can be
 
4076
          considered as sargable for range analisis after reading const tables.
 
4077
          We do not save info about equalities as update_const_equal_items
 
4078
          will take care of updating info on keys from sargable equalities.
 
4079
        */
 
4080
        (*sargables)--;
 
4081
        (*sargables)->field= field;
 
4082
        (*sargables)->arg_value= value;
 
4083
        (*sargables)->num_values= num_values;
 
4084
      }
 
4085
      /*
 
4086
        We can't always use indexes when comparing a string index to a
 
4087
        number. cmp_type() is checked to allow compare of dates to numbers.
 
4088
        eq_func is NEVER true when num_values > 1
 
4089
       */
 
4090
      if (!eq_func)
 
4091
      {
 
4092
        /*
 
4093
          Additional optimization: if we're processing
 
4094
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
 
4095
          "t.key = c1".
 
4096
          TODO: This is a very limited fix. A more generic fix is possible.
 
4097
          There are 2 options:
 
4098
          A) Make equality propagation code be able to handle BETWEEN
 
4099
             (including cases like t1.key BETWEEN t2.key AND t3.key)
 
4100
          B) Make range optimizer to infer additional "t.key = c" equalities
 
4101
             and use them in equality propagation process (see details in
 
4102
             OptimizerKBAndTodo)
 
4103
        */
 
4104
        if ((cond->functype() != Item_func::BETWEEN) ||
 
4105
            ((Item_func_between*) cond)->negated ||
 
4106
            !value[0]->eq(value[1], field->binary()))
 
4107
          return;
 
4108
        eq_func= true;
 
4109
      }
 
4110
 
 
4111
      if (field->result_type() == STRING_RESULT)
 
4112
      {
 
4113
        if ((*value)->result_type() != STRING_RESULT)
 
4114
        {
 
4115
          if (field->cmp_type() != (*value)->result_type())
 
4116
            return;
 
4117
        }
 
4118
        else
 
4119
        {
 
4120
          /*
 
4121
            We can't use indexes if the effective collation
 
4122
            of the operation differ from the field collation.
 
4123
          */
 
4124
          if (field->cmp_type() == STRING_RESULT &&
 
4125
              ((Field_str*)field)->charset() != cond->compare_collation())
 
4126
            return;
 
4127
        }
 
4128
      }
 
4129
    }
 
4130
  }
 
4131
  /*
 
4132
    For the moment eq_func is always true. This slot is reserved for future
 
4133
    extensions where we want to remembers other things than just eq comparisons
 
4134
  */
 
4135
  assert(eq_func);
 
4136
  /* Store possible eq field */
 
4137
  (*key_fields)->field=         field;
 
4138
  (*key_fields)->eq_func=       eq_func;
 
4139
  (*key_fields)->val=           *value;
 
4140
  (*key_fields)->level=         and_level;
 
4141
  (*key_fields)->optimize=      exists_optimize;
 
4142
  /*
 
4143
    If the condition has form "tbl.keypart = othertbl.field" and
 
4144
    othertbl.field can be NULL, there will be no matches if othertbl.field
 
4145
    has NULL value.
 
4146
    We use null_rejecting in add_not_null_conds() to add
 
4147
    'othertbl.field IS NOT NULL' to tab->select_cond.
 
4148
  */
 
4149
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
 
4150
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
 
4151
                                  ((*value)->type() == Item::FIELD_ITEM) &&
 
4152
                                  ((Item_field*)*value)->field->maybe_null());
 
4153
  (*key_fields)->cond_guard= NULL;
 
4154
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name &&
 
4155
                              cond->name < subq_sj_cond_name + 64)?
 
4156
                              cond->name - subq_sj_cond_name: UINT_MAX;
 
4157
  (*key_fields)++;
 
4158
}
 
4159
 
 
4160
/**
 
4161
  Add possible keys to array of possible keys originated from a simple
 
4162
  predicate.
 
4163
 
 
4164
    @param  key_fields     Pointer to add key, if usable
 
4165
    @param  and_level      And level, to be stored in KEY_FIELD
 
4166
    @param  cond           Condition predicate
 
4167
    @param  field          Field used in comparision
 
4168
    @param  eq_func        True if we used =, <=> or IS NULL
 
4169
    @param  value          Value used for comparison with field
 
4170
                           Is NULL for BETWEEN and IN
 
4171
    @param  usable_tables  Tables which can be used for key optimization
 
4172
    @param  sargables      IN/OUT Array of found sargable candidates
 
4173
 
 
4174
  @note
 
4175
    If field items f1 and f2 belong to the same multiple equality and
 
4176
    a key is added for f1, the the same key is added for f2.
 
4177
 
 
4178
  @returns
 
4179
    *key_fields is incremented if we stored a key in the array
 
4180
*/
 
4181
 
 
4182
static void
 
4183
add_key_equal_fields(KEY_FIELD **key_fields, uint32_t and_level,
 
4184
                     Item_func *cond, Item_field *field_item,
 
4185
                     bool eq_func, Item **val,
 
4186
                     uint32_t num_values, table_map usable_tables,
 
4187
                     SARGABLE_PARAM **sargables)
 
4188
{
 
4189
  Field *field= field_item->field;
 
4190
  add_key_field(key_fields, and_level, cond, field,
 
4191
                eq_func, val, num_values, usable_tables, sargables);
 
4192
  Item_equal *item_equal= field_item->item_equal;
 
4193
  if (item_equal)
 
4194
  {
 
4195
    /*
 
4196
      Add to the set of possible key values every substitution of
 
4197
      the field for an equal field included into item_equal
 
4198
    */
 
4199
    Item_equal_iterator it(*item_equal);
 
4200
    Item_field *item;
 
4201
    while ((item= it++))
 
4202
    {
 
4203
      if (!field->eq(item->field))
 
4204
      {
 
4205
        add_key_field(key_fields, and_level, cond, item->field,
 
4206
                      eq_func, val, num_values, usable_tables,
 
4207
                      sargables);
 
4208
      }
 
4209
    }
 
4210
  }
 
4211
}
 
4212
 
 
4213
static void
 
4214
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint32_t *and_level,
 
4215
               COND *cond, table_map usable_tables,
 
4216
               SARGABLE_PARAM **sargables)
 
4217
{
 
4218
  if (cond->type() == Item_func::COND_ITEM)
 
4219
  {
 
4220
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
 
4221
    KEY_FIELD *org_key_fields= *key_fields;
 
4222
 
 
4223
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
4224
    {
 
4225
      Item *item;
 
4226
      while ((item=li++))
 
4227
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
4228
                       sargables);
 
4229
      for (; org_key_fields != *key_fields ; org_key_fields++)
 
4230
        org_key_fields->level= *and_level;
 
4231
    }
 
4232
    else
 
4233
    {
 
4234
      (*and_level)++;
 
4235
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
 
4236
                     sargables);
 
4237
      Item *item;
 
4238
      while ((item=li++))
 
4239
      {
 
4240
        KEY_FIELD *start_key_fields= *key_fields;
 
4241
        (*and_level)++;
 
4242
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
4243
                       sargables);
 
4244
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
 
4245
                                     *key_fields,++(*and_level));
 
4246
      }
 
4247
    }
 
4248
    return;
 
4249
  }
 
4250
 
 
4251
  /*
 
4252
    Subquery optimization: Conditions that are pushed down into subqueries
 
4253
    are wrapped into Item_func_trig_cond. We process the wrapped condition
 
4254
    but need to set cond_guard for KEYUSE elements generated from it.
 
4255
  */
 
4256
  {
 
4257
    if (cond->type() == Item::FUNC_ITEM &&
 
4258
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
 
4259
    {
 
4260
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
 
4261
      if (!join->group_list && !join->order &&
 
4262
          join->unit->item &&
 
4263
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
 
4264
          !join->unit->is_union())
 
4265
      {
 
4266
        KEY_FIELD *save= *key_fields;
 
4267
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
 
4268
                       sargables);
 
4269
        // Indicate that this ref access candidate is for subquery lookup:
 
4270
        for (; save != *key_fields; save++)
 
4271
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
 
4272
      }
 
4273
      return;
 
4274
    }
 
4275
  }
 
4276
 
 
4277
  /* If item is of type 'field op field/constant' add it to key_fields */
 
4278
  if (cond->type() != Item::FUNC_ITEM)
 
4279
    return;
 
4280
  Item_func *cond_func= (Item_func*) cond;
 
4281
  switch (cond_func->select_optimize()) {
 
4282
  case Item_func::OPTIMIZE_NONE:
 
4283
    break;
 
4284
  case Item_func::OPTIMIZE_KEY:
 
4285
  {
 
4286
    Item **values;
 
4287
    // BETWEEN, IN, NE
 
4288
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
 
4289
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
4290
    {
 
4291
      values= cond_func->arguments()+1;
 
4292
      if (cond_func->functype() == Item_func::NE_FUNC &&
 
4293
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
4294
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
4295
        values--;
 
4296
      assert(cond_func->functype() != Item_func::IN_FUNC ||
 
4297
                  cond_func->argument_count() != 2);
 
4298
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4299
                           (Item_field*) (cond_func->key_item()->real_item()),
 
4300
                           0, values,
 
4301
                           cond_func->argument_count()-1,
 
4302
                           usable_tables, sargables);
 
4303
    }
 
4304
    if (cond_func->functype() == Item_func::BETWEEN)
 
4305
    {
 
4306
      values= cond_func->arguments();
 
4307
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
4308
      {
 
4309
        Item_field *field_item;
 
4310
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
 
4311
            &&
 
4312
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
 
4313
        {
 
4314
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
 
4315
          add_key_equal_fields(key_fields, *and_level, cond_func,
 
4316
                               field_item, 0, values, 1, usable_tables,
 
4317
                               sargables);
 
4318
        }
 
4319
      }
 
4320
    }
 
4321
    break;
 
4322
  }
 
4323
  case Item_func::OPTIMIZE_OP:
 
4324
  {
 
4325
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
 
4326
                     cond_func->functype() == Item_func::EQUAL_FUNC);
 
4327
 
 
4328
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
4329
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
4330
    {
 
4331
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4332
                        (Item_field*) (cond_func->arguments()[0])->real_item(),
 
4333
                           equal_func,
 
4334
                           cond_func->arguments()+1, 1, usable_tables,
 
4335
                           sargables);
 
4336
    }
 
4337
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
4338
        cond_func->functype() != Item_func::LIKE_FUNC &&
 
4339
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
 
4340
    {
 
4341
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4342
                       (Item_field*) (cond_func->arguments()[1])->real_item(),
 
4343
                           equal_func,
 
4344
                           cond_func->arguments(),1,usable_tables,
 
4345
                           sargables);
 
4346
    }
 
4347
    break;
 
4348
  }
 
4349
  case Item_func::OPTIMIZE_NULL:
 
4350
    /* column_name IS [NOT] NULL */
 
4351
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
4352
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
4353
    {
 
4354
      Item *tmp=new Item_null;
 
4355
      if (unlikely(!tmp))                       // Should never be true
 
4356
        return;
 
4357
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4358
                    (Item_field*) (cond_func->arguments()[0])->real_item(),
 
4359
                    cond_func->functype() == Item_func::ISNULL_FUNC,
 
4360
                           &tmp, 1, usable_tables, sargables);
 
4361
    }
 
4362
    break;
 
4363
  case Item_func::OPTIMIZE_EQUAL:
 
4364
    Item_equal *item_equal= (Item_equal *) cond;
 
4365
    Item *const_item= item_equal->get_const();
 
4366
    Item_equal_iterator it(*item_equal);
 
4367
    Item_field *item;
 
4368
    if (const_item)
 
4369
    {
 
4370
      /*
 
4371
        For each field field1 from item_equal consider the equality
 
4372
        field1=const_item as a condition allowing an index access of the table
 
4373
        with field1 by the keys value of field1.
 
4374
      */
 
4375
      while ((item= it++))
 
4376
      {
 
4377
        add_key_field(key_fields, *and_level, cond_func, item->field,
 
4378
                      true, &const_item, 1, usable_tables, sargables);
 
4379
      }
 
4380
    }
 
4381
    else
 
4382
    {
 
4383
      /*
 
4384
        Consider all pairs of different fields included into item_equal.
 
4385
        For each of them (field1, field1) consider the equality
 
4386
        field1=field2 as a condition allowing an index access of the table
 
4387
        with field1 by the keys value of field2.
 
4388
      */
 
4389
      Item_equal_iterator fi(*item_equal);
 
4390
      while ((item= fi++))
 
4391
      {
 
4392
        Field *field= item->field;
 
4393
        while ((item= it++))
 
4394
        {
 
4395
          if (!field->eq(item->field))
 
4396
          {
 
4397
            add_key_field(key_fields, *and_level, cond_func, field,
 
4398
                          true, (Item **) &item, 1, usable_tables,
 
4399
                          sargables);
 
4400
          }
 
4401
        }
 
4402
        it.rewind();
 
4403
      }
 
4404
    }
 
4405
    break;
 
4406
  }
 
4407
}
495
4408
 
496
4409
/**
497
4410
  Add all keys with uses 'field' for some keypart.
498
4411
 
499
4412
  If field->and_level != and_level then only mark key_part as const_part.
500
4413
*/
501
 
uint32_t max_part_bit(key_part_map bits)
 
4414
 
 
4415
static uint
 
4416
max_part_bit(key_part_map bits)
502
4417
{
503
4418
  uint32_t found;
504
4419
  for (found=0; bits & 1 ; found++,bits>>=1) ;
505
4420
  return found;
506
4421
}
507
4422
 
508
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b)
 
4423
static void
 
4424
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
 
4425
{
 
4426
  Field *field=key_field->field;
 
4427
  Table *form= field->table;
 
4428
  KEYUSE keyuse;
 
4429
 
 
4430
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
 
4431
  {
 
4432
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
4433
    {
 
4434
      if (!(form->keys_in_use_for_query.is_set(key)))
 
4435
        continue;
 
4436
 
 
4437
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
 
4438
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
4439
      {
 
4440
        if (field->eq(form->key_info[key].key_part[part].field))
 
4441
        {
 
4442
          keyuse.table= field->table;
 
4443
          keyuse.val =  key_field->val;
 
4444
          keyuse.key =  key;
 
4445
          keyuse.keypart=part;
 
4446
          keyuse.keypart_map= (key_part_map) 1 << part;
 
4447
          keyuse.used_tables=key_field->val->used_tables();
 
4448
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
 
4449
          keyuse.null_rejecting= key_field->null_rejecting;
 
4450
          keyuse.cond_guard= key_field->cond_guard;
 
4451
          keyuse.sj_pred_no= key_field->sj_pred_no;
 
4452
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
4453
        }
 
4454
      }
 
4455
    }
 
4456
  }
 
4457
}
 
4458
 
 
4459
static int
 
4460
sort_keyuse(KEYUSE *a,KEYUSE *b)
509
4461
{
510
4462
  int res;
511
 
  if (a->getTable()->tablenr != b->getTable()->tablenr)
512
 
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
513
 
  if (a->getKey() != b->getKey())
514
 
    return static_cast<int>((a->getKey() - b->getKey()));
515
 
  if (a->getKeypart() != b->getKeypart())
516
 
    return static_cast<int>((a->getKeypart() - b->getKeypart()));
 
4463
  if (a->table->tablenr != b->table->tablenr)
 
4464
    return (int) (a->table->tablenr - b->table->tablenr);
 
4465
  if (a->key != b->key)
 
4466
    return (int) (a->key - b->key);
 
4467
  if (a->keypart != b->keypart)
 
4468
    return (int) (a->keypart - b->keypart);
517
4469
  // Place const values before other ones
518
 
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
519
 
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
 
4470
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
 
4471
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
520
4472
    return res;
521
4473
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
522
 
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
523
 
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
 
4474
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
 
4475
                (b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
 
4476
}
 
4477
 
 
4478
 
 
4479
/*
 
4480
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
 
4481
 
 
4482
    This function populates KEY_FIELD array with entries generated from the
 
4483
    ON condition of the given nested join, and does the same for nested joins
 
4484
    contained within this nested join.
 
4485
 
 
4486
  @param[in]      nested_join_table   Nested join pseudo-table to process
 
4487
  @param[in,out]  end                 End of the key field array
 
4488
  @param[in,out]  and_level           And-level
 
4489
  @param[in,out]  sargables           Array of found sargable candidates
 
4490
 
 
4491
 
 
4492
  @note
 
4493
    We can add accesses to the tables that are direct children of this nested
 
4494
    join (1), and are not inner tables w.r.t their neighbours (2).
 
4495
 
 
4496
    Example for #1 (outer brackets pair denotes nested join this function is
 
4497
    invoked for):
 
4498
    @code
 
4499
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
 
4500
    @endcode
 
4501
    Example for #2:
 
4502
    @code
 
4503
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
 
4504
    @endcode
 
4505
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
 
4506
    t1 only.
 
4507
    Example #3:
 
4508
    @code
 
4509
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
 
4510
    @endcode
 
4511
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
 
4512
*/
 
4513
 
 
4514
static void add_key_fields_for_nj(JOIN *join, TableList *nested_join_table,
 
4515
                                  KEY_FIELD **end, uint32_t *and_level,
 
4516
                                  SARGABLE_PARAM **sargables)
 
4517
{
 
4518
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
 
4519
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
 
4520
  bool have_another = false;
 
4521
  table_map tables= 0;
 
4522
  TableList *table;
 
4523
  assert(nested_join_table->nested_join);
 
4524
 
 
4525
  while ((table= li++) || (have_another && (li=li2, have_another=false,
 
4526
                                            (table= li++))))
 
4527
  {
 
4528
    if (table->nested_join)
 
4529
    {
 
4530
      if (!table->on_expr)
 
4531
      {
 
4532
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
 
4533
        have_another= true;
 
4534
        li2= li;
 
4535
        li= List_iterator<TableList>(table->nested_join->join_list);
 
4536
      }
 
4537
      else
 
4538
        add_key_fields_for_nj(join, table, end, and_level, sargables);
 
4539
    }
 
4540
    else
 
4541
      if (!table->on_expr)
 
4542
        tables |= table->table->map;
 
4543
  }
 
4544
  if (nested_join_table->on_expr)
 
4545
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
 
4546
                   sargables);
524
4547
}
525
4548
 
526
4549
 
528
4551
  Update keyuse array with all possible keys we can use to fetch rows.
529
4552
 
530
4553
  @param       session
531
 
  @param[out]  keyuse         Put here ordered array of KeyUse structures
 
4554
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
532
4555
  @param       join_tab       Array in tablenr_order
533
4556
  @param       tables         Number of tables in join
534
4557
  @param       cond           WHERE condition (note that the function analyzes
537
4560
                              for which we can make ref access based the WHERE
538
4561
                              clause)
539
4562
  @param       select_lex     current SELECT
540
 
  @param[out]  sargables      std::vector of found sargable candidates
 
4563
  @param[out]  sargables      Array of found sargable candidates
541
4564
 
542
4565
   @retval
543
4566
     0  OK
544
4567
   @retval
545
4568
     1  Out of memory.
546
4569
*/
547
 
bool update_ref_and_keys(Session *session,
548
 
                         DYNAMIC_ARRAY *keyuse,
549
 
                         JoinTable *join_tab,
550
 
                         uint32_t tables,
551
 
                         COND *cond, 
552
 
                         COND_EQUAL *,
553
 
                         table_map normal_tables,
554
 
                         Select_Lex *select_lex,
555
 
                         vector<optimizer::SargableParam> &sargables)
 
4570
 
 
4571
static bool
 
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,
 
4575
                    SARGABLE_PARAM **sargables)
556
4576
{
557
4577
  uint  and_level,i,found_eq_constant;
558
 
  optimizer::KeyField *key_fields, *end, *field;
 
4578
  KEY_FIELD *key_fields, *end, *field;
559
4579
  uint32_t sz;
560
 
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
 
4580
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
561
4581
 
562
4582
  /*
563
 
    All predicates that are used to fill arrays of KeyField
564
 
    and SargableParam classes have at most 2 arguments
 
4583
    We use the same piece of memory to store both  KEY_FIELD
 
4584
    and SARGABLE_PARAM structure.
 
4585
    KEY_FIELD values are placed at the beginning this memory
 
4586
    while  SARGABLE_PARAM values are put at the end.
 
4587
    All predicates that are used to fill arrays of KEY_FIELD
 
4588
    and SARGABLE_PARAM structures have at most 2 arguments
565
4589
    except BETWEEN predicates that have 3 arguments and
566
4590
    IN predicates.
567
4591
    This any predicate if it's not BETWEEN/IN can be used
568
 
    directly to fill at most 2 array elements, either of KeyField 
569
 
    or SargableParam type. For a BETWEEN predicate 3 elements
 
4592
    directly to fill at most 2 array elements, either of KEY_FIELD
 
4593
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
570
4594
    can be filled as this predicate is considered as
571
4595
    saragable with respect to each of its argument.
572
4596
    An IN predicate can require at most 1 element as currently
576
4600
    can be not more than select_lex->max_equal_elems such
577
4601
    substitutions.
578
4602
  */
579
 
  sz= sizeof(optimizer::KeyField) *
580
 
      (((session->lex->current_select->cond_count+1) +
 
4603
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
 
4604
      (((session->lex->current_select->cond_count+1)*2 +
581
4605
        session->lex->current_select->between_count)*m+1);
582
 
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
583
 
    return true;
 
4606
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
 
4607
    return true; /* purecov: inspected */
584
4608
  and_level= 0;
585
4609
  field= end= key_fields;
 
4610
  *sargables= (SARGABLE_PARAM *) key_fields +
 
4611
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
 
4612
  /* set a barrier for the array of SARGABLE_PARAM */
 
4613
  (*sargables)[0].field= 0;
586
4614
 
587
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
 
4615
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
588
4616
    return true;
589
4617
  if (cond)
590
4618
  {
591
4619
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
592
4620
                   sargables);
593
 
    for (; field != end; field++)
 
4621
    for (; field != end ; field++)
594
4622
    {
595
 
      add_key_part(keyuse, field);
 
4623
      add_key_part(keyuse,field);
596
4624
      /* Mark that we can optimize LEFT JOIN */
597
 
      if (field->getValue()->type() == Item::NULL_ITEM &&
598
 
          ! field->getField()->real_maybe_null())
599
 
      {
600
 
        field->getField()->table->reginfo.not_exists_optimize= 1;
601
 
      }
 
4625
      if (field->val->type() == Item::NULL_ITEM &&
 
4626
          !field->field->real_maybe_null())
 
4627
        field->field->table->reginfo.not_exists_optimize=1;
602
4628
    }
603
4629
  }
604
 
  for (i= 0; i < tables; i++)
 
4630
  for (i=0 ; i < tables ; i++)
605
4631
  {
606
4632
    /*
607
4633
      Block the creation of keys for inner tables of outer joins.
645
4671
  */
646
4672
  if (keyuse->elements)
647
4673
  {
648
 
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
 
4674
    KEYUSE key_end,*prev,*save_pos,*use;
649
4675
 
650
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
651
 
                       (qsort_cmp) sort_keyuse);
 
4676
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
 
4677
          (qsort_cmp) sort_keyuse);
652
4678
 
653
4679
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
654
4680
    insert_dynamic(keyuse,(unsigned char*) &key_end);
655
4681
 
656
 
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
 
4682
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
657
4683
    prev= &key_end;
658
 
    found_eq_constant= 0;
659
 
    for (i= 0; i < keyuse->elements-1; i++, use++)
 
4684
    found_eq_constant=0;
 
4685
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
660
4686
    {
661
 
      if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
662
 
        use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
663
 
      if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
 
4687
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
 
4688
        use->table->const_key_parts[use->key]|= use->keypart_map;
664
4689
      {
665
 
        if (prev->getKeypart() + 1 < use->getKeypart() || 
666
 
            ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
667
 
          continue;                             /* remove */
 
4690
        if (use->key == prev->key && use->table == prev->table)
 
4691
        {
 
4692
          if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
 
4693
            continue;                           /* remove */
 
4694
        }
 
4695
        else if (use->keypart != 0)             // First found must be 0
 
4696
          continue;
668
4697
      }
669
 
      else if (use->getKeypart() != 0)          // First found must be 0
670
 
        continue;
671
4698
 
672
4699
#ifdef HAVE_purify
673
4700
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
675
4702
#endif
676
4703
        *save_pos= *use;
677
4704
      prev=use;
678
 
      found_eq_constant= ! use->getUsedTables();
 
4705
      found_eq_constant= !use->used_tables;
679
4706
      /* Save ptr to first use */
680
 
      if (! use->getTable()->reginfo.join_tab->keyuse)
681
 
        use->getTable()->reginfo.join_tab->keyuse= save_pos;
682
 
      use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
 
4707
      if (!use->table->reginfo.join_tab->keyuse)
 
4708
        use->table->reginfo.join_tab->keyuse=save_pos;
 
4709
      use->table->reginfo.join_tab->checked_keys.set_bit(use->key);
683
4710
      save_pos++;
684
4711
    }
685
 
    i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
686
 
    set_dynamic(keyuse, (unsigned char*) &key_end, i);
687
 
    keyuse->elements= i;
 
4712
    i=(uint32_t) (save_pos-(KEYUSE*) keyuse->buffer);
 
4713
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
4714
    keyuse->elements=i;
688
4715
  }
689
4716
  return false;
690
4717
}
692
4719
/**
693
4720
  Update some values in keyuse for faster choose_plan() loop.
694
4721
*/
695
 
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
 
4722
 
 
4723
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
696
4724
{
697
 
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
698
 
                                                  0, 
699
 
                                                  optimizer::KeyUse*);
 
4725
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);
700
4726
 
701
4727
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
702
4728
  {
709
4735
      Constant tables are ignored.
710
4736
      To avoid bad matches, we don't make ref_table_rows less than 100.
711
4737
    */
712
 
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
713
 
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
 
4738
    keyuse->ref_table_rows= ~(ha_rows) 0;       // If no ref
 
4739
    if (keyuse->used_tables &
 
4740
        (map= (keyuse->used_tables & ~join->const_table_map &
 
4741
               ~OUTER_REF_TABLE_BIT)))
714
4742
    {
715
4743
      uint32_t tablenr;
716
4744
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
717
4745
      if (map == 1)                     // Only one table
718
4746
      {
719
 
        Table *tmp_table=join->all_tables[tablenr];
720
 
        keyuse->setTableRows(max(tmp_table->cursor->stats.records, (ha_rows)100));
 
4747
        Table *tmp_table=join->all_tables[tablenr];
 
4748
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
721
4749
      }
722
4750
    }
723
4751
    /*
724
4752
      Outer reference (external field) is constant for single executing
725
4753
      of subquery
726
4754
    */
727
 
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
728
 
      keyuse->setTableRows(1);
 
4755
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
 
4756
      keyuse->ref_table_rows= 1;
729
4757
  }
730
4758
}
731
4759
 
747
4775
  @return
748
4776
    None
749
4777
*/
750
 
void add_group_and_distinct_keys(JOIN *join, JoinTable *join_tab)
 
4778
 
 
4779
static void
 
4780
add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab)
751
4781
{
752
4782
  List<Item_field> indexed_fields;
753
4783
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
778
4808
 
779
4809
  /* Intersect the keys of all group fields. */
780
4810
  cur_item= indexed_fields_it++;
781
 
  possible_keys|= cur_item->field->part_of_key;
 
4811
  possible_keys.merge(cur_item->field->part_of_key);
782
4812
  while ((cur_item= indexed_fields_it++))
783
4813
  {
784
 
    possible_keys&= cur_item->field->part_of_key;
785
 
  }
786
 
 
787
 
  if (possible_keys.any())
788
 
    join_tab->const_keys|= possible_keys;
789
 
}
790
 
 
791
 
/**
792
 
  Compare two JoinTable objects based on the number of accessed records.
793
 
 
794
 
  @param ptr1 pointer to first JoinTable object
795
 
  @param ptr2 pointer to second JoinTable object
 
4814
    possible_keys.intersect(cur_item->field->part_of_key);
 
4815
  }
 
4816
 
 
4817
  if (!possible_keys.is_clear_all())
 
4818
    join_tab->const_keys.merge(possible_keys);
 
4819
}
 
4820
 
 
4821
 
 
4822
/*****************************************************************************
 
4823
  Go through all combinations of not marked tables and find the one
 
4824
  which uses least records
 
4825
*****************************************************************************/
 
4826
 
 
4827
/** Save const tables first as used tables. */
 
4828
 
 
4829
static void
 
4830
set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
 
4831
{
 
4832
  join->positions[idx].table= table;
 
4833
  join->positions[idx].key=key;
 
4834
  join->positions[idx].records_read=1.0;        /* This is a const table */
 
4835
  join->positions[idx].ref_depend_map= 0;
 
4836
 
 
4837
  /* Move the const table as down as possible in best_ref */
 
4838
  JOIN_TAB **pos=join->best_ref+idx+1;
 
4839
  JOIN_TAB *next=join->best_ref[idx];
 
4840
  for (;next != table ; pos++)
 
4841
  {
 
4842
    JOIN_TAB *tmp=pos[0];
 
4843
    pos[0]=next;
 
4844
    next=tmp;
 
4845
  }
 
4846
  join->best_ref[idx]=table;
 
4847
}
 
4848
 
 
4849
 
 
4850
/*
 
4851
  Given a semi-join nest, find out which of the IN-equalities are bound
 
4852
 
 
4853
  SYNOPSIS
 
4854
    get_bound_sj_equalities()
 
4855
      sj_nest           Semi-join nest
 
4856
      remaining_tables  Tables that are not yet bound
 
4857
 
 
4858
  DESCRIPTION
 
4859
    Given a semi-join nest, find out which of the IN-equalities have their
 
4860
    left part expression bound (i.e. the said expression doesn't refer to
 
4861
    any of remaining_tables and can be evaluated).
 
4862
 
 
4863
  RETURN
 
4864
    Bitmap of bound IN-equalities.
 
4865
*/
 
4866
 
 
4867
uint64_t get_bound_sj_equalities(TableList *sj_nest,
 
4868
                                  table_map remaining_tables)
 
4869
{
 
4870
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
 
4871
  Item *item;
 
4872
  uint32_t i= 0;
 
4873
  uint64_t res= 0;
 
4874
  while ((item= li++))
 
4875
  {
 
4876
    /*
 
4877
      Q: should this take into account equality propagation and how?
 
4878
      A: If e->outer_side is an Item_field, walk over the equality
 
4879
         class and see if there is an element that is bound?
 
4880
      (this is an optional feature)
 
4881
    */
 
4882
    if (!(item->used_tables() & remaining_tables))
 
4883
    {
 
4884
      res |= 1UL < i;
 
4885
    }
 
4886
  }
 
4887
  return res;
 
4888
}
 
4889
 
 
4890
 
 
4891
/**
 
4892
  Find the best access path for an extension of a partial execution
 
4893
  plan and add this path to the plan.
 
4894
 
 
4895
  The function finds the best access path to table 's' from the passed
 
4896
  partial plan where an access path is the general term for any means to
 
4897
  access the data in 's'. An access path may use either an index or a scan,
 
4898
  whichever is cheaper. The input partial plan is passed via the array
 
4899
  'join->positions' of length 'idx'. The chosen access method for 's' and its
 
4900
  cost are stored in 'join->positions[idx]'.
 
4901
 
 
4902
  @param join             pointer to the structure providing all context info
 
4903
                          for the query
 
4904
  @param s                the table to be joined by the function
 
4905
  @param session              thread for the connection that submitted the query
 
4906
  @param remaining_tables set of tables not included into the partial plan yet
 
4907
  @param idx              the length of the partial plan
 
4908
  @param record_count     estimate for the number of records returned by the
 
4909
                          partial plan
 
4910
  @param read_time        the cost of the partial plan
 
4911
 
 
4912
  @return
 
4913
    None
 
4914
*/
 
4915
 
 
4916
static void
 
4917
best_access_path(JOIN      *join,
 
4918
                 JOIN_TAB  *s,
 
4919
                 Session       *session,
 
4920
                 table_map remaining_tables,
 
4921
                 uint32_t      idx,
 
4922
                 double    record_count,
 
4923
                 double)
 
4924
{
 
4925
  KEYUSE *best_key=         0;
 
4926
  uint32_t best_max_key_part=   0;
 
4927
  bool found_constraint= 0;
 
4928
  double best=              DBL_MAX;
 
4929
  double best_time=         DBL_MAX;
 
4930
  double records=           DBL_MAX;
 
4931
  table_map best_ref_depends_map= 0;
 
4932
  double tmp;
 
4933
  ha_rows rec;
 
4934
  uint32_t best_is_sj_inside_out=    0;
 
4935
 
 
4936
  if (s->keyuse)
 
4937
  {                                            /* Use key if possible */
 
4938
    Table *table= s->table;
 
4939
    KEYUSE *keyuse,*start_key=0;
 
4940
    double best_records= DBL_MAX;
 
4941
    uint32_t max_key_part=0;
 
4942
    uint64_t bound_sj_equalities= 0;
 
4943
    bool try_sj_inside_out= false;
 
4944
    /*
 
4945
      Discover the bound equalites. We need to do this, if
 
4946
        1. The next table is an SJ-inner table, and
 
4947
        2. It is the first table from that semijoin, and
 
4948
        3. We're not within a semi-join range (i.e. all semi-joins either have
 
4949
           all or none of their tables in join_table_map), except
 
4950
           s->emb_sj_nest (which we've just entered).
 
4951
        3. All correlation references from this sj-nest are bound
 
4952
    */
 
4953
    if (s->emb_sj_nest &&                                                 // (1)
 
4954
        s->emb_sj_nest->sj_in_exprs < 64 &&
 
4955
        ((remaining_tables & s->emb_sj_nest->sj_inner_tables) ==           // (2)
 
4956
         s->emb_sj_nest->sj_inner_tables) &&                               // (2)
 
4957
        join->cur_emb_sj_nests == s->emb_sj_nest->sj_inner_tables &&       // (3)
 
4958
        !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables)) // (4)
 
4959
    {
 
4960
      /* This table is an InsideOut scan candidate */
 
4961
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest,
 
4962
                                                   remaining_tables);
 
4963
      try_sj_inside_out= true;
 
4964
    }
 
4965
 
 
4966
    /* Test how we can use keys */
 
4967
    rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE;  // Assumed records/key
 
4968
    for (keyuse=s->keyuse ; keyuse->table == table ;)
 
4969
    {
 
4970
      key_part_map found_part= 0;
 
4971
      table_map found_ref= 0;
 
4972
      uint32_t key= keyuse->key;
 
4973
      KEY *keyinfo= table->key_info+key;
 
4974
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
 
4975
      key_part_map const_part= 0;
 
4976
      /* The or-null keypart in ref-or-null access: */
 
4977
      key_part_map ref_or_null_part= 0;
 
4978
 
 
4979
      /* Calculate how many key segments of the current key we can use */
 
4980
      start_key= keyuse;
 
4981
      uint64_t handled_sj_equalities=0;
 
4982
      key_part_map sj_insideout_map= 0;
 
4983
 
 
4984
      do /* For each keypart */
 
4985
      {
 
4986
        uint32_t keypart= keyuse->keypart;
 
4987
        table_map best_part_found_ref= 0;
 
4988
        double best_prev_record_reads= DBL_MAX;
 
4989
 
 
4990
        do /* For each way to access the keypart */
 
4991
        {
 
4992
 
 
4993
          /*
 
4994
            if 1. expression doesn't refer to forward tables
 
4995
               2. we won't get two ref-or-null's
 
4996
          */
 
4997
          if (!(remaining_tables & keyuse->used_tables) &&
 
4998
              !(ref_or_null_part && (keyuse->optimize &
 
4999
                                     KEY_OPTIMIZE_REF_OR_NULL)))
 
5000
          {
 
5001
            found_part|= keyuse->keypart_map;
 
5002
            if (!(keyuse->used_tables & ~join->const_table_map))
 
5003
              const_part|= keyuse->keypart_map;
 
5004
 
 
5005
            double tmp2= prev_record_reads(join, idx, (found_ref |
 
5006
                                                      keyuse->used_tables));
 
5007
            if (tmp2 < best_prev_record_reads)
 
5008
            {
 
5009
              best_part_found_ref= keyuse->used_tables & ~join->const_table_map;
 
5010
              best_prev_record_reads= tmp2;
 
5011
            }
 
5012
            if (rec > keyuse->ref_table_rows)
 
5013
              rec= keyuse->ref_table_rows;
 
5014
            /*
 
5015
              If there is one 'key_column IS NULL' expression, we can
 
5016
              use this ref_or_null optimisation of this field
 
5017
            */
 
5018
            if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)
 
5019
              ref_or_null_part |= keyuse->keypart_map;
 
5020
          }
 
5021
 
 
5022
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
 
5023
          {
 
5024
            if (!(remaining_tables & keyuse->used_tables))
 
5025
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5026
            else
 
5027
            {
 
5028
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5029
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
 
5030
            }
 
5031
          }
 
5032
 
 
5033
          keyuse++;
 
5034
        } while (keyuse->table == table && keyuse->key == key &&
 
5035
                 keyuse->keypart == keypart);
 
5036
        found_ref|= best_part_found_ref;
 
5037
      } while (keyuse->table == table && keyuse->key == key);
 
5038
 
 
5039
      /*
 
5040
        Assume that that each key matches a proportional part of table.
 
5041
      */
 
5042
      if (!found_part && !handled_sj_equalities)
 
5043
        continue;                               // Nothing usable found
 
5044
 
 
5045
      if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
 
5046
        rec= MATCHING_ROWS_IN_OTHER_TABLE;      // Fix for small tables
 
5047
 
 
5048
      bool sj_inside_out_scan= false;
 
5049
      {
 
5050
        found_constraint= 1;
 
5051
        /*
 
5052
          Check if InsideOut scan is applicable:
 
5053
          1. All IN-equalities are either "bound" or "handled"
 
5054
          2. Index keyparts are
 
5055
             ...
 
5056
        */
 
5057
        if (try_sj_inside_out &&
 
5058
            table->covering_keys.is_set(key) &&
 
5059
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
 
5060
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
 
5061
        {
 
5062
          uint32_t n_fixed_parts= max_part_bit(found_part);
 
5063
          if (n_fixed_parts != keyinfo->key_parts &&
 
5064
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
 
5065
               PREV_BITS(uint, keyinfo->key_parts))
 
5066
          {
 
5067
            /*
 
5068
              Not all parts are fixed. Produce bitmap of remaining bits and
 
5069
              check if all of them are covered.
 
5070
            */
 
5071
            sj_inside_out_scan= true;
 
5072
            if (!n_fixed_parts)
 
5073
            {
 
5074
              /*
 
5075
                It's a confluent ref scan.
 
5076
 
 
5077
                That is, all found KEYUSE elements refer to IN-equalities,
 
5078
                and there is really no ref access because there is no
 
5079
                  t.keypart0 = {bound expression}
 
5080
 
 
5081
                Calculate the cost of complete loose index scan.
 
5082
              */
 
5083
              records= (double)s->table->file->stats.records;
 
5084
 
 
5085
              /* The cost is entire index scan cost (divided by 2) */
 
5086
              best_time= s->table->file->index_only_read_time(key, records);
 
5087
 
 
5088
              /* Now figure how many different keys we will get */
 
5089
              ulong rpc;
 
5090
              if ((rpc= keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5091
                records= records / rpc;
 
5092
              start_key= NULL;
 
5093
            }
 
5094
          }
 
5095
        }
 
5096
 
 
5097
        /*
 
5098
          Check if we found full key
 
5099
        */
 
5100
        if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
 
5101
            !ref_or_null_part)
 
5102
        {                                         /* use eq key */
 
5103
          max_key_part= UINT32_MAX;
 
5104
          if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)
 
5105
          {
 
5106
            tmp = prev_record_reads(join, idx, found_ref);
 
5107
            records=1.0;
 
5108
          }
 
5109
          else
 
5110
          {
 
5111
            if (!found_ref)
 
5112
            {                                     /* We found a const key */
 
5113
              /*
 
5114
                ReuseRangeEstimateForRef-1:
 
5115
                We get here if we've found a ref(const) (c_i are constants):
 
5116
                  "(keypart1=c1) AND ... AND (keypartN=cN)"   [ref_const_cond]
 
5117
 
 
5118
                If range optimizer was able to construct a "range"
 
5119
                access on this index, then its condition "quick_cond" was
 
5120
                eqivalent to ref_const_cond (*), and we can re-use E(#rows)
 
5121
                from the range optimizer.
 
5122
 
 
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
 
5128
                empty interval we wouldn't have got here).
 
5129
              */
 
5130
              if (table->quick_keys.is_set(key))
 
5131
                records= (double) table->quick_rows[key];
 
5132
              else
 
5133
              {
 
5134
                /* quick_range couldn't use key! */
 
5135
                records= (double) s->records/rec;
 
5136
              }
 
5137
            }
 
5138
            else
 
5139
            {
 
5140
              if (!(records=keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5141
              {                                   /* Prefer longer keys */
 
5142
                records=
 
5143
                  ((double) s->records / (double) rec *
 
5144
                   (1.0 +
 
5145
                    ((double) (table->s->max_key_length-keyinfo->key_length) /
 
5146
                     (double) table->s->max_key_length)));
 
5147
                if (records < 2.0)
 
5148
                  records=2.0;               /* Can't be as good as a unique */
 
5149
              }
 
5150
              /*
 
5151
                ReuseRangeEstimateForRef-2:  We get here if we could not reuse
 
5152
                E(#rows) from range optimizer. Make another try:
 
5153
 
 
5154
                If range optimizer produced E(#rows) for a prefix of the ref
 
5155
                access we're considering, and that E(#rows) is lower then our
 
5156
                current estimate, make an adjustment. The criteria of when we
 
5157
                can make an adjustment is a special case of the criteria used
 
5158
                in ReuseRangeEstimateForRef-3.
 
5159
              */
 
5160
              if (table->quick_keys.is_set(key) &&
 
5161
                  const_part & (1 << table->quick_key_parts[key]) &&
 
5162
                  table->quick_n_ranges[key] == 1 &&
 
5163
                  records > (double) table->quick_rows[key])
 
5164
              {
 
5165
                records= (double) table->quick_rows[key];
 
5166
              }
 
5167
            }
 
5168
            /* Limit the number of matched rows */
 
5169
            tmp= records;
 
5170
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5171
            if (table->covering_keys.is_set(key))
 
5172
            {
 
5173
              /* we can use only index tree */
 
5174
              tmp= record_count * table->file->index_only_read_time(key, tmp);
 
5175
            }
 
5176
            else
 
5177
              tmp= record_count*cmin(tmp,s->worst_seeks);
 
5178
          }
 
5179
        }
 
5180
        else
 
5181
        {
 
5182
          /*
 
5183
            Use as much key-parts as possible and a uniq key is better
 
5184
            than a not unique key
 
5185
            Set tmp to (previous record count) * (records / combination)
 
5186
          */
 
5187
          if ((found_part & 1) &&
 
5188
              (!(table->file->index_flags(key, 0, 0) & HA_ONLY_WHOLE_INDEX) ||
 
5189
               found_part == PREV_BITS(uint,keyinfo->key_parts)))
 
5190
          {
 
5191
            max_key_part= max_part_bit(found_part);
 
5192
            /*
 
5193
              ReuseRangeEstimateForRef-3:
 
5194
              We're now considering a ref[or_null] access via
 
5195
              (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR
 
5196
              (same-as-above but with one cond replaced
 
5197
               with "t.keypart_i IS NULL")]  (**)
 
5198
 
 
5199
              Try re-using E(#rows) from "range" optimizer:
 
5200
              We can do so if "range" optimizer used the same intervals as
 
5201
              in (**). The intervals used by range optimizer may be not
 
5202
              available at this point (as "range" access might have choosen to
 
5203
              create quick select over another index), so we can't compare
 
5204
              them to (**). We'll make indirect judgements instead.
 
5205
              The sufficient conditions for re-use are:
 
5206
              (C1) All e_i in (**) are constants, i.e. found_ref==false. (if
 
5207
                   this is not satisfied we have no way to know which ranges
 
5208
                   will be actually scanned by 'ref' until we execute the
 
5209
                   join)
 
5210
              (C2) max #key parts in 'range' access == K == max_key_part (this
 
5211
                   is apparently a necessary requirement)
 
5212
 
 
5213
              We also have a property that "range optimizer produces equal or
 
5214
              tighter set of scan intervals than ref(const) optimizer". Each
 
5215
              of the intervals in (**) are "tightest possible" intervals when
 
5216
              one limits itself to using keyparts 1..K (which we do in #2).
 
5217
              From here it follows that range access used either one, or
 
5218
              both of the (I1) and (I2) intervals:
 
5219
 
 
5220
               (t.keypart1=c1 AND ... AND t.keypartK=eK)  (I1)
 
5221
               (same-as-above but with one cond replaced
 
5222
                with "t.keypart_i IS NULL")               (I2)
 
5223
 
 
5224
              The remaining part is to exclude the situation where range
 
5225
              optimizer used one interval while we're considering
 
5226
              ref-or-null and looking for estimate for two intervals. This
 
5227
              is done by last limitation:
 
5228
 
 
5229
              (C3) "range optimizer used (have ref_or_null?2:1) intervals"
 
5230
            */
 
5231
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
 
5232
                table->quick_key_parts[key] == max_key_part &&          //(C2)
 
5233
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
 
5234
            {
 
5235
              tmp= records= (double) table->quick_rows[key];
 
5236
            }
 
5237
            else
 
5238
            {
 
5239
              /* Check if we have statistic about the distribution */
 
5240
              if ((records= keyinfo->rec_per_key[max_key_part-1]))
 
5241
              {
 
5242
                /*
 
5243
                  Fix for the case where the index statistics is too
 
5244
                  optimistic: If
 
5245
                  (1) We're considering ref(const) and there is quick select
 
5246
                      on the same index,
 
5247
                  (2) and that quick select uses more keyparts (i.e. it will
 
5248
                      scan equal/smaller interval then this ref(const))
 
5249
                  (3) and E(#rows) for quick select is higher then our
 
5250
                      estimate,
 
5251
                  Then
 
5252
                    We'll use E(#rows) from quick select.
 
5253
 
 
5254
                  Q: Why do we choose to use 'ref'? Won't quick select be
 
5255
                  cheaper in some cases ?
 
5256
                  TODO: figure this out and adjust the plan choice if needed.
 
5257
                */
 
5258
                if (!found_ref && table->quick_keys.is_set(key) &&    // (1)
 
5259
                    table->quick_key_parts[key] > max_key_part &&     // (2)
 
5260
                    records < (double)table->quick_rows[key])         // (3)
 
5261
                  records= (double)table->quick_rows[key];
 
5262
 
 
5263
                tmp= records;
 
5264
              }
 
5265
              else
 
5266
              {
 
5267
                /*
 
5268
                  Assume that the first key part matches 1% of the file
 
5269
                  and that the whole key matches 10 (duplicates) or 1
 
5270
                  (unique) records.
 
5271
                  Assume also that more key matches proportionally more
 
5272
                  records
 
5273
                  This gives the formula:
 
5274
                  records = (x * (b-a) + a*c-b)/(c-1)
 
5275
 
 
5276
                  b = records matched by whole key
 
5277
                  a = records matched by first key part (1% of all records?)
 
5278
                  c = number of key parts in key
 
5279
                  x = used key parts (1 <= x <= c)
 
5280
                */
 
5281
                double rec_per_key;
 
5282
                if (!(rec_per_key=(double)
 
5283
                      keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5284
                  rec_per_key=(double) s->records/rec+1;
 
5285
 
 
5286
                if (!s->records)
 
5287
                  tmp = 0;
 
5288
                else if (rec_per_key/(double) s->records >= 0.01)
 
5289
                  tmp = rec_per_key;
 
5290
                else
 
5291
                {
 
5292
                  double a=s->records*0.01;
 
5293
                  if (keyinfo->key_parts > 1)
 
5294
                    tmp= (max_key_part * (rec_per_key - a) +
 
5295
                          a*keyinfo->key_parts - rec_per_key)/
 
5296
                         (keyinfo->key_parts-1);
 
5297
                  else
 
5298
                    tmp= a;
 
5299
                  set_if_bigger(tmp,1.0);
 
5300
                }
 
5301
                records = (uint32_t) tmp;
 
5302
              }
 
5303
 
 
5304
              if (ref_or_null_part)
 
5305
              {
 
5306
                /* We need to do two key searches to find key */
 
5307
                tmp *= 2.0;
 
5308
                records *= 2.0;
 
5309
              }
 
5310
 
 
5311
              /*
 
5312
                ReuseRangeEstimateForRef-4:  We get here if we could not reuse
 
5313
                E(#rows) from range optimizer. Make another try:
 
5314
 
 
5315
                If range optimizer produced E(#rows) for a prefix of the ref
 
5316
                access we're considering, and that E(#rows) is lower then our
 
5317
                current estimate, make the adjustment.
 
5318
 
 
5319
                The decision whether we can re-use the estimate from the range
 
5320
                optimizer is the same as in ReuseRangeEstimateForRef-3,
 
5321
                applied to first table->quick_key_parts[key] key parts.
 
5322
              */
 
5323
              if (table->quick_keys.is_set(key) &&
 
5324
                  table->quick_key_parts[key] <= max_key_part &&
 
5325
                  const_part & (1 << table->quick_key_parts[key]) &&
 
5326
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
 
5327
                                                     const_part) ? 1 : 0) &&
 
5328
                  records > (double) table->quick_rows[key])
 
5329
              {
 
5330
                tmp= records= (double) table->quick_rows[key];
 
5331
              }
 
5332
            }
 
5333
 
 
5334
            /* Limit the number of matched rows */
 
5335
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5336
            if (table->covering_keys.is_set(key))
 
5337
            {
 
5338
              /* we can use only index tree */
 
5339
              tmp= record_count * table->file->index_only_read_time(key, tmp);
 
5340
            }
 
5341
            else
 
5342
              tmp= record_count * cmin(tmp,s->worst_seeks);
 
5343
          }
 
5344
          else
 
5345
            tmp= best_time;                    // Do nothing
 
5346
        }
 
5347
 
 
5348
        if (sj_inside_out_scan && !start_key)
 
5349
        {
 
5350
          tmp= tmp/2;
 
5351
          if (records)
 
5352
            records= records/2;
 
5353
        }
 
5354
 
 
5355
      }
 
5356
      if (tmp < best_time - records/(double) TIME_FOR_COMPARE)
 
5357
      {
 
5358
        best_time= tmp + records/(double) TIME_FOR_COMPARE;
 
5359
        best= tmp;
 
5360
        best_records= records;
 
5361
        best_key= start_key;
 
5362
        best_max_key_part= max_key_part;
 
5363
        best_ref_depends_map= found_ref;
 
5364
        best_is_sj_inside_out= sj_inside_out_scan;
 
5365
      }
 
5366
    }
 
5367
    records= best_records;
 
5368
  }
 
5369
 
 
5370
  /*
 
5371
    Don't test table scan if it can't be better.
 
5372
    Prefer key lookup if we would use the same key for scanning.
 
5373
 
 
5374
    Don't do a table scan on InnoDB tables, if we can read the used
 
5375
    parts of the row from any of the used index.
 
5376
    This is because table scans uses index and we would not win
 
5377
    anything by using a table scan.
 
5378
 
 
5379
    A word for word translation of the below if-statement in sergefp's
 
5380
    understanding: we check if we should use table scan if:
 
5381
    (1) The found 'ref' access produces more records than a table scan
 
5382
        (or index scan, or quick select), or 'ref' is more expensive than
 
5383
        any of them.
 
5384
    (2) This doesn't hold: the best way to perform table scan is to to perform
 
5385
        'range' access using index IDX, and the best way to perform 'ref'
 
5386
        access is to use the same index IDX, with the same or more key parts.
 
5387
        (note: it is not clear how this rule is/should be extended to
 
5388
        index_merge quick selects)
 
5389
    (3) See above note about InnoDB.
 
5390
    (4) NOT ("FORCE INDEX(...)" is used for table and there is 'ref' access
 
5391
             path, but there is no quick select)
 
5392
        If the condition in the above brackets holds, then the only possible
 
5393
        "table scan" access method is ALL/index (there is no quick select).
 
5394
        Since we have a 'ref' access path, and FORCE INDEX instructs us to
 
5395
        choose it over ALL/index, there is no need to consider a full table
 
5396
        scan.
 
5397
  */
 
5398
  if ((records >= s->found_records || best > s->read_time) &&            // (1)
 
5399
      !(s->quick && best_key && s->quick->index == best_key->key &&      // (2)
 
5400
        best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2)
 
5401
      !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) &&   // (3)
 
5402
        ! s->table->covering_keys.is_clear_all() && best_key && !s->quick) &&// (3)
 
5403
      !(s->table->force_index && best_key && !s->quick))                 // (4)
 
5404
  {                                             // Check full join
 
5405
    ha_rows rnd_records= s->found_records;
 
5406
    /*
 
5407
      If there is a filtering condition on the table (i.e. ref analyzer found
 
5408
      at least one "table.keyXpartY= exprZ", where exprZ refers only to tables
 
5409
      preceding this table in the join order we're now considering), then
 
5410
      assume that 25% of the rows will be filtered out by this condition.
 
5411
 
 
5412
      This heuristic is supposed to force tables used in exprZ to be before
 
5413
      this table in join order.
 
5414
    */
 
5415
    if (found_constraint)
 
5416
      rnd_records-= rnd_records/4;
 
5417
 
 
5418
    /*
 
5419
      If applicable, get a more accurate estimate. Don't use the two
 
5420
      heuristics at once.
 
5421
    */
 
5422
    if (s->table->quick_condition_rows != s->found_records)
 
5423
      rnd_records= s->table->quick_condition_rows;
 
5424
 
 
5425
    /*
 
5426
      Range optimizer never proposes a RANGE if it isn't better
 
5427
      than FULL: so if RANGE is present, it's always preferred to FULL.
 
5428
      Here we estimate its cost.
 
5429
    */
 
5430
    if (s->quick)
 
5431
    {
 
5432
      /*
 
5433
        For each record we:
 
5434
        - read record range through 'quick'
 
5435
        - skip rows which does not satisfy WHERE constraints
 
5436
        TODO:
 
5437
        We take into account possible use of join cache for ALL/index
 
5438
        access (see first else-branch below), but we don't take it into
 
5439
        account here for range/index_merge access. Find out why this is so.
 
5440
      */
 
5441
      tmp= record_count *
 
5442
        (s->quick->read_time +
 
5443
         (s->found_records - rnd_records)/(double) TIME_FOR_COMPARE);
 
5444
    }
 
5445
    else
 
5446
    {
 
5447
      /* Estimate cost of reading table. */
 
5448
      tmp= s->table->file->scan_time();
 
5449
      if (s->table->map & join->outer_join)     // Can't use join cache
 
5450
      {
 
5451
        /*
 
5452
          For each record we have to:
 
5453
          - read the whole table record
 
5454
          - skip rows which does not satisfy join condition
 
5455
        */
 
5456
        tmp= record_count *
 
5457
          (tmp +
 
5458
           (s->records - rnd_records)/(double) TIME_FOR_COMPARE);
 
5459
      }
 
5460
      else
 
5461
      {
 
5462
        /* We read the table as many times as join buffer becomes full. */
 
5463
        tmp*= (1.0 + floor((double) cache_record_length(join,idx) *
 
5464
                           record_count /
 
5465
                           (double) session->variables.join_buff_size));
 
5466
        /*
 
5467
            We don't make full cartesian product between rows in the scanned
 
5468
           table and existing records because we skip all rows from the
 
5469
           scanned table, which does not satisfy join condition when
 
5470
           we read the table (see flush_cached_records for details). Here we
 
5471
           take into account cost to read and skip these records.
 
5472
        */
 
5473
        tmp+= (s->records - rnd_records)/(double) TIME_FOR_COMPARE;
 
5474
      }
 
5475
    }
 
5476
 
 
5477
    /*
 
5478
      We estimate the cost of evaluating WHERE clause for found records
 
5479
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
 
5480
      tmp give us total cost of using Table SCAN
 
5481
    */
 
5482
    if (best == DBL_MAX ||
 
5483
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
 
5484
         best + record_count/(double) TIME_FOR_COMPARE*records))
 
5485
    {
 
5486
      /*
 
5487
        If the table has a range (s->quick is set) make_join_select()
 
5488
        will ensure that this will be used
 
5489
      */
 
5490
      best= tmp;
 
5491
      records= rows2double(rnd_records);
 
5492
      best_key= 0;
 
5493
      /* range/index_merge/ALL/index access method are "independent", so: */
 
5494
      best_ref_depends_map= 0;
 
5495
      best_is_sj_inside_out= false;
 
5496
    }
 
5497
  }
 
5498
 
 
5499
  /* Update the cost information for the current partial plan */
 
5500
  join->positions[idx].records_read= records;
 
5501
  join->positions[idx].read_time=    best;
 
5502
  join->positions[idx].key=          best_key;
 
5503
  join->positions[idx].table=        s;
 
5504
  join->positions[idx].ref_depend_map= best_ref_depends_map;
 
5505
  join->positions[idx].use_insideout_scan= best_is_sj_inside_out;
 
5506
 
 
5507
  if (!best_key &&
 
5508
      idx == join->const_tables &&
 
5509
      s->table == join->sort_by_table &&
 
5510
      join->unit->select_limit_cnt >= records)
 
5511
    join->sort_by_table= (Table*) 1;  // Must use temporary table
 
5512
 
 
5513
  return;
 
5514
}
 
5515
 
 
5516
 
 
5517
/**
 
5518
  Selects and invokes a search strategy for an optimal query plan.
 
5519
 
 
5520
  The function checks user-configurable parameters that control the search
 
5521
  strategy for an optimal plan, selects the search method and then invokes
 
5522
  it. Each specific optimization procedure stores the final optimal plan in
 
5523
  the array 'join->best_positions', and the cost of the plan in
 
5524
  'join->best_read'.
 
5525
 
 
5526
  @param join         pointer to the structure providing all context info for
 
5527
                      the query
 
5528
  @param join_tables  set of the tables in the query
 
5529
 
 
5530
  @todo
 
5531
    'MAX_TABLES+2' denotes the old implementation of find_best before
 
5532
    the greedy version. Will be removed when greedy_search is approved.
 
5533
 
 
5534
  @retval
 
5535
    false       ok
 
5536
  @retval
 
5537
    true        Fatal error
 
5538
*/
 
5539
 
 
5540
static bool
 
5541
choose_plan(JOIN *join, table_map join_tables)
 
5542
{
 
5543
  uint32_t search_depth= join->session->variables.optimizer_search_depth;
 
5544
  uint32_t prune_level=  join->session->variables.optimizer_prune_level;
 
5545
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
 
5546
 
 
5547
  join->cur_embedding_map= 0;
 
5548
  reset_nj_counters(join->join_list);
 
5549
  /*
 
5550
    if (SELECT_STRAIGHT_JOIN option is set)
 
5551
      reorder tables so dependent tables come after tables they depend
 
5552
      on, otherwise keep tables in the order they were specified in the query
 
5553
    else
 
5554
      Apply heuristic: pre-sort all access plans with respect to the number of
 
5555
      records accessed.
 
5556
  */
 
5557
  my_qsort(join->best_ref + join->const_tables,
 
5558
           join->tables - join->const_tables, sizeof(JOIN_TAB*),
 
5559
           straight_join ? join_tab_cmp_straight : join_tab_cmp);
 
5560
  join->cur_emb_sj_nests= 0;
 
5561
  if (straight_join)
 
5562
  {
 
5563
    optimize_straight_join(join, join_tables);
 
5564
  }
 
5565
  else
 
5566
  {
 
5567
    if (search_depth == MAX_TABLES+2)
 
5568
    { /*
 
5569
        TODO: 'MAX_TABLES+2' denotes the old implementation of find_best before
 
5570
        the greedy version. Will be removed when greedy_search is approved.
 
5571
      */
 
5572
      join->best_read= DBL_MAX;
 
5573
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
 
5574
        return(true);
 
5575
    }
 
5576
    else
 
5577
    {
 
5578
      if (search_depth == 0)
 
5579
        /* Automatically determine a reasonable value for 'search_depth' */
 
5580
        search_depth= determine_search_depth(join);
 
5581
      if (greedy_search(join, join_tables, search_depth, prune_level))
 
5582
        return(true);
 
5583
    }
 
5584
  }
 
5585
 
 
5586
  /*
 
5587
    Store the cost of this query into a user variable
 
5588
    Don't update last_query_cost for statements that are not "flat joins" :
 
5589
    i.e. they have subqueries, unions or call stored procedures.
 
5590
    TODO: calculate a correct cost for a query with subqueries and UNIONs.
 
5591
  */
 
5592
  if (join->session->lex->is_single_level_stmt())
 
5593
    join->session->status_var.last_query_cost= join->best_read;
 
5594
  return(false);
 
5595
}
 
5596
 
 
5597
 
 
5598
/**
 
5599
  Compare two JOIN_TAB objects based on the number of accessed records.
 
5600
 
 
5601
  @param ptr1 pointer to first JOIN_TAB object
 
5602
  @param ptr2 pointer to second JOIN_TAB object
796
5603
 
797
5604
  NOTES
798
5605
    The order relation implemented by join_tab_cmp() is not transitive,
812
5619
  @retval
813
5620
    0  if equal
814
5621
*/
 
5622
 
815
5623
int join_tab_cmp(const void* ptr1, const void* ptr2)
816
5624
{
817
 
  JoinTable *jt1= *(JoinTable**) ptr1;
818
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
5625
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
5626
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
819
5627
 
820
5628
  if (jt1->dependent & jt2->table->map)
821
5629
    return 1;
828
5636
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
829
5637
}
830
5638
 
 
5639
 
831
5640
/**
832
5641
  Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN.
833
5642
*/
 
5643
 
834
5644
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
835
5645
{
836
 
  JoinTable *jt1= *(JoinTable**) ptr1;
837
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
5646
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
5647
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
838
5648
 
839
5649
  if (jt1->dependent & jt2->table->map)
840
5650
    return 1;
844
5654
}
845
5655
 
846
5656
/**
 
5657
  Heuristic procedure to automatically guess a reasonable degree of
 
5658
  exhaustiveness for the greedy search procedure.
 
5659
 
 
5660
  The procedure estimates the optimization time and selects a search depth
 
5661
  big enough to result in a near-optimal QEP, that doesn't take too long to
 
5662
  find. If the number of tables in the query exceeds some constant, then
 
5663
  search_depth is set to this constant.
 
5664
 
 
5665
  @param join   pointer to the structure providing all context info for
 
5666
                the query
 
5667
 
 
5668
  @note
 
5669
    This is an extremely simplistic implementation that serves as a stub for a
 
5670
    more advanced analysis of the join. Ideally the search depth should be
 
5671
    determined by learning from previous query optimizations, because it will
 
5672
    depend on the CPU power (and other factors).
 
5673
 
 
5674
  @todo
 
5675
    this value should be determined dynamically, based on statistics:
 
5676
    uint32_t max_tables_for_exhaustive_opt= 7;
 
5677
 
 
5678
  @todo
 
5679
    this value could be determined by some mapping of the form:
 
5680
    depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE]
 
5681
 
 
5682
  @return
 
5683
    A positive integer that specifies the search depth (and thus the
 
5684
    exhaustiveness) of the depth-first search algorithm used by
 
5685
    'greedy_search'.
 
5686
*/
 
5687
 
 
5688
static uint
 
5689
determine_search_depth(JOIN *join)
 
5690
{
 
5691
  uint32_t table_count=  join->tables - join->const_tables;
 
5692
  uint32_t search_depth;
 
5693
  /* TODO: this value should be determined dynamically, based on statistics: */
 
5694
  uint32_t max_tables_for_exhaustive_opt= 7;
 
5695
 
 
5696
  if (table_count <= max_tables_for_exhaustive_opt)
 
5697
    search_depth= table_count+1; // use exhaustive for small number of tables
 
5698
  else
 
5699
    /*
 
5700
      TODO: this value could be determined by some mapping of the form:
 
5701
      depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE]
 
5702
    */
 
5703
    search_depth= max_tables_for_exhaustive_opt; // use greedy search
 
5704
 
 
5705
  return search_depth;
 
5706
}
 
5707
 
 
5708
 
 
5709
/**
 
5710
  Select the best ways to access the tables in a query without reordering them.
 
5711
 
 
5712
    Find the best access paths for each query table and compute their costs
 
5713
    according to their order in the array 'join->best_ref' (thus without
 
5714
    reordering the join tables). The function calls sequentially
 
5715
    'best_access_path' for each table in the query to select the best table
 
5716
    access method. The final optimal plan is stored in the array
 
5717
    'join->best_positions', and the corresponding cost in 'join->best_read'.
 
5718
 
 
5719
  @param join          pointer to the structure providing all context info for
 
5720
                       the query
 
5721
  @param join_tables   set of the tables in the query
 
5722
 
 
5723
  @note
 
5724
    This function can be applied to:
 
5725
    - queries with STRAIGHT_JOIN
 
5726
    - internally to compute the cost of an arbitrary QEP
 
5727
  @par
 
5728
    Thus 'optimize_straight_join' can be used at any stage of the query
 
5729
    optimization process to finalize a QEP as it is.
 
5730
*/
 
5731
 
 
5732
static void
 
5733
optimize_straight_join(JOIN *join, table_map join_tables)
 
5734
{
 
5735
  JOIN_TAB *s;
 
5736
  uint32_t idx= join->const_tables;
 
5737
  double    record_count= 1.0;
 
5738
  double    read_time=    0.0;
 
5739
 
 
5740
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
5741
  {
 
5742
    /* Find the best access method from 's' to the current partial plan */
 
5743
    advance_sj_state(join_tables, s);
 
5744
    best_access_path(join, s, join->session, join_tables, idx,
 
5745
                     record_count, read_time);
 
5746
    /* compute the cost of the new plan extended with 's' */
 
5747
    record_count*= join->positions[idx].records_read;
 
5748
    read_time+=    join->positions[idx].read_time;
 
5749
    join_tables&= ~(s->table->map);
 
5750
    ++idx;
 
5751
  }
 
5752
 
 
5753
  read_time+= record_count / (double) TIME_FOR_COMPARE;
 
5754
  if (join->sort_by_table &&
 
5755
      join->sort_by_table != join->positions[join->const_tables].table->table)
 
5756
    read_time+= record_count;  // We have to make a temp table
 
5757
  memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
5758
  join->best_read= read_time;
 
5759
}
 
5760
 
 
5761
 
 
5762
/**
 
5763
  Find a good, possibly optimal, query execution plan (QEP) by a greedy search.
 
5764
 
 
5765
    The search procedure uses a hybrid greedy/exhaustive search with controlled
 
5766
    exhaustiveness. The search is performed in N = card(remaining_tables)
 
5767
    steps. Each step evaluates how promising is each of the unoptimized tables,
 
5768
    selects the most promising table, and extends the current partial QEP with
 
5769
    that table.  Currenly the most 'promising' table is the one with least
 
5770
    expensive extension.\
 
5771
 
 
5772
    There are two extreme cases:
 
5773
    -# When (card(remaining_tables) < search_depth), the estimate finds the
 
5774
    best complete continuation of the partial QEP. This continuation can be
 
5775
    used directly as a result of the search.
 
5776
    -# When (search_depth == 1) the 'best_extension_by_limited_search'
 
5777
    consideres the extension of the current QEP with each of the remaining
 
5778
    unoptimized tables.
 
5779
 
 
5780
    All other cases are in-between these two extremes. Thus the parameter
 
5781
    'search_depth' controlls the exhaustiveness of the search. The higher the
 
5782
    value, the longer the optimizaton time and possibly the better the
 
5783
    resulting plan. The lower the value, the fewer alternative plans are
 
5784
    estimated, but the more likely to get a bad QEP.
 
5785
 
 
5786
    All intermediate and final results of the procedure are stored in 'join':
 
5787
    - join->positions     : modified for every partial QEP that is explored
 
5788
    - join->best_positions: modified for the current best complete QEP
 
5789
    - join->best_read     : modified for the current best complete QEP
 
5790
    - join->best_ref      : might be partially reordered
 
5791
 
 
5792
    The final optimal plan is stored in 'join->best_positions', and its
 
5793
    corresponding cost in 'join->best_read'.
 
5794
 
 
5795
  @note
 
5796
    The following pseudocode describes the algorithm of 'greedy_search':
 
5797
 
 
5798
    @code
 
5799
    procedure greedy_search
 
5800
    input: remaining_tables
 
5801
    output: pplan;
 
5802
    {
 
5803
      pplan = <>;
 
5804
      do {
 
5805
        (t, a) = best_extension(pplan, remaining_tables);
 
5806
        pplan = concat(pplan, (t, a));
 
5807
        remaining_tables = remaining_tables - t;
 
5808
      } while (remaining_tables != {})
 
5809
      return pplan;
 
5810
    }
 
5811
 
 
5812
  @endcode
 
5813
    where 'best_extension' is a placeholder for a procedure that selects the
 
5814
    most "promising" of all tables in 'remaining_tables'.
 
5815
    Currently this estimate is performed by calling
 
5816
    'best_extension_by_limited_search' to evaluate all extensions of the
 
5817
    current QEP of size 'search_depth', thus the complexity of 'greedy_search'
 
5818
    mainly depends on that of 'best_extension_by_limited_search'.
 
5819
 
 
5820
  @par
 
5821
    If 'best_extension()' == 'best_extension_by_limited_search()', then the
 
5822
    worst-case complexity of this algorithm is <=
 
5823
    O(N*N^search_depth/search_depth). When serch_depth >= N, then the
 
5824
    complexity of greedy_search is O(N!).
 
5825
 
 
5826
  @par
 
5827
    In the future, 'greedy_search' might be extended to support other
 
5828
    implementations of 'best_extension', e.g. some simpler quadratic procedure.
 
5829
 
 
5830
  @param join             pointer to the structure providing all context info
 
5831
                          for the query
 
5832
  @param remaining_tables set of tables not included into the partial plan yet
 
5833
  @param search_depth     controlls the exhaustiveness of the search
 
5834
  @param prune_level      the pruning heuristics that should be applied during
 
5835
                          search
 
5836
 
 
5837
  @retval
 
5838
    false       ok
 
5839
  @retval
 
5840
    true        Fatal error
 
5841
*/
 
5842
 
 
5843
static bool
 
5844
greedy_search(JOIN      *join,
 
5845
              table_map remaining_tables,
 
5846
              uint32_t      search_depth,
 
5847
              uint32_t      prune_level)
 
5848
{
 
5849
  double    record_count= 1.0;
 
5850
  double    read_time=    0.0;
 
5851
  uint32_t      idx= join->const_tables; // index into 'join->best_ref'
 
5852
  uint32_t      best_idx;
 
5853
  uint32_t      size_remain;    // cardinality of remaining_tables
 
5854
  POSITION  best_pos;
 
5855
  JOIN_TAB  *best_table; // the next plan node to be added to the curr QEP
 
5856
 
 
5857
  /* number of tables that remain to be optimized */
 
5858
  size_remain= my_count_bits(remaining_tables);
 
5859
 
 
5860
  do {
 
5861
    /* Find the extension of the current QEP with the lowest cost */
 
5862
    join->best_read= DBL_MAX;
 
5863
    if (best_extension_by_limited_search(join, remaining_tables, idx, record_count,
 
5864
                                         read_time, search_depth, prune_level))
 
5865
      return(true);
 
5866
 
 
5867
    if (size_remain <= search_depth)
 
5868
    {
 
5869
      /*
 
5870
        'join->best_positions' contains a complete optimal extension of the
 
5871
        current partial QEP.
 
5872
      */
 
5873
      return(false);
 
5874
    }
 
5875
 
 
5876
    /* select the first table in the optimal extension as most promising */
 
5877
    best_pos= join->best_positions[idx];
 
5878
    best_table= best_pos.table;
 
5879
    /*
 
5880
      Each subsequent loop of 'best_extension_by_limited_search' uses
 
5881
      'join->positions' for cost estimates, therefore we have to update its
 
5882
      value.
 
5883
    */
 
5884
    join->positions[idx]= best_pos;
 
5885
 
 
5886
    /* find the position of 'best_table' in 'join->best_ref' */
 
5887
    best_idx= idx;
 
5888
    JOIN_TAB *pos= join->best_ref[best_idx];
 
5889
    while (pos && best_table != pos)
 
5890
      pos= join->best_ref[++best_idx];
 
5891
    assert((pos != NULL)); // should always find 'best_table'
 
5892
    /* move 'best_table' at the first free position in the array of joins */
 
5893
    std::swap(join->best_ref[idx], join->best_ref[best_idx]);
 
5894
 
 
5895
    /* compute the cost of the new plan extended with 'best_table' */
 
5896
    record_count*= join->positions[idx].records_read;
 
5897
    read_time+=    join->positions[idx].read_time;
 
5898
 
 
5899
    remaining_tables&= ~(best_table->table->map);
 
5900
    --size_remain;
 
5901
    ++idx;
 
5902
  } while (true);
 
5903
}
 
5904
 
 
5905
 
 
5906
/**
 
5907
  Find a good, possibly optimal, query execution plan (QEP) by a possibly
 
5908
  exhaustive search.
 
5909
 
 
5910
    The procedure searches for the optimal ordering of the query tables in set
 
5911
    'remaining_tables' of size N, and the corresponding optimal access paths to
 
5912
    each table. The choice of a table order and an access path for each table
 
5913
    constitutes a query execution plan (QEP) that fully specifies how to
 
5914
    execute the query.
 
5915
 
 
5916
    The maximal size of the found plan is controlled by the parameter
 
5917
    'search_depth'. When search_depth == N, the resulting plan is complete and
 
5918
    can be used directly as a QEP. If search_depth < N, the found plan consists
 
5919
    of only some of the query tables. Such "partial" optimal plans are useful
 
5920
    only as input to query optimization procedures, and cannot be used directly
 
5921
    to execute a query.
 
5922
 
 
5923
    The algorithm begins with an empty partial plan stored in 'join->positions'
 
5924
    and a set of N tables - 'remaining_tables'. Each step of the algorithm
 
5925
    evaluates the cost of the partial plan extended by all access plans for
 
5926
    each of the relations in 'remaining_tables', expands the current partial
 
5927
    plan with the access plan that results in lowest cost of the expanded
 
5928
    partial plan, and removes the corresponding relation from
 
5929
    'remaining_tables'. The algorithm continues until it either constructs a
 
5930
    complete optimal plan, or constructs an optimal plartial plan with size =
 
5931
    search_depth.
 
5932
 
 
5933
    The final optimal plan is stored in 'join->best_positions'. The
 
5934
    corresponding cost of the optimal plan is in 'join->best_read'.
 
5935
 
 
5936
  @note
 
5937
    The procedure uses a recursive depth-first search where the depth of the
 
5938
    recursion (and thus the exhaustiveness of the search) is controlled by the
 
5939
    parameter 'search_depth'.
 
5940
 
 
5941
  @note
 
5942
    The pseudocode below describes the algorithm of
 
5943
    'best_extension_by_limited_search'. The worst-case complexity of this
 
5944
    algorithm is O(N*N^search_depth/search_depth). When serch_depth >= N, then
 
5945
    the complexity of greedy_search is O(N!).
 
5946
 
 
5947
    @code
 
5948
    procedure best_extension_by_limited_search(
 
5949
      pplan in,             // in, partial plan of tables-joined-so-far
 
5950
      pplan_cost,           // in, cost of pplan
 
5951
      remaining_tables,     // in, set of tables not referenced in pplan
 
5952
      best_plan_so_far,     // in/out, best plan found so far
 
5953
      best_plan_so_far_cost,// in/out, cost of best_plan_so_far
 
5954
      search_depth)         // in, maximum size of the plans being considered
 
5955
    {
 
5956
      for each table T from remaining_tables
 
5957
      {
 
5958
        // Calculate the cost of using table T as above
 
5959
        cost = complex-series-of-calculations;
 
5960
 
 
5961
        // Add the cost to the cost so far.
 
5962
        pplan_cost+= cost;
 
5963
 
 
5964
        if (pplan_cost >= best_plan_so_far_cost)
 
5965
          // pplan_cost already too great, stop search
 
5966
          continue;
 
5967
 
 
5968
        pplan= expand pplan by best_access_method;
 
5969
        remaining_tables= remaining_tables - table T;
 
5970
        if (remaining_tables is not an empty set
 
5971
            and
 
5972
            search_depth > 1)
 
5973
        {
 
5974
          best_extension_by_limited_search(pplan, pplan_cost,
 
5975
                                           remaining_tables,
 
5976
                                           best_plan_so_far,
 
5977
                                           best_plan_so_far_cost,
 
5978
                                           search_depth - 1);
 
5979
        }
 
5980
        else
 
5981
        {
 
5982
          best_plan_so_far_cost= pplan_cost;
 
5983
          best_plan_so_far= pplan;
 
5984
        }
 
5985
      }
 
5986
    }
 
5987
    @endcode
 
5988
 
 
5989
  @note
 
5990
    When 'best_extension_by_limited_search' is called for the first time,
 
5991
    'join->best_read' must be set to the largest possible value (e.g. DBL_MAX).
 
5992
    The actual implementation provides a way to optionally use pruning
 
5993
    heuristic (controlled by the parameter 'prune_level') to reduce the search
 
5994
    space by skipping some partial plans.
 
5995
 
 
5996
  @note
 
5997
    The parameter 'search_depth' provides control over the recursion
 
5998
    depth, and thus the size of the resulting optimal plan.
 
5999
 
 
6000
  @param join             pointer to the structure providing all context info
 
6001
                          for the query
 
6002
  @param remaining_tables set of tables not included into the partial plan yet
 
6003
  @param idx              length of the partial QEP in 'join->positions';
 
6004
                          since a depth-first search is used, also corresponds
 
6005
                          to the current depth of the search tree;
 
6006
                          also an index in the array 'join->best_ref';
 
6007
  @param record_count     estimate for the number of records returned by the
 
6008
                          best partial plan
 
6009
  @param read_time        the cost of the best partial plan
 
6010
  @param search_depth     maximum depth of the recursion and thus size of the
 
6011
                          found optimal plan
 
6012
                          (0 < search_depth <= join->tables+1).
 
6013
  @param prune_level      pruning heuristics that should be applied during
 
6014
                          optimization
 
6015
                          (values: 0 = EXHAUSTIVE, 1 = PRUNE_BY_TIME_OR_ROWS)
 
6016
 
 
6017
  @retval
 
6018
    false       ok
 
6019
  @retval
 
6020
    true        Fatal error
 
6021
*/
 
6022
 
 
6023
static bool
 
6024
best_extension_by_limited_search(JOIN      *join,
 
6025
                                 table_map remaining_tables,
 
6026
                                 uint32_t      idx,
 
6027
                                 double    record_count,
 
6028
                                 double    read_time,
 
6029
                                 uint32_t      search_depth,
 
6030
                                 uint32_t      prune_level)
 
6031
{
 
6032
  Session *session= join->session;
 
6033
  if (session->killed)  // Abort
 
6034
    return(true);
 
6035
 
 
6036
  /*
 
6037
     'join' is a partial plan with lower cost than the best plan so far,
 
6038
     so continue expanding it further with the tables in 'remaining_tables'.
 
6039
  */
 
6040
  JOIN_TAB *s;
 
6041
  double best_record_count= DBL_MAX;
 
6042
  double best_read_time=    DBL_MAX;
 
6043
 
 
6044
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
6045
  {
 
6046
    table_map real_table_bit= s->table->map;
 
6047
    if ((remaining_tables & real_table_bit) &&
 
6048
        !(remaining_tables & s->dependent) &&
 
6049
        (!idx || !check_interleaving_with_nj(join->positions[idx-1].table, s)))
 
6050
    {
 
6051
      double current_record_count, current_read_time;
 
6052
      advance_sj_state(remaining_tables, s);
 
6053
 
 
6054
      /*
 
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
 
6059
          when the depth is insufficient??)
 
6060
      */
 
6061
      /* Find the best access method from 's' to the current partial plan */
 
6062
      best_access_path(join, s, session, remaining_tables, idx,
 
6063
                       record_count, read_time);
 
6064
      /* Compute the cost of extending the plan with 's' */
 
6065
      current_record_count= record_count * join->positions[idx].records_read;
 
6066
      current_read_time=    read_time + join->positions[idx].read_time;
 
6067
 
 
6068
      /* Expand only partial plans with lower cost than the best QEP so far */
 
6069
      if ((current_read_time +
 
6070
           current_record_count / (double) TIME_FOR_COMPARE) >= join->best_read)
 
6071
      {
 
6072
        restore_prev_nj_state(s);
 
6073
        restore_prev_sj_state(remaining_tables, s);
 
6074
        continue;
 
6075
      }
 
6076
 
 
6077
      /*
 
6078
        Prune some less promising partial plans. This heuristic may miss
 
6079
        the optimal QEPs, thus it results in a non-exhaustive search.
 
6080
      */
 
6081
      if (prune_level == 1)
 
6082
      {
 
6083
        if (best_record_count > current_record_count ||
 
6084
            best_read_time > current_read_time ||
 
6085
            (idx == join->const_tables && s->table == join->sort_by_table)) // 's' is the first table in the QEP
 
6086
        {
 
6087
          if (best_record_count >= current_record_count &&
 
6088
              best_read_time >= current_read_time &&
 
6089
              /* TODO: What is the reasoning behind this condition? */
 
6090
              (!(s->key_dependent & remaining_tables) ||
 
6091
               join->positions[idx].records_read < 2.0))
 
6092
          {
 
6093
            best_record_count= current_record_count;
 
6094
            best_read_time=    current_read_time;
 
6095
          }
 
6096
        }
 
6097
        else
 
6098
        {
 
6099
          restore_prev_nj_state(s);
 
6100
          restore_prev_sj_state(remaining_tables, s);
 
6101
          continue;
 
6102
        }
 
6103
      }
 
6104
 
 
6105
      if ( (search_depth > 1) && (remaining_tables & ~real_table_bit) )
 
6106
      { /* Recursively expand the current partial plan */
 
6107
        std::swap(join->best_ref[idx], *pos);
 
6108
        if (best_extension_by_limited_search(join,
 
6109
                                             remaining_tables & ~real_table_bit,
 
6110
                                             idx + 1,
 
6111
                                             current_record_count,
 
6112
                                             current_read_time,
 
6113
                                             search_depth - 1,
 
6114
                                             prune_level))
 
6115
          return(true);
 
6116
        std::swap(join->best_ref[idx], *pos);
 
6117
      }
 
6118
      else
 
6119
      { /*
 
6120
          'join' is either the best partial QEP with 'search_depth' relations,
 
6121
          or the best complete QEP so far, whichever is smaller.
 
6122
        */
 
6123
        current_read_time+= current_record_count / (double) TIME_FOR_COMPARE;
 
6124
        if (join->sort_by_table &&
 
6125
            join->sort_by_table !=
 
6126
            join->positions[join->const_tables].table->table)
 
6127
          /* We have to make a temp table */
 
6128
          current_read_time+= current_record_count;
 
6129
        if ((search_depth == 1) || (current_read_time < join->best_read))
 
6130
        {
 
6131
          memcpy(join->best_positions, join->positions,
 
6132
                 sizeof(POSITION) * (idx + 1));
 
6133
          join->best_read= current_read_time - 0.001;
 
6134
        }
 
6135
      }
 
6136
      restore_prev_nj_state(s);
 
6137
      restore_prev_sj_state(remaining_tables, s);
 
6138
    }
 
6139
  }
 
6140
  return(false);
 
6141
}
 
6142
 
 
6143
 
 
6144
/**
 
6145
  @todo
 
6146
  - TODO: this function is here only temporarily until 'greedy_search' is
 
6147
  tested and accepted.
 
6148
 
 
6149
  RETURN VALUES
 
6150
    false       ok
 
6151
    true        Fatal error
 
6152
*/
 
6153
static bool
 
6154
find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count,
 
6155
          double read_time)
 
6156
{
 
6157
  Session *session= join->session;
 
6158
  if (session->killed)
 
6159
    return(true);
 
6160
  if (!rest_tables)
 
6161
  {
 
6162
    read_time+=record_count/(double) TIME_FOR_COMPARE;
 
6163
    if (join->sort_by_table &&
 
6164
        join->sort_by_table !=
 
6165
        join->positions[join->const_tables].table->table)
 
6166
      read_time+=record_count;                  // We have to make a temp table
 
6167
    if (read_time < join->best_read)
 
6168
    {
 
6169
      memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
6170
      join->best_read= read_time - 0.001;
 
6171
    }
 
6172
    return(false);
 
6173
  }
 
6174
  if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
 
6175
    return(false);                                      /* Found better before */
 
6176
 
 
6177
  JOIN_TAB *s;
 
6178
  double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
 
6179
  for (JOIN_TAB **pos=join->best_ref+idx ; (s=*pos) ; pos++)
 
6180
  {
 
6181
    table_map real_table_bit=s->table->map;
 
6182
    if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent) &&
 
6183
        (!idx|| !check_interleaving_with_nj(join->positions[idx-1].table, s)))
 
6184
    {
 
6185
      double records, best;
 
6186
      advance_sj_state(rest_tables, s);
 
6187
      best_access_path(join, s, session, rest_tables, idx, record_count,
 
6188
                       read_time);
 
6189
      records= join->positions[idx].records_read;
 
6190
      best= join->positions[idx].read_time;
 
6191
      /*
 
6192
        Go to the next level only if there hasn't been a better key on
 
6193
        this level! This will cut down the search for a lot simple cases!
 
6194
      */
 
6195
      double current_record_count=record_count*records;
 
6196
      double current_read_time=read_time+best;
 
6197
      if (best_record_count > current_record_count ||
 
6198
          best_read_time > current_read_time ||
 
6199
          (idx == join->const_tables && s->table == join->sort_by_table))
 
6200
      {
 
6201
        if (best_record_count >= current_record_count &&
 
6202
            best_read_time >= current_read_time &&
 
6203
            (!(s->key_dependent & rest_tables) || records < 2.0))
 
6204
        {
 
6205
          best_record_count=current_record_count;
 
6206
          best_read_time=current_read_time;
 
6207
        }
 
6208
        std::swap(join->best_ref[idx], *pos);
 
6209
        if (find_best(join,rest_tables & ~real_table_bit,idx+1,
 
6210
                      current_record_count,current_read_time))
 
6211
          return(true);
 
6212
        std::swap(join->best_ref[idx], *pos);
 
6213
      }
 
6214
      restore_prev_nj_state(s);
 
6215
      restore_prev_sj_state(rest_tables, s);
 
6216
      if (join->select_options & SELECT_STRAIGHT_JOIN)
 
6217
        break;                          // Don't test all combinations
 
6218
    }
 
6219
  }
 
6220
  return(false);
 
6221
}
 
6222
 
 
6223
 
 
6224
/**
847
6225
  Find how much space the prevous read not const tables takes in cache.
848
6226
*/
849
 
void calc_used_field_length(Session *, JoinTable *join_tab)
 
6227
 
 
6228
static void calc_used_field_length(Session *, JOIN_TAB *join_tab)
850
6229
{
851
6230
  uint32_t null_fields,blobs,fields,rec_length;
852
6231
  Field **f_ptr,*field;
 
6232
  bitset<MAX_FIELDS> *read_set= join_tab->table->read_set;
853
6233
 
854
6234
  null_fields= blobs= fields= rec_length=0;
855
6235
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
856
6236
  {
857
 
    if (field->isReadSet())
 
6237
    if (read_set->test(field->field_index))
858
6238
    {
859
6239
      uint32_t flags=field->flags;
860
6240
      fields++;
861
6241
      rec_length+=field->pack_length();
862
6242
      if (flags & BLOB_FLAG)
863
 
        blobs++;
 
6243
        blobs++;
864
6244
      if (!(flags & NOT_NULL_FLAG))
865
 
        null_fields++;
 
6245
        null_fields++;
866
6246
    }
867
6247
  }
868
6248
  if (null_fields)
871
6251
    rec_length+=sizeof(bool);
872
6252
  if (blobs)
873
6253
  {
874
 
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
875
 
                                     (join_tab->table->getRecordLength()- rec_length));
876
 
    rec_length+= max((uint32_t)4,blob_length);
 
6254
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
 
6255
                             (join_tab->table->getRecordLength()- rec_length));
 
6256
    rec_length+=(uint32_t) cmax((uint32_t)4,blob_length);
877
6257
  }
878
6258
  join_tab->used_fields= fields;
879
6259
  join_tab->used_fieldlength= rec_length;
880
6260
  join_tab->used_blobs= blobs;
881
6261
}
882
6262
 
883
 
StoredKey *get_store_key(Session *session,
884
 
                         optimizer::KeyUse *keyuse,
885
 
                         table_map used_tables,
886
 
                         KEY_PART_INFO *key_part,
887
 
                         unsigned char *key_buff,
888
 
                         uint32_t maybe_null)
889
 
{
890
 
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
891
 
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
6263
 
 
6264
static uint
 
6265
cache_record_length(JOIN *join,uint32_t idx)
 
6266
{
 
6267
  uint32_t length=0;
 
6268
  JOIN_TAB **pos,**end;
 
6269
  Session *session=join->session;
 
6270
 
 
6271
  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
 
6272
       pos != end ;
 
6273
       pos++)
 
6274
  {
 
6275
    JOIN_TAB *join_tab= *pos;
 
6276
    if (!join_tab->used_fieldlength)            /* Not calced yet */
 
6277
      calc_used_field_length(session, join_tab);
 
6278
    length+=join_tab->used_fieldlength;
 
6279
  }
 
6280
  return length;
 
6281
}
 
6282
 
 
6283
 
 
6284
/*
 
6285
  Get the number of different row combinations for subset of partial join
 
6286
 
 
6287
  SYNOPSIS
 
6288
    prev_record_reads()
 
6289
      join       The join structure
 
6290
      idx        Number of tables in the partial join order (i.e. the
 
6291
                 partial join order is in join->positions[0..idx-1])
 
6292
      found_ref  Bitmap of tables for which we need to find # of distinct
 
6293
                 row combinations.
 
6294
 
 
6295
  DESCRIPTION
 
6296
    Given a partial join order (in join->positions[0..idx-1]) and a subset of
 
6297
    tables within that join order (specified in found_ref), find out how many
 
6298
    distinct row combinations of subset tables will be in the result of the
 
6299
    partial join order.
 
6300
 
 
6301
    This is used as follows: Suppose we have a table accessed with a ref-based
 
6302
    method. The ref access depends on current rows of tables in found_ref.
 
6303
    We want to count # of different ref accesses. We assume two ref accesses
 
6304
    will be different if at least one of access parameters is different.
 
6305
    Example: consider a query
 
6306
 
 
6307
    SELECT * FROM t1, t2, t3 WHERE t1.key=c1 AND t2.key=c2 AND t3.key=t1.field
 
6308
 
 
6309
    and a join order:
 
6310
      t1,  ref access on t1.key=c1
 
6311
      t2,  ref access on t2.key=c2
 
6312
      t3,  ref access on t3.key=t1.field
 
6313
 
 
6314
    For t1: n_ref_scans = 1, n_distinct_ref_scans = 1
 
6315
    For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1
 
6316
    For t3: n_ref_scans = records_read(t1)*records_read(t2)
 
6317
            n_distinct_ref_scans = #records_read(t1)
 
6318
 
 
6319
    The reason for having this function (at least the latest version of it)
 
6320
    is that we need to account for buffering in join execution.
 
6321
 
 
6322
    An edge-case example: if we have a non-first table in join accessed via
 
6323
    ref(const) or ref(param) where there is a small number of different
 
6324
    values of param, then the access will likely hit the disk cache and will
 
6325
    not require any disk seeks.
 
6326
 
 
6327
    The proper solution would be to assume an LRU disk cache of some size,
 
6328
    calculate probability of cache hits, etc. For now we just count
 
6329
    identical ref accesses as one.
 
6330
 
 
6331
  RETURN
 
6332
    Expected number of row combinations
 
6333
*/
 
6334
 
 
6335
static double
 
6336
prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
 
6337
{
 
6338
  double found=1.0;
 
6339
  POSITION *pos_end= join->positions - 1;
 
6340
  for (POSITION *pos= join->positions + idx - 1; pos != pos_end; pos--)
 
6341
  {
 
6342
    if (pos->table->table->map & found_ref)
 
6343
    {
 
6344
      found_ref|= pos->ref_depend_map;
 
6345
      /*
 
6346
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table
 
6347
        with no matching row we will get position[t2].records_read==0.
 
6348
        Actually the size of output is one null-complemented row, therefore
 
6349
        we will use value of 1 whenever we get records_read==0.
 
6350
 
 
6351
        Note
 
6352
        - the above case can't occur if inner part of outer join has more
 
6353
          than one table: table with no matches will not be marked as const.
 
6354
 
 
6355
        - Ideally we should add 1 to records_read for every possible null-
 
6356
          complemented row. We're not doing it because: 1. it will require
 
6357
          non-trivial code and add overhead. 2. The value of records_read
 
6358
          is an inprecise estimate and adding 1 (or, in the worst case,
 
6359
          #max_nested_outer_joins=64-1) will not make it any more precise.
 
6360
      */
 
6361
      if (pos->records_read > DBL_EPSILON)
 
6362
        found*= pos->records_read;
 
6363
    }
 
6364
  }
 
6365
  return found;
 
6366
}
 
6367
 
 
6368
 
 
6369
/**
 
6370
  Set up join struct according to best position.
 
6371
*/
 
6372
 
 
6373
static bool
 
6374
get_best_combination(JOIN *join)
 
6375
{
 
6376
  uint32_t i,tablenr;
 
6377
  table_map used_tables;
 
6378
  JOIN_TAB *join_tab,*j;
 
6379
  KEYUSE *keyuse;
 
6380
  uint32_t table_count;
 
6381
  Session *session=join->session;
 
6382
 
 
6383
  table_count=join->tables;
 
6384
  if (!(join->join_tab=join_tab=
 
6385
        (JOIN_TAB*) session->alloc(sizeof(JOIN_TAB)*table_count)))
 
6386
    return(true);
 
6387
 
 
6388
  join->full_join=0;
 
6389
 
 
6390
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
 
6391
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
 
6392
  {
 
6393
    Table *form;
 
6394
    *j= *join->best_positions[tablenr].table;
 
6395
    form=join->table[tablenr]=j->table;
 
6396
    used_tables|= form->map;
 
6397
    form->reginfo.join_tab=j;
 
6398
    if (!*j->on_expr_ref)
 
6399
      form->reginfo.not_exists_optimize=0;      // Only with LEFT JOIN
 
6400
    if (j->type == JT_CONST)
 
6401
      continue;                                 // Handled in make_join_stat..
 
6402
 
 
6403
    j->ref.key = -1;
 
6404
    j->ref.key_parts=0;
 
6405
 
 
6406
    if (j->type == JT_SYSTEM)
 
6407
      continue;
 
6408
    if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key))
 
6409
    {
 
6410
      j->type=JT_ALL;
 
6411
      if (tablenr != join->const_tables)
 
6412
        join->full_join=1;
 
6413
    }
 
6414
    else if (create_ref_for_key(join, j, keyuse, used_tables))
 
6415
      return(true);                        // Something went wrong
 
6416
  }
 
6417
 
 
6418
  for (i=0 ; i < table_count ; i++)
 
6419
    join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i;
 
6420
  update_depend_map(join);
 
6421
  return(0);
 
6422
}
 
6423
 
 
6424
 
 
6425
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
6426
                               table_map used_tables)
 
6427
{
 
6428
  KEYUSE *keyuse=org_keyuse;
 
6429
  Session  *session= join->session;
 
6430
  uint32_t keyparts,length,key;
 
6431
  Table *table;
 
6432
  KEY *keyinfo;
 
6433
 
 
6434
  /*  Use best key from find_best */
 
6435
  table=j->table;
 
6436
  key=keyuse->key;
 
6437
  keyinfo=table->key_info+key;
 
6438
 
 
6439
  {
 
6440
    keyparts=length=0;
 
6441
    uint32_t found_part_ref_or_null= 0;
 
6442
    /*
 
6443
      Calculate length for the used key
 
6444
      Stop if there is a missing key part or when we find second key_part
 
6445
      with KEY_OPTIMIZE_REF_OR_NULL
 
6446
    */
 
6447
    do
 
6448
    {
 
6449
      if (!(~used_tables & keyuse->used_tables))
 
6450
      {
 
6451
        if (keyparts == keyuse->keypart &&
 
6452
            !(found_part_ref_or_null & keyuse->optimize))
 
6453
        {
 
6454
          keyparts++;
 
6455
          length+= keyinfo->key_part[keyuse->keypart].store_length;
 
6456
          found_part_ref_or_null|= keyuse->optimize;
 
6457
        }
 
6458
      }
 
6459
      keyuse++;
 
6460
    } while (keyuse->table == table && keyuse->key == key);
 
6461
  }
 
6462
 
 
6463
  /* set up fieldref */
 
6464
  keyinfo=table->key_info+key;
 
6465
  j->ref.key_parts=keyparts;
 
6466
  j->ref.key_length=length;
 
6467
  j->ref.key=(int) key;
 
6468
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
 
6469
      !(j->ref.key_copy= (store_key**) session->alloc((sizeof(store_key*) *
 
6470
                                                   (keyparts+1)))) ||
 
6471
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
 
6472
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
 
6473
  {
 
6474
    return(true);
 
6475
  }
 
6476
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
 
6477
  j->ref.key_err=1;
 
6478
  j->ref.null_rejecting= 0;
 
6479
  j->ref.disable_cache= false;
 
6480
  keyuse=org_keyuse;
 
6481
 
 
6482
  store_key **ref_key= j->ref.key_copy;
 
6483
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
 
6484
  bool keyuse_uses_no_tables= true;
 
6485
  {
 
6486
    uint32_t i;
 
6487
    for (i=0 ; i < keyparts ; keyuse++,i++)
 
6488
    {
 
6489
      while (keyuse->keypart != i ||
 
6490
             ((~used_tables) & keyuse->used_tables))
 
6491
        keyuse++;                               /* Skip other parts */
 
6492
 
 
6493
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
 
6494
      j->ref.items[i]=keyuse->val;              // Save for cond removal
 
6495
      j->ref.cond_guards[i]= keyuse->cond_guard;
 
6496
      if (keyuse->null_rejecting)
 
6497
        j->ref.null_rejecting |= 1 << i;
 
6498
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
 
6499
      if (!keyuse->used_tables &&
 
6500
          !(join->select_options & SELECT_DESCRIBE))
 
6501
      {                                 // Compare against constant
 
6502
        store_key_item tmp(session, keyinfo->key_part[i].field,
 
6503
                           key_buff + maybe_null,
 
6504
                           maybe_null ?  key_buff : 0,
 
6505
                           keyinfo->key_part[i].length, keyuse->val);
 
6506
        if (session->is_fatal_error)
 
6507
          return(true);
 
6508
        tmp.copy();
 
6509
      }
 
6510
      else
 
6511
        *ref_key++= get_store_key(session,
 
6512
                                  keyuse,join->const_table_map,
 
6513
                                  &keyinfo->key_part[i],
 
6514
                                  key_buff, maybe_null);
 
6515
      /*
 
6516
        Remember if we are going to use REF_OR_NULL
 
6517
        But only if field _really_ can be null i.e. we force JT_REF
 
6518
        instead of JT_REF_OR_NULL in case if field can't be null
 
6519
      */
 
6520
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
6521
        null_ref_key= key_buff;
 
6522
      key_buff+=keyinfo->key_part[i].store_length;
 
6523
    }
 
6524
  }
 
6525
  *ref_key=0;                           // end_marker
 
6526
  if (j->type == JT_CONST)
 
6527
    j->table->const_table= 1;
 
6528
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
 
6529
           keyparts != keyinfo->key_parts || null_ref_key)
 
6530
  {
 
6531
    /* Must read with repeat */
 
6532
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
 
6533
    j->ref.null_ref_key= null_ref_key;
 
6534
  }
 
6535
  else if (keyuse_uses_no_tables)
 
6536
  {
 
6537
    /*
 
6538
      This happen if we are using a constant expression in the ON part
 
6539
      of an LEFT JOIN.
 
6540
      SELECT * FROM a LEFT JOIN b ON b.key=30
 
6541
      Here we should not mark the table as a 'const' as a field may
 
6542
      have a 'normal' value or a NULL value.
 
6543
    */
 
6544
    j->type=JT_CONST;
 
6545
  }
 
6546
  else
 
6547
    j->type=JT_EQ_REF;
 
6548
  return(0);
 
6549
}
 
6550
 
 
6551
 
 
6552
 
 
6553
static store_key *
 
6554
get_store_key(Session *session, KEYUSE *keyuse, table_map used_tables,
 
6555
              KEY_PART_INFO *key_part, unsigned char *key_buff, uint32_t maybe_null)
 
6556
{
 
6557
  if (!((~used_tables) & keyuse->used_tables))          // if const item
892
6558
  {
893
6559
    return new store_key_const_item(session,
894
6560
                                    key_part->field,
895
6561
                                    key_buff + maybe_null,
896
6562
                                    maybe_null ? key_buff : 0,
897
6563
                                    key_part->length,
898
 
                                    key_use_val);
 
6564
                                    keyuse->val);
899
6565
  }
900
 
  else if (key_use_val->type() == Item::FIELD_ITEM ||
901
 
           (key_use_val->type() == Item::REF_ITEM &&
902
 
            key_use_val->ref_type() == Item_ref::OUTER_REF &&
903
 
            (*(Item_ref**)((Item_ref*)key_use_val)->ref)->ref_type() == Item_ref::DIRECT_REF &&
904
 
            key_use_val->real_item()->type() == Item::FIELD_ITEM))
905
 
  {
 
6566
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
 
6567
           (keyuse->val->type() == Item::REF_ITEM &&
 
6568
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
 
6569
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
 
6570
             Item_ref::DIRECT_REF &&
 
6571
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
906
6572
    return new store_key_field(session,
907
6573
                               key_part->field,
908
6574
                               key_buff + maybe_null,
909
6575
                               maybe_null ? key_buff : 0,
910
6576
                               key_part->length,
911
 
                               ((Item_field*) key_use_val->real_item())->field,
912
 
                               key_use_val->full_name());
913
 
  }
 
6577
                               ((Item_field*) keyuse->val->real_item())->field,
 
6578
                               keyuse->val->full_name());
914
6579
  return new store_key_item(session,
915
6580
                            key_part->field,
916
6581
                            key_buff + maybe_null,
917
6582
                            maybe_null ? key_buff : 0,
918
6583
                            key_part->length,
919
 
                            key_use_val);
 
6584
                            keyuse->val);
920
6585
}
921
6586
 
922
6587
/**
925
6590
  @return
926
6591
    returns 1 if there was some conversion made when the field was stored.
927
6592
*/
928
 
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
 
6593
 
 
6594
bool
 
6595
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
929
6596
{
930
6597
  bool error;
931
6598
  Table *table= field->table;
944
6611
  return error || cuted_fields != session->cuted_fields;
945
6612
}
946
6613
 
 
6614
 
 
6615
static bool
 
6616
make_simple_join(JOIN *join,Table *tmp_table)
 
6617
{
 
6618
  Table **tableptr;
 
6619
  JOIN_TAB *join_tab;
 
6620
 
 
6621
  /*
 
6622
    Reuse Table * and JOIN_TAB if already allocated by a previous call
 
6623
    to this function through JOIN::exec (may happen for sub-queries).
 
6624
  */
 
6625
  if (!join->table_reexec)
 
6626
  {
 
6627
    if (!(join->table_reexec= (Table**) join->session->alloc(sizeof(Table*))))
 
6628
      return(true);                        /* purecov: inspected */
 
6629
    if (join->tmp_join)
 
6630
      join->tmp_join->table_reexec= join->table_reexec;
 
6631
  }
 
6632
  if (!join->join_tab_reexec)
 
6633
  {
 
6634
    if (!(join->join_tab_reexec=
 
6635
          (JOIN_TAB*) join->session->alloc(sizeof(JOIN_TAB))))
 
6636
      return(true);                        /* purecov: inspected */
 
6637
    if (join->tmp_join)
 
6638
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
 
6639
  }
 
6640
  tableptr= join->table_reexec;
 
6641
  join_tab= join->join_tab_reexec;
 
6642
 
 
6643
  join->join_tab=join_tab;
 
6644
  join->table=tableptr; tableptr[0]=tmp_table;
 
6645
  join->tables=1;
 
6646
  join->const_tables=0;
 
6647
  join->const_table_map=0;
 
6648
  join->tmp_table_param.field_count= join->tmp_table_param.sum_func_count=
 
6649
    join->tmp_table_param.func_count=0;
 
6650
  join->tmp_table_param.copy_field=join->tmp_table_param.copy_field_end=0;
 
6651
  join->first_record=join->sort_and_group=0;
 
6652
  join->send_records=(ha_rows) 0;
 
6653
  join->group=0;
 
6654
  join->row_limit=join->unit->select_limit_cnt;
 
6655
  join->do_send_rows = (join->row_limit) ? 1 : 0;
 
6656
 
 
6657
  join_tab->cache.buff=0;                       /* No caching */
 
6658
  join_tab->table=tmp_table;
 
6659
  join_tab->select=0;
 
6660
  join_tab->select_cond=0;
 
6661
  join_tab->quick=0;
 
6662
  join_tab->type= JT_ALL;                       /* Map through all records */
 
6663
  join_tab->keys.init();
 
6664
  join_tab->keys.set_all();                     /* test everything in quick */
 
6665
  join_tab->info=0;
 
6666
  join_tab->on_expr_ref=0;
 
6667
  join_tab->last_inner= 0;
 
6668
  join_tab->first_unmatched= 0;
 
6669
  join_tab->ref.key = -1;
 
6670
  join_tab->not_used_in_distinct=0;
 
6671
  join_tab->read_first_record= join_init_read_record;
 
6672
  join_tab->join=join;
 
6673
  join_tab->ref.key_parts= 0;
 
6674
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
 
6675
  join_tab->do_firstmatch= NULL;
 
6676
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
 
6677
  tmp_table->status=0;
 
6678
  tmp_table->null_row=0;
 
6679
  return(false);
 
6680
}
 
6681
 
 
6682
 
947
6683
inline void add_cond_and_fix(Item **e1, Item *e2)
948
6684
{
949
6685
  if (*e1)
959
6695
    *e1= e2;
960
6696
}
961
6697
 
962
 
bool create_ref_for_key(JOIN *join, 
963
 
                        JoinTable *j, 
964
 
                        optimizer::KeyUse *org_keyuse,
965
 
                        table_map used_tables)
966
 
{
967
 
  optimizer::KeyUse *keyuse= org_keyuse;
968
 
  Session  *session= join->session;
969
 
  uint32_t keyparts;
970
 
  uint32_t length;
971
 
  uint32_t key;
972
 
  Table *table= NULL;
973
 
  KEY *keyinfo= NULL;
974
 
 
975
 
  /*  Use best key from find_best */
976
 
  table= j->table;
977
 
  key= keyuse->getKey();
978
 
  keyinfo= table->key_info + key;
979
 
 
980
 
  {
981
 
    keyparts= length= 0;
982
 
    uint32_t found_part_ref_or_null= 0;
983
 
    /*
984
 
      Calculate length for the used key
985
 
      Stop if there is a missing key part or when we find second key_part
986
 
      with KEY_OPTIMIZE_REF_OR_NULL
987
 
    */
988
 
    do
989
 
    {
990
 
      if (! (~used_tables & keyuse->getUsedTables()))
991
 
      {
992
 
        if (keyparts == keyuse->getKeypart() &&
993
 
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
994
 
        {
995
 
          keyparts++;
996
 
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
997
 
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
998
 
        }
999
 
      }
1000
 
      keyuse++;
1001
 
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
1002
 
  }
1003
 
 
1004
 
  /* set up fieldref */
1005
 
  keyinfo=table->key_info+key;
1006
 
  j->ref.key_parts=keyparts;
1007
 
  j->ref.key_length=length;
1008
 
  j->ref.key=(int) key;
1009
 
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
1010
 
      !(j->ref.key_copy= (StoredKey**) session->alloc((sizeof(StoredKey*) *
1011
 
               (keyparts+1)))) ||
1012
 
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
1013
 
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
1014
 
  {
1015
 
    return(true);
1016
 
  }
1017
 
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
1018
 
  j->ref.key_err=1;
1019
 
  j->ref.null_rejecting= 0;
1020
 
  j->ref.disable_cache= false;
1021
 
  keyuse=org_keyuse;
1022
 
 
1023
 
  StoredKey **ref_key= j->ref.key_copy;
1024
 
  unsigned char *key_buff= j->ref.key_buff, *null_ref_key= 0;
1025
 
  bool keyuse_uses_no_tables= true;
1026
 
  {
1027
 
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
1028
 
    {
1029
 
      while (keyuse->getKeypart() != i ||
1030
 
             ((~used_tables) & keyuse->getUsedTables()))
1031
 
        keyuse++;       /* Skip other parts */
1032
 
 
1033
 
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1034
 
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
1035
 
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
1036
 
      if (keyuse->isNullRejected())
1037
 
        j->ref.null_rejecting |= 1 << i;
1038
 
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
1039
 
      if (! keyuse->getUsedTables() &&  !(join->select_options & SELECT_DESCRIBE))
1040
 
      {         // Compare against constant
1041
 
        store_key_item tmp(session, keyinfo->key_part[i].field,
1042
 
                           key_buff + maybe_null,
1043
 
                           maybe_null ?  key_buff : 0,
1044
 
                           keyinfo->key_part[i].length, keyuse->getVal());
1045
 
        if (session->is_fatal_error)
1046
 
          return(true);
1047
 
        tmp.copy();
1048
 
      }
1049
 
      else
1050
 
        *ref_key++= get_store_key(session,
1051
 
          keyuse,join->const_table_map,
1052
 
          &keyinfo->key_part[i],
1053
 
          key_buff, maybe_null);
1054
 
      /*
1055
 
        Remember if we are going to use REF_OR_NULL
1056
 
        But only if field _really_ can be null i.e. we force AM_REF
1057
 
        instead of AM_REF_OR_NULL in case if field can't be null
1058
 
      */
1059
 
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1060
 
        null_ref_key= key_buff;
1061
 
      key_buff+=keyinfo->key_part[i].store_length;
1062
 
    }
1063
 
  }
1064
 
  *ref_key= 0;       // end_marker
1065
 
  if (j->type == AM_CONST)
1066
 
    j->table->const_table= 1;
1067
 
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1068
 
           keyparts != keyinfo->key_parts || null_ref_key)
1069
 
  {
1070
 
    /* Must read with repeat */
1071
 
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
1072
 
    j->ref.null_ref_key= null_ref_key;
1073
 
  }
1074
 
  else if (keyuse_uses_no_tables)
1075
 
  {
1076
 
    /*
1077
 
      This happen if we are using a constant expression in the ON part
1078
 
      of an LEFT JOIN.
1079
 
      SELECT * FROM a LEFT JOIN b ON b.key=30
1080
 
      Here we should not mark the table as a 'const' as a field may
1081
 
      have a 'normal' value or a NULL value.
1082
 
    */
1083
 
    j->type= AM_CONST;
1084
 
  }
1085
 
  else
1086
 
    j->type= AM_EQ_REF;
1087
 
  return 0;
1088
 
}
1089
6698
 
1090
6699
/**
1091
6700
  Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions
1131
6740
 
1132
6741
    Implementation overview
1133
6742
      1. update_ref_and_keys() accumulates info about null-rejecting
1134
 
         predicates in in KeyField::null_rejecting
1135
 
      1.1 add_key_part saves these to KeyUse.
1136
 
      2. create_ref_for_key copies them to table_reference_st.
 
6743
         predicates in in KEY_FIELD::null_rejecting
 
6744
      1.1 add_key_part saves these to KEYUSE.
 
6745
      2. create_ref_for_key copies them to TABLE_REF.
1137
6746
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1138
 
         appropiate JoinTable members.
 
6747
         appropiate JOIN_TAB members.
1139
6748
*/
1140
 
void add_not_null_conds(JOIN *join)
 
6749
 
 
6750
static void add_not_null_conds(JOIN *join)
1141
6751
{
1142
 
  for (uint32_t i= join->const_tables; i < join->tables; i++)
 
6752
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1143
6753
  {
1144
 
    JoinTable *tab=join->join_tab+i;
1145
 
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1146
 
         tab->type == AM_REF_OR_NULL) &&
 
6754
    JOIN_TAB *tab=join->join_tab+i;
 
6755
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
 
6756
         tab->type == JT_REF_OR_NULL) &&
1147
6757
        !tab->table->maybe_null)
1148
6758
    {
1149
6759
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1154
6764
          Item *notnull;
1155
6765
          assert(item->type() == Item::FIELD_ITEM);
1156
6766
          Item_field *not_null_item= (Item_field*)item;
1157
 
          JoinTable *referred_tab= not_null_item->field->table->reginfo.join_tab;
 
6767
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
1158
6768
          /*
1159
6769
            For UPDATE queries such as:
1160
6770
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1195
6805
    -  pointer to the guarded predicate, if success
1196
6806
    -  0, otherwise
1197
6807
*/
1198
 
COND *add_found_match_trig_cond(JoinTable *tab, COND *cond, JoinTable *root_tab)
 
6808
 
 
6809
static COND*
 
6810
add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab)
1199
6811
{
1200
6812
  COND *tmp;
1201
6813
  assert(cond != 0);
1211
6823
  return tmp;
1212
6824
}
1213
6825
 
 
6826
 
 
6827
/**
 
6828
  Fill in outer join related info for the execution plan structure.
 
6829
 
 
6830
    For each outer join operation left after simplification of the
 
6831
    original query the function set up the following pointers in the linear
 
6832
    structure join->join_tab representing the selected execution plan.
 
6833
    The first inner table t0 for the operation is set to refer to the last
 
6834
    inner table tk through the field t0->last_inner.
 
6835
    Any inner table ti for the operation are set to refer to the first
 
6836
    inner table ti->first_inner.
 
6837
    The first inner table t0 for the operation is set to refer to the
 
6838
    first inner table of the embedding outer join operation, if there is any,
 
6839
    through the field t0->first_upper.
 
6840
    The on expression for the outer join operation is attached to the
 
6841
    corresponding first inner table through the field t0->on_expr_ref.
 
6842
    Here ti are structures of the JOIN_TAB type.
 
6843
 
 
6844
  EXAMPLE. For the query:
 
6845
  @code
 
6846
        SELECT * FROM t1
 
6847
                      LEFT JOIN
 
6848
                      (t2, t3 LEFT JOIN t4 ON t3.a=t4.a)
 
6849
                      ON (t1.a=t2.a AND t1.b=t3.b)
 
6850
          WHERE t1.c > 5,
 
6851
  @endcode
 
6852
 
 
6853
    given the execution plan with the table order t1,t2,t3,t4
 
6854
    is selected, the following references will be set;
 
6855
    t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2]
 
6856
    t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2],
 
6857
    on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to
 
6858
    *t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref.
 
6859
 
 
6860
  @param join   reference to the info fully describing the query
 
6861
 
 
6862
  @note
 
6863
    The function assumes that the simplification procedure has been
 
6864
    already applied to the join query (see simplify_joins).
 
6865
    This function can be called only after the execution plan
 
6866
    has been chosen.
 
6867
*/
 
6868
 
 
6869
static void
 
6870
make_outerjoin_info(JOIN *join)
 
6871
{
 
6872
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6873
  {
 
6874
    JOIN_TAB *tab=join->join_tab+i;
 
6875
    Table *table=tab->table;
 
6876
    TableList *tbl= table->pos_in_table_list;
 
6877
    TableList *embedding= tbl->embedding;
 
6878
 
 
6879
    if (tbl->outer_join)
 
6880
    {
 
6881
      /*
 
6882
        Table tab is the only one inner table for outer join.
 
6883
        (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a
 
6884
        is in the query above.)
 
6885
      */
 
6886
      tab->last_inner= tab->first_inner= tab;
 
6887
      tab->on_expr_ref= &tbl->on_expr;
 
6888
      tab->cond_equal= tbl->cond_equal;
 
6889
      if (embedding)
 
6890
        tab->first_upper= embedding->nested_join->first_nested;
 
6891
    }
 
6892
    for ( ; embedding ; embedding= embedding->embedding)
 
6893
    {
 
6894
      /* Ignore sj-nests: */
 
6895
      if (!embedding->on_expr)
 
6896
        continue;
 
6897
      nested_join_st *nested_join= embedding->nested_join;
 
6898
      if (!nested_join->counter_)
 
6899
      {
 
6900
        /*
 
6901
          Table tab is the first inner table for nested_join.
 
6902
          Save reference to it in the nested join structure.
 
6903
        */
 
6904
        nested_join->first_nested= tab;
 
6905
        tab->on_expr_ref= &embedding->on_expr;
 
6906
        tab->cond_equal= tbl->cond_equal;
 
6907
        if (embedding->embedding)
 
6908
          tab->first_upper= embedding->embedding->nested_join->first_nested;
 
6909
      }
 
6910
      if (!tab->first_inner)
 
6911
        tab->first_inner= nested_join->first_nested;
 
6912
      if (++nested_join->counter_ < nested_join->join_list.elements)
 
6913
        break;
 
6914
      /* Table tab is the last inner table for nested join. */
 
6915
      nested_join->first_nested->last_inner= tab;
 
6916
    }
 
6917
  }
 
6918
  return;
 
6919
}
 
6920
 
 
6921
 
 
6922
static bool
 
6923
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
 
6924
{
 
6925
  Session *session= join->session;
 
6926
  if (select)
 
6927
  {
 
6928
    add_not_null_conds(join);
 
6929
    table_map used_tables;
 
6930
    if (cond)                /* Because of QUICK_GROUP_MIN_MAX_SELECT */
 
6931
    {                        /* there may be a select without a cond. */
 
6932
      if (join->tables > 1)
 
6933
        cond->update_used_tables();             // Tablenr may have changed
 
6934
      if (join->const_tables == join->tables &&
 
6935
          session->lex->current_select->master_unit() ==
 
6936
          &session->lex->unit)          // not upper level SELECT
 
6937
        join->const_table_map|=RAND_TABLE_BIT;
 
6938
      {                                         // Check const tables
 
6939
        COND *const_cond=
 
6940
          make_cond_for_table(cond,
 
6941
                              join->const_table_map,
 
6942
                              (table_map) 0, 1);
 
6943
        for (JOIN_TAB *tab= join->join_tab+join->const_tables;
 
6944
             tab < join->join_tab+join->tables ; tab++)
 
6945
        {
 
6946
          if (*tab->on_expr_ref)
 
6947
          {
 
6948
            JOIN_TAB *cond_tab= tab->first_inner;
 
6949
            COND *tmp= make_cond_for_table(*tab->on_expr_ref,
 
6950
                                           join->const_table_map,
 
6951
                                           (  table_map) 0, 0);
 
6952
            if (!tmp)
 
6953
              continue;
 
6954
            tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
 
6955
            if (!tmp)
 
6956
              return(1);
 
6957
            tmp->quick_fix_field();
 
6958
            cond_tab->select_cond= !cond_tab->select_cond ? tmp :
 
6959
                                    new Item_cond_and(cond_tab->select_cond,
 
6960
                                                      tmp);
 
6961
            if (!cond_tab->select_cond)
 
6962
              return(1);
 
6963
            cond_tab->select_cond->quick_fix_field();
 
6964
          }
 
6965
        }
 
6966
        if (const_cond && !const_cond->val_int())
 
6967
        {
 
6968
          return(1);     // Impossible const condition
 
6969
        }
 
6970
      }
 
6971
    }
 
6972
    used_tables=((select->const_tables=join->const_table_map) |
 
6973
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
6974
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6975
    {
 
6976
      JOIN_TAB *tab=join->join_tab+i;
 
6977
      /*
 
6978
        first_inner is the X in queries like:
 
6979
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
 
6980
      */
 
6981
      JOIN_TAB *first_inner_tab= tab->first_inner;
 
6982
      table_map current_map= tab->table->map;
 
6983
      bool use_quick_range=0;
 
6984
      COND *tmp;
 
6985
 
 
6986
      /*
 
6987
        Following force including random expression in last table condition.
 
6988
        It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
 
6989
      */
 
6990
      if (i == join->tables-1)
 
6991
        current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
 
6992
      used_tables|=current_map;
 
6993
 
 
6994
      if (tab->type == JT_REF && tab->quick &&
 
6995
          (uint32_t) tab->ref.key == tab->quick->index &&
 
6996
          tab->ref.key_length < tab->quick->max_used_key_length)
 
6997
      {
 
6998
        /* Range uses longer key;  Use this instead of ref on key */
 
6999
        tab->type=JT_ALL;
 
7000
        use_quick_range=1;
 
7001
        tab->use_quick=1;
 
7002
        tab->ref.key= -1;
 
7003
        tab->ref.key_parts=0;           // Don't use ref key.
 
7004
        join->best_positions[i].records_read= rows2double(tab->quick->records);
 
7005
        /*
 
7006
          We will use join cache here : prevent sorting of the first
 
7007
          table only and sort at the end.
 
7008
        */
 
7009
        if (i != join->const_tables && join->tables > join->const_tables + 1)
 
7010
          join->full_join= 1;
 
7011
      }
 
7012
 
 
7013
      tmp= NULL;
 
7014
      if (cond)
 
7015
        tmp= make_cond_for_table(cond,used_tables,current_map, 0);
 
7016
      if (cond && !tmp && tab->quick)
 
7017
      {                                         // Outer join
 
7018
        if (tab->type != JT_ALL)
 
7019
        {
 
7020
          /*
 
7021
            Don't use the quick method
 
7022
            We come here in the case where we have 'key=constant' and
 
7023
            the test is removed by make_cond_for_table()
 
7024
          */
 
7025
          delete tab->quick;
 
7026
          tab->quick= 0;
 
7027
        }
 
7028
        else
 
7029
        {
 
7030
          /*
 
7031
            Hack to handle the case where we only refer to a table
 
7032
            in the ON part of an OUTER JOIN. In this case we want the code
 
7033
            below to check if we should use 'quick' instead.
 
7034
          */
 
7035
          tmp= new Item_int((int64_t) 1,1);     // Always true
 
7036
        }
 
7037
 
 
7038
      }
 
7039
      if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
 
7040
          tab->type == JT_EQ_REF)
 
7041
      {
 
7042
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
 
7043
                                       session->memdup((unsigned char*) select,
 
7044
                                                   sizeof(*select)));
 
7045
        if (!sel)
 
7046
          return(1);                    // End of memory
 
7047
        /*
 
7048
          If tab is an inner table of an outer join operation,
 
7049
          add a match guard to the pushed down predicate.
 
7050
          The guard will turn the predicate on only after
 
7051
          the first match for outer tables is encountered.
 
7052
        */
 
7053
        if (cond && tmp)
 
7054
        {
 
7055
          /*
 
7056
            Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
 
7057
            a cond, so neutralize the hack above.
 
7058
          */
 
7059
          if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
 
7060
            return(1);
 
7061
          tab->select_cond=sel->cond=tmp;
 
7062
          /* Push condition to storage engine if this is enabled
 
7063
             and the condition is not guarded */
 
7064
          tab->table->file->pushed_cond= NULL;
 
7065
          if (session->variables.engine_condition_pushdown)
 
7066
          {
 
7067
            COND *push_cond=
 
7068
              make_cond_for_table(tmp, current_map, current_map, 0);
 
7069
            if (push_cond)
 
7070
            {
 
7071
              /* Push condition to handler */
 
7072
              if (!tab->table->file->cond_push(push_cond))
 
7073
                tab->table->file->pushed_cond= push_cond;
 
7074
            }
 
7075
          }
 
7076
        }
 
7077
        else
 
7078
          tab->select_cond= sel->cond= NULL;
 
7079
 
 
7080
        sel->head=tab->table;
 
7081
        if (tab->quick)
 
7082
        {
 
7083
          /* Use quick key read if it's a constant and it's not used
 
7084
             with key reading */
 
7085
          if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
 
7086
              && (tab->type != JT_REF || (uint32_t) tab->ref.key == tab->quick->index))
 
7087
          {
 
7088
            sel->quick=tab->quick;              // Use value from get_quick_...
 
7089
            sel->quick_keys.clear_all();
 
7090
            sel->needed_reg.clear_all();
 
7091
          }
 
7092
          else
 
7093
          {
 
7094
            delete tab->quick;
 
7095
          }
 
7096
          tab->quick=0;
 
7097
        }
 
7098
        uint32_t ref_key=(uint32_t) sel->head->reginfo.join_tab->ref.key+1;
 
7099
        if (i == join->const_tables && ref_key)
 
7100
        {
 
7101
          if (!tab->const_keys.is_clear_all() &&
 
7102
              tab->table->reginfo.impossible_range)
 
7103
            return(1);
 
7104
        }
 
7105
        else if (tab->type == JT_ALL && ! use_quick_range)
 
7106
        {
 
7107
          if (!tab->const_keys.is_clear_all() &&
 
7108
              tab->table->reginfo.impossible_range)
 
7109
            return(1);                          // Impossible range
 
7110
          /*
 
7111
            We plan to scan all rows.
 
7112
            Check again if we should use an index.
 
7113
            We could have used an column from a previous table in
 
7114
            the index if we are using limit and this is the first table
 
7115
          */
 
7116
 
 
7117
          if ((cond && (!tab->keys.is_subset(tab->const_keys) && i > 0)) ||
 
7118
              (!tab->const_keys.is_clear_all() && (i == join->const_tables) && (join->unit->select_limit_cnt < join->best_positions[i].records_read) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
 
7119
          {
 
7120
            /* Join with outer join condition */
 
7121
            COND *orig_cond=sel->cond;
 
7122
            sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
 
7123
 
 
7124
            /*
 
7125
              We can't call sel->cond->fix_fields,
 
7126
              as it will break tab->on_expr if it's AND condition
 
7127
              (fix_fields currently removes extra AND/OR levels).
 
7128
              Yet attributes of the just built condition are not needed.
 
7129
              Thus we call sel->cond->quick_fix_field for safety.
 
7130
            */
 
7131
            if (sel->cond && !sel->cond->fixed)
 
7132
              sel->cond->quick_fix_field();
 
7133
 
 
7134
            if (sel->test_quick_select(session, tab->keys,
 
7135
                                       used_tables & ~ current_map,
 
7136
                                       (join->select_options &
 
7137
                                        OPTION_FOUND_ROWS ?
 
7138
                                        HA_POS_ERROR :
 
7139
                                        join->unit->select_limit_cnt), 0,
 
7140
                                        false) < 0)
 
7141
            {
 
7142
              /*
 
7143
                Before reporting "Impossible WHERE" for the whole query
 
7144
                we have to check isn't it only "impossible ON" instead
 
7145
              */
 
7146
              sel->cond=orig_cond;
 
7147
              if (!*tab->on_expr_ref ||
 
7148
                  sel->test_quick_select(session, tab->keys,
 
7149
                                         used_tables & ~ current_map,
 
7150
                                         (join->select_options &
 
7151
                                          OPTION_FOUND_ROWS ?
 
7152
                                          HA_POS_ERROR :
 
7153
                                          join->unit->select_limit_cnt),0,
 
7154
                                          false) < 0)
 
7155
                return(1);                      // Impossible WHERE
 
7156
            }
 
7157
            else
 
7158
              sel->cond=orig_cond;
 
7159
 
 
7160
            /* Fix for EXPLAIN */
 
7161
            if (sel->quick)
 
7162
              join->best_positions[i].records_read= (double)sel->quick->records;
 
7163
          }
 
7164
          else
 
7165
          {
 
7166
            sel->needed_reg=tab->needed_reg;
 
7167
            sel->quick_keys.clear_all();
 
7168
          }
 
7169
          if (!sel->quick_keys.is_subset(tab->checked_keys) ||
 
7170
              !sel->needed_reg.is_subset(tab->checked_keys))
 
7171
          {
 
7172
            tab->keys=sel->quick_keys;
 
7173
            tab->keys.merge(sel->needed_reg);
 
7174
            tab->use_quick= (!sel->needed_reg.is_clear_all() &&
 
7175
                             (select->quick_keys.is_clear_all() ||
 
7176
                              (select->quick &&
 
7177
                               (select->quick->records >= 100L)))) ?
 
7178
              2 : 1;
 
7179
            sel->read_tables= used_tables & ~current_map;
 
7180
          }
 
7181
          if (i != join->const_tables && tab->use_quick != 2)
 
7182
          {                                     /* Read with cache */
 
7183
            if (cond &&
 
7184
                (tmp=make_cond_for_table(cond,
 
7185
                                         join->const_table_map |
 
7186
                                         current_map,
 
7187
                                         current_map, 0)))
 
7188
            {
 
7189
              tab->cache.select=(SQL_SELECT*)
 
7190
                session->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
7191
              tab->cache.select->cond=tmp;
 
7192
              tab->cache.select->read_tables=join->const_table_map;
 
7193
            }
 
7194
          }
 
7195
        }
 
7196
      }
 
7197
 
 
7198
      /*
 
7199
        Push down conditions from all on expressions.
 
7200
        Each of these conditions are guarded by a variable
 
7201
        that turns if off just before null complemented row for
 
7202
        outer joins is formed. Thus, the condition from an
 
7203
        'on expression' are guaranteed not to be checked for
 
7204
        the null complemented row.
 
7205
      */
 
7206
 
 
7207
      /* First push down constant conditions from on expressions */
 
7208
      for (JOIN_TAB *join_tab= join->join_tab+join->const_tables;
 
7209
           join_tab < join->join_tab+join->tables ; join_tab++)
 
7210
      {
 
7211
        if (*join_tab->on_expr_ref)
 
7212
        {
 
7213
          JOIN_TAB *cond_tab= join_tab->first_inner;
 
7214
          tmp= make_cond_for_table(*join_tab->on_expr_ref,
 
7215
                                   join->const_table_map,
 
7216
                                   (table_map) 0, 0);
 
7217
          if (!tmp)
 
7218
            continue;
 
7219
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
 
7220
          if (!tmp)
 
7221
            return(1);
 
7222
          tmp->quick_fix_field();
 
7223
          cond_tab->select_cond= !cond_tab->select_cond ? tmp :
 
7224
                                    new Item_cond_and(cond_tab->select_cond,tmp);
 
7225
          if (!cond_tab->select_cond)
 
7226
            return(1);
 
7227
          cond_tab->select_cond->quick_fix_field();
 
7228
        }
 
7229
      }
 
7230
 
 
7231
      /* Push down non-constant conditions from on expressions */
 
7232
      JOIN_TAB *last_tab= tab;
 
7233
      while (first_inner_tab && first_inner_tab->last_inner == last_tab)
 
7234
      {
 
7235
        /*
 
7236
          Table tab is the last inner table of an outer join.
 
7237
          An on expression is always attached to it.
 
7238
        */
 
7239
        COND *on_expr= *first_inner_tab->on_expr_ref;
 
7240
 
 
7241
        table_map used_tables2= (join->const_table_map |
 
7242
                                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
7243
        for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++)
 
7244
        {
 
7245
          current_map= tab->table->map;
 
7246
          used_tables2|= current_map;
 
7247
          COND *tmp_cond= make_cond_for_table(on_expr, used_tables2,
 
7248
                                              current_map, 0);
 
7249
          if (tmp_cond)
 
7250
          {
 
7251
            JOIN_TAB *cond_tab= tab < first_inner_tab ? first_inner_tab : tab;
 
7252
            /*
 
7253
              First add the guards for match variables of
 
7254
              all embedding outer join operations.
 
7255
            */
 
7256
            if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner,
 
7257
                                                     tmp_cond,
 
7258
                                                     first_inner_tab)))
 
7259
              return(1);
 
7260
            /*
 
7261
              Now add the guard turning the predicate off for
 
7262
              the null complemented row.
 
7263
            */
 
7264
            tmp_cond= new Item_func_trig_cond(tmp_cond,
 
7265
                                              &first_inner_tab->
 
7266
                                              not_null_compl);
 
7267
            if (tmp_cond)
 
7268
              tmp_cond->quick_fix_field();
 
7269
            /* Add the predicate to other pushed down predicates */
 
7270
            cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond :
 
7271
                                  new Item_cond_and(cond_tab->select_cond,
 
7272
                                                    tmp_cond);
 
7273
            if (!cond_tab->select_cond)
 
7274
              return(1);
 
7275
            cond_tab->select_cond->quick_fix_field();
 
7276
          }
 
7277
        }
 
7278
        first_inner_tab= first_inner_tab->first_upper;
 
7279
      }
 
7280
    }
 
7281
  }
 
7282
  return(0);
 
7283
}
 
7284
 
 
7285
 
1214
7286
/*
1215
7287
  Check if given expression uses only table fields covered by the given index
1216
7288
 
1232
7304
    true   Yes
1233
7305
    false  No
1234
7306
*/
1235
 
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
 
7307
 
 
7308
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno,
 
7309
                            bool other_tbls_ok)
1236
7310
{
1237
7311
  if (item->const_item())
1238
7312
    return true;
1285
7359
      Item_field *item_field= (Item_field*)item;
1286
7360
      if (item_field->field->table != tbl)
1287
7361
        return true;
1288
 
      return item_field->field->part_of_key.test(keyno);
 
7362
      return item_field->field->part_of_key.is_set(keyno);
1289
7363
    }
1290
7364
  case Item::REF_ITEM:
1291
7365
    return uses_index_fields_only(item->real_item(), tbl, keyno,
1295
7369
  }
1296
7370
}
1297
7371
 
 
7372
 
1298
7373
#define ICP_COND_USES_INDEX_ONLY 10
1299
7374
 
1300
7375
/*
1324
7399
  RETURN
1325
7400
    Index condition, or NULL if no condition could be inferred.
1326
7401
*/
1327
 
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
 
7402
 
 
7403
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno,
 
7404
                          bool other_tbls_ok)
1328
7405
{
1329
7406
  if (!cond)
1330
7407
    return NULL;
1335
7412
    {
1336
7413
      Item_cond_and *new_cond=new Item_cond_and;
1337
7414
      if (!new_cond)
1338
 
        return (COND*) 0;
 
7415
        return (COND*) 0;
1339
7416
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1340
7417
      Item *item;
1341
7418
      while ((item=li++))
1342
7419
      {
1343
 
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
1344
 
        if (fix)
1345
 
          new_cond->argument_list()->push_back(fix);
 
7420
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
7421
        if (fix)
 
7422
          new_cond->argument_list()->push_back(fix);
1346
7423
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
1347
7424
      }
1348
7425
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
1349
7426
        cond->marker= ICP_COND_USES_INDEX_ONLY;
1350
7427
      switch (new_cond->argument_list()->elements) {
1351
7428
      case 0:
1352
 
        return (COND*) 0;
 
7429
        return (COND*) 0;
1353
7430
      case 1:
1354
 
        return new_cond->argument_list()->head();
 
7431
        return new_cond->argument_list()->head();
1355
7432
      default:
1356
 
        new_cond->quick_fix_field();
1357
 
        return new_cond;
 
7433
        new_cond->quick_fix_field();
 
7434
        return new_cond;
1358
7435
      }
1359
7436
    }
1360
7437
    else /* It's OR */
1361
7438
    {
1362
7439
      Item_cond_or *new_cond=new Item_cond_or;
1363
7440
      if (!new_cond)
1364
 
        return (COND*) 0;
 
7441
        return (COND*) 0;
1365
7442
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1366
7443
      Item *item;
1367
7444
      while ((item=li++))
1368
7445
      {
1369
 
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
1370
 
        if (!fix)
1371
 
          return (COND*) 0;
1372
 
        new_cond->argument_list()->push_back(fix);
 
7446
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
7447
        if (!fix)
 
7448
          return (COND*) 0;
 
7449
        new_cond->argument_list()->push_back(fix);
1373
7450
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
1374
7451
      }
1375
7452
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
1387
7464
}
1388
7465
 
1389
7466
 
1390
 
static Item *make_cond_remainder(Item *cond, bool exclude_index)
 
7467
Item *make_cond_remainder(Item *cond, bool exclude_index)
1391
7468
{
1392
7469
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
1393
7470
    return 0; /* Already checked */
1400
7477
      /* Create new top level AND item */
1401
7478
      Item_cond_and *new_cond=new Item_cond_and;
1402
7479
      if (!new_cond)
1403
 
        return (COND*) 0;
 
7480
        return (COND*) 0;
1404
7481
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1405
7482
      Item *item;
1406
7483
      while ((item=li++))
1407
7484
      {
1408
 
        Item *fix= make_cond_remainder(item, exclude_index);
1409
 
        if (fix)
 
7485
        Item *fix= make_cond_remainder(item, exclude_index);
 
7486
        if (fix)
1410
7487
        {
1411
 
          new_cond->argument_list()->push_back(fix);
 
7488
          new_cond->argument_list()->push_back(fix);
1412
7489
          tbl_map |= fix->used_tables();
1413
7490
        }
1414
7491
      }
1415
7492
      switch (new_cond->argument_list()->elements) {
1416
7493
      case 0:
1417
 
        return (COND*) 0;
 
7494
        return (COND*) 0;
1418
7495
      case 1:
1419
 
        return new_cond->argument_list()->head();
 
7496
        return new_cond->argument_list()->head();
1420
7497
      default:
1421
 
        new_cond->quick_fix_field();
 
7498
        new_cond->quick_fix_field();
1422
7499
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
1423
 
        return new_cond;
 
7500
        return new_cond;
1424
7501
      }
1425
7502
    }
1426
7503
    else /* It's OR */
1427
7504
    {
1428
7505
      Item_cond_or *new_cond=new Item_cond_or;
1429
7506
      if (!new_cond)
1430
 
        return (COND*) 0;
 
7507
        return (COND*) 0;
1431
7508
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
1432
7509
      Item *item;
1433
7510
      while ((item=li++))
1434
7511
      {
1435
 
        Item *fix= make_cond_remainder(item, false);
1436
 
        if (!fix)
1437
 
          return (COND*) 0;
1438
 
        new_cond->argument_list()->push_back(fix);
 
7512
        Item *fix= make_cond_remainder(item, false);
 
7513
        if (!fix)
 
7514
          return (COND*) 0;
 
7515
        new_cond->argument_list()->push_back(fix);
1439
7516
        tbl_map |= fix->used_tables();
1440
7517
      }
1441
7518
      new_cond->quick_fix_field();
1447
7524
  return cond;
1448
7525
}
1449
7526
 
1450
 
/**
1451
 
  cleanup JoinTable.
1452
 
*/
1453
 
void JoinTable::cleanup()
 
7527
 
 
7528
/*
 
7529
  Try to extract and push the index condition
 
7530
 
 
7531
  SYNOPSIS
 
7532
    push_index_cond()
 
7533
      tab            A join tab that has tab->table->file and its condition
 
7534
                     in tab->select_cond
 
7535
      keyno          Index for which extract and push the condition
 
7536
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7537
 
 
7538
  DESCRIPTION
 
7539
    Try to extract and push the index condition down to table handler
 
7540
*/
 
7541
 
 
7542
static void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
 
7543
{
 
7544
  Item *idx_cond;
 
7545
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
 
7546
      tab->join->session->variables.engine_condition_pushdown)
 
7547
  {
 
7548
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
 
7549
                                  other_tbls_ok);
 
7550
 
 
7551
    if (idx_cond)
 
7552
    {
 
7553
      tab->pre_idx_push_select_cond= tab->select_cond;
 
7554
      Item *idx_remainder_cond=
 
7555
        tab->table->file->idx_cond_push(keyno, idx_cond);
 
7556
 
 
7557
      /*
 
7558
        Disable eq_ref's "lookup cache" if we've pushed down an index
 
7559
        condition.
 
7560
        TODO: This check happens to work on current ICP implementations, but
 
7561
        there may exist a compliant implementation that will not work
 
7562
        correctly with it. Sort this out when we stabilize the condition
 
7563
        pushdown APIs.
 
7564
      */
 
7565
      if (idx_remainder_cond != idx_cond)
 
7566
        tab->ref.disable_cache= true;
 
7567
 
 
7568
      Item *row_cond= make_cond_remainder(tab->select_cond, true);
 
7569
 
 
7570
      if (row_cond)
 
7571
      {
 
7572
        if (!idx_remainder_cond)
 
7573
          tab->select_cond= row_cond;
 
7574
        else
 
7575
        {
 
7576
          tab->select_cond= new Item_cond_and(row_cond, idx_remainder_cond);
 
7577
          tab->select_cond->quick_fix_field();
 
7578
          ((Item_cond_and*)tab->select_cond)->used_tables_cache=
 
7579
            row_cond->used_tables() | idx_remainder_cond->used_tables();
 
7580
        }
 
7581
      }
 
7582
      else
 
7583
        tab->select_cond= idx_remainder_cond;
 
7584
      if (tab->select)
 
7585
      {
 
7586
        tab->select->cond= tab->select_cond;
 
7587
      }
 
7588
    }
 
7589
  }
 
7590
  return;
 
7591
}
 
7592
 
 
7593
 
 
7594
 
 
7595
    /*
 
7596
      Determine if the set is already ordered for order_st BY, so it can
 
7597
      disable join cache because it will change the ordering of the results.
 
7598
      Code handles sort table that is at any location (not only first after
 
7599
      the const tables) despite the fact that it's currently prohibited.
 
7600
      We must disable join cache if the first non-const table alone is
 
7601
      ordered. If there is a temp table the ordering is done as a last
 
7602
      operation and doesn't prevent join cache usage.
 
7603
    */
 
7604
uint32_t make_join_orderinfo(JOIN *join)
 
7605
{
 
7606
  uint32_t i;
 
7607
  if (join->need_tmp)
 
7608
    return join->tables;
 
7609
 
 
7610
  for (i=join->const_tables ; i < join->tables ; i++)
 
7611
  {
 
7612
    JOIN_TAB *tab=join->join_tab+i;
 
7613
    Table *table=tab->table;
 
7614
    if ((table == join->sort_by_table &&
 
7615
         (!join->order || join->skip_sort_order)) ||
 
7616
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
 
7617
    {
 
7618
      break;
 
7619
    }
 
7620
  }
 
7621
  return i;
 
7622
}
 
7623
 
 
7624
 
 
7625
/*
 
7626
  Plan refinement stage: do various set ups for the executioner
 
7627
 
 
7628
  SYNOPSIS
 
7629
    make_join_readinfo()
 
7630
      join           Join being processed
 
7631
      options        Join's options (checking for SELECT_DESCRIBE,
 
7632
                     SELECT_NO_JOIN_CACHE)
 
7633
      no_jbuf_after  Don't use join buffering after table with this number.
 
7634
 
 
7635
  DESCRIPTION
 
7636
    Plan refinement stage: do various set ups for the executioner
 
7637
      - set up use of join buffering
 
7638
      - push index conditions
 
7639
      - increment counters
 
7640
      - etc
 
7641
 
 
7642
  RETURN
 
7643
    false - OK
 
7644
    true  - Out of memory
 
7645
*/
 
7646
 
 
7647
static bool
 
7648
make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
7649
{
 
7650
  uint32_t i;
 
7651
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
 
7652
  bool sorted= 1;
 
7653
 
 
7654
  for (i=join->const_tables ; i < join->tables ; i++)
 
7655
  {
 
7656
    JOIN_TAB *tab=join->join_tab+i;
 
7657
    Table *table=tab->table;
 
7658
    bool using_join_cache;
 
7659
    tab->read_record.table= table;
 
7660
    tab->read_record.file=table->file;
 
7661
    tab->next_select=sub_select;                /* normal select */
 
7662
    /*
 
7663
      TODO: don't always instruct first table's ref/range access method to
 
7664
      produce sorted output.
 
7665
    */
 
7666
    tab->sorted= sorted;
 
7667
    sorted= 0;                                  // only first must be sorted
 
7668
    if (tab->insideout_match_tab)
 
7669
    {
 
7670
      if (!(tab->insideout_buf= (unsigned char*)join->session->alloc(tab->table->key_info
 
7671
                                                         [tab->index].
 
7672
                                                         key_length)))
 
7673
        return true;
 
7674
    }
 
7675
    switch (tab->type) {
 
7676
    case JT_SYSTEM:                             // Only happens with left join
 
7677
      table->status=STATUS_NO_RECORD;
 
7678
      tab->read_first_record= join_read_system;
 
7679
      tab->read_record.read_record= join_no_more_records;
 
7680
      break;
 
7681
    case JT_CONST:                              // Only happens with left join
 
7682
      table->status=STATUS_NO_RECORD;
 
7683
      tab->read_first_record= join_read_const;
 
7684
      tab->read_record.read_record= join_no_more_records;
 
7685
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7686
          !table->no_keyread)
 
7687
      {
 
7688
        table->key_read=1;
 
7689
        table->file->extra(HA_EXTRA_KEYREAD);
 
7690
      }
 
7691
      break;
 
7692
    case JT_EQ_REF:
 
7693
      table->status=STATUS_NO_RECORD;
 
7694
      if (tab->select)
 
7695
      {
 
7696
        delete tab->select->quick;
 
7697
        tab->select->quick=0;
 
7698
      }
 
7699
      delete tab->quick;
 
7700
      tab->quick=0;
 
7701
      tab->read_first_record= join_read_key;
 
7702
      tab->read_record.read_record= join_no_more_records;
 
7703
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7704
          !table->no_keyread)
 
7705
      {
 
7706
        table->key_read=1;
 
7707
        table->file->extra(HA_EXTRA_KEYREAD);
 
7708
      }
 
7709
      else
 
7710
        push_index_cond(tab, tab->ref.key, true);
 
7711
      break;
 
7712
    case JT_REF_OR_NULL:
 
7713
    case JT_REF:
 
7714
      table->status=STATUS_NO_RECORD;
 
7715
      if (tab->select)
 
7716
      {
 
7717
        delete tab->select->quick;
 
7718
        tab->select->quick=0;
 
7719
      }
 
7720
      delete tab->quick;
 
7721
      tab->quick=0;
 
7722
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7723
          !table->no_keyread)
 
7724
      {
 
7725
        table->key_read=1;
 
7726
        table->file->extra(HA_EXTRA_KEYREAD);
 
7727
      }
 
7728
      else
 
7729
        push_index_cond(tab, tab->ref.key, true);
 
7730
      if (tab->type == JT_REF)
 
7731
      {
 
7732
        tab->read_first_record= join_read_always_key;
 
7733
        tab->read_record.read_record= tab->insideout_match_tab?
 
7734
           join_read_next_same_diff : join_read_next_same;
 
7735
      }
 
7736
      else
 
7737
      {
 
7738
        tab->read_first_record= join_read_always_key_or_null;
 
7739
        tab->read_record.read_record= join_read_next_same_or_null;
 
7740
      }
 
7741
      break;
 
7742
    case JT_ALL:
 
7743
      /*
 
7744
        If previous table use cache
 
7745
        If the incoming data set is already sorted don't use cache.
 
7746
      */
 
7747
      table->status=STATUS_NO_RECORD;
 
7748
      using_join_cache= false;
 
7749
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
7750
          tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
 
7751
          !tab->insideout_match_tab)
 
7752
      {
 
7753
        if ((options & SELECT_DESCRIBE) ||
 
7754
            !join_init_cache(join->session,join->join_tab+join->const_tables,
 
7755
                             i-join->const_tables))
 
7756
        {
 
7757
          using_join_cache= true;
 
7758
          tab[-1].next_select=sub_select_cache; /* Patch previous */
 
7759
        }
 
7760
      }
 
7761
      /* These init changes read_record */
 
7762
      if (tab->use_quick == 2)
 
7763
      {
 
7764
        join->session->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
 
7765
        tab->read_first_record= join_init_quick_read_record;
 
7766
        if (statistics)
 
7767
          status_var_increment(join->session->status_var.select_range_check_count);
 
7768
      }
 
7769
      else
 
7770
      {
 
7771
        tab->read_first_record= join_init_read_record;
 
7772
        if (i == join->const_tables)
 
7773
        {
 
7774
          if (tab->select && tab->select->quick)
 
7775
          {
 
7776
            if (statistics)
 
7777
              status_var_increment(join->session->status_var.select_range_count);
 
7778
          }
 
7779
          else
 
7780
          {
 
7781
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7782
            if (statistics)
 
7783
              status_var_increment(join->session->status_var.select_scan_count);
 
7784
          }
 
7785
        }
 
7786
        else
 
7787
        {
 
7788
          if (tab->select && tab->select->quick)
 
7789
          {
 
7790
            if (statistics)
 
7791
              status_var_increment(join->session->status_var.select_full_range_join_count);
 
7792
          }
 
7793
          else
 
7794
          {
 
7795
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7796
            if (statistics)
 
7797
              status_var_increment(join->session->status_var.select_full_join_count);
 
7798
          }
 
7799
        }
 
7800
        if (!table->no_keyread)
 
7801
        {
 
7802
          if (tab->select && tab->select->quick &&
 
7803
              tab->select->quick->index != MAX_KEY && //not index_merge
 
7804
              table->covering_keys.is_set(tab->select->quick->index))
 
7805
          {
 
7806
            table->key_read=1;
 
7807
            table->file->extra(HA_EXTRA_KEYREAD);
 
7808
          }
 
7809
          else if (!table->covering_keys.is_clear_all() &&
 
7810
                   !(tab->select && tab->select->quick))
 
7811
          {                                     // Only read index tree
 
7812
            if (!tab->insideout_match_tab)
 
7813
            {
 
7814
              /*
 
7815
                See bug #26447: "Using the clustered index for a table scan
 
7816
                is always faster than using a secondary index".
 
7817
              */
 
7818
              if (table->s->primary_key != MAX_KEY &&
 
7819
                  table->file->primary_key_is_clustered())
 
7820
                tab->index= table->s->primary_key;
 
7821
              else
 
7822
                tab->index= table->find_shortest_key(&table->covering_keys);
 
7823
            }
 
7824
            tab->read_first_record= join_read_first;
 
7825
            tab->type=JT_NEXT;          // Read with index_first / index_next
 
7826
          }
 
7827
        }
 
7828
        if (tab->select && tab->select->quick &&
 
7829
            tab->select->quick->index != MAX_KEY && ! tab->table->key_read)
 
7830
          push_index_cond(tab, tab->select->quick->index, !using_join_cache);
 
7831
      }
 
7832
      break;
 
7833
    default:
 
7834
      break;                                    /* purecov: deadcode */
 
7835
    case JT_UNKNOWN:
 
7836
    case JT_MAYBE_REF:
 
7837
      abort();                                  /* purecov: deadcode */
 
7838
    }
 
7839
  }
 
7840
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
 
7841
  return(false);
 
7842
}
 
7843
 
 
7844
 
 
7845
/**
 
7846
  Give error if we some tables are done with a full join.
 
7847
 
 
7848
  This is used by multi_table_update and multi_table_delete when running
 
7849
  in safe mode.
 
7850
 
 
7851
  @param join           Join condition
 
7852
 
 
7853
  @retval
 
7854
    0   ok
 
7855
  @retval
 
7856
    1   Error (full join used)
 
7857
*/
 
7858
 
 
7859
bool error_if_full_join(JOIN *join)
 
7860
{
 
7861
  for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables;
 
7862
       tab < end;
 
7863
       tab++)
 
7864
  {
 
7865
    if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
 
7866
    {
 
7867
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
 
7868
                 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
 
7869
      return(1);
 
7870
    }
 
7871
  }
 
7872
  return(0);
 
7873
}
 
7874
 
 
7875
 
 
7876
/**
 
7877
  cleanup JOIN_TAB.
 
7878
*/
 
7879
 
 
7880
void JOIN_TAB::cleanup()
1454
7881
{
1455
7882
  delete select;
1456
7883
  select= 0;
1465
7892
    if (table->key_read)
1466
7893
    {
1467
7894
      table->key_read= 0;
1468
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
7895
      table->file->extra(HA_EXTRA_NO_KEYREAD);
1469
7896
    }
1470
 
    table->cursor->ha_index_or_rnd_end();
 
7897
    table->file->ha_index_or_rnd_end();
1471
7898
    /*
1472
7899
      We need to reset this for next select
1473
7900
      (Tested in part_of_refkey)
1477
7904
  end_read_record(&read_record);
1478
7905
}
1479
7906
 
1480
 
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
1481
 
{
1482
 
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1483
 
  {
1484
 
    if (tables & 1 && !eq_ref_table(join, order, *tab))
1485
 
      return 0;
1486
 
  }
1487
 
  return 1;
1488
 
}
1489
 
 
1490
 
/**
1491
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
7907
 
 
7908
/**
 
7909
  Partially cleanup JOIN after it has executed: close index or rnd read
 
7910
  (table cursors), free quick selects.
 
7911
 
 
7912
    This function is called in the end of execution of a JOIN, before the used
 
7913
    tables are unlocked and closed.
 
7914
 
 
7915
    For a join that is resolved using a temporary table, the first sweep is
 
7916
    performed against actual tables and an intermediate result is inserted
 
7917
    into the temprorary table.
 
7918
    The last sweep is performed against the temporary table. Therefore,
 
7919
    the base tables and associated buffers used to fill the temporary table
 
7920
    are no longer needed, and this function is called to free them.
 
7921
 
 
7922
    For a join that is performed without a temporary table, this function
 
7923
    is called after all rows are sent, but before EOF packet is sent.
 
7924
 
 
7925
    For a simple SELECT with no subqueries this function performs a full
 
7926
    cleanup of the JOIN and calls mysql_unlock_read_tables to free used base
 
7927
    tables.
 
7928
 
 
7929
    If a JOIN is executed for a subquery or if it has a subquery, we can't
 
7930
    do the full cleanup and need to do a partial cleanup only.
 
7931
    - If a JOIN is not the top level join, we must not unlock the tables
 
7932
    because the outer select may not have been evaluated yet, and we
 
7933
    can't unlock only selected tables of a query.
 
7934
    - Additionally, if this JOIN corresponds to a correlated subquery, we
 
7935
    should not free quick selects and join buffers because they will be
 
7936
    needed for the next execution of the correlated subquery.
 
7937
    - However, if this is a JOIN for a [sub]select, which is not
 
7938
    a correlated subquery itself, but has subqueries, we can free it
 
7939
    fully and also free JOINs of all its subqueries. The exception
 
7940
    is a subquery in SELECT list, e.g: @n
 
7941
    SELECT a, (select cmax(b) from t1) group by c @n
 
7942
    This subquery will not be evaluated at first sweep and its value will
 
7943
    not be inserted into the temporary table. Instead, it's evaluated
 
7944
    when selecting from the temporary table. Therefore, it can't be freed
 
7945
    here even though it's not correlated.
 
7946
 
 
7947
  @todo
 
7948
    Unlock tables even if the join isn't top level select in the tree
 
7949
*/
 
7950
 
 
7951
void JOIN::join_free()
 
7952
{
 
7953
  Select_Lex_Unit *tmp_unit;
 
7954
  Select_Lex *sl;
 
7955
  /*
 
7956
    Optimization: if not EXPLAIN and we are done with the JOIN,
 
7957
    free all tables.
 
7958
  */
 
7959
  bool full= (!select_lex->uncacheable && !session->lex->describe);
 
7960
  bool can_unlock= full;
 
7961
 
 
7962
  cleanup(full);
 
7963
 
 
7964
  for (tmp_unit= select_lex->first_inner_unit();
 
7965
       tmp_unit;
 
7966
       tmp_unit= tmp_unit->next_unit())
 
7967
    for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())
 
7968
    {
 
7969
      Item_subselect *subselect= sl->master_unit()->item;
 
7970
      bool full_local= full && (!subselect || subselect->is_evaluated());
 
7971
      /*
 
7972
        If this join is evaluated, we can fully clean it up and clean up all
 
7973
        its underlying joins even if they are correlated -- they will not be
 
7974
        used any more anyway.
 
7975
        If this join is not yet evaluated, we still must clean it up to
 
7976
        close its table cursors -- it may never get evaluated, as in case of
 
7977
        ... HAVING false OR a IN (SELECT ...))
 
7978
        but all table cursors must be closed before the unlock.
 
7979
      */
 
7980
      sl->cleanup_all_joins(full_local);
 
7981
      /* Can't unlock if at least one JOIN is still needed */
 
7982
      can_unlock= can_unlock && full_local;
 
7983
    }
 
7984
 
 
7985
  /*
 
7986
    We are not using tables anymore
 
7987
    Unlock all tables. We may be in an INSERT .... SELECT statement.
 
7988
  */
 
7989
  if (can_unlock && lock && session->lock &&
 
7990
      !(select_options & SELECT_NO_UNLOCK) &&
 
7991
      !select_lex->subquery_in_having &&
 
7992
      (select_lex == (session->lex->unit.fake_select_lex ?
 
7993
                      session->lex->unit.fake_select_lex : &session->lex->select_lex)))
 
7994
  {
 
7995
    /*
 
7996
      TODO: unlock tables even if the join isn't top level select in the
 
7997
      tree.
 
7998
    */
 
7999
    mysql_unlock_read_tables(session, lock);           // Don't free join->lock
 
8000
    lock= 0;
 
8001
  }
 
8002
 
 
8003
  return;
 
8004
}
 
8005
 
 
8006
 
 
8007
/**
 
8008
  Free resources of given join.
 
8009
 
 
8010
  @param fill   true if we should free all resources, call with full==1
 
8011
                should be last, before it this function can be called with
 
8012
                full==0
 
8013
 
 
8014
  @note
 
8015
    With subquery this function definitely will be called several times,
 
8016
    but even for simple query it can be called several times.
 
8017
*/
 
8018
 
 
8019
void JOIN::cleanup(bool full)
 
8020
{
 
8021
  if (table)
 
8022
  {
 
8023
    JOIN_TAB *tab,*end;
 
8024
    /*
 
8025
      Only a sorted table may be cached.  This sorted table is always the
 
8026
      first non const table in join->table
 
8027
    */
 
8028
    if (tables > const_tables) // Test for not-const tables
 
8029
    {
 
8030
      free_io_cache(table[const_tables]);
 
8031
      filesort_free_buffers(table[const_tables],full);
 
8032
    }
 
8033
 
 
8034
    if (full)
 
8035
    {
 
8036
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
 
8037
        tab->cleanup();
 
8038
      table= 0;
 
8039
    }
 
8040
    else
 
8041
    {
 
8042
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
 
8043
      {
 
8044
        if (tab->table)
 
8045
          tab->table->file->ha_index_or_rnd_end();
 
8046
      }
 
8047
    }
 
8048
    cleanup_sj_tmp_tables(this);//
 
8049
  }
 
8050
  /*
 
8051
    We are not using tables anymore
 
8052
    Unlock all tables. We may be in an INSERT .... SELECT statement.
 
8053
  */
 
8054
  if (full)
 
8055
  {
 
8056
    if (tmp_join)
 
8057
      tmp_table_param.copy_field= 0;
 
8058
    group_fields.delete_elements();
 
8059
    /*
 
8060
      We can't call delete_elements() on copy_funcs as this will cause
 
8061
      problems in free_elements() as some of the elements are then deleted.
 
8062
    */
 
8063
    tmp_table_param.copy_funcs.empty();
 
8064
    /*
 
8065
      If we have tmp_join and 'this' JOIN is not tmp_join and
 
8066
      tmp_table_param.copy_field's  of them are equal then we have to remove
 
8067
      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
 
8068
      be removed in tmp_table_param.cleanup().
 
8069
    */
 
8070
    if (tmp_join &&
 
8071
        tmp_join != this &&
 
8072
        tmp_join->tmp_table_param.copy_field ==
 
8073
        tmp_table_param.copy_field)
 
8074
    {
 
8075
      tmp_join->tmp_table_param.copy_field=
 
8076
        tmp_join->tmp_table_param.save_copy_field= 0;
 
8077
    }
 
8078
    tmp_table_param.cleanup();
 
8079
  }
 
8080
  return;
 
8081
}
 
8082
 
 
8083
 
 
8084
/**
 
8085
  Remove the following expressions from order_st BY and GROUP BY:
1492
8086
  Constant expressions @n
1493
8087
  Expression that only uses tables that are of type EQ_REF and the reference
1494
8088
  is in the order_st list or if all refereed tables are of the above type.
1495
8089
 
1496
8090
  In the following, the X field can be removed:
1497
8091
  @code
1498
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
1499
 
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
 
8092
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
 
8093
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1500
8094
  @endcode
1501
8095
 
1502
8096
  These can't be optimized:
1503
8097
  @code
1504
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
1505
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
1506
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
 
8098
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
 
8099
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
 
8100
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1507
8101
  @endcode
1508
8102
*/
1509
 
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
 
8103
 
 
8104
static bool
 
8105
eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
1510
8106
{
1511
8107
  if (tab->cached_eq_ref_table)                 // If cached
1512
8108
    return tab->eq_ref_table;
1513
8109
  tab->cached_eq_ref_table=1;
1514
8110
  /* We can skip const tables only if not an outer table */
1515
 
  if (tab->type == AM_CONST && !tab->first_inner)
1516
 
    return (tab->eq_ref_table=1);
1517
 
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
 
8111
  if (tab->type == JT_CONST && !tab->first_inner)
 
8112
    return (tab->eq_ref_table=1);               /* purecov: inspected */
 
8113
  if (tab->type != JT_EQ_REF || tab->table->maybe_null)
1518
8114
    return (tab->eq_ref_table=0);               // We must use this
1519
8115
  Item **ref_item=tab->ref.items;
1520
8116
  Item **end=ref_item+tab->ref.key_parts;
1528
8124
      order_st *order;
1529
8125
      for (order=start_order ; order ; order=order->next)
1530
8126
      {
1531
 
        if ((*ref_item)->eq(order->item[0],0))
1532
 
          break;
 
8127
        if ((*ref_item)->eq(order->item[0],0))
 
8128
          break;
1533
8129
      }
1534
8130
      if (order)
1535
8131
      {
1536
 
        found++;
1537
 
        assert(!(order->used & map));
1538
 
        order->used|=map;
1539
 
        continue;                               // Used in order_st BY
 
8132
        found++;
 
8133
        assert(!(order->used & map));
 
8134
        order->used|=map;
 
8135
        continue;                               // Used in order_st BY
1540
8136
      }
1541
8137
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
1542
 
        return (tab->eq_ref_table= 0);
 
8138
        return (tab->eq_ref_table=0);
1543
8139
    }
1544
8140
  }
1545
8141
  /* Check that there was no reference to table before sort order */
1551
8147
      continue;
1552
8148
    }
1553
8149
    if (start_order->depend_map & map)
1554
 
      return (tab->eq_ref_table= 0);
1555
 
  }
1556
 
  return tab->eq_ref_table= 1;
1557
 
}
 
8150
      return (tab->eq_ref_table=0);
 
8151
  }
 
8152
  return tab->eq_ref_table=1;
 
8153
}
 
8154
 
 
8155
 
 
8156
static bool
 
8157
only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
 
8158
{
 
8159
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
 
8160
  {
 
8161
    if (tables & 1 && !eq_ref_table(join, order, *tab))
 
8162
      return 0;
 
8163
  }
 
8164
  return 1;
 
8165
}
 
8166
 
 
8167
 
 
8168
/** Update the dependency map for the tables. */
 
8169
 
 
8170
static void update_depend_map(JOIN *join)
 
8171
{
 
8172
  JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables;
 
8173
 
 
8174
  for (; join_tab != end ; join_tab++)
 
8175
  {
 
8176
    TABLE_REF *ref= &join_tab->ref;
 
8177
    table_map depend_map=0;
 
8178
    Item **item=ref->items;
 
8179
    uint32_t i;
 
8180
    for (i=0 ; i < ref->key_parts ; i++,item++)
 
8181
      depend_map|=(*item)->used_tables();
 
8182
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
 
8183
    depend_map&= ~OUTER_REF_TABLE_BIT;
 
8184
    for (JOIN_TAB **tab=join->map2table;
 
8185
         depend_map ;
 
8186
         tab++,depend_map>>=1 )
 
8187
    {
 
8188
      if (depend_map & 1)
 
8189
        ref->depend_map|=(*tab)->ref.depend_map;
 
8190
    }
 
8191
  }
 
8192
}
 
8193
 
 
8194
 
 
8195
/** Update the dependency map for the sort order. */
 
8196
 
 
8197
static void update_depend_map(JOIN *join, order_st *order)
 
8198
{
 
8199
  for (; order ; order=order->next)
 
8200
  {
 
8201
    table_map depend_map;
 
8202
    order->item[0]->update_used_tables();
 
8203
    order->depend_map=depend_map=order->item[0]->used_tables();
 
8204
    // Not item_sum(), RAND() and no reference to table outside of sub select
 
8205
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT))
 
8206
        && !order->item[0]->with_sum_func)
 
8207
    {
 
8208
      for (JOIN_TAB **tab=join->map2table;
 
8209
           depend_map ;
 
8210
           tab++, depend_map>>=1)
 
8211
      {
 
8212
        if (depend_map & 1)
 
8213
          order->depend_map|=(*tab)->ref.depend_map;
 
8214
      }
 
8215
    }
 
8216
  }
 
8217
}
 
8218
 
 
8219
 
 
8220
/**
 
8221
  Remove all constants and check if order_st only contains simple
 
8222
  expressions.
 
8223
 
 
8224
  simple_order is set to 1 if sort_order only uses fields from head table
 
8225
  and the head table is not a LEFT JOIN table.
 
8226
 
 
8227
  @param join                   Join handler
 
8228
  @param first_order            List of SORT or GROUP order
 
8229
  @param cond                   WHERE statement
 
8230
  @param change_list            Set to 1 if we should remove things from list.
 
8231
                               If this is not set, then only simple_order is
 
8232
                               calculated.
 
8233
  @param simple_order           Set to 1 if we are only using simple expressions
 
8234
 
 
8235
  @return
 
8236
    Returns new sort order
 
8237
*/
 
8238
 
 
8239
static order_st *
 
8240
remove_constants(JOIN *join,order_st *first_order, COND *cond,
 
8241
                 bool change_list, bool *simple_order)
 
8242
{
 
8243
  if (join->tables == join->const_tables)
 
8244
    return change_list ? 0 : first_order;               // No need to sort
 
8245
 
 
8246
  order_st *order,**prev_ptr;
 
8247
  table_map first_table= join->join_tab[join->const_tables].table->map;
 
8248
  table_map not_const_tables= ~join->const_table_map;
 
8249
  table_map ref;
 
8250
 
 
8251
  prev_ptr= &first_order;
 
8252
  *simple_order= *join->join_tab[join->const_tables].on_expr_ref ? 0 : 1;
 
8253
 
 
8254
  /* NOTE: A variable of not_const_tables ^ first_table; breaks gcc 2.7 */
 
8255
 
 
8256
  update_depend_map(join, first_order);
 
8257
  for (order=first_order; order ; order=order->next)
 
8258
  {
 
8259
    table_map order_tables=order->item[0]->used_tables();
 
8260
    if (order->item[0]->with_sum_func)
 
8261
      *simple_order=0;                          // Must do a temp table to sort
 
8262
    else if (!(order_tables & not_const_tables))
 
8263
    {
 
8264
      if (order->item[0]->with_subselect)
 
8265
        order->item[0]->val_str(&order->item[0]->str_value);
 
8266
      continue;                                 // skip const item
 
8267
    }
 
8268
    else
 
8269
    {
 
8270
      if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))
 
8271
        *simple_order=0;
 
8272
      else
 
8273
      {
 
8274
        Item *comp_item=0;
 
8275
        if (cond && const_expression_in_where(cond,order->item[0], &comp_item))
 
8276
        {
 
8277
          continue;
 
8278
        }
 
8279
        if ((ref=order_tables & (not_const_tables ^ first_table)))
 
8280
        {
 
8281
          if (!(order_tables & first_table) &&
 
8282
              only_eq_ref_tables(join,first_order, ref))
 
8283
          {
 
8284
            continue;
 
8285
          }
 
8286
          *simple_order=0;                      // Must do a temp table to sort
 
8287
        }
 
8288
      }
 
8289
    }
 
8290
    if (change_list)
 
8291
      *prev_ptr= order;                         // use this entry
 
8292
    prev_ptr= &order->next;
 
8293
  }
 
8294
  if (change_list)
 
8295
    *prev_ptr=0;
 
8296
  if (prev_ptr == &first_order)                 // Nothing to sort/group
 
8297
    *simple_order=1;
 
8298
  return(first_order);
 
8299
}
 
8300
 
 
8301
 
 
8302
static int
 
8303
return_zero_rows(JOIN *join, select_result *result,TableList *tables,
 
8304
                 List<Item> &fields, bool send_row, uint64_t select_options,
 
8305
                 const char *info, Item *having)
 
8306
{
 
8307
  if (select_options & SELECT_DESCRIBE)
 
8308
  {
 
8309
    select_describe(join, false, false, false, info);
 
8310
    return(0);
 
8311
  }
 
8312
 
 
8313
  join->join_free();
 
8314
 
 
8315
  if (send_row)
 
8316
  {
 
8317
    for (TableList *table= tables; table; table= table->next_leaf)
 
8318
      table->table->mark_as_null_row();         // All fields are NULL
 
8319
    if (having && having->val_int() == 0)
 
8320
      send_row=0;
 
8321
  }
 
8322
  if (!(result->send_fields(fields,
 
8323
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)))
 
8324
  {
 
8325
    if (send_row)
 
8326
    {
 
8327
      List_iterator_fast<Item> it(fields);
 
8328
      Item *item;
 
8329
      while ((item= it++))
 
8330
        item->no_rows_in_result();
 
8331
      result->send_data(fields);
 
8332
    }
 
8333
    result->send_eof();                         // Should be safe
 
8334
  }
 
8335
  /* Update results for FOUND_ROWS */
 
8336
  join->session->limit_found_rows= join->session->examined_row_count= 0;
 
8337
  return(0);
 
8338
}
 
8339
 
 
8340
/*
 
8341
  used only in JOIN::clear
 
8342
*/
 
8343
static void clear_tables(JOIN *join)
 
8344
{
 
8345
  /*
 
8346
    must clear only the non-const tables, as const tables
 
8347
    are not re-calculated.
 
8348
  */
 
8349
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
8350
    join->table[i]->mark_as_null_row();         // All fields are NULL
 
8351
}
 
8352
 
 
8353
/*****************************************************************************
 
8354
  Make som simple condition optimization:
 
8355
  If there is a test 'field = const' change all refs to 'field' to 'const'
 
8356
  Remove all dummy tests 'item = item', 'const op const'.
 
8357
  Remove all 'item is NULL', when item can never be null!
 
8358
  item->marker should be 0 for all items on entry
 
8359
  Return in cond_value false if condition is impossible (1 = 2)
 
8360
*****************************************************************************/
 
8361
 
 
8362
class COND_CMP :public ilink {
 
8363
public:
 
8364
  static void *operator new(size_t size)
 
8365
  {
 
8366
    return (void*) sql_alloc((uint32_t) size);
 
8367
  }
 
8368
  static void operator delete(void *, size_t)
 
8369
  { TRASH(ptr, size); }
 
8370
 
 
8371
  Item *and_level;
 
8372
  Item_func *cmp_func;
 
8373
  COND_CMP(Item *a,Item_func *b) :and_level(a),cmp_func(b) {}
 
8374
};
 
8375
 
 
8376
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
8377
template class I_List<COND_CMP>;
 
8378
template class I_List_iterator<COND_CMP>;
 
8379
#endif
 
8380
 
1558
8381
 
1559
8382
/**
1560
8383
  Find the multiple equality predicate containing a field.
1574
8397
    - Item_equal for the found multiple equality predicate if a success;
1575
8398
    - NULL otherwise.
1576
8399
*/
1577
 
static Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
 
8400
 
 
8401
Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field,
 
8402
                            bool *inherited_fl)
1578
8403
{
1579
8404
  Item_equal *item= 0;
1580
8405
  bool in_upper_level= false;
1595
8420
  return item;
1596
8421
}
1597
8422
 
 
8423
 
1598
8424
/**
1599
8425
  Check whether an equality can be used to build multiple equalities.
1600
8426
 
1676
8502
  @retval
1677
8503
    false   otherwise
1678
8504
*/
1679
 
static bool check_simple_equality(Item *left_item,
1680
 
                                  Item *right_item,
1681
 
                                  Item *item,
1682
 
                                  COND_EQUAL *cond_equal)
 
8505
 
 
8506
static bool check_simple_equality(Item *left_item, Item *right_item,
 
8507
                                  Item *item, COND_EQUAL *cond_equal)
1683
8508
{
1684
8509
  if (left_item->type() == Item::FIELD_ITEM &&
1685
8510
      right_item->type() == Item::FIELD_ITEM &&
1840
8665
  return false;
1841
8666
}
1842
8667
 
 
8668
 
1843
8669
/**
1844
8670
  Convert row equalities into a conjunction of regular equalities.
1845
8671
 
1865
8691
  @retval
1866
8692
    false   otherwise
1867
8693
*/
1868
 
static bool check_row_equality(Session *session,
1869
 
                               Item *left_row, 
1870
 
                               Item_row *right_row,
1871
 
                               COND_EQUAL *cond_equal,
1872
 
                               List<Item>* eq_list)
 
8694
 
 
8695
static bool check_row_equality(Session *session, Item *left_row, Item_row *right_row,
 
8696
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
1873
8697
{
1874
8698
  uint32_t n= left_row->cols();
1875
8699
  for (uint32_t i= 0 ; i < n; i++)
1906
8730
  return true;
1907
8731
}
1908
8732
 
 
8733
 
1909
8734
/**
1910
8735
  Eliminate row equalities and form multiple equalities predicates.
1911
8736
 
1935
8760
           or, if the equality is neither a simple one nor a row equality,
1936
8761
           or, if the procedure fails by a fatal error.
1937
8762
*/
1938
 
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal, List<Item> *eq_list)
 
8763
 
 
8764
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal,
 
8765
                           List<Item> *eq_list)
1939
8766
{
1940
8767
  if (item->type() == Item::FUNC_ITEM &&
1941
8768
         ((Item_func*) item)->functype() == Item_func::EQ_FUNC)
1958
8785
  return false;
1959
8786
}
1960
8787
 
 
8788
 
1961
8789
/**
1962
8790
  Replace all equality predicates in a condition by multiple equality items.
1963
8791
 
2021
8849
  @return
2022
8850
    pointer to the transformed condition
2023
8851
*/
2024
 
static COND *build_equal_items_for_cond(Session *session, COND *cond, COND_EQUAL *inherited)
 
8852
 
 
8853
static COND *build_equal_items_for_cond(Session *session, COND *cond,
 
8854
                                        COND_EQUAL *inherited)
2025
8855
{
2026
8856
  Item_equal *item_equal;
2027
8857
  COND_EQUAL cond_equal;
2117
8947
        {
2118
8948
          item_equal->fix_length_and_dec();
2119
8949
          item_equal->update_used_tables();
2120
 
        }
 
8950
        }
2121
8951
        else
2122
8952
          item_equal= (Item_equal *) eq_list.pop();
2123
8953
        set_if_bigger(session->lex->current_select->max_equal_elems,
2129
8959
        /*
2130
8960
          Here a new AND level must be created. It can happen only
2131
8961
          when a row equality is processed as a standalone predicate.
2132
 
        */
 
8962
        */
2133
8963
        Item_cond_and *and_cond= new Item_cond_and(eq_list);
2134
8964
        and_cond->quick_fix_field();
2135
8965
        List<Item> *args= and_cond->argument_list();
2163
8993
  return cond;
2164
8994
}
2165
8995
 
 
8996
 
2166
8997
/**
2167
8998
  Build multiple equalities for a condition and all on expressions that
2168
8999
  inherit these multiple equalities.
2217
9048
    can get more freedom in performing join operations.
2218
9049
    Althogh we don't use this property now, it probably makes sense to use
2219
9050
    it in the future.
2220
 
  @param session                      Thread Cursor
 
9051
  @param session                      Thread handler
2221
9052
  @param cond                condition to build the multiple equalities for
2222
9053
  @param inherited           path to all inherited multiple equality items
2223
9054
  @param join_list           list of join tables to which the condition
2228
9059
  @return
2229
9060
    pointer to the transformed condition containing multiple equalities
2230
9061
*/
 
9062
 
2231
9063
static COND *build_equal_items(Session *session, COND *cond,
2232
9064
                               COND_EQUAL *inherited,
2233
9065
                               List<TableList> *join_list,
2281
9113
  return cond;
2282
9114
}
2283
9115
 
 
9116
 
2284
9117
/**
2285
9118
  Compare field items by table order in the execution plan.
2286
9119
 
2300
9133
  @retval
2301
9134
    0  otherwise
2302
9135
*/
 
9136
 
2303
9137
static int compare_fields_by_table_order(Item_field *field1,
2304
 
                                         Item_field *field2,
2305
 
                                         void *table_join_idx)
 
9138
                                  Item_field *field2,
 
9139
                                  void *table_join_idx)
2306
9140
{
2307
9141
  int cmp= 0;
2308
9142
  bool outer_ref= 0;
2318
9152
  }
2319
9153
  if (outer_ref)
2320
9154
    return cmp;
2321
 
  JoinTable **idx= (JoinTable **) table_join_idx;
 
9155
  JOIN_TAB **idx= (JOIN_TAB **) table_join_idx;
2322
9156
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2323
9157
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2324
9158
}
2325
9159
 
 
9160
 
2326
9161
/**
2327
9162
  Generate minimal set of simple equalities equivalent to a multiple equality.
2328
9163
 
2362
9197
    a pointer to the simple generated equality, if success.
2363
9198
    - 0, otherwise.
2364
9199
*/
2365
 
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels, Item_equal *item_equal)
 
9200
 
 
9201
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels,
 
9202
                                  Item_equal *item_equal)
2366
9203
{
2367
9204
  List<Item> eq_list;
2368
9205
  Item_func_eq *eq_item= 0;
2432
9269
  return cond;
2433
9270
}
2434
9271
 
 
9272
 
2435
9273
/**
2436
9274
  Substitute every field reference in a condition by the best equal field
2437
9275
  and eliminate all multiple equality predicates.
2459
9297
  @return
2460
9298
    The transformed condition
2461
9299
*/
2462
 
COND* substitute_for_best_equal_field(COND *cond, COND_EQUAL *cond_equal, void *table_join_idx)
 
9300
 
 
9301
static COND* substitute_for_best_equal_field(COND *cond,
 
9302
                                             COND_EQUAL *cond_equal,
 
9303
                                             void *table_join_idx)
2463
9304
{
2464
9305
  Item_equal *item_equal;
2465
9306
 
2527
9368
  return cond;
2528
9369
}
2529
9370
 
 
9371
 
2530
9372
/**
2531
9373
  Check appearance of new constant items in multiple equalities
2532
9374
  of a condition after reading a constant table.
2539
9381
  @param cond       condition whose multiple equalities are to be checked
2540
9382
  @param table      constant table that has been read
2541
9383
*/
2542
 
static void update_const_equal_items(COND *cond, JoinTable *tab)
 
9384
 
 
9385
static void update_const_equal_items(COND *cond, JOIN_TAB *tab)
2543
9386
{
2544
9387
  if (!(cond->used_tables() & tab->table->map))
2545
9388
    return;
2566
9409
      while ((item_field= it++))
2567
9410
      {
2568
9411
        Field *field= item_field->field;
2569
 
        JoinTable *stat= field->table->reginfo.join_tab;
 
9412
        JOIN_TAB *stat= field->table->reginfo.join_tab;
2570
9413
        key_map possible_keys= field->key_start;
2571
 
        possible_keys&= field->table->keys_in_use_for_query;
2572
 
        stat[0].const_keys|= possible_keys;
 
9414
        possible_keys.intersect(field->table->keys_in_use_for_query);
 
9415
        stat[0].const_keys.merge(possible_keys);
2573
9416
 
2574
9417
        /*
2575
9418
          For each field in the multiple equality (for which we know that it
2576
9419
          is a constant) we have to find its corresponding key part, and set
2577
9420
          that key part in const_key_parts.
2578
9421
        */
2579
 
        if (possible_keys.any())
 
9422
        if (!possible_keys.is_clear_all())
2580
9423
        {
2581
9424
          Table *field_tab= field->table;
2582
 
          optimizer::KeyUse *use;
2583
 
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
2584
 
            if (possible_keys.test(use->getKey()) &&
2585
 
                field_tab->key_info[use->getKey()].key_part[use->getKeypart()].field ==
 
9425
          KEYUSE *use;
 
9426
          for (use= stat->keyuse; use && use->table == field_tab; use++)
 
9427
            if (possible_keys.is_set(use->key) &&
 
9428
                field_tab->key_info[use->key].key_part[use->keypart].field ==
2586
9429
                field)
2587
 
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
9430
              field_tab->const_key_parts[use->key]|= use->keypart_map;
2588
9431
        }
2589
9432
      }
2590
9433
    }
2591
9434
  }
2592
9435
}
2593
9436
 
 
9437
 
2594
9438
/*
2595
9439
  change field = field to field = const for each found field = const in the
2596
9440
  and_level
2597
9441
*/
2598
 
static void change_cond_ref_to_const(Session *session,
2599
 
                                     vector<COND_CMP>& save_list,
2600
 
                                     Item *and_father,
2601
 
                                     Item *cond,
2602
 
                                     Item *field,
2603
 
                                     Item *value)
 
9442
 
 
9443
static void
 
9444
change_cond_ref_to_const(Session *session, I_List<COND_CMP> *save_list,
 
9445
                         Item *and_father, Item *cond,
 
9446
                         Item *field, Item *value)
2604
9447
{
2605
9448
  if (cond->type() == Item::COND_ITEM)
2606
9449
  {
2607
 
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
 
9450
    bool and_level= ((Item_cond*) cond)->functype() ==
 
9451
      Item_func::COND_AND_FUNC;
2608
9452
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
2609
9453
    Item *item;
2610
9454
    while ((item=li++))
2611
 
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
 
9455
      change_cond_ref_to_const(session, save_list,and_level ? cond : item, item,
 
9456
                               field, value);
2612
9457
    return;
2613
9458
  }
2614
9459
  if (cond->eq_cmp_result() == Item::COND_OK)
2633
9478
    {
2634
9479
      session->change_item_tree(args + 1, tmp);
2635
9480
      func->update_used_tables();
2636
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2637
 
                and_father != cond && 
2638
 
          ! left_item->const_item())
 
9481
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
 
9482
          && and_father != cond && !left_item->const_item())
2639
9483
      {
2640
 
        cond->marker=1;
2641
 
        save_list.push_back( COND_CMP(and_father, func) );
 
9484
        cond->marker=1;
 
9485
        COND_CMP *tmp2;
 
9486
        if ((tmp2=new COND_CMP(and_father,func)))
 
9487
          save_list->push_back(tmp2);
2642
9488
      }
2643
9489
      func->set_cmp_func();
2644
9490
    }
2657
9503
      session->change_item_tree(args, tmp);
2658
9504
      value= tmp;
2659
9505
      func->update_used_tables();
2660
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2661
 
          and_father != cond && 
2662
 
          ! right_item->const_item())
 
9506
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
 
9507
          && and_father != cond && !right_item->const_item())
2663
9508
      {
2664
9509
        args[0]= args[1];                       // For easy check
2665
9510
        session->change_item_tree(args + 1, value);
2666
 
        cond->marker=1;
2667
 
        save_list.push_back( COND_CMP(and_father, func) );
 
9511
        cond->marker=1;
 
9512
        COND_CMP *tmp2;
 
9513
        if ((tmp2=new COND_CMP(and_father,func)))
 
9514
          save_list->push_back(tmp2);
2668
9515
      }
2669
9516
      func->set_cmp_func();
2670
9517
    }
2679
9526
  @return
2680
9527
    new conditions
2681
9528
*/
2682
 
Item *remove_additional_cond(Item* conds)
 
9529
 
 
9530
static Item *remove_additional_cond(Item* conds)
2683
9531
{
2684
9532
  if (conds->name == in_additional_cond)
2685
9533
    return 0;
2702
9550
  return conds;
2703
9551
}
2704
9552
 
2705
 
static void propagate_cond_constants(Session *session, 
2706
 
                                     vector<COND_CMP>& save_list, 
2707
 
                                     COND *and_father, 
2708
 
                                     COND *cond)
 
9553
static void
 
9554
propagate_cond_constants(Session *session, I_List<COND_CMP> *save_list,
 
9555
                         COND *and_father, COND *cond)
2709
9556
{
2710
9557
  if (cond->type() == Item::COND_ITEM)
2711
9558
  {
2712
 
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
 
9559
    bool and_level= ((Item_cond*) cond)->functype() ==
 
9560
      Item_func::COND_AND_FUNC;
2713
9561
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
2714
9562
    Item *item;
2715
 
    vector<COND_CMP> save;
 
9563
    I_List<COND_CMP> save;
2716
9564
    while ((item=li++))
2717
9565
    {
2718
 
      propagate_cond_constants(session, save, and_level ? cond : item, item);
 
9566
      propagate_cond_constants(session, &save,and_level ? cond : item, item);
2719
9567
    }
2720
9568
    if (and_level)
2721
 
    {
2722
 
      // Handle other found items
2723
 
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
 
9569
    {                                           // Handle other found items
 
9570
      I_List_iterator<COND_CMP> cond_itr(save);
 
9571
      COND_CMP *cond_cmp;
 
9572
      while ((cond_cmp=cond_itr++))
2724
9573
      {
2725
 
        Item **args= iter->cmp_func->arguments();
 
9574
        Item **args= cond_cmp->cmp_func->arguments();
2726
9575
        if (!args[0]->const_item())
2727
 
        {
2728
 
          change_cond_ref_to_const( session, save, iter->and_level,
2729
 
                                    iter->and_level, args[0], args[1] );
2730
 
        }
 
9576
          change_cond_ref_to_const(session, &save,cond_cmp->and_level,
 
9577
                                   cond_cmp->and_level, args[0], args[1]);
2731
9578
      }
2732
9579
    }
2733
9580
  }
2734
9581
  else if (and_father != cond && !cond->marker)         // In a AND group
2735
9582
  {
2736
9583
    if (cond->type() == Item::FUNC_ITEM &&
2737
 
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
2738
 
        ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
 
9584
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
 
9585
         ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
2739
9586
    {
2740
9587
      Item_func_eq *func=(Item_func_eq*) cond;
2741
9588
      Item **args= func->arguments();
2744
9591
      if (!(left_const && right_const) &&
2745
9592
          args[0]->result_type() == args[1]->result_type())
2746
9593
      {
2747
 
        if (right_const)
2748
 
        {
2749
 
                resolve_const_item(session, &args[1], args[0]);
2750
 
          func->update_used_tables();
2751
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2752
 
                                        args[0], args[1]);
2753
 
        }
2754
 
        else if (left_const)
2755
 
        {
2756
 
                resolve_const_item(session, &args[0], args[1]);
2757
 
          func->update_used_tables();
2758
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2759
 
                                        args[1], args[0]);
2760
 
        }
2761
 
      }
2762
 
    }
2763
 
  }
2764
 
}
 
9594
        if (right_const)
 
9595
        {
 
9596
          resolve_const_item(session, &args[1], args[0]);
 
9597
          func->update_used_tables();
 
9598
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
9599
                                   args[0], args[1]);
 
9600
        }
 
9601
        else if (left_const)
 
9602
        {
 
9603
          resolve_const_item(session, &args[0], args[1]);
 
9604
          func->update_used_tables();
 
9605
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
9606
                                   args[1], args[0]);
 
9607
        }
 
9608
      }
 
9609
    }
 
9610
  }
 
9611
}
 
9612
 
 
9613
 
 
9614
/**
 
9615
  Simplify joins replacing outer joins by inner joins whenever it's
 
9616
  possible.
 
9617
 
 
9618
    The function, during a retrieval of join_list,  eliminates those
 
9619
    outer joins that can be converted into inner join, possibly nested.
 
9620
    It also moves the on expressions for the converted outer joins
 
9621
    and from inner joins to conds.
 
9622
    The function also calculates some attributes for nested joins:
 
9623
    - used_tables
 
9624
    - not_null_tables
 
9625
    - dep_tables.
 
9626
    - on_expr_dep_tables
 
9627
    The first two attributes are used to test whether an outer join can
 
9628
    be substituted for an inner join. The third attribute represents the
 
9629
    relation 'to be dependent on' for tables. If table t2 is dependent
 
9630
    on table t1, then in any evaluated execution plan table access to
 
9631
    table t2 must precede access to table t2. This relation is used also
 
9632
    to check whether the query contains  invalid cross-references.
 
9633
    The forth attribute is an auxiliary one and is used to calculate
 
9634
    dep_tables.
 
9635
    As the attribute dep_tables qualifies possibles orders of tables in the
 
9636
    execution plan, the dependencies required by the straight join
 
9637
    modifiers are reflected in this attribute as well.
 
9638
    The function also removes all braces that can be removed from the join
 
9639
    expression without changing its meaning.
 
9640
 
 
9641
  @note
 
9642
    An outer join can be replaced by an inner join if the where condition
 
9643
    or the on expression for an embedding nested join contains a conjunctive
 
9644
    predicate rejecting null values for some attribute of the inner tables.
 
9645
 
 
9646
    E.g. in the query:
 
9647
    @code
 
9648
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
 
9649
    @endcode
 
9650
    the predicate t2.b < 5 rejects nulls.
 
9651
    The query is converted first to:
 
9652
    @code
 
9653
      SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
 
9654
    @endcode
 
9655
    then to the equivalent form:
 
9656
    @code
 
9657
      SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a
 
9658
    @endcode
 
9659
 
 
9660
 
 
9661
    Similarly the following query:
 
9662
    @code
 
9663
      SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b
 
9664
        WHERE t2.c < 5
 
9665
    @endcode
 
9666
    is converted to:
 
9667
    @code
 
9668
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b
 
9669
 
 
9670
    @endcode
 
9671
 
 
9672
    One conversion might trigger another:
 
9673
    @code
 
9674
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a
 
9675
                       LEFT JOIN t3 ON t3.b=t2.b
 
9676
        WHERE t3 IS NOT NULL =>
 
9677
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3
 
9678
        WHERE t3 IS NOT NULL AND t3.b=t2.b =>
 
9679
      SELECT * FROM t1, t2, t3
 
9680
        WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a
 
9681
  @endcode
 
9682
 
 
9683
    The function removes all unnecessary braces from the expression
 
9684
    produced by the conversions.
 
9685
    E.g.
 
9686
    @code
 
9687
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
 
9688
    @endcode
 
9689
    finally is converted to:
 
9690
    @code
 
9691
      SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
 
9692
 
 
9693
    @endcode
 
9694
 
 
9695
 
 
9696
    It also will remove braces from the following queries:
 
9697
    @code
 
9698
      SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b
 
9699
      SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b.
 
9700
    @endcode
 
9701
 
 
9702
    The benefit of this simplification procedure is that it might return
 
9703
    a query for which the optimizer can evaluate execution plan with more
 
9704
    join orders. With a left join operation the optimizer does not
 
9705
    consider any plan where one of the inner tables is before some of outer
 
9706
    tables.
 
9707
 
 
9708
  IMPLEMENTATION
 
9709
    The function is implemented by a recursive procedure.  On the recursive
 
9710
    ascent all attributes are calculated, all outer joins that can be
 
9711
    converted are replaced and then all unnecessary braces are removed.
 
9712
    As join list contains join tables in the reverse order sequential
 
9713
    elimination of outer joins does not require extra recursive calls.
 
9714
 
 
9715
  SEMI-JOIN NOTES
 
9716
    Remove all semi-joins that have are within another semi-join (i.e. have
 
9717
    an "ancestor" semi-join nest)
 
9718
 
 
9719
  EXAMPLES
 
9720
    Here is an example of a join query with invalid cross references:
 
9721
    @code
 
9722
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b
 
9723
    @endcode
 
9724
 
 
9725
  @param join        reference to the query info
 
9726
  @param join_list   list representation of the join to be converted
 
9727
  @param conds       conditions to add on expressions for converted joins
 
9728
  @param top         true <=> conds is the where condition
 
9729
 
 
9730
  @return
 
9731
    - The new condition, if success
 
9732
    - 0, otherwise
 
9733
*/
 
9734
 
 
9735
static COND *
 
9736
simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top,
 
9737
               bool in_sj)
 
9738
{
 
9739
  TableList *table;
 
9740
  nested_join_st *nested_join;
 
9741
  TableList *prev_table= 0;
 
9742
  List_iterator<TableList> li(*join_list);
 
9743
 
 
9744
  /*
 
9745
    Try to simplify join operations from join_list.
 
9746
    The most outer join operation is checked for conversion first.
 
9747
  */
 
9748
  while ((table= li++))
 
9749
  {
 
9750
    table_map used_tables;
 
9751
    table_map not_null_tables= (table_map) 0;
 
9752
 
 
9753
    if ((nested_join= table->nested_join))
 
9754
    {
 
9755
      /*
 
9756
         If the element of join_list is a nested join apply
 
9757
         the procedure to its nested join list first.
 
9758
      */
 
9759
      if (table->on_expr)
 
9760
      {
 
9761
        Item *expr= table->on_expr;
 
9762
        /*
 
9763
           If an on expression E is attached to the table,
 
9764
           check all null rejected predicates in this expression.
 
9765
           If such a predicate over an attribute belonging to
 
9766
           an inner table of an embedded outer join is found,
 
9767
           the outer join is converted to an inner join and
 
9768
           the corresponding on expression is added to E.
 
9769
        */
 
9770
        expr= simplify_joins(join, &nested_join->join_list,
 
9771
                             expr, false, in_sj || table->sj_on_expr);
 
9772
 
 
9773
        if (!table->prep_on_expr || expr != table->on_expr)
 
9774
        {
 
9775
          assert(expr);
 
9776
 
 
9777
          table->on_expr= expr;
 
9778
          table->prep_on_expr= expr->copy_andor_structure(join->session);
 
9779
        }
 
9780
      }
 
9781
      nested_join->used_tables= (table_map) 0;
 
9782
      nested_join->not_null_tables=(table_map) 0;
 
9783
      conds= simplify_joins(join, &nested_join->join_list, conds, top,
 
9784
                            in_sj || table->sj_on_expr);
 
9785
      used_tables= nested_join->used_tables;
 
9786
      not_null_tables= nested_join->not_null_tables;
 
9787
    }
 
9788
    else
 
9789
    {
 
9790
      if (!table->prep_on_expr)
 
9791
        table->prep_on_expr= table->on_expr;
 
9792
      used_tables= table->table->map;
 
9793
      if (conds)
 
9794
        not_null_tables= conds->not_null_tables();
 
9795
    }
 
9796
 
 
9797
    if (table->embedding)
 
9798
    {
 
9799
      table->embedding->nested_join->used_tables|= used_tables;
 
9800
      table->embedding->nested_join->not_null_tables|= not_null_tables;
 
9801
    }
 
9802
 
 
9803
    if (!table->outer_join || (used_tables & not_null_tables))
 
9804
    {
 
9805
      /*
 
9806
        For some of the inner tables there are conjunctive predicates
 
9807
        that reject nulls => the outer join can be replaced by an inner join.
 
9808
      */
 
9809
      table->outer_join= 0;
 
9810
      if (table->on_expr)
 
9811
      {
 
9812
        /* Add ON expression to the WHERE or upper-level ON condition. */
 
9813
        if (conds)
 
9814
        {
 
9815
          conds= and_conds(conds, table->on_expr);
 
9816
          conds->top_level_item();
 
9817
          /* conds is always a new item as both cond and on_expr existed */
 
9818
          assert(!conds->fixed);
 
9819
          conds->fix_fields(join->session, &conds);
 
9820
        }
 
9821
        else
 
9822
          conds= table->on_expr;
 
9823
        table->prep_on_expr= table->on_expr= 0;
 
9824
      }
 
9825
    }
 
9826
 
 
9827
    if (!top)
 
9828
      continue;
 
9829
 
 
9830
    /*
 
9831
      Only inner tables of non-convertible outer joins
 
9832
      remain with on_expr.
 
9833
    */
 
9834
    if (table->on_expr)
 
9835
    {
 
9836
      table->dep_tables|= table->on_expr->used_tables();
 
9837
      if (table->embedding)
 
9838
      {
 
9839
        table->dep_tables&= ~table->embedding->nested_join->used_tables;
 
9840
        /*
 
9841
           Embedding table depends on tables used
 
9842
           in embedded on expressions.
 
9843
        */
 
9844
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
 
9845
      }
 
9846
      else
 
9847
        table->dep_tables&= ~table->table->map;
 
9848
    }
 
9849
 
 
9850
    if (prev_table)
 
9851
    {
 
9852
      /* The order of tables is reverse: prev_table follows table */
 
9853
      if (prev_table->straight)
 
9854
        prev_table->dep_tables|= used_tables;
 
9855
      if (prev_table->on_expr)
 
9856
      {
 
9857
        prev_table->dep_tables|= table->on_expr_dep_tables;
 
9858
        table_map prev_used_tables= prev_table->nested_join ?
 
9859
                                    prev_table->nested_join->used_tables :
 
9860
                                    prev_table->table->map;
 
9861
        /*
 
9862
          If on expression contains only references to inner tables
 
9863
          we still make the inner tables dependent on the outer tables.
 
9864
          It would be enough to set dependency only on one outer table
 
9865
          for them. Yet this is really a rare case.
 
9866
        */
 
9867
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
 
9868
          prev_table->dep_tables|= used_tables;
 
9869
      }
 
9870
    }
 
9871
    prev_table= table;
 
9872
  }
 
9873
 
 
9874
  /*
 
9875
    Flatten nested joins that can be flattened.
 
9876
    no ON expression and not a semi-join => can be flattened.
 
9877
  */
 
9878
  li.rewind();
 
9879
  while ((table= li++))
 
9880
  {
 
9881
    nested_join= table->nested_join;
 
9882
    if (table->sj_on_expr && !in_sj)
 
9883
    {
 
9884
       /*
 
9885
         If this is a semi-join that is not contained within another semi-join,
 
9886
         leave it intact (otherwise it is flattened)
 
9887
       */
 
9888
      join->select_lex->sj_nests.push_back(table);
 
9889
    }
 
9890
    else if (nested_join && !table->on_expr)
 
9891
    {
 
9892
      TableList *tbl;
 
9893
      List_iterator<TableList> it(nested_join->join_list);
 
9894
      while ((tbl= it++))
 
9895
      {
 
9896
        tbl->embedding= table->embedding;
 
9897
        tbl->join_list= table->join_list;
 
9898
      }
 
9899
      li.replace(nested_join->join_list);
 
9900
    }
 
9901
  }
 
9902
  return(conds);
 
9903
}
 
9904
 
 
9905
 
 
9906
/**
 
9907
  Assign each nested join structure a bit in nested_join_map.
 
9908
 
 
9909
    Assign each nested join structure (except "confluent" ones - those that
 
9910
    embed only one element) a bit in nested_join_map.
 
9911
 
 
9912
  @param join          Join being processed
 
9913
  @param join_list     List of tables
 
9914
  @param first_unused  Number of first unused bit in nested_join_map before the
 
9915
                       call
 
9916
 
 
9917
  @note
 
9918
    This function is called after simplify_joins(), when there are no
 
9919
    redundant nested joins, #non_confluent_nested_joins <= #tables_in_join so
 
9920
    we will not run out of bits in nested_join_map.
 
9921
 
 
9922
  @return
 
9923
    First unused bit in nested_join_map after the call.
 
9924
*/
 
9925
 
 
9926
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
 
9927
                                          uint32_t first_unused)
 
9928
{
 
9929
  List_iterator<TableList> li(*join_list);
 
9930
  TableList *table;
 
9931
  while ((table= li++))
 
9932
  {
 
9933
    nested_join_st *nested_join;
 
9934
    if ((nested_join= table->nested_join))
 
9935
    {
 
9936
      /*
 
9937
        It is guaranteed by simplify_joins() function that a nested join
 
9938
        that has only one child is either
 
9939
         - a single-table view (the child is the underlying table), or
 
9940
         - a single-table semi-join nest
 
9941
 
 
9942
        We don't assign bits to such sj-nests because
 
9943
        1. it is redundant (a "sequence" of one table cannot be interleaved
 
9944
            with anything)
 
9945
        2. we could run out bits in nested_join_map otherwise.
 
9946
      */
 
9947
      if (nested_join->join_list.elements != 1)
 
9948
      {
 
9949
        /* Don't assign bits to sj-nests */
 
9950
        if (table->on_expr)
 
9951
          nested_join->nj_map= (nested_join_map) 1 << first_unused++;
 
9952
        first_unused= build_bitmap_for_nested_joins(&nested_join->join_list,
 
9953
                                                    first_unused);
 
9954
      }
 
9955
    }
 
9956
  }
 
9957
  return(first_unused);
 
9958
}
 
9959
 
 
9960
 
 
9961
/**
 
9962
  Set nested_join_st::counter=0 in all nested joins in passed list.
 
9963
 
 
9964
    Recursively set nested_join_st::counter=0 for all nested joins contained in
 
9965
    the passed join_list.
 
9966
 
 
9967
  @param join_list  List of nested joins to process. It may also contain base
 
9968
                    tables which will be ignored.
 
9969
*/
 
9970
 
 
9971
static void reset_nj_counters(List<TableList> *join_list)
 
9972
{
 
9973
  List_iterator<TableList> li(*join_list);
 
9974
  TableList *table;
 
9975
  while ((table= li++))
 
9976
  {
 
9977
    nested_join_st *nested_join;
 
9978
    if ((nested_join= table->nested_join))
 
9979
    {
 
9980
      nested_join->counter_= 0;
 
9981
      reset_nj_counters(&nested_join->join_list);
 
9982
    }
 
9983
  }
 
9984
  return;
 
9985
}
 
9986
 
2765
9987
 
2766
9988
/**
2767
9989
  Check interleaving with an inner tables of an outer join for
2855
10077
  @retval
2856
10078
    true   Requested join order extension not allowed.
2857
10079
*/
2858
 
bool check_interleaving_with_nj(JoinTable *last_tab, JoinTable *next_tab)
 
10080
 
 
10081
static bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
2859
10082
{
2860
10083
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
2861
10084
  JOIN *join= last_tab->join;
2862
10085
 
2863
 
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
 
10086
  if (join->cur_embedding_map & ~next_tab->embedding_map)
2864
10087
  {
2865
10088
    /*
2866
10089
      next_tab is outside of the "pair of brackets" we're currently in.
2899
10122
  return false;
2900
10123
}
2901
10124
 
2902
 
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
 
10125
 
 
10126
/**
 
10127
  Nested joins perspective: Remove the last table from the join order.
 
10128
 
 
10129
    Remove the last table from the partial join order and update the nested
 
10130
    joins counters and join->cur_embedding_map. It is ok to call this
 
10131
    function for the first table in join order (for which
 
10132
    check_interleaving_with_nj has not been called)
 
10133
 
 
10134
  @param last  join table to remove, it is assumed to be the last in current
 
10135
               partial join order.
 
10136
*/
 
10137
 
 
10138
static void restore_prev_nj_state(JOIN_TAB *last)
 
10139
{
 
10140
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
10141
  JOIN *join= last->join;
 
10142
  while (last_emb)
 
10143
  {
 
10144
    if (last_emb->on_expr)
 
10145
    {
 
10146
      if (!(--last_emb->nested_join->counter_))
 
10147
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
 
10148
      else if (last_emb->nested_join->join_list.elements-1 ==
 
10149
               last_emb->nested_join->counter_)
 
10150
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
 
10151
      else
 
10152
        break;
 
10153
    }
 
10154
    last_emb= last_emb->embedding;
 
10155
  }
 
10156
}
 
10157
 
 
10158
 
 
10159
 
 
10160
static
 
10161
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
 
10162
{
 
10163
  TableList *emb_sj_nest;
 
10164
  if ((emb_sj_nest= tab->emb_sj_nest))
 
10165
  {
 
10166
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
 
10167
    /* Remove the sj_nest if all of its SJ-inner tables are in cur_table_map */
 
10168
    if (!(remaining_tables & emb_sj_nest->sj_inner_tables))
 
10169
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
10170
  }
 
10171
}
 
10172
 
 
10173
 
 
10174
/*
 
10175
  we assume remaining_tables doesnt contain @tab.
 
10176
*/
 
10177
 
 
10178
static void restore_prev_sj_state(const table_map remaining_tables,
 
10179
                                  const JOIN_TAB *tab)
 
10180
{
 
10181
  TableList *emb_sj_nest;
 
10182
  if ((emb_sj_nest= tab->emb_sj_nest))
 
10183
  {
 
10184
    /* If we're removing the last SJ-inner table, remove the sj-nest */
 
10185
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) ==
 
10186
        (emb_sj_nest->sj_inner_tables & ~tab->table->map))
 
10187
    {
 
10188
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
10189
    }
 
10190
  }
 
10191
}
 
10192
 
 
10193
 
 
10194
static COND *
 
10195
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
 
10196
              Item::cond_result *cond_value)
2903
10197
{
2904
10198
  Session *session= join->session;
2905
10199
 
2919
10213
                             &join->cond_equal);
2920
10214
 
2921
10215
    /* change field = field to field = const for each found field = const */
2922
 
    vector<COND_CMP> temp;
2923
 
    propagate_cond_constants(session, temp, conds, conds);
 
10216
    propagate_cond_constants(session, (I_List<COND_CMP> *) 0, conds, conds);
2924
10217
    /*
2925
10218
      Remove all instances of item == item
2926
10219
      Remove all and-levels where CONST item != CONST item
2930
10223
  return(conds);
2931
10224
}
2932
10225
 
 
10226
 
2933
10227
/**
2934
10228
  Remove const and eq items.
2935
10229
 
2940
10234
    - COND_TRUE   : always true ( 1 = 1 )
2941
10235
    - COND_FALSE  : always false        ( 1 = 2 )
2942
10236
*/
2943
 
COND *remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
 
10237
 
 
10238
COND *
 
10239
remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
2944
10240
{
2945
10241
  if (cond->type() == Item::COND_ITEM)
2946
10242
  {
2986
10282
          }
2987
10283
          break;
2988
10284
        case Item::COND_UNDEF:                  /* Impossible */
2989
 
          break;
 
10285
          break; /* purecov: deadcode */
2990
10286
      }
2991
10287
    }
2992
10288
 
3129
10425
    true    can be used
3130
10426
    false   cannot be used
3131
10427
*/
3132
 
static bool test_if_equality_guarantees_uniqueness(Item *l, Item *r)
 
10428
static bool
 
10429
test_if_equality_guarantees_uniqueness(Item *l, Item *r)
3133
10430
{
3134
10431
  return r->const_item() &&
3135
10432
    /* elements must be compared as dates */
3144
10441
/**
3145
10442
  Return true if the item is a const value in all the WHERE clause.
3146
10443
*/
3147
 
bool const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
 
10444
 
 
10445
static bool
 
10446
const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
3148
10447
{
3149
10448
  if (cond->type() == Item::COND_ITEM)
3150
10449
  {
3157
10456
      bool res=const_expression_in_where(item, comp_item, const_item);
3158
10457
      if (res)                                  // Is a const value
3159
10458
      {
3160
 
        if (and_level)
3161
 
          return 1;
 
10459
        if (and_level)
 
10460
          return 1;
3162
10461
      }
3163
10462
      else if (!and_level)
3164
 
        return 0;
 
10463
        return 0;
3165
10464
    }
3166
10465
    return and_level ? 0 : 1;
3167
10466
  }
3169
10468
  {                                             // boolan compare function
3170
10469
    Item_func* func= (Item_func*) cond;
3171
10470
    if (func->functype() != Item_func::EQUAL_FUNC &&
3172
 
              func->functype() != Item_func::EQ_FUNC)
 
10471
        func->functype() != Item_func::EQ_FUNC)
3173
10472
      return 0;
3174
10473
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
3175
10474
    Item *right_item= ((Item_func*) cond)->arguments()[1];
3177
10476
    {
3178
10477
      if (test_if_equality_guarantees_uniqueness (left_item, right_item))
3179
10478
      {
3180
 
        if (*const_item)
3181
 
          return right_item->eq(*const_item, 1);
3182
 
        *const_item=right_item;
3183
 
        return 1;
 
10479
        if (*const_item)
 
10480
          return right_item->eq(*const_item, 1);
 
10481
        *const_item=right_item;
 
10482
        return 1;
3184
10483
      }
3185
10484
    }
3186
10485
    else if (right_item->eq(comp_item,1))
3187
10486
    {
3188
10487
      if (test_if_equality_guarantees_uniqueness (right_item, left_item))
3189
10488
      {
3190
 
        if (*const_item)
3191
 
          return left_item->eq(*const_item, 1);
3192
 
        *const_item=left_item;
3193
 
        return 1;
 
10489
        if (*const_item)
 
10490
          return left_item->eq(*const_item, 1);
 
10491
        *const_item=left_item;
 
10492
        return 1;
3194
10493
      }
3195
10494
    }
3196
10495
  }
3197
10496
  return 0;
3198
10497
}
3199
10498
 
 
10499
 
3200
10500
/**
3201
10501
  @details
3202
10502
  Rows produced by a join sweep may end up in a temporary table or be sent
3208
10508
  @return
3209
10509
    end_select function to use. This function can't fail.
3210
10510
*/
 
10511
 
3211
10512
Next_select_func setup_end_select_func(JOIN *join)
3212
10513
{
3213
10514
  Table *table= join->tmp_table;
3222
10523
    {
3223
10524
      if (table->s->keys)
3224
10525
      {
3225
 
        end_select= end_update;
 
10526
        end_select=end_update;
3226
10527
      }
3227
10528
      else
3228
10529
      {
3229
 
        end_select= end_unique_update;
 
10530
        end_select=end_unique_update;
3230
10531
      }
3231
10532
    }
3232
10533
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
3263
10564
  return end_select;
3264
10565
}
3265
10566
 
 
10567
 
3266
10568
/**
3267
10569
  Make a join of all tables and write it on socket or to table.
3268
10570
 
3273
10575
  @retval
3274
10576
    -1  if error should be sent
3275
10577
*/
3276
 
int do_select(JOIN *join, List<Item> *fields, Table *table)
 
10578
 
 
10579
static int
 
10580
do_select(JOIN *join,List<Item> *fields,Table *table)
3277
10581
{
3278
10582
  int rc= 0;
3279
10583
  enum_nested_loop_state error= NESTED_LOOP_OK;
3280
 
  JoinTable *join_tab= NULL;
 
10584
  JOIN_TAB *join_tab= NULL;
3281
10585
 
3282
10586
  join->tmp_table= table;                       /* Save for easy recursion */
3283
10587
  join->fields= fields;
3284
10588
 
3285
10589
  if (table)
3286
10590
  {
3287
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
3288
 
    table->emptyRecord();
 
10591
    table->file->extra(HA_EXTRA_WRITE_CACHE);
 
10592
    empty_record(table);
3289
10593
    if (table->group && join->tmp_table_param.sum_func_count &&
3290
 
        table->s->keys && !table->cursor->inited)
3291
 
      table->cursor->ha_index_init(0, 0);
 
10594
        table->s->keys && !table->file->inited)
 
10595
      table->file->ha_index_init(0, 0);
3292
10596
  }
3293
10597
  /* Set up select_end */
3294
10598
  Next_select_func end_select= setup_end_select_func(join);
3309
10613
    {
3310
10614
      error= (*end_select)(join, 0, 0);
3311
10615
      if (error == NESTED_LOOP_OK || error == NESTED_LOOP_QUERY_LIMIT)
3312
 
              error= (*end_select)(join, 0, 1);
 
10616
        error= (*end_select)(join, 0, 1);
3313
10617
 
3314
10618
      /*
3315
10619
        If we don't go through evaluate_join_record(), do the counting
3347
10651
    if (!table)                                 // If sending data to client
3348
10652
    {
3349
10653
      /*
3350
 
        The following will unlock all cursors if the command wasn't an
3351
 
        update command
 
10654
        The following will unlock all cursors if the command wasn't an
 
10655
        update command
3352
10656
      */
3353
10657
      join->join_free();                        // Unlock all cursors
3354
10658
      if (join->result->send_eof())
3355
 
        rc= 1;                                  // Don't send error
 
10659
        rc= 1;                                  // Don't send error
3356
10660
    }
3357
10661
  }
3358
10662
  else
3360
10664
  if (table)
3361
10665
  {
3362
10666
    int tmp, new_errno= 0;
3363
 
    if ((tmp=table->cursor->extra(HA_EXTRA_NO_CACHE)))
 
10667
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
3364
10668
    {
3365
10669
      new_errno= tmp;
3366
10670
    }
3367
 
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
 
10671
    if ((tmp=table->file->ha_index_or_rnd_end()))
3368
10672
    {
3369
10673
      new_errno= tmp;
3370
10674
    }
3371
10675
    if (new_errno)
3372
 
      table->print_error(new_errno,MYF(0));
 
10676
      table->file->print_error(new_errno,MYF(0));
3373
10677
  }
3374
10678
  return(join->session->is_error() ? -1 : rc);
3375
10679
}
3376
10680
 
3377
 
enum_nested_loop_state sub_select_cache(JOIN *join, JoinTable *join_tab, bool end_of_records)
 
10681
 
 
10682
enum_nested_loop_state
 
10683
sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
3378
10684
{
3379
10685
  enum_nested_loop_state rc;
3380
10686
 
3388
10694
  if (join->session->killed)            // If aborted by user
3389
10695
  {
3390
10696
    join->session->send_kill_message();
3391
 
    return NESTED_LOOP_KILLED;
 
10697
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
3392
10698
  }
3393
10699
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3394
10700
  {
3395
 
    if (! store_record_in_cache(&join_tab->cache))
 
10701
    if (!store_record_in_cache(&join_tab->cache))
3396
10702
      return NESTED_LOOP_OK;                     // There is more room in cache
3397
10703
    return flush_cached_records(join,join_tab,false);
3398
10704
  }
3521
10827
  @return
3522
10828
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
3523
10829
*/
3524
 
enum_nested_loop_state sub_select(JOIN *join, JoinTable *join_tab, bool end_of_records)
 
10830
int do_sj_reset(SJ_TMP_TABLE *sj_tbl);
 
10831
 
 
10832
enum_nested_loop_state
 
10833
sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
3525
10834
{
3526
10835
  join_tab->table->null_row=0;
3527
10836
  if (end_of_records)
3531
10840
  enum_nested_loop_state rc;
3532
10841
  READ_RECORD *info= &join_tab->read_record;
3533
10842
 
 
10843
  if (join_tab->flush_weedout_table)
 
10844
  {
 
10845
    do_sj_reset(join_tab->flush_weedout_table);
 
10846
  }
 
10847
 
3534
10848
  if (join->resume_nested_loop)
3535
10849
  {
3536
10850
    /* If not the last table, plunge down the nested loop */
3582
10896
  return rc;
3583
10897
}
3584
10898
 
3585
 
int safe_index_read(JoinTable *tab)
 
10899
 
 
10900
 
 
10901
 
 
10902
/*
 
10903
  SemiJoinDuplicateElimination: Weed out duplicate row combinations
 
10904
 
 
10905
  SYNPOSIS
 
10906
    do_sj_dups_weedout()
 
10907
 
 
10908
  RETURN
 
10909
    -1  Error
 
10910
    1   The row combination is a duplicate (discard it)
 
10911
    0   The row combination is not a duplicate (continue)
 
10912
*/
 
10913
 
 
10914
int do_sj_dups_weedout(Session *session, SJ_TMP_TABLE *sjtbl)
 
10915
{
 
10916
  int error;
 
10917
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
 
10918
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
 
10919
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
 
10920
  unsigned char *nulls_ptr= ptr;
 
10921
 
 
10922
  /* Put the the rowids tuple into table->record[0]: */
 
10923
 
 
10924
  // 1. Store the length
 
10925
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
 
10926
  {
 
10927
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
 
10928
    ptr++;
 
10929
  }
 
10930
  else
 
10931
  {
 
10932
    int2store(ptr, sjtbl->rowid_len + sjtbl->null_bytes);
 
10933
    ptr += 2;
 
10934
  }
 
10935
 
 
10936
  // 2. Zero the null bytes
 
10937
  if (sjtbl->null_bytes)
 
10938
  {
 
10939
    memset(ptr, 0, sjtbl->null_bytes);
 
10940
    ptr += sjtbl->null_bytes;
 
10941
  }
 
10942
 
 
10943
  // 3. Put the rowids
 
10944
  for (uint32_t i=0; tab != tab_end; tab++, i++)
 
10945
  {
 
10946
    handler *h= tab->join_tab->table->file;
 
10947
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
 
10948
    {
 
10949
      /* It's a NULL-complemented row */
 
10950
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
 
10951
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
 
10952
    }
 
10953
    else
 
10954
    {
 
10955
      /* Copy the rowid value */
 
10956
      if (tab->join_tab->rowid_keep_flags & JOIN_TAB::CALL_POSITION)
 
10957
        h->position(tab->join_tab->table->record[0]);
 
10958
      memcpy(ptr + tab->rowid_offset, h->ref, h->ref_length);
 
10959
    }
 
10960
  }
 
10961
 
 
10962
  error= sjtbl->tmp_table->file->ha_write_row(sjtbl->tmp_table->record[0]);
 
10963
  if (error)
 
10964
  {
 
10965
    /* create_myisam_from_heap will generate error if needed */
 
10966
    if (sjtbl->tmp_table->file->is_fatal_error(error, HA_CHECK_DUP) &&
 
10967
        create_myisam_from_heap(session, sjtbl->tmp_table, sjtbl->start_recinfo,
 
10968
                                &sjtbl->recinfo, error, 1))
 
10969
      return -1;
 
10970
    //return (error == HA_ERR_FOUND_DUPP_KEY || error== HA_ERR_FOUND_DUPP_UNIQUE) ? 1: -1;
 
10971
    return 1;
 
10972
  }
 
10973
  return 0;
 
10974
}
 
10975
 
 
10976
 
 
10977
/*
 
10978
  SemiJoinDuplicateElimination: Reset the temporary table
 
10979
*/
 
10980
 
 
10981
int do_sj_reset(SJ_TMP_TABLE *sj_tbl)
 
10982
{
 
10983
  if (sj_tbl->tmp_table)
 
10984
    return sj_tbl->tmp_table->file->ha_delete_all_rows();
 
10985
  return 0;
 
10986
}
 
10987
 
 
10988
/*
 
10989
  Process one record of the nested loop join.
 
10990
 
 
10991
    This function will evaluate parts of WHERE/ON clauses that are
 
10992
    applicable to the partial record on hand and in case of success
 
10993
    submit this record to the next level of the nested loop.
 
10994
*/
 
10995
 
 
10996
static enum_nested_loop_state
 
10997
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
 
10998
                     int error)
 
10999
{
 
11000
  bool not_used_in_distinct=join_tab->not_used_in_distinct;
 
11001
  ha_rows found_records=join->found_records;
 
11002
  COND *select_cond= join_tab->select_cond;
 
11003
 
 
11004
  if (error > 0 || (join->session->is_error()))     // Fatal error
 
11005
    return NESTED_LOOP_ERROR;
 
11006
  if (error < 0)
 
11007
    return NESTED_LOOP_NO_MORE_ROWS;
 
11008
  if (join->session->killed)                    // Aborted by user
 
11009
  {
 
11010
    join->session->send_kill_message();
 
11011
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
 
11012
  }
 
11013
  if (!select_cond || select_cond->val_int())
 
11014
  {
 
11015
    /*
 
11016
      There is no select condition or the attached pushed down
 
11017
      condition is true => a match is found.
 
11018
    */
 
11019
    bool found= 1;
 
11020
    while (join_tab->first_unmatched && found)
 
11021
    {
 
11022
      /*
 
11023
        The while condition is always false if join_tab is not
 
11024
        the last inner join table of an outer join operation.
 
11025
      */
 
11026
      JOIN_TAB *first_unmatched= join_tab->first_unmatched;
 
11027
      /*
 
11028
        Mark that a match for current outer table is found.
 
11029
        This activates push down conditional predicates attached
 
11030
        to the all inner tables of the outer join.
 
11031
      */
 
11032
      first_unmatched->found= 1;
 
11033
      for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
 
11034
      {
 
11035
        if (tab->table->reginfo.not_exists_optimize)
 
11036
          return NESTED_LOOP_NO_MORE_ROWS;
 
11037
        /* Check all predicates that has just been activated. */
 
11038
        /*
 
11039
          Actually all predicates non-guarded by first_unmatched->found
 
11040
          will be re-evaluated again. It could be fixed, but, probably,
 
11041
          it's not worth doing now.
 
11042
        */
 
11043
        if (tab->select_cond && !tab->select_cond->val_int())
 
11044
        {
 
11045
          /* The condition attached to table tab is false */
 
11046
          if (tab == join_tab)
 
11047
            found= 0;
 
11048
          else
 
11049
          {
 
11050
            /*
 
11051
              Set a return point if rejected predicate is attached
 
11052
              not to the last table of the current nest level.
 
11053
            */
 
11054
            join->return_tab= tab;
 
11055
            return NESTED_LOOP_OK;
 
11056
          }
 
11057
        }
 
11058
      }
 
11059
      /*
 
11060
        Check whether join_tab is not the last inner table
 
11061
        for another embedding outer join.
 
11062
      */
 
11063
      if ((first_unmatched= first_unmatched->first_upper) &&
 
11064
          first_unmatched->last_inner != join_tab)
 
11065
        first_unmatched= 0;
 
11066
      join_tab->first_unmatched= first_unmatched;
 
11067
    }
 
11068
 
 
11069
    JOIN_TAB *return_tab= join->return_tab;
 
11070
    join_tab->found_match= true;
 
11071
    if (join_tab->check_weed_out_table)
 
11072
    {
 
11073
      int res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table);
 
11074
      if (res == -1)
 
11075
        return NESTED_LOOP_ERROR;
 
11076
      if (res == 1)
 
11077
        return NESTED_LOOP_OK;
 
11078
    }
 
11079
    else if (join_tab->do_firstmatch)
 
11080
    {
 
11081
      /*
 
11082
        We should return to the join_tab->do_firstmatch after we have
 
11083
        enumerated all the suffixes for current prefix row combination
 
11084
      */
 
11085
      return_tab= join_tab->do_firstmatch;
 
11086
    }
 
11087
 
 
11088
    /*
 
11089
      It was not just a return to lower loop level when one
 
11090
      of the newly activated predicates is evaluated as false
 
11091
      (See above join->return_tab= tab).
 
11092
    */
 
11093
    join->examined_rows++;
 
11094
    join->session->row_count++;
 
11095
 
 
11096
    if (found)
 
11097
    {
 
11098
      enum enum_nested_loop_state rc;
 
11099
      /* A match from join_tab is found for the current partial join. */
 
11100
      rc= (*join_tab->next_select)(join, join_tab+1, 0);
 
11101
      if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
11102
        return rc;
 
11103
      if (return_tab < join->return_tab)
 
11104
        join->return_tab= return_tab;
 
11105
 
 
11106
      if (join->return_tab < join_tab)
 
11107
        return NESTED_LOOP_OK;
 
11108
      /*
 
11109
        Test if this was a SELECT DISTINCT query on a table that
 
11110
        was not in the field list;  In this case we can abort if
 
11111
        we found a row, as no new rows can be added to the result.
 
11112
      */
 
11113
      if (not_used_in_distinct && found_records != join->found_records)
 
11114
        return NESTED_LOOP_NO_MORE_ROWS;
 
11115
    }
 
11116
    else
 
11117
      join_tab->read_record.file->unlock_row();
 
11118
  }
 
11119
  else
 
11120
  {
 
11121
    /*
 
11122
      The condition pushed down to the table join_tab rejects all rows
 
11123
      with the beginning coinciding with the current partial join.
 
11124
    */
 
11125
    join->examined_rows++;
 
11126
    join->session->row_count++;
 
11127
    join_tab->read_record.file->unlock_row();
 
11128
  }
 
11129
  return NESTED_LOOP_OK;
 
11130
}
 
11131
 
 
11132
 
 
11133
/**
 
11134
 
 
11135
  @details
 
11136
    Construct a NULL complimented partial join record and feed it to the next
 
11137
    level of the nested loop. This function is used in case we have
 
11138
    an OUTER join and no matching record was found.
 
11139
*/
 
11140
 
 
11141
static enum_nested_loop_state
 
11142
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab)
 
11143
{
 
11144
  /*
 
11145
    The table join_tab is the first inner table of a outer join operation
 
11146
    and no matches has been found for the current outer row.
 
11147
  */
 
11148
  JOIN_TAB *last_inner_tab= join_tab->last_inner;
 
11149
  /* Cache variables for faster loop */
 
11150
  COND *select_cond;
 
11151
  for ( ; join_tab <= last_inner_tab ; join_tab++)
 
11152
  {
 
11153
    /* Change the the values of guard predicate variables. */
 
11154
    join_tab->found= 1;
 
11155
    join_tab->not_null_compl= 0;
 
11156
    /* The outer row is complemented by nulls for each inner tables */
 
11157
    restore_record(join_tab->table,s->default_values);  // Make empty record
 
11158
    join_tab->table->mark_as_null_row();       // For group by without error
 
11159
    select_cond= join_tab->select_cond;
 
11160
    /* Check all attached conditions for inner table rows. */
 
11161
    if (select_cond && !select_cond->val_int())
 
11162
      return NESTED_LOOP_OK;
 
11163
  }
 
11164
  join_tab--;
 
11165
  /*
 
11166
    The row complemented by nulls might be the first row
 
11167
    of embedding outer joins.
 
11168
    If so, perform the same actions as in the code
 
11169
    for the first regular outer join row above.
 
11170
  */
 
11171
  for ( ; ; )
 
11172
  {
 
11173
    JOIN_TAB *first_unmatched= join_tab->first_unmatched;
 
11174
    if ((first_unmatched= first_unmatched->first_upper) &&
 
11175
        first_unmatched->last_inner != join_tab)
 
11176
      first_unmatched= 0;
 
11177
    join_tab->first_unmatched= first_unmatched;
 
11178
    if (!first_unmatched)
 
11179
      break;
 
11180
    first_unmatched->found= 1;
 
11181
    for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
 
11182
    {
 
11183
      if (tab->select_cond && !tab->select_cond->val_int())
 
11184
      {
 
11185
        join->return_tab= tab;
 
11186
        return NESTED_LOOP_OK;
 
11187
      }
 
11188
    }
 
11189
  }
 
11190
  /*
 
11191
    The row complemented by nulls satisfies all conditions
 
11192
    attached to inner tables.
 
11193
    Send the row complemented by nulls to be joined with the
 
11194
    remaining tables.
 
11195
  */
 
11196
  return (*join_tab->next_select)(join, join_tab+1, 0);
 
11197
}
 
11198
 
 
11199
 
 
11200
static enum_nested_loop_state
 
11201
flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last)
 
11202
{
 
11203
  enum_nested_loop_state rc= NESTED_LOOP_OK;
 
11204
  int error;
 
11205
  READ_RECORD *info;
 
11206
 
 
11207
  join_tab->table->null_row= 0;
 
11208
  if (!join_tab->cache.records)
 
11209
    return NESTED_LOOP_OK;                      /* Nothing to do */
 
11210
  if (skip_last)
 
11211
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
 
11212
  if (join_tab->use_quick == 2)
 
11213
  {
 
11214
    if (join_tab->select->quick)
 
11215
    {                                   /* Used quick select last. reset it */
 
11216
      delete join_tab->select->quick;
 
11217
      join_tab->select->quick=0;
 
11218
    }
 
11219
  }
 
11220
 /* read through all records */
 
11221
  if ((error=join_init_read_record(join_tab)))
 
11222
  {
 
11223
    reset_cache_write(&join_tab->cache);
 
11224
    return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR;
 
11225
  }
 
11226
 
 
11227
  for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++)
 
11228
  {
 
11229
    tmp->status=tmp->table->status;
 
11230
    tmp->table->status=0;
 
11231
  }
 
11232
 
 
11233
  info= &join_tab->read_record;
 
11234
  do
 
11235
  {
 
11236
    if (join->session->killed)
 
11237
    {
 
11238
      join->session->send_kill_message();
 
11239
      return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */
 
11240
    }
 
11241
    SQL_SELECT *select=join_tab->select;
 
11242
    if (rc == NESTED_LOOP_OK &&
 
11243
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
 
11244
    {
 
11245
      uint32_t i;
 
11246
      reset_cache_read(&join_tab->cache);
 
11247
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
 
11248
      {
 
11249
        read_cached_record(join_tab);
 
11250
        if (!select || !select->skip_record())
 
11251
        {
 
11252
          int res= 0;
 
11253
          if (!join_tab->check_weed_out_table ||
 
11254
              !(res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table)))
 
11255
          {
 
11256
            rc= (join_tab->next_select)(join,join_tab+1,0);
 
11257
            if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
11258
            {
 
11259
              reset_cache_write(&join_tab->cache);
 
11260
              return rc;
 
11261
            }
 
11262
          }
 
11263
          if (res == -1)
 
11264
            return NESTED_LOOP_ERROR;
 
11265
        }
 
11266
      }
 
11267
    }
 
11268
  } while (!(error=info->read_record(info)));
 
11269
 
 
11270
  if (skip_last)
 
11271
    read_cached_record(join_tab);               // Restore current record
 
11272
  reset_cache_write(&join_tab->cache);
 
11273
  if (error > 0)                                // Fatal error
 
11274
    return NESTED_LOOP_ERROR;                   /* purecov: inspected */
 
11275
  for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
 
11276
    tmp2->table->status=tmp2->status;
 
11277
  return NESTED_LOOP_OK;
 
11278
}
 
11279
 
 
11280
int safe_index_read(JOIN_TAB *tab)
3586
11281
{
3587
11282
  int error;
3588
11283
  Table *table= tab->table;
3589
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
11284
  if ((error=table->file->index_read_map(table->record[0],
3590
11285
                                         tab->ref.key_buff,
3591
11286
                                         make_prev_keypart_map(tab->ref.key_parts),
3592
11287
                                         HA_READ_KEY_EXACT)))
3594
11289
  return 0;
3595
11290
}
3596
11291
 
3597
 
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
 
11292
 
 
11293
static int
 
11294
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
3598
11295
{
3599
11296
  int error;
3600
11297
  Table *table=tab->table;
3602
11299
  table->null_row=0;
3603
11300
  table->status=STATUS_NO_RECORD;
3604
11301
 
3605
 
  if (tab->type == AM_SYSTEM)
 
11302
  if (tab->type == JT_SYSTEM)
3606
11303
  {
3607
11304
    if ((error=join_read_system(tab)))
3608
11305
    {                                           // Info for DESCRIBE
3609
11306
      tab->info="const row not found";
3610
11307
      /* Mark for EXPLAIN that the row was not found */
3611
 
      pos->setFanout(0.0);
3612
 
      pos->clearRefDependMap();
3613
 
      if (! table->maybe_null || error > 0)
3614
 
        return(error);
 
11308
      pos->records_read=0.0;
 
11309
      pos->ref_depend_map= 0;
 
11310
      if (!table->maybe_null || error > 0)
 
11311
        return(error);
3615
11312
    }
3616
11313
  }
3617
11314
  else
3618
11315
  {
3619
 
    if (! table->key_read && 
3620
 
        table->covering_keys.test(tab->ref.key) && 
3621
 
        ! table->no_keyread &&
3622
 
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
 
11316
    if (!table->key_read && table->covering_keys.is_set(tab->ref.key) &&
 
11317
        !table->no_keyread &&
 
11318
        (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY)
3623
11319
    {
3624
11320
      table->key_read=1;
3625
 
      table->cursor->extra(HA_EXTRA_KEYREAD);
 
11321
      table->file->extra(HA_EXTRA_KEYREAD);
3626
11322
      tab->index= tab->ref.key;
3627
11323
    }
3628
11324
    error=join_read_const(tab);
3629
11325
    if (table->key_read)
3630
11326
    {
3631
11327
      table->key_read=0;
3632
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
11328
      table->file->extra(HA_EXTRA_NO_KEYREAD);
3633
11329
    }
3634
11330
    if (error)
3635
11331
    {
3636
11332
      tab->info="unique row not found";
3637
11333
      /* Mark for EXPLAIN that the row was not found */
3638
 
      pos->setFanout(0.0);
3639
 
      pos->clearRefDependMap();
 
11334
      pos->records_read=0.0;
 
11335
      pos->ref_depend_map= 0;
3640
11336
      if (!table->maybe_null || error > 0)
3641
 
        return(error);
 
11337
        return(error);
3642
11338
    }
3643
11339
  }
3644
11340
  if (*tab->on_expr_ref && !table->null_row)
3672
11368
  return(0);
3673
11369
}
3674
11370
 
3675
 
int join_read_system(JoinTable *tab)
 
11371
 
 
11372
static int
 
11373
join_read_system(JOIN_TAB *tab)
3676
11374
{
3677
11375
  Table *table= tab->table;
3678
11376
  int error;
3679
11377
  if (table->status & STATUS_GARBAGE)           // If first read
3680
11378
  {
3681
 
    if ((error=table->cursor->read_first_row(table->record[0],
 
11379
    if ((error=table->file->read_first_row(table->record[0],
3682
11380
                                           table->s->primary_key)))
3683
11381
    {
3684
11382
      if (error != HA_ERR_END_OF_FILE)
3685
 
        return table->report_error(error);
 
11383
        return table->report_error(error);
3686
11384
      tab->table->mark_as_null_row();
3687
 
      table->emptyRecord();                     // Make empty record
 
11385
      empty_record(table);                      // Make empty record
3688
11386
      return -1;
3689
11387
    }
3690
 
    table->storeRecord();
 
11388
    update_virtual_fields_marked_for_write(table);
 
11389
    store_record(table,record[1]);
3691
11390
  }
3692
11391
  else if (!table->status)                      // Only happens with left join
3693
 
    table->restoreRecord();                     // restore old record
 
11392
    restore_record(table,record[1]);                    // restore old record
3694
11393
  table->null_row=0;
3695
11394
  return table->status ? -1 : 0;
3696
11395
}
3697
11396
 
 
11397
 
3698
11398
/**
3699
11399
  Read a (constant) table when there is at most one matching row.
3700
11400
 
3707
11407
  @retval
3708
11408
    1   Got an error (other than row not found) during read
3709
11409
*/
3710
 
int join_read_const(JoinTable *tab)
 
11410
 
 
11411
static int
 
11412
join_read_const(JOIN_TAB *tab)
3711
11413
{
3712
11414
  int error;
3713
11415
  Table *table= tab->table;
3715
11417
  {
3716
11418
    table->status= 0;
3717
11419
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3718
 
      error= HA_ERR_KEY_NOT_FOUND;
 
11420
      error=HA_ERR_KEY_NOT_FOUND;
3719
11421
    else
3720
11422
    {
3721
 
      error=table->cursor->index_read_idx_map(table->record[0],tab->ref.key,
 
11423
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
3722
11424
                                            (unsigned char*) tab->ref.key_buff,
3723
11425
                                            make_prev_keypart_map(tab->ref.key_parts),
3724
11426
                                            HA_READ_KEY_EXACT);
3727
11429
    {
3728
11430
      table->status= STATUS_NOT_FOUND;
3729
11431
      tab->table->mark_as_null_row();
3730
 
      table->emptyRecord();
 
11432
      empty_record(table);
3731
11433
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3732
 
        return table->report_error(error);
 
11434
        return table->report_error(error);
3733
11435
      return -1;
3734
11436
    }
3735
 
    table->storeRecord();
 
11437
    update_virtual_fields_marked_for_write(table);
 
11438
    store_record(table,record[1]);
3736
11439
  }
3737
11440
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
3738
11441
  {
3739
11442
    table->status=0;
3740
 
    table->restoreRecord();                     // restore old record
 
11443
    restore_record(table,record[1]);                    // restore old record
3741
11444
  }
3742
11445
  table->null_row=0;
3743
11446
  return table->status ? -1 : 0;
3744
11447
}
3745
11448
 
 
11449
 
3746
11450
/*
3747
11451
  eq_ref access method implementation: "read_first" function
3748
11452
 
3749
11453
  SYNOPSIS
3750
11454
    join_read_key()
3751
 
      tab  JoinTable of the accessed table
 
11455
      tab  JOIN_TAB of the accessed table
3752
11456
 
3753
11457
  DESCRIPTION
3754
11458
    This is "read_fist" function for the "ref" access method. The difference
3759
11463
   -1  - Row not found
3760
11464
    1  - Error
3761
11465
*/
3762
 
int join_read_key(JoinTable *tab)
 
11466
 
 
11467
static int
 
11468
join_read_key(JOIN_TAB *tab)
3763
11469
{
3764
11470
  int error;
3765
11471
  Table *table= tab->table;
3766
11472
 
3767
 
  if (!table->cursor->inited)
 
11473
  if (!table->file->inited)
3768
11474
  {
3769
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
11475
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3770
11476
  }
3771
11477
 
3772
11478
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3778
11484
      table->status=STATUS_NOT_FOUND;
3779
11485
      return -1;
3780
11486
    }
3781
 
    error=table->cursor->index_read_map(table->record[0],
 
11487
    error=table->file->index_read_map(table->record[0],
3782
11488
                                      tab->ref.key_buff,
3783
11489
                                      make_prev_keypart_map(tab->ref.key_parts),
3784
11490
                                      HA_READ_KEY_EXACT);
3789
11495
  return table->status ? -1 : 0;
3790
11496
}
3791
11497
 
 
11498
 
3792
11499
/*
3793
11500
  ref access method implementation: "read_first" function
3794
11501
 
3795
11502
  SYNOPSIS
3796
11503
    join_read_always_key()
3797
 
      tab  JoinTable of the accessed table
 
11504
      tab  JOIN_TAB of the accessed table
3798
11505
 
3799
11506
  DESCRIPTION
3800
 
    This is "read_first" function for the "ref" access method.
 
11507
    This is "read_fist" function for the "ref" access method.
3801
11508
 
3802
11509
    The functon must leave the index initialized when it returns.
3803
11510
    ref_or_null access implementation depends on that.
3807
11514
   -1  - Row not found
3808
11515
    1  - Error
3809
11516
*/
3810
 
int join_read_always_key(JoinTable *tab)
 
11517
 
 
11518
static int
 
11519
join_read_always_key(JOIN_TAB *tab)
3811
11520
{
3812
11521
  int error;
3813
11522
  Table *table= tab->table;
3814
11523
 
3815
11524
  /* Initialize the index first */
3816
 
  if (!table->cursor->inited)
3817
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
11525
  if (!table->file->inited)
 
11526
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3818
11527
 
3819
11528
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3820
11529
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3825
11534
 
3826
11535
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3827
11536
    return -1;
3828
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
11537
  if ((error=table->file->index_read_map(table->record[0],
3829
11538
                                         tab->ref.key_buff,
3830
11539
                                         make_prev_keypart_map(tab->ref.key_parts),
3831
11540
                                         HA_READ_KEY_EXACT)))
3832
11541
  {
3833
11542
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3834
11543
      return table->report_error(error);
3835
 
    return -1;
 
11544
    return -1; /* purecov: inspected */
3836
11545
  }
3837
 
 
 
11546
  update_virtual_fields_marked_for_write(table);
3838
11547
  return 0;
3839
11548
}
3840
11549
 
 
11550
 
3841
11551
/**
3842
 
  This function is used when optimizing away ORDER BY in
3843
 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
 
11552
  This function is used when optimizing away order_st BY in
 
11553
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
3844
11554
*/
3845
 
int join_read_last_key(JoinTable *tab)
 
11555
 
 
11556
static int
 
11557
join_read_last_key(JOIN_TAB *tab)
3846
11558
{
3847
11559
  int error;
3848
11560
  Table *table= tab->table;
3849
11561
 
3850
 
  if (!table->cursor->inited)
3851
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
11562
  if (!table->file->inited)
 
11563
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3852
11564
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3853
11565
    return -1;
3854
 
  if ((error=table->cursor->index_read_last_map(table->record[0],
 
11566
  if ((error=table->file->index_read_last_map(table->record[0],
3855
11567
                                              tab->ref.key_buff,
3856
11568
                                              make_prev_keypart_map(tab->ref.key_parts))))
3857
11569
  {
3858
11570
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3859
11571
      return table->report_error(error);
3860
 
    return -1;
 
11572
    return -1; /* purecov: inspected */
3861
11573
  }
3862
11574
  return 0;
3863
11575
}
3864
11576
 
3865
 
int join_no_more_records(READ_RECORD *)
 
11577
 
 
11578
        /* ARGSUSED */
 
11579
static int
 
11580
join_no_more_records(READ_RECORD *)
3866
11581
{
3867
11582
  return -1;
3868
11583
}
3869
11584
 
3870
 
int join_read_next_same_diff(READ_RECORD *info)
 
11585
static int
 
11586
join_read_next_same_diff(READ_RECORD *info)
3871
11587
{
3872
11588
  Table *table= info->table;
3873
 
  JoinTable *tab=table->reginfo.join_tab;
 
11589
  JOIN_TAB *tab=table->reginfo.join_tab;
3874
11590
  if (tab->insideout_match_tab->found_match)
3875
11591
  {
3876
11592
    KEY *key= tab->table->key_info + tab->index;
3880
11596
      /* Save index tuple from record to the buffer */
3881
11597
      key_copy(tab->insideout_buf, info->record, key, 0);
3882
11598
 
3883
 
      if ((error=table->cursor->index_next_same(table->record[0],
 
11599
      if ((error=table->file->index_next_same(table->record[0],
3884
11600
                                              tab->ref.key_buff,
3885
11601
                                              tab->ref.key_length)))
3886
11602
      {
3898
11614
    return join_read_next_same(info);
3899
11615
}
3900
11616
 
3901
 
int join_read_next_same(READ_RECORD *info)
 
11617
static int
 
11618
join_read_next_same(READ_RECORD *info)
3902
11619
{
3903
11620
  int error;
3904
11621
  Table *table= info->table;
3905
 
  JoinTable *tab=table->reginfo.join_tab;
 
11622
  JOIN_TAB *tab=table->reginfo.join_tab;
3906
11623
 
3907
 
  if ((error=table->cursor->index_next_same(table->record[0],
 
11624
  if ((error=table->file->index_next_same(table->record[0],
3908
11625
                                          tab->ref.key_buff,
3909
11626
                                          tab->ref.key_length)))
3910
11627
  {
3913
11630
    table->status= STATUS_GARBAGE;
3914
11631
    return -1;
3915
11632
  }
3916
 
 
 
11633
  update_virtual_fields_marked_for_write(table);
3917
11634
  return 0;
3918
11635
}
3919
11636
 
3920
 
int join_read_prev_same(READ_RECORD *info)
 
11637
 
 
11638
static int
 
11639
join_read_prev_same(READ_RECORD *info)
3921
11640
{
3922
11641
  int error;
3923
11642
  Table *table= info->table;
3924
 
  JoinTable *tab=table->reginfo.join_tab;
 
11643
  JOIN_TAB *tab=table->reginfo.join_tab;
3925
11644
 
3926
 
  if ((error=table->cursor->index_prev(table->record[0])))
 
11645
  if ((error=table->file->index_prev(table->record[0])))
3927
11646
    return table->report_error(error);
3928
11647
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3929
11648
                      tab->ref.key_length))
3931
11650
    table->status=STATUS_NOT_FOUND;
3932
11651
    error= -1;
3933
11652
  }
 
11653
  update_virtual_fields_marked_for_write(table);
3934
11654
  return error;
3935
11655
}
3936
11656
 
3937
 
int join_init_quick_read_record(JoinTable *tab)
 
11657
 
 
11658
static int
 
11659
join_init_quick_read_record(JOIN_TAB *tab)
3938
11660
{
3939
11661
  if (test_if_quick_select(tab) == -1)
3940
11662
    return -1;                                  /* No possible records */
3941
11663
  return join_init_read_record(tab);
3942
11664
}
3943
11665
 
 
11666
 
3944
11667
int rr_sequential(READ_RECORD *info);
3945
 
int init_read_record_seq(JoinTable *tab)
 
11668
int init_read_record_seq(JOIN_TAB *tab)
3946
11669
{
3947
11670
  tab->read_record.read_record= rr_sequential;
3948
 
  if (tab->read_record.cursor->ha_rnd_init(1))
 
11671
  if (tab->read_record.file->ha_rnd_init(1))
3949
11672
    return 1;
3950
11673
  return (*tab->read_record.read_record)(&tab->read_record);
3951
11674
}
3952
11675
 
3953
 
int test_if_quick_select(JoinTable *tab)
 
11676
static int
 
11677
test_if_quick_select(JOIN_TAB *tab)
3954
11678
{
3955
11679
  delete tab->select->quick;
3956
 
  tab->select->quick= 0;
 
11680
  tab->select->quick=0;
3957
11681
  return tab->select->test_quick_select(tab->join->session, tab->keys,
3958
 
                                        (table_map) 0, HA_POS_ERROR, 0, false);
 
11682
                                        (table_map) 0, HA_POS_ERROR, 0,
 
11683
                                        false);
3959
11684
}
3960
11685
 
3961
 
int join_init_read_record(JoinTable *tab)
 
11686
 
 
11687
static int
 
11688
join_init_read_record(JOIN_TAB *tab)
3962
11689
{
3963
11690
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3964
11691
    return 1;
3967
11694
  return (*tab->read_record.read_record)(&tab->read_record);
3968
11695
}
3969
11696
 
3970
 
int join_read_first(JoinTable *tab)
 
11697
 
 
11698
static int
 
11699
join_read_first(JOIN_TAB *tab)
3971
11700
{
3972
11701
  int error;
3973
11702
  Table *table=tab->table;
3974
 
  if (!table->key_read && table->covering_keys.test(tab->index) &&
 
11703
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
3975
11704
      !table->no_keyread)
3976
11705
  {
3977
11706
    table->key_read=1;
3978
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
11707
    table->file->extra(HA_EXTRA_KEYREAD);
3979
11708
  }
3980
11709
  tab->table->status=0;
3981
11710
  tab->read_record.table=table;
3982
 
  tab->read_record.cursor=table->cursor;
 
11711
  tab->read_record.file=table->file;
3983
11712
  tab->read_record.index=tab->index;
3984
11713
  tab->read_record.record=table->record[0];
3985
11714
  if (tab->insideout_match_tab)
3994
11723
    tab->read_record.do_insideout_scan= 0;
3995
11724
  }
3996
11725
 
3997
 
  if (!table->cursor->inited)
3998
 
    table->cursor->ha_index_init(tab->index, tab->sorted);
3999
 
  if ((error=tab->table->cursor->index_first(tab->table->record[0])))
 
11726
  if (!table->file->inited)
 
11727
    table->file->ha_index_init(tab->index, tab->sorted);
 
11728
  if ((error=tab->table->file->index_first(tab->table->record[0])))
4000
11729
  {
4001
11730
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
4002
11731
      table->report_error(error);
4003
11732
    return -1;
4004
11733
  }
4005
 
 
 
11734
  if (not error)
 
11735
    update_virtual_fields_marked_for_write(tab->table);
4006
11736
  return 0;
4007
11737
}
4008
11738
 
4009
 
int join_read_next_different(READ_RECORD *info)
 
11739
 
 
11740
static int
 
11741
join_read_next_different(READ_RECORD *info)
4010
11742
{
4011
 
  JoinTable *tab= info->do_insideout_scan;
 
11743
  JOIN_TAB *tab= info->do_insideout_scan;
4012
11744
  if (tab->insideout_match_tab->found_match)
4013
11745
  {
4014
11746
    KEY *key= tab->table->key_info + tab->index;
4018
11750
      /* Save index tuple from record to the buffer */
4019
11751
      key_copy(tab->insideout_buf, info->record, key, 0);
4020
11752
 
4021
 
      if ((error=info->cursor->index_next(info->record)))
 
11753
      if ((error=info->file->index_next(info->record)))
4022
11754
        return info->table->report_error(error);
 
11755
      if (not error)
 
11756
        update_virtual_fields_marked_for_write(tab->table);
4023
11757
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
4024
11758
                      tab->insideout_buf, key->key_length));
4025
11759
    tab->insideout_match_tab->found_match= 0;
4029
11763
    return join_read_next(info);
4030
11764
}
4031
11765
 
4032
 
int join_read_next(READ_RECORD *info)
 
11766
 
 
11767
static int
 
11768
join_read_next(READ_RECORD *info)
4033
11769
{
4034
11770
  int error;
4035
 
  if ((error=info->cursor->index_next(info->record)))
 
11771
  if ((error=info->file->index_next(info->record)))
4036
11772
    return info->table->report_error(error);
 
11773
  if (not error)
 
11774
    update_virtual_fields_marked_for_write(info->table);
4037
11775
  return 0;
4038
11776
}
4039
11777
 
4040
 
int join_read_last(JoinTable *tab)
 
11778
 
 
11779
static int
 
11780
join_read_last(JOIN_TAB *tab)
4041
11781
{
4042
11782
  Table *table=tab->table;
4043
11783
  int error;
4044
 
  if (!table->key_read && table->covering_keys.test(tab->index) &&
 
11784
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
4045
11785
      !table->no_keyread)
4046
11786
  {
4047
11787
    table->key_read=1;
4048
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
11788
    table->file->extra(HA_EXTRA_KEYREAD);
4049
11789
  }
4050
11790
  tab->table->status=0;
4051
11791
  tab->read_record.read_record=join_read_prev;
4052
11792
  tab->read_record.table=table;
4053
 
  tab->read_record.cursor=table->cursor;
 
11793
  tab->read_record.file=table->file;
4054
11794
  tab->read_record.index=tab->index;
4055
11795
  tab->read_record.record=table->record[0];
4056
 
  if (!table->cursor->inited)
4057
 
    table->cursor->ha_index_init(tab->index, 1);
4058
 
  if ((error= tab->table->cursor->index_last(tab->table->record[0])))
 
11796
  if (!table->file->inited)
 
11797
    table->file->ha_index_init(tab->index, 1);
 
11798
  if ((error= tab->table->file->index_last(tab->table->record[0])))
4059
11799
    return table->report_error(error);
4060
 
 
 
11800
  if (not error)
 
11801
    update_virtual_fields_marked_for_write(tab->table);
4061
11802
  return 0;
4062
11803
}
4063
11804
 
4064
 
int join_read_prev(READ_RECORD *info)
 
11805
 
 
11806
static int
 
11807
join_read_prev(READ_RECORD *info)
4065
11808
{
4066
11809
  int error;
4067
 
  if ((error= info->cursor->index_prev(info->record)))
 
11810
  if ((error= info->file->index_prev(info->record)))
4068
11811
    return info->table->report_error(error);
4069
 
 
 
11812
  if (not error)
 
11813
    update_virtual_fields_marked_for_write(info->table);
4070
11814
  return 0;
4071
11815
}
4072
11816
 
4073
11817
/**
4074
11818
  Reading of key with key reference and one part that may be NULL.
4075
11819
*/
4076
 
int join_read_always_key_or_null(JoinTable *tab)
 
11820
 
 
11821
int
 
11822
join_read_always_key_or_null(JOIN_TAB *tab)
4077
11823
{
4078
11824
  int res;
4079
11825
 
4087
11833
  return safe_index_read(tab);
4088
11834
}
4089
11835
 
4090
 
int join_read_next_same_or_null(READ_RECORD *info)
 
11836
 
 
11837
int
 
11838
join_read_next_same_or_null(READ_RECORD *info)
4091
11839
{
4092
11840
  int error;
4093
11841
  if ((error= join_read_next_same(info)) >= 0)
4094
11842
    return error;
4095
 
  JoinTable *tab= info->table->reginfo.join_tab;
 
11843
  JOIN_TAB *tab= info->table->reginfo.join_tab;
4096
11844
 
4097
11845
  /* Test if we have already done a read after null key */
4098
11846
  if (*tab->ref.null_ref_key)
4101
11849
  return safe_index_read(tab);                  // then read null keys
4102
11850
}
4103
11851
 
4104
 
enum_nested_loop_state end_send_group(JOIN *join, JoinTable *, bool end_of_records)
 
11852
 
 
11853
/*****************************************************************************
 
11854
  DESCRIPTION
 
11855
    Functions that end one nested loop iteration. Different functions
 
11856
    are used to support GROUP BY clause and to redirect records
 
11857
    to a table (e.g. in case of SELECT into a temporary table) or to the
 
11858
    network client.
 
11859
 
 
11860
  RETURN VALUES
 
11861
    NESTED_LOOP_OK           - the record has been successfully handled
 
11862
    NESTED_LOOP_ERROR        - a fatal error (like table corruption)
 
11863
                               was detected
 
11864
    NESTED_LOOP_KILLED       - thread shutdown was requested while processing
 
11865
                               the record
 
11866
    NESTED_LOOP_QUERY_LIMIT  - the record has been successfully handled;
 
11867
                               additionally, the nested loop produced the
 
11868
                               number of rows specified in the LIMIT clause
 
11869
                               for the query
 
11870
    NESTED_LOOP_CURSOR_LIMIT - the record has been successfully handled;
 
11871
                               additionally, there is a cursor and the nested
 
11872
                               loop algorithm produced the number of rows
 
11873
                               that is specified for current cursor fetch
 
11874
                               operation.
 
11875
   All return values except NESTED_LOOP_OK abort the nested loop.
 
11876
*****************************************************************************/
 
11877
 
 
11878
/* ARGSUSED */
 
11879
static enum_nested_loop_state
 
11880
end_send(JOIN *join, JOIN_TAB *,
 
11881
         bool end_of_records)
 
11882
{
 
11883
  if (!end_of_records)
 
11884
  {
 
11885
    int error;
 
11886
    if (join->having && join->having->val_int() == 0)
 
11887
      return(NESTED_LOOP_OK);               // Didn't match having
 
11888
    error=0;
 
11889
    if (join->do_send_rows)
 
11890
      error=join->result->send_data(*join->fields);
 
11891
    if (error)
 
11892
      return(NESTED_LOOP_ERROR); /* purecov: inspected */
 
11893
    if (++join->send_records >= join->unit->select_limit_cnt &&
 
11894
        join->do_send_rows)
 
11895
    {
 
11896
      if (join->select_options & OPTION_FOUND_ROWS)
 
11897
      {
 
11898
        JOIN_TAB *jt=join->join_tab;
 
11899
        if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group
 
11900
            && !join->send_group_parts && !join->having && !jt->select_cond &&
 
11901
            !(jt->select && jt->select->quick) &&
 
11902
            (jt->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
11903
            (jt->ref.key < 0))
 
11904
        {
 
11905
          /* Join over all rows in table;  Return number of found rows */
 
11906
          Table *table=jt->table;
 
11907
 
 
11908
          join->select_options ^= OPTION_FOUND_ROWS;
 
11909
          if (table->sort.record_pointers ||
 
11910
              (table->sort.io_cache && my_b_inited(table->sort.io_cache)))
 
11911
          {
 
11912
            /* Using filesort */
 
11913
            join->send_records= table->sort.found_records;
 
11914
          }
 
11915
          else
 
11916
          {
 
11917
            table->file->info(HA_STATUS_VARIABLE);
 
11918
            join->send_records= table->file->stats.records;
 
11919
          }
 
11920
        }
 
11921
        else
 
11922
        {
 
11923
          join->do_send_rows= 0;
 
11924
          if (join->unit->fake_select_lex)
 
11925
            join->unit->fake_select_lex->select_limit= 0;
 
11926
          return(NESTED_LOOP_OK);
 
11927
        }
 
11928
      }
 
11929
      return(NESTED_LOOP_QUERY_LIMIT);      // Abort nicely
 
11930
    }
 
11931
    else if (join->send_records >= join->fetch_limit)
 
11932
    {
 
11933
      /*
 
11934
        There is a server side cursor and all rows for
 
11935
        this fetch request are sent.
 
11936
      */
 
11937
      return(NESTED_LOOP_CURSOR_LIMIT);
 
11938
    }
 
11939
  }
 
11940
 
 
11941
  return(NESTED_LOOP_OK);
 
11942
}
 
11943
 
 
11944
 
 
11945
/* ARGSUSED */
 
11946
enum_nested_loop_state
 
11947
end_send_group(JOIN *join, JOIN_TAB *, bool end_of_records)
4105
11948
{
4106
11949
  int idx= -1;
4107
11950
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
4114
11957
    {
4115
11958
      if (idx < (int) join->send_group_parts)
4116
11959
      {
4117
 
        int error=0;
4118
 
        {
4119
 
          if (!join->first_record)
4120
 
          {
4121
 
                  List_iterator_fast<Item> it(*join->fields);
4122
 
                  Item *item;
4123
 
            /* No matching rows for group function */
4124
 
            join->clear();
 
11960
        int error=0;
 
11961
        {
 
11962
          if (!join->first_record)
 
11963
          {
 
11964
            List_iterator_fast<Item> it(*join->fields);
 
11965
            Item *item;
 
11966
            /* No matching rows for group function */
 
11967
            join->clear();
4125
11968
 
4126
11969
            while ((item= it++))
4127
11970
              item->no_rows_in_result();
4128
 
          }
4129
 
          if (join->having && join->having->val_int() == 0)
4130
 
            error= -1;                          // Didn't satisfy having
4131
 
          else
4132
 
          {
4133
 
            if (join->do_send_rows)
4134
 
              error=join->result->send_data(*join->fields) ? 1 : 0;
4135
 
            join->send_records++;
4136
 
          }
4137
 
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
4138
 
          {
4139
 
            if (join->rollup_send_data((uint32_t) (idx+1)))
4140
 
              error= 1;
4141
 
          }
4142
 
        }
4143
 
        if (error > 0)
4144
 
          return(NESTED_LOOP_ERROR);
4145
 
        if (end_of_records)
4146
 
          return(NESTED_LOOP_OK);
4147
 
        if (join->send_records >= join->unit->select_limit_cnt &&
4148
 
            join->do_send_rows)
4149
 
        {
4150
 
          if (!(join->select_options & OPTION_FOUND_ROWS))
4151
 
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
4152
 
          join->do_send_rows=0;
4153
 
          join->unit->select_limit_cnt = HA_POS_ERROR;
 
11971
          }
 
11972
          if (join->having && join->having->val_int() == 0)
 
11973
            error= -1;                          // Didn't satisfy having
 
11974
          else
 
11975
          {
 
11976
            if (join->do_send_rows)
 
11977
              error=join->result->send_data(*join->fields) ? 1 : 0;
 
11978
            join->send_records++;
 
11979
          }
 
11980
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
 
11981
          {
 
11982
            if (join->rollup_send_data((uint32_t) (idx+1)))
 
11983
              error= 1;
 
11984
          }
 
11985
        }
 
11986
        if (error > 0)
 
11987
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
 
11988
        if (end_of_records)
 
11989
          return(NESTED_LOOP_OK);
 
11990
        if (join->send_records >= join->unit->select_limit_cnt &&
 
11991
            join->do_send_rows)
 
11992
        {
 
11993
          if (!(join->select_options & OPTION_FOUND_ROWS))
 
11994
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
 
11995
          join->do_send_rows=0;
 
11996
          join->unit->select_limit_cnt = HA_POS_ERROR;
4154
11997
        }
4155
11998
        else if (join->send_records >= join->fetch_limit)
4156
11999
        {
4169
12012
    else
4170
12013
    {
4171
12014
      if (end_of_records)
4172
 
        return(NESTED_LOOP_OK);
 
12015
        return(NESTED_LOOP_OK);
4173
12016
      join->first_record=1;
4174
12017
      test_if_item_cache_changed(join->group_fields);
4175
12018
    }
4181
12024
      */
4182
12025
      copy_fields(&join->tmp_table_param);
4183
12026
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
4184
 
        return(NESTED_LOOP_ERROR);
 
12027
        return(NESTED_LOOP_ERROR);
4185
12028
      return(ok_code);
4186
12029
    }
4187
12030
  }
4190
12033
  return(NESTED_LOOP_OK);
4191
12034
}
4192
12035
 
4193
 
enum_nested_loop_state end_write_group(JOIN *join, JoinTable *, bool end_of_records)
 
12036
 
 
12037
/* ARGSUSED */
 
12038
enum_nested_loop_state
 
12039
end_write(JOIN *join, JOIN_TAB *,
 
12040
          bool end_of_records)
 
12041
{
 
12042
  Table *table=join->tmp_table;
 
12043
 
 
12044
  if (join->session->killed)                    // Aborted by user
 
12045
  {
 
12046
    join->session->send_kill_message();
 
12047
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12048
  }
 
12049
  if (!end_of_records)
 
12050
  {
 
12051
    copy_fields(&join->tmp_table_param);
 
12052
    copy_funcs(join->tmp_table_param.items_to_copy);
 
12053
    if (!join->having || join->having->val_int())
 
12054
    {
 
12055
      int error;
 
12056
      join->found_records++;
 
12057
      if ((error=table->file->ha_write_row(table->record[0])))
 
12058
      {
 
12059
        if (!table->file->is_fatal_error(error, HA_CHECK_DUP))
 
12060
          goto end;
 
12061
        if (create_myisam_from_heap(join->session, table,
 
12062
                                    join->tmp_table_param.start_recinfo,
 
12063
                                    &join->tmp_table_param.recinfo,
 
12064
                                    error, 1))
 
12065
          return(NESTED_LOOP_ERROR);        // Not a table_is_full error
 
12066
        table->s->uniques=0;                    // To ensure rows are the same
 
12067
      }
 
12068
      if (++join->send_records >= join->tmp_table_param.end_write_records &&
 
12069
          join->do_send_rows)
 
12070
      {
 
12071
        if (!(join->select_options & OPTION_FOUND_ROWS))
 
12072
          return(NESTED_LOOP_QUERY_LIMIT);
 
12073
        join->do_send_rows=0;
 
12074
        join->unit->select_limit_cnt = HA_POS_ERROR;
 
12075
        return(NESTED_LOOP_OK);
 
12076
      }
 
12077
    }
 
12078
  }
 
12079
end:
 
12080
  return(NESTED_LOOP_OK);
 
12081
}
 
12082
 
 
12083
/* ARGSUSED */
 
12084
/** Group by searching after group record and updating it if possible. */
 
12085
 
 
12086
static enum_nested_loop_state
 
12087
end_update(JOIN *join, JOIN_TAB *,
 
12088
           bool end_of_records)
 
12089
{
 
12090
  Table *table=join->tmp_table;
 
12091
  order_st   *group;
 
12092
  int     error;
 
12093
 
 
12094
  if (end_of_records)
 
12095
    return(NESTED_LOOP_OK);
 
12096
  if (join->session->killed)                    // Aborted by user
 
12097
  {
 
12098
    join->session->send_kill_message();
 
12099
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12100
  }
 
12101
 
 
12102
  join->found_records++;
 
12103
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
 
12104
  /* Make a key of group index */
 
12105
  for (group=table->group ; group ; group=group->next)
 
12106
  {
 
12107
    Item *item= *group->item;
 
12108
    item->save_org_in_field(group->field);
 
12109
    /* Store in the used key if the field was 0 */
 
12110
    if (item->maybe_null)
 
12111
      group->buff[-1]= (char) group->field->is_null();
 
12112
  }
 
12113
  if (!table->file->index_read_map(table->record[1],
 
12114
                                   join->tmp_table_param.group_buff,
 
12115
                                   HA_WHOLE_KEY,
 
12116
                                   HA_READ_KEY_EXACT))
 
12117
  {                                             /* Update old record */
 
12118
    restore_record(table,record[1]);
 
12119
    update_tmptable_sum_func(join->sum_funcs,table);
 
12120
    if ((error=table->file->ha_update_row(table->record[1],
 
12121
                                          table->record[0])))
 
12122
    {
 
12123
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12124
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12125
    }
 
12126
    return(NESTED_LOOP_OK);
 
12127
  }
 
12128
 
 
12129
  /*
 
12130
    Copy null bits from group key to table
 
12131
    We can't copy all data as the key may have different format
 
12132
    as the row data (for example as with VARCHAR keys)
 
12133
  */
 
12134
  KEY_PART_INFO *key_part;
 
12135
  for (group=table->group,key_part=table->key_info[0].key_part;
 
12136
       group ;
 
12137
       group=group->next,key_part++)
 
12138
  {
 
12139
    if (key_part->null_bit)
 
12140
      memcpy(table->record[0]+key_part->offset, group->buff, 1);
 
12141
  }
 
12142
  init_tmptable_sum_functions(join->sum_funcs);
 
12143
  copy_funcs(join->tmp_table_param.items_to_copy);
 
12144
  if ((error=table->file->ha_write_row(table->record[0])))
 
12145
  {
 
12146
    if (create_myisam_from_heap(join->session, table,
 
12147
                                join->tmp_table_param.start_recinfo,
 
12148
                                &join->tmp_table_param.recinfo,
 
12149
                                error, 0))
 
12150
      return(NESTED_LOOP_ERROR);            // Not a table_is_full error
 
12151
    /* Change method to update rows */
 
12152
    table->file->ha_index_init(0, 0);
 
12153
    join->join_tab[join->tables-1].next_select=end_unique_update;
 
12154
  }
 
12155
  join->send_records++;
 
12156
  return(NESTED_LOOP_OK);
 
12157
}
 
12158
 
 
12159
 
 
12160
/** Like end_update, but this is done with unique constraints instead of keys.  */
 
12161
 
 
12162
static enum_nested_loop_state
 
12163
end_unique_update(JOIN *join, JOIN_TAB *,
 
12164
                  bool end_of_records)
 
12165
{
 
12166
  Table *table=join->tmp_table;
 
12167
  int     error;
 
12168
 
 
12169
  if (end_of_records)
 
12170
    return(NESTED_LOOP_OK);
 
12171
  if (join->session->killed)                    // Aborted by user
 
12172
  {
 
12173
    join->session->send_kill_message();
 
12174
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12175
  }
 
12176
 
 
12177
  init_tmptable_sum_functions(join->sum_funcs);
 
12178
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
 
12179
  copy_funcs(join->tmp_table_param.items_to_copy);
 
12180
 
 
12181
  if (!(error=table->file->ha_write_row(table->record[0])))
 
12182
    join->send_records++;                       // New group
 
12183
  else
 
12184
  {
 
12185
    if ((int) table->file->get_dup_key(error) < 0)
 
12186
    {
 
12187
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12188
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12189
    }
 
12190
    if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
 
12191
    {
 
12192
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12193
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12194
    }
 
12195
    restore_record(table,record[1]);
 
12196
    update_tmptable_sum_func(join->sum_funcs,table);
 
12197
    if ((error=table->file->ha_update_row(table->record[1],
 
12198
                                          table->record[0])))
 
12199
    {
 
12200
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12201
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12202
    }
 
12203
  }
 
12204
  return(NESTED_LOOP_OK);
 
12205
}
 
12206
 
 
12207
 
 
12208
/* ARGSUSED */
 
12209
enum_nested_loop_state
 
12210
end_write_group(JOIN *join, JOIN_TAB *,
 
12211
                bool end_of_records)
4194
12212
{
4195
12213
  Table *table=join->tmp_table;
4196
12214
  int     idx= -1;
4198
12216
  if (join->session->killed)
4199
12217
  {                                             // Aborted by user
4200
12218
    join->session->send_kill_message();
4201
 
    return NESTED_LOOP_KILLED;
 
12219
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
4202
12220
  }
4203
12221
  if (!join->first_record || end_of_records ||
4204
12222
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
4208
12226
      int send_group_parts= join->send_group_parts;
4209
12227
      if (idx < send_group_parts)
4210
12228
      {
4211
 
        if (!join->first_record)
4212
 
        {
4213
 
          /* No matching rows for group function */
4214
 
          join->clear();
4215
 
        }
4216
 
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
4217
 
        if (!join->having || join->having->val_int())
4218
 
        {
4219
 
          int error= table->cursor->ha_write_row(table->record[0]);
 
12229
        if (!join->first_record)
 
12230
        {
 
12231
          /* No matching rows for group function */
 
12232
          join->clear();
 
12233
        }
 
12234
        copy_sum_funcs(join->sum_funcs,
 
12235
                       join->sum_funcs_end[send_group_parts]);
 
12236
        if (!join->having || join->having->val_int())
 
12237
        {
 
12238
          int error= table->file->ha_write_row(table->record[0]);
4220
12239
          if (error && create_myisam_from_heap(join->session, table,
4221
 
                                              join->tmp_table_param.start_recinfo,
 
12240
                                               join->tmp_table_param.start_recinfo,
4222
12241
                                                &join->tmp_table_param.recinfo,
4223
 
                                              error, 0))
4224
 
          return NESTED_LOOP_ERROR;
 
12242
                                               error, 0))
 
12243
            return(NESTED_LOOP_ERROR);
4225
12244
        }
4226
12245
        if (join->rollup.state != ROLLUP::STATE_NONE)
4227
 
        {
4228
 
          if (join->rollup_write_data((uint32_t) (idx+1), table))
4229
 
            return NESTED_LOOP_ERROR;
4230
 
        }
4231
 
        if (end_of_records)
4232
 
          return NESTED_LOOP_OK;
 
12246
        {
 
12247
          if (join->rollup_write_data((uint32_t) (idx+1), table))
 
12248
            return(NESTED_LOOP_ERROR);
 
12249
        }
 
12250
        if (end_of_records)
 
12251
          return(NESTED_LOOP_OK);
4233
12252
      }
4234
12253
    }
4235
12254
    else
4236
12255
    {
4237
12256
      if (end_of_records)
4238
 
        return NESTED_LOOP_OK;
 
12257
        return(NESTED_LOOP_OK);
4239
12258
      join->first_record=1;
4240
12259
      test_if_item_cache_changed(join->group_fields);
4241
12260
    }
4244
12263
      copy_fields(&join->tmp_table_param);
4245
12264
      copy_funcs(join->tmp_table_param.items_to_copy);
4246
12265
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
4247
 
        return NESTED_LOOP_ERROR;
4248
 
      return NESTED_LOOP_OK;
 
12266
        return(NESTED_LOOP_ERROR);
 
12267
      return(NESTED_LOOP_OK);
4249
12268
    }
4250
12269
  }
4251
12270
  if (update_sum_func(join->sum_funcs))
4252
 
    return NESTED_LOOP_ERROR;
4253
 
  return NESTED_LOOP_OK;
 
12271
    return(NESTED_LOOP_ERROR);
 
12272
  return(NESTED_LOOP_OK);
4254
12273
}
4255
12274
 
 
12275
 
4256
12276
/*****************************************************************************
4257
12277
  Remove calculation with tables that aren't yet read. Remove also tests
4258
12278
  against fields that are read through key where the table is not a
4265
12285
  @return
4266
12286
    1 if right_item is used removable reference key on left_item
4267
12287
*/
4268
 
bool test_if_ref(Item_field *left_item,Item *right_item)
 
12288
 
 
12289
static bool test_if_ref(Item_field *left_item,Item *right_item)
4269
12290
{
4270
12291
  Field *field=left_item->field;
4271
12292
  // No need to change const test. We also have to keep tests on LEFT JOIN
4276
12297
    {
4277
12298
      right_item= right_item->real_item();
4278
12299
      if (right_item->type() == Item::FIELD_ITEM)
4279
 
        return (field->eq_def(((Item_field *) right_item)->field));
 
12300
        return (field->eq_def(((Item_field *) right_item)->field));
4280
12301
      /* remove equalities injected by IN->EXISTS transformation */
4281
12302
      else if (right_item->type() == Item::CACHE_ITEM)
4282
12303
        return ((Item_cache *)right_item)->eq_def (field);
4283
12304
      if (right_item->const_item() && !(right_item->is_null()))
4284
12305
      {
4285
 
        /*
4286
 
          We can remove binary fields and numerical fields except float,
4287
 
          as float comparison isn't 100 % secure
4288
 
          We have to keep normal strings to be able to check for end spaces
 
12306
        /*
 
12307
          We can remove binary fields and numerical fields except float,
 
12308
          as float comparison isn't 100 % secure
 
12309
          We have to keep normal strings to be able to check for end spaces
4289
12310
 
4290
 
                sergefp: the above seems to be too restrictive. Counterexample:
4291
 
                  create table t100 (v varchar(10), key(v)) default charset=latin1;
4292
 
                  insert into t100 values ('a'),('a ');
4293
 
                  explain select * from t100 where v='a';
4294
 
                The EXPLAIN shows 'using Where'. Running the query returns both
4295
 
                rows, so it seems there are no problems with endspace in the most
4296
 
                frequent case?
4297
 
        */
4298
 
        if (field->binary() &&
4299
 
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
4300
 
            field->decimals() == 0)
4301
 
        {
4302
 
          return ! store_val_in_field(field, right_item, CHECK_FIELD_WARN);
4303
 
        }
 
12311
          sergefp: the above seems to be too restrictive. Counterexample:
 
12312
            create table t100 (v varchar(10), key(v)) default charset=latin1;
 
12313
            insert into t100 values ('a'),('a ');
 
12314
            explain select * from t100 where v='a';
 
12315
          The EXPLAIN shows 'using Where'. Running the query returns both
 
12316
          rows, so it seems there are no problems with endspace in the most
 
12317
          frequent case?
 
12318
        */
 
12319
        if (field->binary() &&
 
12320
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
 
12321
            field->decimals() == 0)
 
12322
        {
 
12323
          return !store_val_in_field(field, right_item, CHECK_FIELD_WARN);
 
12324
        }
4304
12325
      }
4305
12326
    }
4306
12327
  }
4307
 
  return 0;
 
12328
  return 0;                                     // keep test
 
12329
}
 
12330
 
 
12331
/**
 
12332
   @brief Replaces an expression destructively inside the expression tree of
 
12333
   the WHERE clase.
 
12334
 
 
12335
   @note Because of current requirements for semijoin flattening, we do not
 
12336
   need to recurse here, hence this function will only examine the top-level
 
12337
   AND conditions. (see JOIN::prepare, comment above the line
 
12338
   'if (do_materialize)'
 
12339
 
 
12340
   @param join The top-level query.
 
12341
   @param old_cond The expression to be replaced.
 
12342
   @param new_cond The expression to be substituted.
 
12343
   @param do_fix_fields If true, Item::fix_fields(Session*, Item**) is called for
 
12344
   the new expression.
 
12345
   @return <code>true</code> if there was an error, <code>false</code> if
 
12346
   successful.
 
12347
*/
 
12348
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
 
12349
                                       Item *new_cond, bool do_fix_fields)
 
12350
{
 
12351
  if (join->conds == old_cond) {
 
12352
    join->conds= new_cond;
 
12353
    if (do_fix_fields)
 
12354
      new_cond->fix_fields(join->session, &join->conds);
 
12355
    return false;
 
12356
  }
 
12357
 
 
12358
  if (join->conds->type() == Item::COND_ITEM) {
 
12359
    List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
 
12360
    Item *item;
 
12361
    while ((item= li++))
 
12362
      if (item == old_cond)
 
12363
      {
 
12364
        li.replace(new_cond);
 
12365
        if (do_fix_fields)
 
12366
          new_cond->fix_fields(join->session, li.ref());
 
12367
        return false;
 
12368
      }
 
12369
  }
 
12370
 
 
12371
  return true;
4308
12372
}
4309
12373
 
4310
12374
/*
4338
12402
  RETURN
4339
12403
    Extracted condition
4340
12404
*/
4341
 
COND *make_cond_for_table(COND *cond, table_map tables, table_map used_table, bool exclude_expensive_cond)
 
12405
 
 
12406
static COND *
 
12407
make_cond_for_table(COND *cond, table_map tables, table_map used_table,
 
12408
                    bool exclude_expensive_cond)
4342
12409
{
4343
12410
  if (used_table && !(cond->used_tables() & used_table) &&
4344
 
    /*
4345
 
      Exclude constant conditions not checked at optimization time if
4346
 
      the table we are pushing conditions to is the first one.
4347
 
      As a result, such conditions are not considered as already checked
4348
 
      and will be checked at execution time, attached to the first table.
4349
 
    */
4350
 
    !((used_table & 1) && cond->is_expensive()))
 
12411
      /*
 
12412
        Exclude constant conditions not checked at optimization time if
 
12413
        the table we are pushing conditions to is the first one.
 
12414
        As a result, such conditions are not considered as already checked
 
12415
        and will be checked at execution time, attached to the first table.
 
12416
      */
 
12417
      !((used_table & 1) && cond->is_expensive()))
4351
12418
    return (COND*) 0;                           // Already checked
4352
12419
  if (cond->type() == Item::COND_ITEM)
4353
12420
  {
4356
12423
      /* Create new top level AND item */
4357
12424
      Item_cond_and *new_cond=new Item_cond_and;
4358
12425
      if (!new_cond)
4359
 
        return (COND*) 0;
 
12426
        return (COND*) 0;                       // OOM /* purecov: inspected */
4360
12427
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4361
12428
      Item *item;
4362
12429
      while ((item=li++))
4363
12430
      {
4364
 
        Item *fix= make_cond_for_table(item,tables,used_table,
4365
 
                                            exclude_expensive_cond);
4366
 
        if (fix)
4367
 
          new_cond->argument_list()->push_back(fix);
 
12431
        Item *fix=make_cond_for_table(item,tables,used_table,
 
12432
                                      exclude_expensive_cond);
 
12433
        if (fix)
 
12434
          new_cond->argument_list()->push_back(fix);
4368
12435
      }
4369
 
      switch (new_cond->argument_list()->elements) 
4370
 
      {
4371
 
        case 0:
4372
 
          return (COND*) 0;                     // Always true
4373
 
        case 1:
4374
 
          return new_cond->argument_list()->head();
4375
 
        default:
4376
 
          /*
4377
 
            Item_cond_and do not need fix_fields for execution, its parameters
4378
 
            are fixed or do not need fix_fields, too
4379
 
          */
4380
 
          new_cond->quick_fix_field();
4381
 
          new_cond->used_tables_cache= ((Item_cond_and*) cond)->used_tables_cache & tables;
4382
 
          return new_cond;
 
12436
      switch (new_cond->argument_list()->elements) {
 
12437
      case 0:
 
12438
        return (COND*) 0;                       // Always true
 
12439
      case 1:
 
12440
        return new_cond->argument_list()->head();
 
12441
      default:
 
12442
        /*
 
12443
          Item_cond_and do not need fix_fields for execution, its parameters
 
12444
          are fixed or do not need fix_fields, too
 
12445
        */
 
12446
        new_cond->quick_fix_field();
 
12447
        new_cond->used_tables_cache=
 
12448
          ((Item_cond_and*) cond)->used_tables_cache &
 
12449
          tables;
 
12450
        return new_cond;
4383
12451
      }
4384
12452
    }
4385
12453
    else
4386
12454
    {                                           // Or list
4387
12455
      Item_cond_or *new_cond=new Item_cond_or;
4388
12456
      if (!new_cond)
4389
 
        return (COND*) 0;
 
12457
        return (COND*) 0;                       // OOM /* purecov: inspected */
4390
12458
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4391
12459
      Item *item;
4392
12460
      while ((item=li++))
4393
12461
      {
4394
 
        Item *fix= make_cond_for_table(item,tables,0L, exclude_expensive_cond);
4395
 
        if (!fix)
4396
 
          return (COND*) 0;                     // Always true
4397
 
        new_cond->argument_list()->push_back(fix);
 
12462
        Item *fix=make_cond_for_table(item,tables,0L, exclude_expensive_cond);
 
12463
        if (!fix)
 
12464
          return (COND*) 0;                     // Always true
 
12465
        new_cond->argument_list()->push_back(fix);
4398
12466
      }
4399
12467
      /*
4400
 
        Item_cond_and do not need fix_fields for execution, its parameters
4401
 
        are fixed or do not need fix_fields, too
 
12468
        Item_cond_and do not need fix_fields for execution, its parameters
 
12469
        are fixed or do not need fix_fields, too
4402
12470
      */
4403
12471
      new_cond->quick_fix_field();
4404
12472
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
4431
12499
  {
4432
12500
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
4433
12501
    Item *right_item= ((Item_func*) cond)->arguments()[1];
4434
 
    if (left_item->type() == Item::FIELD_ITEM && test_if_ref((Item_field*) left_item,right_item))
 
12502
    if (left_item->type() == Item::FIELD_ITEM &&
 
12503
        test_if_ref((Item_field*) left_item,right_item))
4435
12504
    {
4436
12505
      cond->marker=3;                   // Checked when read
4437
12506
      return (COND*) 0;
4438
12507
    }
4439
 
    if (right_item->type() == Item::FIELD_ITEM &&       test_if_ref((Item_field*) right_item,left_item))
 
12508
    if (right_item->type() == Item::FIELD_ITEM &&
 
12509
        test_if_ref((Item_field*) right_item,left_item))
4440
12510
    {
4441
12511
      cond->marker=3;                   // Checked when read
4442
12512
      return (COND*) 0;
4446
12516
  return cond;
4447
12517
}
4448
12518
 
4449
 
static Item *part_of_refkey(Table *table,Field *field)
 
12519
 
 
12520
static Item *
 
12521
part_of_refkey(Table *table,Field *field)
4450
12522
{
4451
12523
  if (!table->reginfo.join_tab)
4452
12524
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
4472
12544
  return (Item*) 0;
4473
12545
}
4474
12546
 
 
12547
 
4475
12548
/**
4476
12549
  Test if one can use the key to resolve order_st BY.
4477
12550
 
4492
12565
  @retval
4493
12566
    -1   Reverse key can be used
4494
12567
*/
4495
 
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
 
12568
 
 
12569
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx,
 
12570
                                uint32_t *used_key_parts)
4496
12571
{
4497
 
  KEY_PART_INFO *key_part= NULL;
4498
 
  KEY_PART_INFO *key_part_end= NULL;
4499
 
  key_part= table->key_info[idx].key_part;
4500
 
  key_part_end= key_part + table->key_info[idx].key_parts;
 
12572
  KEY_PART_INFO *key_part,*key_part_end;
 
12573
  key_part=table->key_info[idx].key_part;
 
12574
  key_part_end=key_part+table->key_info[idx].key_parts;
4501
12575
  key_part_map const_key_parts=table->const_key_parts[idx];
4502
 
  int reverse= 0;
 
12576
  int reverse=0;
4503
12577
  bool on_primary_key= false;
4504
12578
 
4505
12579
  for (; order ; order=order->next, const_key_parts>>=1)
4509
12583
 
4510
12584
    /*
4511
12585
      Skip key parts that are constants in the WHERE clause.
4512
 
      These are already skipped in the ORDER BY by const_expression_in_where()
 
12586
      These are already skipped in the order_st BY by const_expression_in_where()
4513
12587
    */
4514
12588
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4515
12589
      key_part++;
4522
12596
        the primary key as a suffix.
4523
12597
      */
4524
12598
      if (!on_primary_key &&
4525
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
 
12599
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
4526
12600
          table->s->primary_key != MAX_KEY)
4527
12601
      {
4528
12602
        on_primary_key= true;
4556
12630
  }
4557
12631
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4558
12632
    (uint32_t) (key_part - table->key_info[idx].key_part);
4559
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
12633
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
4560
12634
                         HA_READ_PREV))
4561
12635
    reverse= 0;                                 // Index can't be used
4562
12636
  return(reverse);
4563
12637
}
4564
12638
 
 
12639
 
4565
12640
/**
4566
12641
  Test if a second key is the subkey of the first one.
4567
12642
 
4577
12652
  @retval
4578
12653
    0   no sub key
4579
12654
*/
4580
 
inline bool is_subkey(KEY_PART_INFO *key_part,
4581
 
                      KEY_PART_INFO *ref_key_part,
4582
 
                      KEY_PART_INFO *ref_key_part_end)
 
12655
 
 
12656
inline bool
 
12657
is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
 
12658
          KEY_PART_INFO *ref_key_part_end)
4583
12659
{
4584
12660
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4585
 
    if (! key_part->field->eq(ref_key_part->field))
 
12661
    if (!key_part->field->eq(ref_key_part->field))
4586
12662
      return 0;
4587
12663
  return 1;
4588
12664
}
4598
12674
    - MAX_KEY                   If we can't use other key
4599
12675
    - the number of found key   Otherwise
4600
12676
*/
4601
 
static uint32_t test_if_subkey(order_st *order,
4602
 
                               Table *table,
4603
 
                               uint32_t ref,
4604
 
                               uint32_t ref_key_parts,
4605
 
                               const key_map *usable_keys)
 
12677
 
 
12678
static uint
 
12679
test_if_subkey(order_st *order, Table *table, uint32_t ref, uint32_t ref_key_parts,
 
12680
               const key_map *usable_keys)
4606
12681
{
4607
12682
  uint32_t nr;
4608
12683
  uint32_t min_length= UINT32_MAX;
4613
12688
 
4614
12689
  for (nr= 0 ; nr < table->s->keys ; nr++)
4615
12690
  {
4616
 
    if (usable_keys->test(nr) &&
 
12691
    if (usable_keys->is_set(nr) &&
4617
12692
        table->key_info[nr].key_length < min_length &&
4618
12693
        table->key_info[nr].key_parts >= ref_key_parts &&
4619
12694
        is_subkey(table->key_info[nr].key_part, ref_key_part,
4627
12702
  return best;
4628
12703
}
4629
12704
 
 
12705
 
4630
12706
/**
4631
12707
  Check if GROUP BY/DISTINCT can be optimized away because the set is
4632
12708
  already known to be distinct.
4658
12734
  @retval
4659
12735
    0                    not found.
4660
12736
*/
4661
 
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
 
12737
 
 
12738
static bool
 
12739
list_contains_unique_index(Table *table,
 
12740
                          bool (*find_func) (Field *, void *), void *data)
4662
12741
{
4663
12742
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
4664
12743
  {
4666
12745
         (table->key_info[keynr].flags & HA_NOSAME))
4667
12746
    {
4668
12747
      KEY *keyinfo= table->key_info + keynr;
4669
 
      KEY_PART_INFO *key_part= NULL;
4670
 
      KEY_PART_INFO *key_part_end= NULL;
 
12748
      KEY_PART_INFO *key_part, *key_part_end;
4671
12749
 
4672
12750
      for (key_part=keyinfo->key_part,
4673
12751
           key_part_end=key_part+ keyinfo->key_parts;
4675
12753
           key_part++)
4676
12754
      {
4677
12755
        if (key_part->field->maybe_null() ||
4678
 
            ! find_func(key_part->field, data))
 
12756
            !find_func(key_part->field, data))
4679
12757
          break;
4680
12758
      }
4681
12759
      if (key_part == key_part_end)
4685
12763
  return 0;
4686
12764
}
4687
12765
 
 
12766
 
4688
12767
/**
4689
12768
  Helper function for list_contains_unique_index.
4690
12769
  Find a field reference in a list of order_st structures.
4698
12777
  @retval
4699
12778
    0                    not found.
4700
12779
*/
4701
 
bool find_field_in_order_list (Field *field, void *data)
 
12780
 
 
12781
static bool
 
12782
find_field_in_order_list (Field *field, void *data)
4702
12783
{
4703
12784
  order_st *group= (order_st *) data;
4704
12785
  bool part_found= 0;
4715
12796
  return part_found;
4716
12797
}
4717
12798
 
 
12799
 
4718
12800
/**
4719
12801
  Helper function for list_contains_unique_index.
4720
12802
  Find a field reference in a dynamic list of Items.
4728
12810
  @retval
4729
12811
    0                    not found.
4730
12812
*/
4731
 
bool find_field_in_item_list (Field *field, void *data)
 
12813
 
 
12814
static bool
 
12815
find_field_in_item_list (Field *field, void *data)
4732
12816
{
4733
12817
  List<Item> *fields= (List<Item> *) data;
4734
12818
  bool part_found= 0;
4747
12831
  return part_found;
4748
12832
}
4749
12833
 
 
12834
 
4750
12835
/**
4751
 
  Test if we can skip the ORDER BY by using an index.
 
12836
  Test if we can skip the order_st BY by using an index.
4752
12837
 
4753
12838
  SYNOPSIS
4754
12839
    test_if_skip_sort_order()
4758
12843
      no_changes
4759
12844
      map
4760
12845
 
4761
 
  If we can use an index, the JoinTable / tab->select struct
 
12846
  If we can use an index, the JOIN_TAB / tab->select struct
4762
12847
  is changed to use the index.
4763
12848
 
4764
12849
  The index must cover all fields in <order>, or it will not be considered.
4772
12857
  @retval
4773
12858
    1    We can use an index.
4774
12859
*/
4775
 
bool test_if_skip_sort_order(JoinTable *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
 
12860
 
 
12861
static bool
 
12862
test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,ha_rows select_limit,
 
12863
                        bool no_changes, const key_map *map)
4776
12864
{
4777
12865
  int32_t ref_key;
4778
12866
  uint32_t ref_key_parts;
4779
12867
  int order_direction;
4780
12868
  uint32_t used_key_parts;
4781
12869
  Table *table=tab->table;
4782
 
  optimizer::SqlSelect *select= tab->select;
 
12870
  SQL_SELECT *select=tab->select;
4783
12871
  key_map usable_keys;
4784
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
12872
  QUICK_SELECT_I *save_quick= 0;
4785
12873
 
4786
12874
  /*
4787
12875
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4794
12882
    Item *item= (*tmp_order->item)->real_item();
4795
12883
    if (item->type() != Item::FIELD_ITEM)
4796
12884
    {
4797
 
      usable_keys.reset();
 
12885
      usable_keys.clear_all();
4798
12886
      return(0);
4799
12887
    }
4800
 
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
4801
 
    if (usable_keys.none())
 
12888
    usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey);
 
12889
    if (usable_keys.is_clear_all())
4802
12890
      return(0);                                        // No usable keys
4803
12891
  }
4804
12892
 
4808
12896
  {
4809
12897
    ref_key=       tab->ref.key;
4810
12898
    ref_key_parts= tab->ref.key_parts;
4811
 
    if (tab->type == AM_REF_OR_NULL)
 
12899
    if (tab->type == JT_REF_OR_NULL)
4812
12900
      return(0);
4813
12901
  }
4814
 
  else if (select && select->quick)             // Range found by optimizer/range
 
12902
  else if (select && select->quick)             // Range found by opt_range
4815
12903
  {
4816
12904
    int quick_type= select->quick->get_type();
4817
12905
    save_quick= select->quick;
4821
12909
      by clustered PK values.
4822
12910
    */
4823
12911
 
4824
 
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4825
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4826
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT)
 
12912
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
12913
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
12914
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
4827
12915
      return(0);
4828
12916
    ref_key=       select->quick->index;
4829
12917
    ref_key_parts= select->quick->used_key_parts;
4834
12922
    /*
4835
12923
      We come here when there is a REF key.
4836
12924
    */
4837
 
    if (! usable_keys.test(ref_key))
 
12925
    if (!usable_keys.is_set(ref_key))
4838
12926
    {
4839
12927
      /*
4840
 
        We come here when ref_key is not among usable_keys
 
12928
        We come here when ref_key is not among usable_keys
4841
12929
      */
4842
12930
      uint32_t new_ref_key;
4843
12931
      /*
4844
 
        If using index only read, only consider other possible index only
4845
 
        keys
 
12932
        If using index only read, only consider other possible index only
 
12933
        keys
4846
12934
      */
4847
 
      if (table->covering_keys.test(ref_key))
4848
 
        usable_keys&= table->covering_keys;
 
12935
      if (table->covering_keys.is_set(ref_key))
 
12936
        usable_keys.intersect(table->covering_keys);
4849
12937
      if (tab->pre_idx_push_select_cond)
4850
12938
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
4851
12939
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
4852
12940
                                       &usable_keys)) < MAX_KEY)
4853
12941
      {
4854
 
        /* Found key that can be used to retrieve data in sorted order */
4855
 
        if (tab->ref.key >= 0)
4856
 
        {
 
12942
        /* Found key that can be used to retrieve data in sorted order */
 
12943
        if (tab->ref.key >= 0)
 
12944
        {
4857
12945
          /*
4858
12946
            We'll use ref access method on key new_ref_key. In general case
4859
12947
            the index search tuple for new_ref_key will be different (e.g.
4862
12950
            "part1 = const1 AND part2=const2".
4863
12951
            So we build tab->ref from scratch here.
4864
12952
          */
4865
 
          optimizer::KeyUse *keyuse= tab->keyuse;
4866
 
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
 
12953
          KEYUSE *keyuse= tab->keyuse;
 
12954
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
4867
12955
            keyuse++;
4868
12956
 
4869
12957
          if (create_ref_for_key(tab->join, tab, keyuse,
4870
12958
                                 tab->join->const_table_map))
4871
12959
            return(0);
4872
 
        }
4873
 
        else
4874
 
        {
 
12960
        }
 
12961
        else
 
12962
        {
4875
12963
          /*
4876
 
            The range optimizer constructed QuickRange for ref_key, and
 
12964
            The range optimizer constructed QUICK_RANGE for ref_key, and
4877
12965
            we want to use instead new_ref_key as the index. We can't
4878
12966
            just change the index of the quick select, because this may
4879
12967
            result in an incosistent QUICK_SELECT object. Below we
4881
12969
            parameres are set correctly by the range optimizer.
4882
12970
           */
4883
12971
          key_map new_ref_key_map;
4884
 
          new_ref_key_map.reset();  // Force the creation of quick select
4885
 
          new_ref_key_map.set(new_ref_key); // only for new_ref_key.
 
12972
          new_ref_key_map.clear_all();  // Force the creation of quick select
 
12973
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
4886
12974
 
4887
12975
          if (select->test_quick_select(tab->join->session, new_ref_key_map, 0,
4888
12976
                                        (tab->join->select_options &
4892
12980
                                        true) <=
4893
12981
              0)
4894
12982
            return(0);
4895
 
        }
 
12983
        }
4896
12984
        ref_key= new_ref_key;
4897
12985
      }
4898
12986
    }
4899
12987
    /* Check if we get the rows in requested sorted order by using the key */
4900
 
    if (usable_keys.test(ref_key) &&
 
12988
    if (usable_keys.is_set(ref_key) &&
4901
12989
        (order_direction= test_if_order_by_key(order,table,ref_key,
4902
12990
                                               &used_key_parts)))
4903
12991
      goto check_reverse_order;
4920
13008
    double fanout= 1;
4921
13009
    JOIN *join= tab->join;
4922
13010
    uint32_t tablenr= tab - join->join_tab;
4923
 
    ha_rows table_records= table->cursor->stats.records;
 
13011
    ha_rows table_records= table->file->stats.records;
4924
13012
    bool group= join->group && order == join->group_list;
4925
 
    optimizer::Position cur_pos;
4926
13013
 
4927
13014
    /*
4928
13015
      If not used with LIMIT, only use keys if the whole query can be
4935
13022
        filesort() and join cache are usually faster than reading in
4936
13023
        index order and not using join cache
4937
13024
        */
4938
 
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
 
13025
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
4939
13026
        return(0);
4940
 
      keys= *table->cursor->keys_to_use_for_scanning();
4941
 
      keys|= table->covering_keys;
 
13027
      keys= *table->file->keys_to_use_for_scanning();
 
13028
      keys.merge(table->covering_keys);
4942
13029
 
4943
13030
      /*
4944
 
        We are adding here also the index specified in FORCE INDEX clause,
4945
 
        if any.
 
13031
        We are adding here also the index specified in FORCE INDEX clause,
 
13032
        if any.
4946
13033
        This is to allow users to use index in order_st BY.
4947
13034
      */
4948
13035
      if (table->force_index)
4949
 
        keys|= (group ? table->keys_in_use_for_group_by :
4950
 
                                table->keys_in_use_for_order_by);
4951
 
      keys&= usable_keys;
 
13036
        keys.merge(group ? table->keys_in_use_for_group_by :
 
13037
                           table->keys_in_use_for_order_by);
 
13038
      keys.intersect(usable_keys);
4952
13039
    }
4953
13040
    else
4954
13041
      keys= usable_keys;
4955
13042
 
4956
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4957
 
    read_time= cur_pos.getCost();
 
13043
    read_time= join->best_positions[tablenr].read_time;
4958
13044
    for (uint32_t i= tablenr+1; i < join->tables; i++)
4959
 
    {
4960
 
      cur_pos= join->getPosFromOptimalPlan(i);
4961
 
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
4962
 
    }
 
13045
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
4963
13046
 
4964
13047
    for (nr=0; nr < table->s->keys ; nr++)
4965
13048
    {
4966
13049
      int direction;
4967
 
      if (keys.test(nr) &&
 
13050
      if (keys.is_set(nr) &&
4968
13051
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4969
13052
      {
4970
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->cursor->primary_key_is_clustered());
 
13053
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
4971
13054
 
4972
13055
        /*
4973
 
          Don't use an index scan with ORDER BY without limit.
 
13056
          Don't use an index scan with order_st BY without limit.
4974
13057
          For GROUP BY without limit always use index scan
4975
13058
          if there is a suitable index.
4976
13059
          Why we hold to this asymmetry hardly can be explained
4977
13060
          rationally. It's easy to demonstrate that using
4978
13061
          temporary table + filesort could be cheaper for grouping
4979
13062
          queries too.
4980
 
        */
 
13063
        */
4981
13064
        if (is_covering ||
4982
13065
            select_limit != HA_POS_ERROR ||
4983
13066
            (ref_key < 0 && (group || table->force_index)))
4995
13078
              With a grouping query each group containing on average
4996
13079
              rec_per_key records produces only one row that will
4997
13080
              be included into the result set.
4998
 
            */
 
13081
            */
4999
13082
            if (select_limit > table_records/rec_per_key)
5000
13083
                select_limit= table_records;
5001
13084
            else
5010
13093
            So the estimate for L/fanout(tk,tn) will be too optimistic
5011
13094
            and as result we'll choose an index scan when using ref/range
5012
13095
            access + filesort will be cheaper.
5013
 
          */
 
13096
          */
5014
13097
          select_limit= (ha_rows) (select_limit < fanout ?
5015
13098
                                   1 : select_limit/fanout);
5016
13099
          /*
5037
13120
            Rows in such a sequence are supposed to be ordered
5038
13121
            by rowid/primary key. When reading the data
5039
13122
            in a sequence we'll touch not more pages than the
5040
 
            table cursor contains.
 
13123
            table file contains.
5041
13124
            TODO. Use the formula for a disk sweep sequential access
5042
13125
            to calculate the cost of accessing data rows for one
5043
13126
            index entry.
5044
 
          */
 
13127
          */
5045
13128
          index_scan_time= select_limit/rec_per_key *
5046
 
                           min(rec_per_key, table->cursor->scan_time());
 
13129
                           cmin(rec_per_key, table->file->scan_time());
5047
13130
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
5048
13131
              index_scan_time < read_time)
5049
13132
          {
5050
13133
            ha_rows quick_records= table_records;
5051
13134
            if (is_best_covering && !is_covering)
5052
13135
              continue;
5053
 
            if (table->quick_keys.test(nr))
 
13136
            if (table->quick_keys.is_set(nr))
5054
13137
              quick_records= table->quick_rows[nr];
5055
13138
            if (best_key < 0 ||
5056
 
                (select_limit <= min(quick_records,best_records) ?
 
13139
                (select_limit <= cmin(quick_records,best_records) ?
5057
13140
                 keyinfo->key_parts < best_key_parts :
5058
13141
                 quick_records < best_records))
5059
13142
            {
5064
13147
              best_key_direction= direction;
5065
13148
            }
5066
13149
          }
5067
 
        }
 
13150
        }
5068
13151
      }
5069
13152
    }
5070
13153
    if (best_key >= 0)
5071
13154
    {
5072
13155
      bool quick_created= false;
5073
 
      if (table->quick_keys.test(best_key) && best_key != ref_key)
 
13156
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
5074
13157
      {
5075
13158
        key_map test_map;
5076
 
        test_map.reset();       // Force the creation of quick select
5077
 
        test_map.set(best_key); // only best_key.
 
13159
        test_map.clear_all();       // Force the creation of quick select
 
13160
        test_map.set_bit(best_key); // only best_key.
5078
13161
        quick_created=
5079
13162
          select->test_quick_select(join->session, test_map, 0,
5080
13163
                                    join->select_options & OPTION_FOUND_ROWS ?
5085
13168
      if (!no_changes)
5086
13169
      {
5087
13170
        if (!quick_created)
5088
 
        {
 
13171
        {
5089
13172
          tab->index= best_key;
5090
13173
          tab->read_first_record= best_key_direction > 0 ?
5091
13174
                                  join_read_first:join_read_last;
5092
 
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
 
13175
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
5093
13176
          if (select && select->quick)
5094
13177
          {
5095
13178
            delete select->quick;
5096
13179
            select->quick= 0;
5097
13180
          }
5098
 
          if (table->covering_keys.test(best_key))
 
13181
          if (table->covering_keys.is_set(best_key))
5099
13182
          {
5100
13183
            table->key_read=1;
5101
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
13184
            table->file->extra(HA_EXTRA_KEYREAD);
5102
13185
          }
5103
 
          table->cursor->ha_index_or_rnd_end();
 
13186
          table->file->ha_index_or_rnd_end();
5104
13187
          if (join->select_options & SELECT_DESCRIBE)
5105
13188
          {
5106
13189
            tab->ref.key= -1;
5109
13192
              tab->limit= select_limit;
5110
13193
          }
5111
13194
        }
5112
 
        else if (tab->type != AM_ALL)
 
13195
        else if (tab->type != JT_ALL)
5113
13196
        {
5114
13197
          /*
5115
13198
            We're about to use a quick access to the table.
5117
13200
            method is actually used.
5118
13201
          */
5119
13202
          assert(tab->select->quick);
5120
 
          tab->type= AM_ALL;
 
13203
          tab->type=JT_ALL;
5121
13204
          tab->use_quick=1;
5122
13205
          tab->ref.key= -1;
5123
13206
          tab->ref.key_parts=0;         // Don't use ref key.
5124
13207
          tab->read_first_record= join_init_read_record;
 
13208
          /*
 
13209
            TODO: update the number of records in join->best_positions[tablenr]
 
13210
          */
5125
13211
        }
5126
13212
      }
5127
13213
      used_key_parts= best_key_parts;
5132
13218
  }
5133
13219
 
5134
13220
check_reverse_order:
5135
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
13221
  if (order_direction == -1)            // If order_st BY ... DESC
5136
13222
  {
5137
13223
    if (select && select->quick)
5138
13224
    {
5139
13225
      /*
5140
 
        Don't reverse the sort order, if it's already done.
 
13226
        Don't reverse the sort order, if it's already done.
5141
13227
        (In some cases test_if_order_by_key() can be called multiple times
5142
13228
      */
5143
 
      if (! select->quick->reverse_sorted())
 
13229
      if (!select->quick->reverse_sorted())
5144
13230
      {
5145
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
13231
        QUICK_SELECT_DESC *tmp;
5146
13232
        bool error= false;
5147
13233
        int quick_type= select->quick->get_type();
5148
 
        if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
5149
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT ||
5150
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
5151
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX)
 
13234
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
13235
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
13236
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
13237
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
5152
13238
        {
5153
13239
          tab->limit= 0;
5154
13240
          select->quick= save_quick;
5155
 
          return 0; // Use filesort
 
13241
          return(0);                   // Use filesort
5156
13242
        }
5157
13243
 
5158
 
        /* ORDER BY range_key DESC */
5159
 
        tmp= new optimizer::QuickSelectDescending((optimizer::QuickRangeSelect*)(select->quick),
5160
 
                                                  used_key_parts, 
5161
 
                                                  &error);
5162
 
        if (! tmp || error)
5163
 
        {
5164
 
          delete tmp;
 
13244
        /* order_st BY range_key DESC */
 
13245
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
13246
                                    used_key_parts, &error);
 
13247
        if (!tmp || error)
 
13248
        {
 
13249
          delete tmp;
5165
13250
          select->quick= save_quick;
5166
13251
          tab->limit= 0;
5167
 
          return 0; // Reverse sort not supported
5168
 
        }
5169
 
        select->quick=tmp;
 
13252
          return(0);            // Reverse sort not supported
 
13253
        }
 
13254
        select->quick=tmp;
5170
13255
      }
5171
13256
    }
5172
 
    else if (tab->type != AM_NEXT &&
 
13257
    else if (tab->type != JT_NEXT &&
5173
13258
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
5174
13259
    {
5175
13260
      /*
5176
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
13261
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
5177
13262
 
5178
 
        Use a traversal function that starts by reading the last row
5179
 
        with key part (A) and then traverse the index backwards.
 
13263
        Use a traversal function that starts by reading the last row
 
13264
        with key part (A) and then traverse the index backwards.
5180
13265
      */
5181
13266
      tab->read_first_record= join_read_last_key;
5182
13267
      tab->read_record.read_record= join_read_prev_same;
5184
13269
  }
5185
13270
  else if (select && select->quick)
5186
13271
    select->quick->sorted= 1;
5187
 
  return 1;
 
13272
  return(1);
5188
13273
}
5189
13274
 
 
13275
 
5190
13276
/*
5191
13277
  If not selecting by given key, create an index how records should be read
5192
13278
 
5193
13279
  SYNOPSIS
5194
13280
   create_sort_index()
5195
 
     session            Thread Cursor
 
13281
     session            Thread handler
5196
13282
     tab                Table to sort (in join structure)
5197
13283
     order              How table should be sorted
5198
13284
     filesort_limit     Max number of rows that needs to be sorted
5205
13291
  IMPLEMENTATION
5206
13292
   - If there is an index that can be used, 'tab' is modified to use
5207
13293
     this index.
5208
 
   - If no index, create with filesort() an index cursor that can be used to
 
13294
   - If no index, create with filesort() an index file that can be used to
5209
13295
     retrieve rows in order (should be done with 'read_record').
5210
13296
     The sorted data is stored in tab->table and will be freed when calling
5211
 
     tab->table->free_io_cache().
 
13297
     free_io_cache(tab->table).
5212
13298
 
5213
13299
  RETURN VALUES
5214
13300
    0           ok
5215
13301
    -1          Some fatal error
5216
13302
    1           No records
5217
13303
*/
5218
 
int create_sort_index(Session *session, JOIN *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
 
13304
 
 
13305
static int
 
13306
create_sort_index(Session *session, JOIN *join, order_st *order,
 
13307
                  ha_rows filesort_limit, ha_rows select_limit,
 
13308
                  bool is_order_by)
5219
13309
{
5220
13310
  uint32_t length= 0;
5221
13311
  ha_rows examined_rows;
5222
13312
  Table *table;
5223
 
  optimizer::SqlSelect *select= NULL;
5224
 
  JoinTable *tab;
 
13313
  SQL_SELECT *select;
 
13314
  JOIN_TAB *tab;
5225
13315
 
5226
13316
  if (join->tables == join->const_tables)
5227
13317
    return(0);                          // One row, no need to sort
5237
13327
  */
5238
13328
  if ((order != join->group_list ||
5239
13329
       !(join->select_options & SELECT_BIG_RESULT) ||
5240
 
       (select && select->quick && (select->quick->get_type() == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))) &&
 
13330
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
5241
13331
      test_if_skip_sort_order(tab,order,select_limit,0,
5242
13332
                              is_order_by ?  &table->keys_in_use_for_order_by :
5243
13333
                              &table->keys_in_use_for_group_by))
5246
13336
    length++;
5247
13337
  if (!(join->sortorder=
5248
13338
        make_unireg_sortorder(order, &length, join->sortorder)))
5249
 
    goto err;
 
13339
    goto err;                           /* purecov: inspected */
5250
13340
 
5251
 
  table->sort.io_cache= new internal::IO_CACHE;
5252
 
  memset(table->sort.io_cache, 0, sizeof(internal::IO_CACHE));
 
13341
  table->sort.io_cache= new IO_CACHE;
 
13342
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
5253
13343
  table->status=0;                              // May be wrong if quick_select
5254
13344
 
5255
13345
  // If table has a range, move it to select
5265
13355
      */
5266
13356
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
5267
13357
      {
5268
 
        table->key_read=0;
5269
 
        table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
13358
        table->key_read=0;
 
13359
        table->file->extra(HA_EXTRA_NO_KEYREAD);
5270
13360
      }
5271
13361
    }
5272
13362
    else
5273
13363
    {
5274
13364
      /*
5275
 
        We have a ref on a const;  Change this to a range that filesort
5276
 
        can use.
5277
 
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5278
 
        field, quick will contain an empty record set.
 
13365
        We have a ref on a const;  Change this to a range that filesort
 
13366
        can use.
 
13367
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
 
13368
        field, quick will contain an empty record set.
5279
13369
      */
5280
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
5281
 
                                                                 table, 
5282
 
                                                                 &tab->ref,
5283
 
                                                                 tab->found_records))))
5284
 
      {
5285
 
        goto err;
5286
 
      }
 
13370
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
13371
                                                     tab->found_records))))
 
13372
        goto err;
5287
13373
    }
5288
13374
  }
5289
13375
 
 
13376
  /* Fill schema tables with data before filesort if it's necessary */
 
13377
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
 
13378
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
 
13379
    goto err;
 
13380
 
5290
13381
  if (table->s->tmp_table)
5291
 
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
 
13382
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
5292
13383
  table->sort.found_records=filesort(session, table,join->sortorder, length,
5293
13384
                                     select, filesort_limit, 0,
5294
13385
                                     &examined_rows);
5301
13392
  tab->select_cond=0;
5302
13393
  tab->last_inner= 0;
5303
13394
  tab->first_unmatched= 0;
5304
 
  tab->type= AM_ALL;                            // Read with normal read_record
 
13395
  tab->type=JT_ALL;                             // Read with normal read_record
5305
13396
  tab->read_first_record= join_init_read_record;
5306
13397
  tab->join->examined_rows+=examined_rows;
5307
13398
  if (table->key_read)                          // Restore if we used indexes
5308
13399
  {
5309
13400
    table->key_read=0;
5310
 
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
13401
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5311
13402
  }
5312
13403
  return(table->sort.found_records == HA_POS_ERROR);
5313
13404
err:
5314
13405
  return(-1);
5315
13406
}
5316
13407
 
5317
 
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5318
 
{
5319
 
  Cursor *cursor=table->cursor;
 
13408
static bool copy_blobs(Field **ptr)
 
13409
{
 
13410
  for (; *ptr ; ptr++)
 
13411
  {
 
13412
    if ((*ptr)->flags & BLOB_FLAG)
 
13413
      if (((Field_blob *) (*ptr))->copy())
 
13414
        return 1;                               // Error
 
13415
  }
 
13416
  return 0;
 
13417
}
 
13418
 
 
13419
static void free_blobs(Field **ptr)
 
13420
{
 
13421
  for (; *ptr ; ptr++)
 
13422
  {
 
13423
    if ((*ptr)->flags & BLOB_FLAG)
 
13424
      ((Field_blob *) (*ptr))->free();
 
13425
  }
 
13426
}
 
13427
 
 
13428
 
 
13429
static int
 
13430
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
 
13431
{
 
13432
  int error;
 
13433
  uint32_t reclength,offset;
 
13434
  uint32_t field_count;
 
13435
  Session *session= join->session;
 
13436
 
 
13437
  entry->reginfo.lock_type=TL_WRITE;
 
13438
 
 
13439
  /* Calculate how many saved fields there is in list */
 
13440
  field_count=0;
 
13441
  List_iterator<Item> it(fields);
 
13442
  Item *item;
 
13443
  while ((item=it++))
 
13444
  {
 
13445
    if (item->get_tmp_table_field() && ! item->const_item())
 
13446
      field_count++;
 
13447
  }
 
13448
 
 
13449
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having)
 
13450
  {                    // only const items with no OPTION_FOUND_ROWS
 
13451
    join->unit->select_limit_cnt= 1;            // Only send first row
 
13452
    return(0);
 
13453
  }
 
13454
  Field **first_field=entry->field+entry->s->fields - field_count;
 
13455
  offset= (field_count ?
 
13456
           entry->field[entry->s->fields - field_count]->
 
13457
           offset(entry->record[0]) : 0);
 
13458
  reclength= entry->s->reclength-offset;
 
13459
 
 
13460
  free_io_cache(entry);                         // Safety
 
13461
  entry->file->info(HA_STATUS_VARIABLE);
 
13462
  if (entry->s->db_type() == heap_engine ||
 
13463
      (!entry->s->blob_fields &&
 
13464
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
 
13465
        session->variables.sortbuff_size)))
 
13466
    error= remove_dup_with_hash_index(join->session, entry,
 
13467
                                     field_count, first_field,
 
13468
                                     reclength, having);
 
13469
  else
 
13470
    error= remove_dup_with_compare(join->session, entry, first_field, offset,
 
13471
                                  having);
 
13472
 
 
13473
  free_blobs(first_field);
 
13474
  return(error);
 
13475
}
 
13476
 
 
13477
 
 
13478
static int remove_dup_with_compare(Session *session, Table *table, Field **first_field,
 
13479
                                   uint32_t offset, Item *having)
 
13480
{
 
13481
  handler *file=table->file;
5320
13482
  char *org_record,*new_record;
5321
13483
  unsigned char *record;
5322
13484
  int error;
5325
13487
  org_record=(char*) (record=table->record[0])+offset;
5326
13488
  new_record=(char*) table->record[1]+offset;
5327
13489
 
5328
 
  cursor->ha_rnd_init(1);
5329
 
  error=cursor->rnd_next(record);
 
13490
  file->ha_rnd_init(1);
 
13491
  error=file->rnd_next(record);
5330
13492
  for (;;)
5331
13493
  {
5332
13494
    if (session->killed)
5338
13500
    if (error)
5339
13501
    {
5340
13502
      if (error == HA_ERR_RECORD_DELETED)
5341
 
        continue;
 
13503
        continue;
5342
13504
      if (error == HA_ERR_END_OF_FILE)
5343
 
        break;
 
13505
        break;
5344
13506
      goto err;
5345
13507
    }
5346
13508
    if (having && !having->val_int())
5347
13509
    {
5348
 
      if ((error=cursor->ha_delete_row(record)))
5349
 
        goto err;
5350
 
      error=cursor->rnd_next(record);
 
13510
      if ((error=file->ha_delete_row(record)))
 
13511
        goto err;
 
13512
      error=file->rnd_next(record);
5351
13513
      continue;
5352
13514
    }
5353
13515
    if (copy_blobs(first_field))
5358
13520
    }
5359
13521
    memcpy(new_record,org_record,reclength);
5360
13522
 
5361
 
    /* Read through rest of cursor and mark duplicated rows deleted */
 
13523
    /* Read through rest of file and mark duplicated rows deleted */
5362
13524
    bool found=0;
5363
13525
    for (;;)
5364
13526
    {
5365
 
      if ((error=cursor->rnd_next(record)))
 
13527
      if ((error=file->rnd_next(record)))
5366
13528
      {
5367
 
        if (error == HA_ERR_RECORD_DELETED)
5368
 
          continue;
5369
 
        if (error == HA_ERR_END_OF_FILE)
5370
 
          break;
5371
 
        goto err;
 
13529
        if (error == HA_ERR_RECORD_DELETED)
 
13530
          continue;
 
13531
        if (error == HA_ERR_END_OF_FILE)
 
13532
          break;
 
13533
        goto err;
5372
13534
      }
5373
13535
      if (table->compare_record(first_field) == 0)
5374
13536
      {
5375
 
        if ((error=cursor->ha_delete_row(record)))
5376
 
          goto err;
 
13537
        if ((error=file->ha_delete_row(record)))
 
13538
          goto err;
5377
13539
      }
5378
13540
      else if (!found)
5379
13541
      {
5380
 
        found= 1;
5381
 
        cursor->position(record);       // Remember position
 
13542
        found=1;
 
13543
        file->position(record); // Remember position
5382
13544
      }
5383
13545
    }
5384
13546
    if (!found)
5385
 
      break;                                    // End of cursor
 
13547
      break;                                    // End of file
5386
13548
    /* Restart search on next row */
5387
 
    error=cursor->restart_rnd_next(record,cursor->ref);
 
13549
    error=file->restart_rnd_next(record,file->ref);
5388
13550
  }
5389
13551
 
5390
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
13552
  file->extra(HA_EXTRA_NO_CACHE);
5391
13553
  return(0);
5392
13554
err:
5393
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
13555
  file->extra(HA_EXTRA_NO_CACHE);
5394
13556
  if (error)
5395
 
    table->print_error(error,MYF(0));
 
13557
    file->print_error(error,MYF(0));
5396
13558
  return(1);
5397
13559
}
5398
13560
 
 
13561
 
5399
13562
/**
5400
13563
  Generate a hash index for each row to quickly find duplicate rows.
5401
13564
 
5402
13565
  @note
5403
13566
    Note that this will not work on tables with blobs!
5404
13567
*/
5405
 
int remove_dup_with_hash_index(Session *session, 
5406
 
                               Table *table,
5407
 
                               uint32_t field_count,
5408
 
                               Field **first_field,
5409
 
                               uint32_t key_length,
5410
 
                               Item *having)
 
13568
 
 
13569
static int remove_dup_with_hash_index(Session *session, Table *table,
 
13570
                                      uint32_t field_count,
 
13571
                                      Field **first_field,
 
13572
                                      uint32_t key_length,
 
13573
                                      Item *having)
5411
13574
{
5412
13575
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5413
13576
  int error;
5414
 
  Cursor *cursor= table->cursor;
 
13577
  handler *file= table->file;
5415
13578
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5416
13579
  uint32_t *field_lengths,*field_length;
5417
13580
  HASH hash;
5418
13581
 
5419
 
  if (! memory::multi_malloc(false,
 
13582
  if (!my_multi_malloc(MYF(MY_WME),
5420
13583
                       &key_buffer,
5421
13584
                       (uint32_t) ((key_length + extra_length) *
5422
 
                               (long) cursor->stats.records),
 
13585
                               (long) file->stats.records),
5423
13586
                       &field_lengths,
5424
13587
                       (uint32_t) (field_count*sizeof(*field_lengths)),
5425
13588
                       NULL))
5439
13602
    extra_length= ALIGN_SIZE(key_length)-key_length;
5440
13603
  }
5441
13604
 
5442
 
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor->stats.records, 0,
 
13605
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
5443
13606
                key_length, (hash_get_key) 0, 0, 0))
5444
13607
  {
5445
13608
    free((char*) key_buffer);
5446
13609
    return(1);
5447
13610
  }
5448
13611
 
5449
 
  cursor->ha_rnd_init(1);
 
13612
  file->ha_rnd_init(1);
5450
13613
  key_pos=key_buffer;
5451
13614
  for (;;)
5452
13615
  {
5457
13620
      error=0;
5458
13621
      goto err;
5459
13622
    }
5460
 
    if ((error=cursor->rnd_next(record)))
 
13623
    if ((error=file->rnd_next(record)))
5461
13624
    {
5462
13625
      if (error == HA_ERR_RECORD_DELETED)
5463
 
        continue;
 
13626
        continue;
5464
13627
      if (error == HA_ERR_END_OF_FILE)
5465
 
        break;
 
13628
        break;
5466
13629
      goto err;
5467
13630
    }
5468
13631
    if (having && !having->val_int())
5469
13632
    {
5470
 
      if ((error=cursor->ha_delete_row(record)))
5471
 
        goto err;
 
13633
      if ((error=file->ha_delete_row(record)))
 
13634
        goto err;
5472
13635
      continue;
5473
13636
    }
5474
13637
 
5484
13647
    if (hash_search(&hash, org_key_pos, key_length))
5485
13648
    {
5486
13649
      /* Duplicated found ; Remove the row */
5487
 
      if ((error=cursor->ha_delete_row(record)))
5488
 
        goto err;
 
13650
      if ((error=file->ha_delete_row(record)))
 
13651
        goto err;
5489
13652
    }
5490
13653
    else
5491
13654
      (void) my_hash_insert(&hash, org_key_pos);
5493
13656
  }
5494
13657
  free((char*) key_buffer);
5495
13658
  hash_free(&hash);
5496
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5497
 
  (void) cursor->ha_rnd_end();
 
13659
  file->extra(HA_EXTRA_NO_CACHE);
 
13660
  (void) file->ha_rnd_end();
5498
13661
  return(0);
5499
13662
 
5500
13663
err:
5501
13664
  free((char*) key_buffer);
5502
13665
  hash_free(&hash);
5503
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5504
 
  (void) cursor->ha_rnd_end();
 
13666
  file->extra(HA_EXTRA_NO_CACHE);
 
13667
  (void) file->ha_rnd_end();
5505
13668
  if (error)
5506
 
    table->print_error(error,MYF(0));
 
13669
    file->print_error(error,MYF(0));
5507
13670
  return(1);
5508
13671
}
5509
13672
 
5510
 
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length, SORT_FIELD *sortorder)
 
13673
 
 
13674
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length,
 
13675
                                  SORT_FIELD *sortorder)
5511
13676
{
5512
13677
  uint32_t count;
5513
13678
  SORT_FIELD *sort,*pos;
5516
13681
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5517
13682
    count++;
5518
13683
  if (!sortorder)
5519
 
    sortorder= (SORT_FIELD*) memory::sql_alloc(sizeof(SORT_FIELD) *
5520
 
                                       (max(count, *length) + 1));
 
13684
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
 
13685
                                       (cmax(count, *length) + 1));
5521
13686
  pos= sort= sortorder;
5522
13687
 
5523
13688
  if (!pos)
5543
13708
  return(sort);
5544
13709
}
5545
13710
 
 
13711
 
 
13712
/*****************************************************************************
 
13713
  Fill join cache with packed records
 
13714
  Records are stored in tab->cache.buffer and last record in
 
13715
  last record is stored with pointers to blobs to support very big
 
13716
  records
 
13717
******************************************************************************/
 
13718
 
 
13719
static int
 
13720
join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count)
 
13721
{
 
13722
  register unsigned int i;
 
13723
  unsigned int length, blobs;
 
13724
  size_t size;
 
13725
  CACHE_FIELD *copy,**blob_ptr;
 
13726
  JOIN_CACHE  *cache;
 
13727
  JOIN_TAB *join_tab;
 
13728
 
 
13729
  cache= &tables[table_count].cache;
 
13730
  cache->fields=blobs=0;
 
13731
 
 
13732
  join_tab=tables;
 
13733
  for (i=0 ; i < table_count ; i++,join_tab++)
 
13734
  {
 
13735
    if (!join_tab->used_fieldlength)            /* Not calced yet */
 
13736
      calc_used_field_length(session, join_tab);
 
13737
    cache->fields+=join_tab->used_fields;
 
13738
    blobs+=join_tab->used_blobs;
 
13739
 
 
13740
    /* SemiJoinDuplicateElimination: reserve space for rowid */
 
13741
    if (join_tab->rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
 
13742
    {
 
13743
      cache->fields++;
 
13744
      join_tab->used_fieldlength += join_tab->table->file->ref_length;
 
13745
    }
 
13746
  }
 
13747
  if (!(cache->field=(CACHE_FIELD*)
 
13748
        sql_alloc(sizeof(CACHE_FIELD)*(cache->fields+table_count*2)+(blobs+1)*
 
13749
 
 
13750
                  sizeof(CACHE_FIELD*))))
 
13751
  {
 
13752
    free((unsigned char*) cache->buff);         /* purecov: inspected */
 
13753
    cache->buff=0;                              /* purecov: inspected */
 
13754
    return(1);                          /* purecov: inspected */
 
13755
  }
 
13756
  copy=cache->field;
 
13757
  blob_ptr=cache->blob_ptr=(CACHE_FIELD**)
 
13758
    (cache->field+cache->fields+table_count*2);
 
13759
 
 
13760
  length=0;
 
13761
  for (i=0 ; i < table_count ; i++)
 
13762
  {
 
13763
    uint32_t null_fields=0, used_fields;
 
13764
    Field **f_ptr,*field;
 
13765
    bitset<MAX_FIELDS> *read_set= tables[i].table->read_set;
 
13766
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
 
13767
         used_fields ;
 
13768
         f_ptr++)
 
13769
    {
 
13770
      field= *f_ptr;
 
13771
      if (read_set->test(field->field_index))
 
13772
      {
 
13773
        used_fields--;
 
13774
        length+=field->fill_cache_field(copy);
 
13775
        if (copy->blob_field)
 
13776
          (*blob_ptr++)=copy;
 
13777
        if (field->maybe_null())
 
13778
          null_fields++;
 
13779
        copy->get_rowid= NULL;
 
13780
        copy++;
 
13781
      }
 
13782
    }
 
13783
    /* Copy null bits from table */
 
13784
    if (null_fields && tables[i].table->getNullFields())
 
13785
    {                                           /* must copy null bits */
 
13786
      copy->str= tables[i].table->null_flags;
 
13787
      copy->length= tables[i].table->s->null_bytes;
 
13788
      copy->strip=0;
 
13789
      copy->blob_field=0;
 
13790
      copy->get_rowid= NULL;
 
13791
      length+=copy->length;
 
13792
      copy++;
 
13793
      cache->fields++;
 
13794
    }
 
13795
    /* If outer join table, copy null_row flag */
 
13796
    if (tables[i].table->maybe_null)
 
13797
    {
 
13798
      copy->str= (unsigned char*) &tables[i].table->null_row;
 
13799
      copy->length=sizeof(tables[i].table->null_row);
 
13800
      copy->strip=0;
 
13801
      copy->blob_field=0;
 
13802
      copy->get_rowid= NULL;
 
13803
      length+=copy->length;
 
13804
      copy++;
 
13805
      cache->fields++;
 
13806
    }
 
13807
    /* SemiJoinDuplicateElimination: Allocate space for rowid if needed */
 
13808
    if (tables[i].rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
 
13809
    {
 
13810
      copy->str= tables[i].table->file->ref;
 
13811
      copy->length= tables[i].table->file->ref_length;
 
13812
      copy->strip=0;
 
13813
      copy->blob_field=0;
 
13814
      copy->get_rowid= NULL;
 
13815
      if (tables[i].rowid_keep_flags & JOIN_TAB::CALL_POSITION)
 
13816
      {
 
13817
        /* We will need to call h->position(): */
 
13818
        copy->get_rowid= tables[i].table;
 
13819
        /* And those after us won't have to: */
 
13820
        tables[i].rowid_keep_flags &=  ~((int)JOIN_TAB::CALL_POSITION);
 
13821
      }
 
13822
      copy++;
 
13823
    }
 
13824
  }
 
13825
 
 
13826
  cache->length=length+blobs*sizeof(char*);
 
13827
  cache->blobs=blobs;
 
13828
  *blob_ptr= NULL;                                      /* End sequentel */
 
13829
  size= max((size_t)session->variables.join_buff_size,
 
13830
            (size_t)cache->length);
 
13831
  if (!(cache->buff=(unsigned char*) malloc(size)))
 
13832
    return 1;                           /* Don't use cache */ /* purecov: inspected */
 
13833
  cache->end= cache->buff+size;
 
13834
  reset_cache_write(cache);
 
13835
  return 0;
 
13836
}
 
13837
 
 
13838
 
 
13839
static uint32_t used_blob_length(CACHE_FIELD **ptr)
 
13840
{
 
13841
  uint32_t length,blob_length;
 
13842
  for (length=0 ; *ptr ; ptr++)
 
13843
  {
 
13844
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
 
13845
    length+=blob_length;
 
13846
    (*ptr)->blob_field->get_ptr(&(*ptr)->str);
 
13847
  }
 
13848
  return length;
 
13849
}
 
13850
 
 
13851
 
 
13852
static bool
 
13853
store_record_in_cache(JOIN_CACHE *cache)
 
13854
{
 
13855
  uint32_t length;
 
13856
  unsigned char *pos;
 
13857
  CACHE_FIELD *copy,*end_field;
 
13858
  bool last_record;
 
13859
 
 
13860
  pos=cache->pos;
 
13861
  end_field=cache->field+cache->fields;
 
13862
 
 
13863
  length=cache->length;
 
13864
  if (cache->blobs)
 
13865
    length+= used_blob_length(cache->blob_ptr);
 
13866
  if ((last_record= (length + cache->length > (size_t) (cache->end - pos))))
 
13867
    cache->ptr_record=cache->records;
 
13868
  /*
 
13869
    There is room in cache. Put record there
 
13870
  */
 
13871
  cache->records++;
 
13872
  for (copy=cache->field ; copy < end_field; copy++)
 
13873
  {
 
13874
    if (copy->blob_field)
 
13875
    {
 
13876
      if (last_record)
 
13877
      {
 
13878
        copy->blob_field->get_image(pos, copy->length+sizeof(char*),
 
13879
                                    copy->blob_field->charset());
 
13880
        pos+=copy->length+sizeof(char*);
 
13881
      }
 
13882
      else
 
13883
      {
 
13884
        copy->blob_field->get_image(pos, copy->length, // blob length
 
13885
                                    copy->blob_field->charset());
 
13886
        memcpy(pos+copy->length,copy->str,copy->blob_length);  // Blob data
 
13887
        pos+=copy->length+copy->blob_length;
 
13888
      }
 
13889
    }
 
13890
    else
 
13891
    {
 
13892
      // SemiJoinDuplicateElimination: Get the rowid into table->ref:
 
13893
      if (copy->get_rowid)
 
13894
        copy->get_rowid->file->position(copy->get_rowid->record[0]);
 
13895
 
 
13896
      if (copy->strip)
 
13897
      {
 
13898
        unsigned char *str,*end;
 
13899
        for (str=copy->str,end= str+copy->length;
 
13900
             end > str && end[-1] == ' ' ;
 
13901
             end--) ;
 
13902
        length=(uint32_t) (end-str);
 
13903
        memcpy(pos+2, str, length);
 
13904
        int2store(pos, length);
 
13905
        pos+= length+2;
 
13906
      }
 
13907
      else
 
13908
      {
 
13909
        memcpy(pos,copy->str,copy->length);
 
13910
        pos+=copy->length;
 
13911
      }
 
13912
    }
 
13913
  }
 
13914
  cache->pos=pos;
 
13915
  return last_record || (size_t) (cache->end - pos) < cache->length;
 
13916
}
 
13917
 
 
13918
 
 
13919
static void
 
13920
reset_cache_read(JOIN_CACHE *cache)
 
13921
{
 
13922
  cache->record_nr=0;
 
13923
  cache->pos=cache->buff;
 
13924
}
 
13925
 
 
13926
 
 
13927
static void reset_cache_write(JOIN_CACHE *cache)
 
13928
{
 
13929
  reset_cache_read(cache);
 
13930
  cache->records= 0;
 
13931
  cache->ptr_record= UINT32_MAX;
 
13932
}
 
13933
 
 
13934
 
 
13935
static void
 
13936
read_cached_record(JOIN_TAB *tab)
 
13937
{
 
13938
  unsigned char *pos;
 
13939
  uint32_t length;
 
13940
  bool last_record;
 
13941
  CACHE_FIELD *copy,*end_field;
 
13942
 
 
13943
  last_record=tab->cache.record_nr++ == tab->cache.ptr_record;
 
13944
  pos=tab->cache.pos;
 
13945
  for (copy=tab->cache.field,end_field=copy+tab->cache.fields ;
 
13946
       copy < end_field;
 
13947
       copy++)
 
13948
  {
 
13949
    if (copy->blob_field)
 
13950
    {
 
13951
      if (last_record)
 
13952
      {
 
13953
        copy->blob_field->set_image(pos, copy->length+sizeof(char*),
 
13954
                                    copy->blob_field->charset());
 
13955
        pos+=copy->length+sizeof(char*);
 
13956
      }
 
13957
      else
 
13958
      {
 
13959
        copy->blob_field->set_ptr(pos, pos+copy->length);
 
13960
        pos+=copy->length+copy->blob_field->get_length();
 
13961
      }
 
13962
    }
 
13963
    else
 
13964
    {
 
13965
      if (copy->strip)
 
13966
      {
 
13967
        length= uint2korr(pos);
 
13968
        memcpy(copy->str, pos+2, length);
 
13969
        memset(copy->str+length, ' ', copy->length-length);
 
13970
        pos+= 2 + length;
 
13971
      }
 
13972
      else
 
13973
      {
 
13974
        memcpy(copy->str,pos,copy->length);
 
13975
        pos+=copy->length;
 
13976
      }
 
13977
    }
 
13978
  }
 
13979
  tab->cache.pos=pos;
 
13980
  return;
 
13981
}
 
13982
 
 
13983
 
5546
13984
/*
5547
13985
  eq_ref: Create the lookup key and check if it is the same as saved key
5548
13986
 
5561
13999
    false  The created key is the same as the previous one (and the record
5562
14000
           is already in table->record)
5563
14001
*/
5564
 
static bool cmp_buffer_with_ref(JoinTable *tab)
 
14002
 
 
14003
static bool
 
14004
cmp_buffer_with_ref(JOIN_TAB *tab)
5565
14005
{
5566
14006
  bool no_prev_key;
5567
14007
  if (!tab->ref.disable_cache)
5581
14021
    != 0;
5582
14022
}
5583
14023
 
5584
 
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
 
14024
 
 
14025
bool
 
14026
cp_buffer_from_ref(Session *session, TABLE_REF *ref)
5585
14027
{
5586
14028
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
5587
14029
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
5588
14030
  bool result= 0;
5589
14031
 
5590
 
  for (StoredKey **copy=ref->key_copy ; *copy ; copy++)
 
14032
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
5591
14033
  {
5592
14034
    if ((*copy)->copy() & 1)
5593
14035
    {
5599
14041
  return result;
5600
14042
}
5601
14043
 
 
14044
 
5602
14045
/*****************************************************************************
5603
14046
  Group and order functions
5604
14047
*****************************************************************************/
5605
14048
 
5606
14049
/**
5607
 
  Resolve an ORDER BY or GROUP BY column reference.
 
14050
  Resolve an order_st BY or GROUP BY column reference.
5608
14051
 
5609
14052
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5610
14053
  BY clause, find the actual column it represents. If the column being
5611
14054
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5612
14055
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
5613
 
  the ORDER BY clause, only the SELECT list is being searched.
 
14056
  the order_st BY clause, only the SELECT list is being searched.
5614
14057
 
5615
14058
  If 'order' is resolved to an Item, then order->item is set to the found
5616
14059
  Item. If there is no item for the found column (that is, it was resolved
5635
14078
  @retval
5636
14079
    true  if error occurred
5637
14080
*/
5638
 
static bool find_order_in_list(Session *session, 
5639
 
                               Item **ref_pointer_array, 
5640
 
                               TableList *tables,
5641
 
                               order_st *order,
5642
 
                               List<Item> &fields,
5643
 
                               List<Item> &all_fields,
5644
 
                               bool is_group_field)
 
14081
 
 
14082
static bool
 
14083
find_order_in_list(Session *session, Item **ref_pointer_array, TableList *tables,
 
14084
                   order_st *order, List<Item> &fields, List<Item> &all_fields,
 
14085
                   bool is_group_field)
5645
14086
{
5646
14087
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
5647
14088
  Item::Type order_item_type;
5696
14137
        order_item_type == Item::REF_ITEM)
5697
14138
    {
5698
14139
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5699
 
                                       NULL, &view_ref, IGNORE_ERRORS, false);
 
14140
                                       NULL, &view_ref, IGNORE_ERRORS, true,
 
14141
                                       false);
5700
14142
      if (!from_field)
5701
14143
        from_field= (Field*) not_found_field;
5702
14144
    }
5766
14208
  return false;
5767
14209
}
5768
14210
 
 
14211
 
5769
14212
/**
5770
14213
  Change order to point at item in select list.
5771
14214
 
5772
14215
  If item isn't a number and doesn't exits in the select list, add it the
5773
14216
  the field list.
5774
14217
*/
5775
 
int setup_order(Session *session,
5776
 
                Item **ref_pointer_array,
5777
 
                TableList *tables,
5778
 
                            List<Item> &fields,
5779
 
                List<Item> &all_fields,
5780
 
                order_st *order)
 
14218
 
 
14219
int setup_order(Session *session, Item **ref_pointer_array, TableList *tables,
 
14220
                List<Item> &fields, List<Item> &all_fields, order_st *order)
5781
14221
{
5782
14222
  session->where="order clause";
5783
14223
  for (; order; order=order->next)
5789
14229
  return 0;
5790
14230
}
5791
14231
 
 
14232
 
5792
14233
/**
5793
14234
  Intitialize the GROUP BY list.
5794
14235
 
5795
 
  @param session                        Thread Cursor
 
14236
  @param session                        Thread handler
5796
14237
  @param ref_pointer_array      We store references to all fields that was
5797
14238
                               not in 'fields' here.
5798
14239
  @param fields         All fields in the select part. Any item in
5814
14255
  @retval
5815
14256
    1  error (probably out of memory)
5816
14257
*/
5817
 
int setup_group(Session *session,
5818
 
                Item **ref_pointer_array,
5819
 
                TableList *tables,
5820
 
                      List<Item> &fields,
5821
 
                List<Item> &all_fields,
5822
 
                order_st *order,
5823
 
                      bool *hidden_group_fields)
 
14258
 
 
14259
int
 
14260
setup_group(Session *session, Item **ref_pointer_array, TableList *tables,
 
14261
            List<Item> &fields, List<Item> &all_fields, order_st *order,
 
14262
            bool *hidden_group_fields)
5824
14263
{
5825
14264
  *hidden_group_fields=0;
5826
14265
  order_st *ord;
5913
14352
  Try to use the fields in the order given by 'order' to allow one to
5914
14353
  optimize away 'order by'.
5915
14354
*/
5916
 
order_st *create_distinct_group(Session *session,
5917
 
                                Item **ref_pointer_array,
5918
 
                                order_st *order_list,
5919
 
                                List<Item> &fields,
5920
 
                                List<Item> &,
5921
 
                                bool *all_order_by_fields_used)
 
14355
 
 
14356
static order_st *
 
14357
create_distinct_group(Session *session, Item **ref_pointer_array,
 
14358
                      order_st *order_list, List<Item> &fields,
 
14359
                      List<Item> &, bool *all_order_by_fields_used)
5922
14360
{
5923
14361
  List_iterator<Item> li(fields);
5924
14362
  Item *item;
5935
14373
    {
5936
14374
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
5937
14375
      if (!ord)
5938
 
        return 0;
 
14376
        return 0;
5939
14377
      *prev=ord;
5940
14378
      prev= &ord->next;
5941
14379
      (*ord->item)->marker=1;
5960
14398
 
5961
14399
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
5962
14400
      if (!ord)
5963
 
        return 0;
 
14401
        return 0;
5964
14402
 
5965
14403
      /*
5966
14404
        We have here only field_list (not all_field_list), so we can use
5979
14417
  return group;
5980
14418
}
5981
14419
 
 
14420
 
5982
14421
/**
5983
14422
  Update join with count of the different type of fields.
5984
14423
*/
5985
 
void count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param, List<Item> &fields, bool reset_with_sum_func)
 
14424
 
 
14425
void
 
14426
count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param,
 
14427
                  List<Item> &fields, bool reset_with_sum_func)
5986
14428
{
5987
14429
  List_iterator<Item> li(fields);
5988
14430
  Item *field;
5999
14441
    {
6000
14442
      if (! field->const_item())
6001
14443
      {
6002
 
        Item_sum *sum_item=(Item_sum*) field->real_item();
 
14444
        Item_sum *sum_item=(Item_sum*) field->real_item();
6003
14445
        if (!sum_item->depended_from() ||
6004
14446
            sum_item->depended_from() == select_lex)
6005
14447
        {
6022
14464
    {
6023
14465
      param->func_count++;
6024
14466
      if (reset_with_sum_func)
6025
 
        field->with_sum_func=0;
6026
 
    }
6027
 
  }
6028
 
}
 
14467
        field->with_sum_func=0;
 
14468
    }
 
14469
  }
 
14470
}
 
14471
 
 
14472
 
 
14473
/**
 
14474
  Return 1 if second is a subpart of first argument.
 
14475
 
 
14476
  If first parts has different direction, change it to second part
 
14477
  (group is sorted like order)
 
14478
*/
 
14479
 
 
14480
static bool
 
14481
test_if_subpart(order_st *a,order_st *b)
 
14482
{
 
14483
  for (; a && b; a=a->next,b=b->next)
 
14484
  {
 
14485
    if ((*a->item)->eq(*b->item,1))
 
14486
      a->asc=b->asc;
 
14487
    else
 
14488
      return 0;
 
14489
  }
 
14490
  return test(!b);
 
14491
}
 
14492
 
 
14493
/**
 
14494
  Return table number if there is only one table in sort order
 
14495
  and group and order is compatible, else return 0.
 
14496
*/
 
14497
 
 
14498
static Table *
 
14499
get_sort_by_table(order_st *a,order_st *b,TableList *tables)
 
14500
{
 
14501
  table_map map= (table_map) 0;
 
14502
 
 
14503
  if (!a)
 
14504
    a=b;                                        // Only one need to be given
 
14505
  else if (!b)
 
14506
    b=a;
 
14507
 
 
14508
  for (; a && b; a=a->next,b=b->next)
 
14509
  {
 
14510
    if (!(*a->item)->eq(*b->item,1))
 
14511
      return(0);
 
14512
    map|=a->item[0]->used_tables();
 
14513
  }
 
14514
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
 
14515
    return(0);
 
14516
 
 
14517
  for (; !(map & tables->table->map); tables= tables->next_leaf) {};
 
14518
  if (map != tables->table->map)
 
14519
    return(0);                          // More than one table
 
14520
  return(tables->table);
 
14521
}
 
14522
 
 
14523
 
 
14524
/**
 
14525
  calc how big buffer we need for comparing group entries.
 
14526
*/
 
14527
 
 
14528
static void
 
14529
calc_group_buffer(JOIN *join,order_st *group)
 
14530
{
 
14531
  uint32_t key_length=0, parts=0, null_parts=0;
 
14532
 
 
14533
  if (group)
 
14534
    join->group= 1;
 
14535
  for (; group ; group=group->next)
 
14536
  {
 
14537
    Item *group_item= *group->item;
 
14538
    Field *field= group_item->get_tmp_table_field();
 
14539
    if (field)
 
14540
    {
 
14541
      enum_field_types type;
 
14542
      if ((type= field->type()) == DRIZZLE_TYPE_BLOB)
 
14543
        key_length+=MAX_BLOB_WIDTH;             // Can't be used as a key
 
14544
      else if (type == DRIZZLE_TYPE_VARCHAR)
 
14545
        key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
 
14546
      else
 
14547
        key_length+= field->pack_length();
 
14548
    }
 
14549
    else
 
14550
    {
 
14551
      switch (group_item->result_type()) {
 
14552
      case REAL_RESULT:
 
14553
        key_length+= sizeof(double);
 
14554
        break;
 
14555
      case INT_RESULT:
 
14556
        key_length+= sizeof(int64_t);
 
14557
        break;
 
14558
      case DECIMAL_RESULT:
 
14559
        key_length+= my_decimal_get_binary_size(group_item->max_length -
 
14560
                                                (group_item->decimals ? 1 : 0),
 
14561
                                                group_item->decimals);
 
14562
        break;
 
14563
      case STRING_RESULT:
 
14564
      {
 
14565
        enum enum_field_types type= group_item->field_type();
 
14566
        /*
 
14567
          As items represented as DATE/TIME fields in the group buffer
 
14568
          have STRING_RESULT result type, we increase the length
 
14569
          by 8 as maximum pack length of such fields.
 
14570
        */
 
14571
        if (type == DRIZZLE_TYPE_DATE ||
 
14572
            type == DRIZZLE_TYPE_DATETIME ||
 
14573
            type == DRIZZLE_TYPE_TIMESTAMP)
 
14574
        {
 
14575
          key_length+= 8;
 
14576
        }
 
14577
        else
 
14578
        {
 
14579
          /*
 
14580
            Group strings are taken as varstrings and require an length field.
 
14581
            A field is not yet created by create_tmp_field()
 
14582
            and the sizes should match up.
 
14583
          */
 
14584
          key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
 
14585
        }
 
14586
        break;
 
14587
      }
 
14588
      default:
 
14589
        /* This case should never be choosen */
 
14590
        assert(0);
 
14591
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
14592
      }
 
14593
    }
 
14594
    parts++;
 
14595
    if (group_item->maybe_null)
 
14596
      null_parts++;
 
14597
  }
 
14598
  join->tmp_table_param.group_length=key_length+null_parts;
 
14599
  join->tmp_table_param.group_parts=parts;
 
14600
  join->tmp_table_param.group_null_parts=null_parts;
 
14601
}
 
14602
 
 
14603
 
 
14604
/**
 
14605
  allocate group fields or take prepared (cached).
 
14606
 
 
14607
  @param main_join   join of current select
 
14608
  @param curr_join   current join (join of current select or temporary copy
 
14609
                     of it)
 
14610
 
 
14611
  @retval
 
14612
    0   ok
 
14613
  @retval
 
14614
    1   failed
 
14615
*/
 
14616
 
 
14617
static bool
 
14618
make_group_fields(JOIN *main_join, JOIN *curr_join)
 
14619
{
 
14620
  if (main_join->group_fields_cache.elements)
 
14621
  {
 
14622
    curr_join->group_fields= main_join->group_fields_cache;
 
14623
    curr_join->sort_and_group= 1;
 
14624
  }
 
14625
  else
 
14626
  {
 
14627
    if (alloc_group_fields(curr_join, curr_join->group_list))
 
14628
      return (1);
 
14629
    main_join->group_fields_cache= curr_join->group_fields;
 
14630
  }
 
14631
  return (0);
 
14632
}
 
14633
 
 
14634
 
 
14635
/**
 
14636
  Get a list of buffers for saveing last group.
 
14637
 
 
14638
  Groups are saved in reverse order for easyer check loop.
 
14639
*/
 
14640
 
 
14641
static bool
 
14642
alloc_group_fields(JOIN *join,order_st *group)
 
14643
{
 
14644
  if (group)
 
14645
  {
 
14646
    for (; group ; group=group->next)
 
14647
    {
 
14648
      Cached_item *tmp=new_Cached_item(join->session, *group->item, false);
 
14649
      if (!tmp || join->group_fields.push_front(tmp))
 
14650
        return true;
 
14651
    }
 
14652
  }
 
14653
  join->sort_and_group=1;                       /* Mark for do_select */
 
14654
  return false;
 
14655
}
 
14656
 
6029
14657
 
6030
14658
/*
6031
14659
  Test if a single-row cache of items changed, and update the cache.
6039
14667
  @return -1 if no item changed
6040
14668
  @return index of the first item that changed
6041
14669
*/
 
14670
 
6042
14671
int test_if_item_cache_changed(List<Cached_item> &list)
6043
14672
{
6044
14673
  List_iterator<Cached_item> li(list);
6053
14682
  return(idx);
6054
14683
}
6055
14684
 
 
14685
 
6056
14686
/**
6057
14687
  Setup copy_fields to save fields at start of new group.
6058
14688
 
6081
14711
  @retval
6082
14712
    !=0   error
6083
14713
*/
6084
 
bool setup_copy_fields(Session *session,
6085
 
                       Tmp_Table_Param *param,
6086
 
                       Item **ref_pointer_array,
6087
 
                       List<Item> &res_selected_fields,
6088
 
                       List<Item> &res_all_fields,
6089
 
                       uint32_t elements,
6090
 
                       List<Item> &all_fields)
 
14714
 
 
14715
bool
 
14716
setup_copy_fields(Session *session, Tmp_Table_Param *param,
 
14717
                  Item **ref_pointer_array,
 
14718
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
 
14719
                  uint32_t elements, List<Item> &all_fields)
6091
14720
{
6092
14721
  Item *pos;
6093
14722
  List_iterator_fast<Item> li(all_fields);
6094
 
  CopyField *copy= NULL;
 
14723
  Copy_field *copy= NULL;
6095
14724
  res_selected_fields.empty();
6096
14725
  res_all_fields.empty();
6097
14726
  List_iterator_fast<Item> itr(res_all_fields);
6099
14728
  uint32_t i, border= all_fields.elements - elements;
6100
14729
 
6101
14730
  if (param->field_count &&
6102
 
      !(copy=param->copy_field= new CopyField[param->field_count]))
 
14731
      !(copy=param->copy_field= new Copy_field[param->field_count]))
6103
14732
    goto err2;
6104
14733
 
6105
14734
  param->copy_funcs.empty();
6112
14741
    {
6113
14742
      Item_field *item;
6114
14743
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
6115
 
        goto err;
 
14744
        goto err;
6116
14745
      if (pos->type() == Item::REF_ITEM)
6117
14746
      {
6118
14747
        /* preserve the names of the ref when dereferncing */
6124
14753
      pos= item;
6125
14754
      if (item->field->flags & BLOB_FLAG)
6126
14755
      {
6127
 
        if (!(pos= new Item_copy_string(pos)))
6128
 
          goto err;
6129
 
            /*
6130
 
              Item_copy_string::copy for function can call
6131
 
              Item_copy_string::val_int for blob via Item_ref.
6132
 
              But if Item_copy_string::copy for blob isn't called before,
6133
 
              it's value will be wrong
6134
 
              so let's insert Item_copy_string for blobs in the beginning of
6135
 
              copy_funcs
6136
 
              (to see full test case look at having.test, BUG #4358)
6137
 
            */
6138
 
        if (param->copy_funcs.push_front(pos))
6139
 
          goto err;
 
14756
        if (!(pos= new Item_copy_string(pos)))
 
14757
          goto err;
 
14758
       /*
 
14759
         Item_copy_string::copy for function can call
 
14760
         Item_copy_string::val_int for blob via Item_ref.
 
14761
         But if Item_copy_string::copy for blob isn't called before,
 
14762
         it's value will be wrong
 
14763
         so let's insert Item_copy_string for blobs in the beginning of
 
14764
         copy_funcs
 
14765
         (to see full test case look at having.test, BUG #4358)
 
14766
       */
 
14767
        if (param->copy_funcs.push_front(pos))
 
14768
          goto err;
6140
14769
      }
6141
14770
      else
6142
14771
      {
 
14772
        /*
 
14773
           set up save buffer and change result_field to point at
 
14774
           saved value
 
14775
        */
 
14776
        field= item->field;
 
14777
        item->result_field=field->new_field(session->mem_root,field->table, 1);
6143
14778
        /*
6144
 
          set up save buffer and change result_field to point at
6145
 
          saved value
 
14779
          We need to allocate one extra byte for null handling and
 
14780
          another extra byte to not get warnings from purify in
 
14781
          Field_varstring::val_int
6146
14782
        */
6147
 
        field= item->field;
6148
 
        item->result_field=field->new_field(session->mem_root,field->table, 1);
6149
 
              /*
6150
 
                We need to allocate one extra byte for null handling and
6151
 
                another extra byte to not get warnings from purify in
6152
 
                Field_varstring::val_int
6153
 
              */
6154
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
6155
 
          goto err;
 
14783
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
 
14784
          goto err;
6156
14785
        if (copy)
6157
14786
        {
6158
14787
          copy->set(tmp, item->result_field);
6172
14801
    {                                           // Save for send fields
6173
14802
      pos= real_pos;
6174
14803
      /* TODO:
6175
 
        In most cases this result will be sent to the user.
6176
 
        This should be changed to use copy_int or copy_real depending
6177
 
        on how the value is to be used: In some cases this may be an
6178
 
        argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
 
14804
         In most cases this result will be sent to the user.
 
14805
         This should be changed to use copy_int or copy_real depending
 
14806
         on how the value is to be used: In some cases this may be an
 
14807
         argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
6179
14808
      */
6180
14809
      if (!(pos=new Item_copy_string(pos)))
6181
 
        goto err;
 
14810
        goto err;
6182
14811
      if (i < border)                           // HAVING, order_st and GROUP BY
6183
14812
      {
6184
14813
        if (extra_funcs.push_back(pos))
6185
14814
          goto err;
6186
14815
      }
6187
14816
      else if (param->copy_funcs.push_back(pos))
6188
 
        goto err;
 
14817
        goto err;
6189
14818
    }
6190
14819
    res_all_fields.push_back(pos);
6191
14820
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
6197
14826
    itr++;
6198
14827
  itr.sublist(res_selected_fields, elements);
6199
14828
  /*
6200
 
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
 
14829
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
6201
14830
    reference used in these will resolve to a item that is already calculated
6202
14831
  */
6203
14832
  param->copy_funcs.concat(&extra_funcs);
6204
14833
 
6205
14834
  return(0);
6206
14835
 
6207
 
err:
 
14836
 err:
6208
14837
  if (copy)
6209
14838
    delete [] param->copy_field;                        // This is never 0
6210
14839
  param->copy_field=0;
6212
14841
  return(true);
6213
14842
}
6214
14843
 
 
14844
 
6215
14845
/**
6216
14846
  Make a copy of all simple SELECT'ed items.
6217
14847
 
6218
14848
  This is done at the start of a new group so that we can retrieve
6219
14849
  these later when the group changes.
6220
14850
*/
6221
 
void copy_fields(Tmp_Table_Param *param)
 
14851
 
 
14852
void
 
14853
copy_fields(Tmp_Table_Param *param)
6222
14854
{
6223
 
  CopyField *ptr= param->copy_field;
6224
 
  CopyField *end= param->copy_field_end;
 
14855
  Copy_field *ptr=param->copy_field;
 
14856
  Copy_field *end=param->copy_field_end;
6225
14857
 
6226
14858
  for (; ptr != end; ptr++)
6227
14859
    (*ptr->do_copy)(ptr);
6232
14864
    item->copy();
6233
14865
}
6234
14866
 
 
14867
 
 
14868
/**
 
14869
  Make an array of pointers to sum_functions to speed up
 
14870
  sum_func calculation.
 
14871
 
 
14872
  @retval
 
14873
    0   ok
 
14874
  @retval
 
14875
    1   Error
 
14876
*/
 
14877
 
 
14878
bool JOIN::alloc_func_list()
 
14879
{
 
14880
  uint32_t func_count, group_parts;
 
14881
 
 
14882
  func_count= tmp_table_param.sum_func_count;
 
14883
  /*
 
14884
    If we are using rollup, we need a copy of the summary functions for
 
14885
    each level
 
14886
  */
 
14887
  if (rollup.state != ROLLUP::STATE_NONE)
 
14888
    func_count*= (send_group_parts+1);
 
14889
 
 
14890
  group_parts= send_group_parts;
 
14891
  /*
 
14892
    If distinct, reserve memory for possible
 
14893
    disctinct->group_by optimization
 
14894
  */
 
14895
  if (select_distinct)
 
14896
  {
 
14897
    group_parts+= fields_list.elements;
 
14898
    /*
 
14899
      If the order_st clause is specified then it's possible that
 
14900
      it also will be optimized, so reserve space for it too
 
14901
    */
 
14902
    if (order)
 
14903
    {
 
14904
      order_st *ord;
 
14905
      for (ord= order; ord; ord= ord->next)
 
14906
        group_parts++;
 
14907
    }
 
14908
  }
 
14909
 
 
14910
  /* This must use calloc() as rollup_make_fields depends on this */
 
14911
  sum_funcs= (Item_sum**) session->calloc(sizeof(Item_sum**) * (func_count+1) +
 
14912
                                      sizeof(Item_sum***) * (group_parts+1));
 
14913
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
 
14914
  return(sum_funcs == 0);
 
14915
}
 
14916
 
 
14917
 
 
14918
/**
 
14919
  Initialize 'sum_funcs' array with all Item_sum objects.
 
14920
 
 
14921
  @param field_list        All items
 
14922
  @param send_fields       Items in select list
 
14923
  @param before_group_by   Set to 1 if this is called before GROUP BY handling
 
14924
  @param recompute         Set to true if sum_funcs must be recomputed
 
14925
 
 
14926
  @retval
 
14927
    0  ok
 
14928
  @retval
 
14929
    1  error
 
14930
*/
 
14931
 
 
14932
bool JOIN::make_sum_func_list(List<Item> &field_list, List<Item> &send_fields,
 
14933
                              bool before_group_by, bool recompute)
 
14934
{
 
14935
  List_iterator_fast<Item> it(field_list);
 
14936
  Item_sum **func;
 
14937
  Item *item;
 
14938
 
 
14939
  if (*sum_funcs && !recompute)
 
14940
    return(false); /* We have already initialized sum_funcs. */
 
14941
 
 
14942
  func= sum_funcs;
 
14943
  while ((item=it++))
 
14944
  {
 
14945
    if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
 
14946
        (!((Item_sum*) item)->depended_from() ||
 
14947
         ((Item_sum *)item)->depended_from() == select_lex))
 
14948
      *func++= (Item_sum*) item;
 
14949
  }
 
14950
  if (before_group_by && rollup.state == ROLLUP::STATE_INITED)
 
14951
  {
 
14952
    rollup.state= ROLLUP::STATE_READY;
 
14953
    if (rollup_make_fields(field_list, send_fields, &func))
 
14954
      return(true);                     // Should never happen
 
14955
  }
 
14956
  else if (rollup.state == ROLLUP::STATE_NONE)
 
14957
  {
 
14958
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
 
14959
      sum_funcs_end[i]= func;
 
14960
  }
 
14961
  else if (rollup.state == ROLLUP::STATE_READY)
 
14962
    return(false);                         // Don't put end marker
 
14963
  *func=0;                                      // End marker
 
14964
  return(false);
 
14965
}
 
14966
 
 
14967
 
6235
14968
/**
6236
14969
  Change all funcs and sum_funcs to fields in tmp table, and create
6237
14970
  new list of all items.
6248
14981
  @retval
6249
14982
    !=0   error
6250
14983
*/
6251
 
bool change_to_use_tmp_fields(Session *session,
6252
 
                              Item **ref_pointer_array,
6253
 
                                                List<Item> &res_selected_fields,
6254
 
                                                List<Item> &res_all_fields,
6255
 
                                                uint32_t elements,
6256
 
                              List<Item> &all_fields)
 
14984
 
 
14985
static bool
 
14986
change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
 
14987
                         List<Item> &res_selected_fields,
 
14988
                         List<Item> &res_all_fields,
 
14989
                         uint32_t elements, List<Item> &all_fields)
6257
14990
{
6258
14991
  List_iterator_fast<Item> it(all_fields);
6259
14992
  Item *item_field,*item;
6274
15007
    {
6275
15008
      if (item->type() == Item::FIELD_ITEM)
6276
15009
      {
6277
 
        item_field= item->get_tmp_table_item(session);
 
15010
        item_field= item->get_tmp_table_item(session);
6278
15011
      }
6279
15012
      else if ((field= item->get_tmp_table_field()))
6280
15013
      {
6281
 
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
6282
 
          item_field= ((Item_sum*) item)->result_item(field);
6283
 
        else
6284
 
          item_field= (Item*) new Item_field(field);
6285
 
        if (!item_field)
6286
 
          return(true);                    // Fatal error
 
15014
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
 
15015
          item_field= ((Item_sum*) item)->result_item(field);
 
15016
        else
 
15017
          item_field= (Item*) new Item_field(field);
 
15018
        if (!item_field)
 
15019
          return(true);                    // Fatal error
6287
15020
 
6288
15021
        if (item->real_item()->type() != Item::FIELD_ITEM)
6289
15022
          field->orig_table= 0;
6290
 
        item_field->name= item->name;
 
15023
        item_field->name= item->name;
6291
15024
        if (item->type() == Item::REF_ITEM)
6292
15025
        {
6293
15026
          Item_field *ifield= (Item_field *) item_field;
6297
15030
        }
6298
15031
      }
6299
15032
      else
6300
 
        item_field= item;
 
15033
        item_field= item;
6301
15034
    }
6302
15035
    res_all_fields.push_back(item_field);
6303
15036
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
6311
15044
  return(false);
6312
15045
}
6313
15046
 
 
15047
 
6314
15048
/**
6315
15049
  Change all sum_func refs to fields to point at fields in tmp table.
6316
15050
  Change all funcs to be fields in tmp table.
6327
15061
  @retval
6328
15062
    1   error
6329
15063
*/
6330
 
bool change_refs_to_tmp_fields(Session *session,
6331
 
                               Item **ref_pointer_array,
6332
 
                               List<Item> &res_selected_fields,
6333
 
                               List<Item> &res_all_fields,
6334
 
                               uint32_t elements,
6335
 
                                                 List<Item> &all_fields)
 
15064
 
 
15065
static bool
 
15066
change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
 
15067
                          List<Item> &res_selected_fields,
 
15068
                          List<Item> &res_all_fields, uint32_t elements,
 
15069
                          List<Item> &all_fields)
6336
15070
{
6337
15071
  List_iterator_fast<Item> it(all_fields);
6338
15072
  Item *item, *new_item;
6355
15089
  return session->is_fatal_error;
6356
15090
}
6357
15091
 
 
15092
 
 
15093
 
6358
15094
/******************************************************************************
6359
15095
  Code for calculating functions
6360
15096
******************************************************************************/
6361
15097
 
 
15098
 
6362
15099
/**
6363
15100
  Call ::setup for all sum functions.
6364
15101
 
6365
 
  @param session           thread Cursor
 
15102
  @param session           thread handler
6366
15103
  @param func_ptr      sum function list
6367
15104
 
6368
15105
  @retval
6370
15107
  @retval
6371
15108
    true   error
6372
15109
*/
6373
 
bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
 
15110
 
 
15111
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
6374
15112
{
6375
15113
  Item_sum *func;
6376
15114
  while ((func= *(func_ptr++)))
6381
15119
  return(false);
6382
15120
}
6383
15121
 
6384
 
void init_tmptable_sum_functions(Item_sum **func_ptr)
 
15122
 
 
15123
static void
 
15124
init_tmptable_sum_functions(Item_sum **func_ptr)
6385
15125
{
6386
15126
  Item_sum *func;
6387
15127
  while ((func= *(func_ptr++)))
6388
15128
    func->reset_field();
6389
15129
}
6390
15130
 
 
15131
 
6391
15132
/** Update record 0 in tmp_table from record 1. */
6392
 
void update_tmptable_sum_func(Item_sum **func_ptr, Table *)
 
15133
 
 
15134
static void
 
15135
update_tmptable_sum_func(Item_sum **func_ptr, Table *)
6393
15136
{
6394
15137
  Item_sum *func;
6395
15138
  while ((func= *(func_ptr++)))
6396
15139
    func->update_field();
6397
15140
}
6398
15141
 
 
15142
 
6399
15143
/** Copy result of sum functions to record in tmp_table. */
6400
 
void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
 
15144
 
 
15145
static void
 
15146
copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
6401
15147
{
6402
15148
  for (; func_ptr != end_ptr ; func_ptr++)
6403
15149
    (void) (*func_ptr)->save_in_result_field(1);
6404
15150
  return;
6405
15151
}
6406
15152
 
6407
 
bool init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
 
15153
 
 
15154
static bool
 
15155
init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
6408
15156
{
6409
15157
  for (; func_ptr != end_ptr ;func_ptr++)
6410
15158
  {
6420
15168
  return 0;
6421
15169
}
6422
15170
 
6423
 
bool update_sum_func(Item_sum **func_ptr)
 
15171
 
 
15172
static bool
 
15173
update_sum_func(Item_sum **func_ptr)
6424
15174
{
6425
15175
  Item_sum *func;
6426
15176
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
6430
15180
}
6431
15181
 
6432
15182
/** Copy result of functions to record in tmp_table. */
6433
 
void copy_funcs(Item **func_ptr)
 
15183
 
 
15184
void
 
15185
copy_funcs(Item **func_ptr)
6434
15186
{
6435
15187
  Item *func;
6436
15188
  for (; (func = *func_ptr) ; func_ptr++)
6437
15189
    func->save_in_result_field(1);
6438
15190
}
6439
15191
 
 
15192
 
 
15193
/**
 
15194
  Create a condition for a const reference and add this to the
 
15195
  currenct select for the table.
 
15196
*/
 
15197
 
 
15198
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab)
 
15199
{
 
15200
  if (!join_tab->ref.key_parts)
 
15201
    return(false);
 
15202
 
 
15203
  Item_cond_and *cond=new Item_cond_and();
 
15204
  Table *table=join_tab->table;
 
15205
  int error;
 
15206
  if (!cond)
 
15207
    return(true);
 
15208
 
 
15209
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
 
15210
  {
 
15211
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
 
15212
                              fieldnr-1];
 
15213
    Item *value=join_tab->ref.items[i];
 
15214
    cond->add(new Item_func_equal(new Item_field(field), value));
 
15215
  }
 
15216
  if (session->is_fatal_error)
 
15217
    return(true);
 
15218
 
 
15219
  if (!cond->fixed)
 
15220
    cond->fix_fields(session, (Item**)&cond);
 
15221
  if (join_tab->select)
 
15222
  {
 
15223
    error=(int) cond->add(join_tab->select->cond);
 
15224
    join_tab->select_cond=join_tab->select->cond=cond;
 
15225
  }
 
15226
  else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0,
 
15227
                                          &error)))
 
15228
    join_tab->select_cond=cond;
 
15229
 
 
15230
  return(error ? true : false);
 
15231
}
 
15232
 
 
15233
 
6440
15234
/**
6441
15235
  Free joins of subselect of this select.
6442
15236
 
6443
15237
  @param session      Session pointer
6444
15238
  @param select   pointer to Select_Lex which subselects joins we will free
6445
15239
*/
 
15240
 
6446
15241
void free_underlaid_joins(Session *, Select_Lex *select)
6447
15242
{
6448
15243
  for (Select_Lex_Unit *unit= select->first_inner_unit();
6494
15289
  @retval
6495
15290
    1   on error
6496
15291
*/
6497
 
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
 
15292
 
 
15293
static bool change_group_ref(Session *session, Item_func *expr, order_st *group_list,
 
15294
                             bool *changed)
6498
15295
{
6499
15296
  if (expr->arg_count)
6500
15297
  {
6538
15335
}
6539
15336
 
6540
15337
 
 
15338
/** Allocate memory needed for other rollup functions. */
 
15339
 
 
15340
bool JOIN::rollup_init()
 
15341
{
 
15342
  uint32_t i,j;
 
15343
  Item **ref_array;
 
15344
 
 
15345
  tmp_table_param.quick_group= 0;       // Can't create groups in tmp table
 
15346
  rollup.state= ROLLUP::STATE_INITED;
 
15347
 
 
15348
  /*
 
15349
    Create pointers to the different sum function groups
 
15350
    These are updated by rollup_make_fields()
 
15351
  */
 
15352
  tmp_table_param.group_parts= send_group_parts;
 
15353
 
 
15354
  if (!(rollup.null_items= (Item_null_result**) session->alloc((sizeof(Item*) +
 
15355
                                                sizeof(Item**) +
 
15356
                                                sizeof(List<Item>) +
 
15357
                                                ref_pointer_array_size)
 
15358
                                                * send_group_parts )))
 
15359
    return 1;
 
15360
 
 
15361
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
 
15362
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
 
15363
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
 
15364
 
 
15365
  /*
 
15366
    Prepare space for field list for the different levels
 
15367
    These will be filled up in rollup_make_fields()
 
15368
  */
 
15369
  for (i= 0 ; i < send_group_parts ; i++)
 
15370
  {
 
15371
    rollup.null_items[i]= new (session->mem_root) Item_null_result();
 
15372
    List<Item> *rollup_fields= &rollup.fields[i];
 
15373
    rollup_fields->empty();
 
15374
    rollup.ref_pointer_arrays[i]= ref_array;
 
15375
    ref_array+= all_fields.elements;
 
15376
  }
 
15377
  for (i= 0 ; i < send_group_parts; i++)
 
15378
  {
 
15379
    for (j=0 ; j < fields_list.elements ; j++)
 
15380
      rollup.fields[i].push_back(rollup.null_items[i]);
 
15381
  }
 
15382
  List_iterator<Item> it(all_fields);
 
15383
  Item *item;
 
15384
  while ((item= it++))
 
15385
  {
 
15386
    order_st *group_tmp;
 
15387
    bool found_in_group= 0;
 
15388
 
 
15389
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
 
15390
    {
 
15391
      if (*group_tmp->item == item)
 
15392
      {
 
15393
        item->maybe_null= 1;
 
15394
        found_in_group= 1;
 
15395
        if (item->const_item())
 
15396
        {
 
15397
          /*
 
15398
            For ROLLUP queries each constant item referenced in GROUP BY list
 
15399
            is wrapped up into an Item_func object yielding the same value
 
15400
            as the constant item. The objects of the wrapper class are never
 
15401
            considered as constant items and besides they inherit all
 
15402
            properties of the Item_result_field class.
 
15403
            This wrapping allows us to ensure writing constant items
 
15404
            into temporary tables whenever the result of the ROLLUP
 
15405
            operation has to be written into a temporary table, e.g. when
 
15406
            ROLLUP is used together with DISTINCT in the SELECT list.
 
15407
            Usually when creating temporary tables for a intermidiate
 
15408
            result we do not include fields for constant expressions.
 
15409
          */
 
15410
          Item* new_item= new Item_func_rollup_const(item);
 
15411
          if (!new_item)
 
15412
            return 1;
 
15413
          new_item->fix_fields(session, (Item **) 0);
 
15414
          session->change_item_tree(it.ref(), new_item);
 
15415
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
 
15416
          {
 
15417
            if (*tmp->item == item)
 
15418
              session->change_item_tree(tmp->item, new_item);
 
15419
          }
 
15420
        }
 
15421
      }
 
15422
    }
 
15423
    if (item->type() == Item::FUNC_ITEM && !found_in_group)
 
15424
    {
 
15425
      bool changed= false;
 
15426
      if (change_group_ref(session, (Item_func *) item, group_list, &changed))
 
15427
        return 1;
 
15428
      /*
 
15429
        We have to prevent creation of a field in a temporary table for
 
15430
        an expression that contains GROUP BY attributes.
 
15431
        Marking the expression item as 'with_sum_func' will ensure this.
 
15432
      */
 
15433
      if (changed)
 
15434
        item->with_sum_func= 1;
 
15435
    }
 
15436
  }
 
15437
  return 0;
 
15438
}
 
15439
 
 
15440
 
 
15441
/**
 
15442
  Fill up rollup structures with pointers to fields to use.
 
15443
 
 
15444
  Creates copies of item_sum items for each sum level.
 
15445
 
 
15446
  @param fields_arg             List of all fields (hidden and real ones)
 
15447
  @param sel_fields             Pointer to selected fields
 
15448
  @param func                   Store here a pointer to all fields
 
15449
 
 
15450
  @retval
 
15451
    0   if ok;
 
15452
    In this case func is pointing to next not used element.
 
15453
  @retval
 
15454
    1    on error
 
15455
*/
 
15456
 
 
15457
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields,
 
15458
                              Item_sum ***func)
 
15459
{
 
15460
  List_iterator_fast<Item> it(fields_arg);
 
15461
  Item *first_field= sel_fields.head();
 
15462
  uint32_t level;
 
15463
 
 
15464
  /*
 
15465
    Create field lists for the different levels
 
15466
 
 
15467
    The idea here is to have a separate field list for each rollup level to
 
15468
    avoid all runtime checks of which columns should be NULL.
 
15469
 
 
15470
    The list is stored in reverse order to get sum function in such an order
 
15471
    in func that it makes it easy to reset them with init_sum_functions()
 
15472
 
 
15473
    Assuming:  SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
 
15474
 
 
15475
    rollup.fields[0] will contain list where a,b,c is NULL
 
15476
    rollup.fields[1] will contain list where b,c is NULL
 
15477
    ...
 
15478
    rollup.ref_pointer_array[#] points to fields for rollup.fields[#]
 
15479
    ...
 
15480
    sum_funcs_end[0] points to all sum functions
 
15481
    sum_funcs_end[1] points to all sum functions, except grand totals
 
15482
    ...
 
15483
  */
 
15484
 
 
15485
  for (level=0 ; level < send_group_parts ; level++)
 
15486
  {
 
15487
    uint32_t i;
 
15488
    uint32_t pos= send_group_parts - level -1;
 
15489
    bool real_fields= 0;
 
15490
    Item *item;
 
15491
    List_iterator<Item> new_it(rollup.fields[pos]);
 
15492
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
 
15493
    order_st *start_group;
 
15494
 
 
15495
    /* Point to first hidden field */
 
15496
    Item **ref_array= ref_array_start + fields_arg.elements-1;
 
15497
 
 
15498
    /* Remember where the sum functions ends for the previous level */
 
15499
    sum_funcs_end[pos+1]= *func;
 
15500
 
 
15501
    /* Find the start of the group for this level */
 
15502
    for (i= 0, start_group= group_list ;
 
15503
         i++ < pos ;
 
15504
         start_group= start_group->next)
 
15505
      ;
 
15506
 
 
15507
    it.rewind();
 
15508
    while ((item= it++))
 
15509
    {
 
15510
      if (item == first_field)
 
15511
      {
 
15512
        real_fields= 1;                         // End of hidden fields
 
15513
        ref_array= ref_array_start;
 
15514
      }
 
15515
 
 
15516
      if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
 
15517
          (!((Item_sum*) item)->depended_from() ||
 
15518
           ((Item_sum *)item)->depended_from() == select_lex))
 
15519
 
 
15520
      {
 
15521
        /*
 
15522
          This is a top level summary function that must be replaced with
 
15523
          a sum function that is reset for this level.
 
15524
 
 
15525
          NOTE: This code creates an object which is not that nice in a
 
15526
          sub select.  Fortunately it's not common to have rollup in
 
15527
          sub selects.
 
15528
        */
 
15529
        item= item->copy_or_same(session);
 
15530
        ((Item_sum*) item)->make_unique();
 
15531
        *(*func)= (Item_sum*) item;
 
15532
        (*func)++;
 
15533
      }
 
15534
      else
 
15535
      {
 
15536
        /* Check if this is something that is part of this group by */
 
15537
        order_st *group_tmp;
 
15538
        for (group_tmp= start_group, i= pos ;
 
15539
             group_tmp ; group_tmp= group_tmp->next, i++)
 
15540
        {
 
15541
          if (*group_tmp->item == item)
 
15542
          {
 
15543
            /*
 
15544
              This is an element that is used by the GROUP BY and should be
 
15545
              set to NULL in this level
 
15546
            */
 
15547
            Item_null_result *null_item= new (session->mem_root) Item_null_result();
 
15548
            if (!null_item)
 
15549
              return 1;
 
15550
            item->maybe_null= 1;                // Value will be null sometimes
 
15551
            null_item->result_field= item->get_tmp_table_field();
 
15552
            item= null_item;
 
15553
            break;
 
15554
          }
 
15555
        }
 
15556
      }
 
15557
      *ref_array= item;
 
15558
      if (real_fields)
 
15559
      {
 
15560
        (void) new_it++;                        // Point to next item
 
15561
        new_it.replace(item);                   // Replace previous
 
15562
        ref_array++;
 
15563
      }
 
15564
      else
 
15565
        ref_array--;
 
15566
    }
 
15567
  }
 
15568
  sum_funcs_end[0]= *func;                      // Point to last function
 
15569
  return 0;
 
15570
}
 
15571
 
 
15572
/**
 
15573
  Send all rollup levels higher than the current one to the client.
 
15574
 
 
15575
  @b SAMPLE
 
15576
    @code
 
15577
      SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
 
15578
  @endcode
 
15579
 
 
15580
  @param idx            Level we are on:
 
15581
                        - 0 = Total sum level
 
15582
                        - 1 = First group changed  (a)
 
15583
                        - 2 = Second group changed (a,b)
 
15584
 
 
15585
  @retval
 
15586
    0   ok
 
15587
  @retval
 
15588
    1   If send_data_failed()
 
15589
*/
 
15590
 
 
15591
int JOIN::rollup_send_data(uint32_t idx)
 
15592
{
 
15593
  uint32_t i;
 
15594
  for (i= send_group_parts ; i-- > idx ; )
 
15595
  {
 
15596
    /* Get reference pointers to sum functions in place */
 
15597
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
15598
           ref_pointer_array_size);
 
15599
    if ((!having || having->val_int()))
 
15600
    {
 
15601
      if (send_records < unit->select_limit_cnt && do_send_rows &&
 
15602
          result->send_data(rollup.fields[i]))
 
15603
        return 1;
 
15604
      send_records++;
 
15605
    }
 
15606
  }
 
15607
  /* Restore ref_pointer_array */
 
15608
  set_items_ref_array(current_ref_pointer_array);
 
15609
  return 0;
 
15610
}
 
15611
 
 
15612
/**
 
15613
  Write all rollup levels higher than the current one to a temp table.
 
15614
 
 
15615
  @b SAMPLE
 
15616
    @code
 
15617
      SELECT a, b, SUM(c) FROM t1 GROUP BY a,b WITH ROLLUP
 
15618
  @endcode
 
15619
 
 
15620
  @param idx                 Level we are on:
 
15621
                               - 0 = Total sum level
 
15622
                               - 1 = First group changed  (a)
 
15623
                               - 2 = Second group changed (a,b)
 
15624
  @param table               reference to temp table
 
15625
 
 
15626
  @retval
 
15627
    0   ok
 
15628
  @retval
 
15629
    1   if write_data_failed()
 
15630
*/
 
15631
 
 
15632
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
 
15633
{
 
15634
  uint32_t i;
 
15635
  for (i= send_group_parts ; i-- > idx ; )
 
15636
  {
 
15637
    /* Get reference pointers to sum functions in place */
 
15638
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
15639
           ref_pointer_array_size);
 
15640
    if ((!having || having->val_int()))
 
15641
    {
 
15642
      int write_error;
 
15643
      Item *item;
 
15644
      List_iterator_fast<Item> it(rollup.fields[i]);
 
15645
      while ((item= it++))
 
15646
      {
 
15647
        if (item->type() == Item::NULL_ITEM && item->is_result_field())
 
15648
          item->save_in_result_field(1);
 
15649
      }
 
15650
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
 
15651
      if ((write_error= table_arg->file->ha_write_row(table_arg->record[0])))
 
15652
      {
 
15653
        if (create_myisam_from_heap(session, table_arg,
 
15654
                                    tmp_table_param.start_recinfo,
 
15655
                                    &tmp_table_param.recinfo,
 
15656
                                    write_error, 0))
 
15657
          return 1;
 
15658
      }
 
15659
    }
 
15660
  }
 
15661
  /* Restore ref_pointer_array */
 
15662
  set_items_ref_array(current_ref_pointer_array);
 
15663
  return 0;
 
15664
}
 
15665
 
 
15666
/**
 
15667
  clear results if there are not rows found for group
 
15668
  (end_send_group/end_write_group)
 
15669
*/
 
15670
 
 
15671
void JOIN::clear()
 
15672
{
 
15673
  clear_tables(this);
 
15674
  copy_fields(&tmp_table_param);
 
15675
 
 
15676
  if (sum_funcs)
 
15677
  {
 
15678
    Item_sum *func, **func_ptr= sum_funcs;
 
15679
    while ((func= *(func_ptr++)))
 
15680
      func->clear();
 
15681
  }
 
15682
}
 
15683
 
 
15684
/**
 
15685
  EXPLAIN handling.
 
15686
 
 
15687
  Send a description about what how the select will be done to stdout.
 
15688
*/
 
15689
 
 
15690
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
 
15691
                     bool distinct,const char *message)
 
15692
{
 
15693
  List<Item> field_list;
 
15694
  List<Item> item_list;
 
15695
  Session *session=join->session;
 
15696
  select_result *result=join->result;
 
15697
  Item *item_null= new Item_null();
 
15698
  const CHARSET_INFO * const cs= system_charset_info;
 
15699
  int quick_type;
 
15700
  /* Don't log this into the slow query log */
 
15701
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
15702
  join->unit->offset_limit_cnt= 0;
 
15703
 
 
15704
  /*
 
15705
    NOTE: the number/types of items pushed into item_list must be in sync with
 
15706
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
 
15707
  */
 
15708
  if (message)
 
15709
  {
 
15710
    item_list.push_back(new Item_int((int32_t)
 
15711
                                     join->select_lex->select_number));
 
15712
    item_list.push_back(new Item_string(join->select_lex->type,
 
15713
                                        strlen(join->select_lex->type), cs));
 
15714
    for (uint32_t i=0 ; i < 7; i++)
 
15715
      item_list.push_back(item_null);
 
15716
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15717
      item_list.push_back(item_null);
 
15718
 
 
15719
    item_list.push_back(new Item_string(message,strlen(message),cs));
 
15720
    if (result->send_data(item_list))
 
15721
      join->error= 1;
 
15722
  }
 
15723
  else if (join->select_lex == join->unit->fake_select_lex)
 
15724
  {
 
15725
    /*
 
15726
      here we assume that the query will return at least two rows, so we
 
15727
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
 
15728
      and no filesort will be actually done, but executing all selects in
 
15729
      the UNION to provide precise EXPLAIN information will hardly be
 
15730
      appreciated :)
 
15731
    */
 
15732
    char table_name_buffer[NAME_LEN];
 
15733
    item_list.empty();
 
15734
    /* id */
 
15735
    item_list.push_back(new Item_null);
 
15736
    /* select_type */
 
15737
    item_list.push_back(new Item_string(join->select_lex->type,
 
15738
                                        strlen(join->select_lex->type),
 
15739
                                        cs));
 
15740
    /* table */
 
15741
    {
 
15742
      Select_Lex *sl= join->unit->first_select();
 
15743
      uint32_t len= 6, lastop= 0;
 
15744
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
 
15745
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
 
15746
      {
 
15747
        len+= lastop;
 
15748
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
 
15749
                         "%u,", sl->select_number);
 
15750
      }
 
15751
      if (sl || len + lastop >= NAME_LEN)
 
15752
      {
 
15753
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
 
15754
        len+= 4;
 
15755
      }
 
15756
      else
 
15757
      {
 
15758
        len+= lastop;
 
15759
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
 
15760
      }
 
15761
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
15762
    }
 
15763
    /* type */
 
15764
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
 
15765
                                          strlen(join_type_str[JT_ALL]),
 
15766
                                          cs));
 
15767
    /* possible_keys */
 
15768
    item_list.push_back(item_null);
 
15769
    /* key*/
 
15770
    item_list.push_back(item_null);
 
15771
    /* key_len */
 
15772
    item_list.push_back(item_null);
 
15773
    /* ref */
 
15774
    item_list.push_back(item_null);
 
15775
    /* in_rows */
 
15776
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15777
      item_list.push_back(item_null);
 
15778
    /* rows */
 
15779
    item_list.push_back(item_null);
 
15780
    /* extra */
 
15781
    if (join->unit->global_parameters->order_list.first)
 
15782
      item_list.push_back(new Item_string("Using filesort",
 
15783
                                          14, cs));
 
15784
    else
 
15785
      item_list.push_back(new Item_string("", 0, cs));
 
15786
 
 
15787
    if (result->send_data(item_list))
 
15788
      join->error= 1;
 
15789
  }
 
15790
  else
 
15791
  {
 
15792
    table_map used_tables=0;
 
15793
    for (uint32_t i=0 ; i < join->tables ; i++)
 
15794
    {
 
15795
      JOIN_TAB *tab=join->join_tab+i;
 
15796
      Table *table=tab->table;
 
15797
      TableList *table_list= tab->table->pos_in_table_list;
 
15798
      char buff[512];
 
15799
      char buff1[512], buff2[512], buff3[512];
 
15800
      char keylen_str_buf[64];
 
15801
      String extra(buff, sizeof(buff),cs);
 
15802
      char table_name_buffer[NAME_LEN];
 
15803
      String tmp1(buff1,sizeof(buff1),cs);
 
15804
      String tmp2(buff2,sizeof(buff2),cs);
 
15805
      String tmp3(buff3,sizeof(buff3),cs);
 
15806
      extra.length(0);
 
15807
      tmp1.length(0);
 
15808
      tmp2.length(0);
 
15809
      tmp3.length(0);
 
15810
 
 
15811
      quick_type= -1;
 
15812
      item_list.empty();
 
15813
      /* id */
 
15814
      item_list.push_back(new Item_uint((uint32_t)
 
15815
                                       join->select_lex->select_number));
 
15816
      /* select_type */
 
15817
      item_list.push_back(new Item_string(join->select_lex->type,
 
15818
                                          strlen(join->select_lex->type),
 
15819
                                          cs));
 
15820
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
 
15821
      {
 
15822
        quick_type= tab->select->quick->get_type();
 
15823
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
 
15824
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
 
15825
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
 
15826
          tab->type = JT_INDEX_MERGE;
 
15827
        else
 
15828
          tab->type = JT_RANGE;
 
15829
      }
 
15830
      /* table */
 
15831
      if (table->derived_select_number)
 
15832
      {
 
15833
        /* Derived table name generation */
 
15834
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
15835
                          "<derived%u>",
 
15836
                          table->derived_select_number);
 
15837
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
15838
      }
 
15839
      else
 
15840
      {
 
15841
        TableList *real_table= table->pos_in_table_list;
 
15842
        item_list.push_back(new Item_string(real_table->alias,
 
15843
                                            strlen(real_table->alias),
 
15844
                                            cs));
 
15845
      }
 
15846
      /* "type" column */
 
15847
      item_list.push_back(new Item_string(join_type_str[tab->type],
 
15848
                                          strlen(join_type_str[tab->type]),
 
15849
                                          cs));
 
15850
      /* Build "possible_keys" value and add it to item_list */
 
15851
      if (!tab->keys.is_clear_all())
 
15852
      {
 
15853
        uint32_t j;
 
15854
        for (j=0 ; j < table->s->keys ; j++)
 
15855
        {
 
15856
          if (tab->keys.is_set(j))
 
15857
          {
 
15858
            if (tmp1.length())
 
15859
              tmp1.append(',');
 
15860
            tmp1.append(table->key_info[j].name,
 
15861
                        strlen(table->key_info[j].name),
 
15862
                        system_charset_info);
 
15863
          }
 
15864
        }
 
15865
      }
 
15866
      if (tmp1.length())
 
15867
        item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
 
15868
      else
 
15869
        item_list.push_back(item_null);
 
15870
 
 
15871
      /* Build "key", "key_len", and "ref" values and add them to item_list */
 
15872
      if (tab->ref.key_parts)
 
15873
      {
 
15874
        KEY *key_info=table->key_info+ tab->ref.key;
 
15875
        register uint32_t length;
 
15876
        item_list.push_back(new Item_string(key_info->name,
 
15877
                                            strlen(key_info->name),
 
15878
                                            system_charset_info));
 
15879
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
 
15880
                keylen_str_buf;
 
15881
        item_list.push_back(new Item_string(keylen_str_buf, length,
 
15882
                                            system_charset_info));
 
15883
        for (store_key **ref=tab->ref.key_copy ; *ref ; ref++)
 
15884
        {
 
15885
          if (tmp2.length())
 
15886
            tmp2.append(',');
 
15887
          tmp2.append((*ref)->name(), strlen((*ref)->name()),
 
15888
                      system_charset_info);
 
15889
        }
 
15890
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15891
      }
 
15892
      else if (tab->type == JT_NEXT)
 
15893
      {
 
15894
        KEY *key_info=table->key_info+ tab->index;
 
15895
        register uint32_t length;
 
15896
        item_list.push_back(new Item_string(key_info->name,
 
15897
                                            strlen(key_info->name),cs));
 
15898
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
 
15899
                keylen_str_buf;
 
15900
        item_list.push_back(new Item_string(keylen_str_buf,
 
15901
                                            length,
 
15902
                                            system_charset_info));
 
15903
        item_list.push_back(item_null);
 
15904
      }
 
15905
      else if (tab->select && tab->select->quick)
 
15906
      {
 
15907
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
 
15908
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15909
        item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
 
15910
        item_list.push_back(item_null);
 
15911
      }
 
15912
      else
 
15913
      {
 
15914
        if (table_list->schema_table && table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
15915
        {
 
15916
          const char *tmp_buff;
 
15917
          int f_idx;
 
15918
          if (table_list->has_db_lookup_value)
 
15919
          {
 
15920
            f_idx= table_list->schema_table->idx_field1;
 
15921
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
 
15922
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
 
15923
          }
 
15924
          if (table_list->has_table_lookup_value)
 
15925
          {
 
15926
            if (table_list->has_db_lookup_value)
 
15927
              tmp2.append(',');
 
15928
            f_idx= table_list->schema_table->idx_field2;
 
15929
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
 
15930
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
 
15931
          }
 
15932
          if (tmp2.length())
 
15933
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15934
          else
 
15935
            item_list.push_back(item_null);
 
15936
        }
 
15937
        else
 
15938
          item_list.push_back(item_null);
 
15939
        item_list.push_back(item_null);
 
15940
        item_list.push_back(item_null);
 
15941
      }
 
15942
 
 
15943
      /* Add "rows" field to item_list. */
 
15944
      if (table_list->schema_table)
 
15945
      {
 
15946
        /* in_rows */
 
15947
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15948
          item_list.push_back(item_null);
 
15949
        /* rows */
 
15950
        item_list.push_back(item_null);
 
15951
      }
 
15952
      else
 
15953
      {
 
15954
        double examined_rows;
 
15955
        if (tab->select && tab->select->quick)
 
15956
          examined_rows= rows2double(tab->select->quick->records);
 
15957
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
 
15958
          examined_rows= rows2double(tab->limit ? tab->limit :
 
15959
                                     tab->table->file->records());
 
15960
        else
 
15961
          examined_rows= join->best_positions[i].records_read;
 
15962
 
 
15963
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
 
15964
                                         MY_INT64_NUM_DECIMAL_DIGITS));
 
15965
 
 
15966
        /* Add "filtered" field to item_list. */
 
15967
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15968
        {
 
15969
          float f= 0.0;
 
15970
          if (examined_rows)
 
15971
            f= (float) (100.0 * join->best_positions[i].records_read /
 
15972
                        examined_rows);
 
15973
          item_list.push_back(new Item_float(f, 2));
 
15974
        }
 
15975
      }
 
15976
 
 
15977
      /* Build "Extra" field and add it to item_list. */
 
15978
      bool key_read=table->key_read;
 
15979
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
 
15980
          table->covering_keys.is_set(tab->index))
 
15981
        key_read=1;
 
15982
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
 
15983
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
 
15984
        key_read=1;
 
15985
 
 
15986
      if (tab->info)
 
15987
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
 
15988
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
 
15989
      {
 
15990
        if (tab->packed_info & TAB_INFO_USING_INDEX)
 
15991
          extra.append(STRING_WITH_LEN("; Using index"));
 
15992
        if (tab->packed_info & TAB_INFO_USING_WHERE)
 
15993
          extra.append(STRING_WITH_LEN("; Using where"));
 
15994
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
 
15995
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
15996
        /* Skip initial "; "*/
 
15997
        const char *str= extra.ptr();
 
15998
        uint32_t len= extra.length();
 
15999
        if (len)
 
16000
        {
 
16001
          str += 2;
 
16002
          len -= 2;
 
16003
        }
 
16004
        item_list.push_back(new Item_string(str, len, cs));
 
16005
      }
 
16006
      else
 
16007
      {
 
16008
        uint32_t keyno= MAX_KEY;
 
16009
        if (tab->ref.key_parts)
 
16010
          keyno= tab->ref.key;
 
16011
        else if (tab->select && tab->select->quick)
 
16012
          keyno = tab->select->quick->index;
 
16013
 
 
16014
        if (keyno != MAX_KEY && keyno == table->file->pushed_idx_cond_keyno &&
 
16015
            table->file->pushed_idx_cond)
 
16016
          extra.append(STRING_WITH_LEN("; Using index condition"));
 
16017
 
 
16018
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
16019
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
16020
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
 
16021
        {
 
16022
          extra.append(STRING_WITH_LEN("; Using "));
 
16023
          tab->select->quick->add_info_string(&extra);
 
16024
        }
 
16025
          if (tab->select)
 
16026
        {
 
16027
          if (tab->use_quick == 2)
 
16028
          {
 
16029
            /* 4 bits per 1 hex digit + terminating '\0' */
 
16030
            char buf[MAX_KEY / 4 + 1];
 
16031
            extra.append(STRING_WITH_LEN("; Range checked for each "
 
16032
                                         "record (index map: 0x"));
 
16033
            extra.append(tab->keys.print(buf));
 
16034
            extra.append(')');
 
16035
          }
 
16036
          else if (tab->select->cond)
 
16037
          {
 
16038
            const COND *pushed_cond= tab->table->file->pushed_cond;
 
16039
 
 
16040
            if (session->variables.engine_condition_pushdown && pushed_cond)
 
16041
            {
 
16042
              extra.append(STRING_WITH_LEN("; Using where with pushed "
 
16043
                                           "condition"));
 
16044
              if (session->lex->describe & DESCRIBE_EXTENDED)
 
16045
              {
 
16046
                extra.append(STRING_WITH_LEN(": "));
 
16047
                ((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
 
16048
              }
 
16049
            }
 
16050
            else
 
16051
              extra.append(STRING_WITH_LEN("; Using where"));
 
16052
          }
 
16053
        }
 
16054
        if (key_read)
 
16055
        {
 
16056
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
 
16057
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
 
16058
          else
 
16059
            extra.append(STRING_WITH_LEN("; Using index"));
 
16060
        }
 
16061
        if (table->reginfo.not_exists_optimize)
 
16062
          extra.append(STRING_WITH_LEN("; Not exists"));
 
16063
 
 
16064
        if (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE &&
 
16065
            !(((QUICK_RANGE_SELECT*)(tab->select->quick))->mrr_flags &
 
16066
             HA_MRR_USE_DEFAULT_IMPL))
 
16067
        {
 
16068
          extra.append(STRING_WITH_LEN("; Using MRR"));
 
16069
        }
 
16070
 
 
16071
        if (table_list->schema_table &&
 
16072
            table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
16073
        {
 
16074
          if (!table_list->table_open_method)
 
16075
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
 
16076
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
 
16077
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
 
16078
          else
 
16079
            extra.append(STRING_WITH_LEN("; Open_full_table"));
 
16080
          if (table_list->has_db_lookup_value &&
 
16081
              table_list->has_table_lookup_value)
 
16082
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
 
16083
          else if (table_list->has_db_lookup_value ||
 
16084
                   table_list->has_table_lookup_value)
 
16085
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
 
16086
          else
 
16087
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
 
16088
        }
 
16089
        if (need_tmp_table)
 
16090
        {
 
16091
          need_tmp_table=0;
 
16092
          extra.append(STRING_WITH_LEN("; Using temporary"));
 
16093
        }
 
16094
        if (need_order)
 
16095
        {
 
16096
          need_order=0;
 
16097
          extra.append(STRING_WITH_LEN("; Using filesort"));
 
16098
        }
 
16099
        if (distinct & test_all_bits(used_tables,session->used_tables))
 
16100
          extra.append(STRING_WITH_LEN("; Distinct"));
 
16101
 
 
16102
        if (tab->insideout_match_tab)
 
16103
        {
 
16104
          extra.append(STRING_WITH_LEN("; LooseScan"));
 
16105
        }
 
16106
 
 
16107
        if (tab->flush_weedout_table)
 
16108
          extra.append(STRING_WITH_LEN("; Start temporary"));
 
16109
        else if (tab->check_weed_out_table)
 
16110
          extra.append(STRING_WITH_LEN("; End temporary"));
 
16111
        else if (tab->do_firstmatch)
 
16112
        {
 
16113
          extra.append(STRING_WITH_LEN("; FirstMatch("));
 
16114
          Table *prev_table=tab->do_firstmatch->table;
 
16115
          if (prev_table->derived_select_number)
 
16116
          {
 
16117
            char namebuf[NAME_LEN];
 
16118
            /* Derived table name generation */
 
16119
            int len= snprintf(namebuf, sizeof(namebuf)-1,
 
16120
                              "<derived%u>",
 
16121
                              prev_table->derived_select_number);
 
16122
            extra.append(namebuf, len);
 
16123
          }
 
16124
          else
 
16125
            extra.append(prev_table->pos_in_table_list->alias);
 
16126
          extra.append(STRING_WITH_LEN(")"));
 
16127
        }
 
16128
 
 
16129
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
16130
        {
 
16131
          if (tab->ref.cond_guards[part])
 
16132
          {
 
16133
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
16134
            break;
 
16135
          }
 
16136
        }
 
16137
 
 
16138
        if (i > 0 && tab[-1].next_select == sub_select_cache)
 
16139
          extra.append(STRING_WITH_LEN("; Using join buffer"));
 
16140
 
 
16141
        /* Skip initial "; "*/
 
16142
        const char *str= extra.ptr();
 
16143
        uint32_t len= extra.length();
 
16144
        if (len)
 
16145
        {
 
16146
          str += 2;
 
16147
          len -= 2;
 
16148
        }
 
16149
        item_list.push_back(new Item_string(str, len, cs));
 
16150
      }
 
16151
      // For next iteration
 
16152
      used_tables|=table->map;
 
16153
      if (result->send_data(item_list))
 
16154
        join->error= 1;
 
16155
    }
 
16156
  }
 
16157
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
 
16158
       unit;
 
16159
       unit= unit->next_unit())
 
16160
  {
 
16161
    if (mysql_explain_union(session, unit, result))
 
16162
      return;
 
16163
  }
 
16164
  return;
 
16165
}
 
16166
 
 
16167
 
 
16168
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
 
16169
{
 
16170
  bool res= false;
 
16171
  Select_Lex *first= unit->first_select();
 
16172
 
 
16173
  for (Select_Lex *sl= first;
 
16174
       sl;
 
16175
       sl= sl->next_select())
 
16176
  {
 
16177
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
 
16178
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
16179
    sl->type= (((&session->lex->select_lex)==sl)?
 
16180
               (sl->first_inner_unit() || sl->next_select() ?
 
16181
                "PRIMARY" : "SIMPLE"):
 
16182
               ((sl == first)?
 
16183
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
 
16184
                 "DERIVED":
 
16185
                 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
16186
                  "DEPENDENT SUBQUERY":
 
16187
                  (uncacheable?"UNCACHEABLE SUBQUERY":
 
16188
                   "SUBQUERY"))):
 
16189
                ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
16190
                 "DEPENDENT UNION":
 
16191
                 uncacheable?"UNCACHEABLE UNION":
 
16192
                 "UNION")));
 
16193
    sl->options|= SELECT_DESCRIBE;
 
16194
  }
 
16195
  if (unit->is_union())
 
16196
  {
 
16197
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
 
16198
    unit->fake_select_lex->type= "UNION RESULT";
 
16199
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
 
16200
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
16201
      res= unit->exec();
 
16202
    res|= unit->cleanup();
 
16203
  }
 
16204
  else
 
16205
  {
 
16206
    session->lex->current_select= first;
 
16207
    unit->set_limit(unit->global_parameters);
 
16208
    res= mysql_select(session, &first->ref_pointer_array,
 
16209
                        (TableList*) first->table_list.first,
 
16210
                        first->with_wild, first->item_list,
 
16211
                        first->where,
 
16212
                        first->order_list.elements +
 
16213
                        first->group_list.elements,
 
16214
                        (order_st*) first->order_list.first,
 
16215
                        (order_st*) first->group_list.first,
 
16216
                        first->having,
 
16217
                        first->options | session->options | SELECT_DESCRIBE,
 
16218
                        result, unit, first);
 
16219
  }
 
16220
  return(res || session->is_error());
 
16221
}
 
16222
 
 
16223
 
6541
16224
static void print_table_array(Session *session, String *str, TableList **table,
6542
16225
                              TableList **end)
6543
16226
{
6553
16236
    }
6554
16237
    else if (curr->straight)
6555
16238
      str->append(STRING_WITH_LEN(" straight_join "));
 
16239
    else if (curr->sj_inner_tables)
 
16240
      str->append(STRING_WITH_LEN(" semi join "));
6556
16241
    else
6557
16242
      str->append(STRING_WITH_LEN(" join "));
6558
16243
    curr->print(session, str, QT_ORDINARY);
6565
16250
  }
6566
16251
}
6567
16252
 
 
16253
 
6568
16254
/**
6569
16255
  Print joins from the FROM clause.
6570
 
  @param session     thread Cursor
 
16256
  @param session     thread handler
6571
16257
  @param str     string where table should be printed
6572
16258
  @param tables  list of tables in join
6573
16259
  @query_type    type of the query is being generated
6574
16260
*/
6575
 
void print_join(Session *session, String *str,
6576
 
                List<TableList> *tables, enum_query_type)
 
16261
 
 
16262
static void print_join(Session *session, String *str,
 
16263
                       List<TableList> *tables, enum_query_type)
6577
16264
{
6578
16265
  /* List is reversed => we should reverse it before using */
6579
16266
  List_iterator_fast<TableList> ti(*tables);
6584
16271
 
6585
16272
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
6586
16273
    *t= ti++;
 
16274
 
 
16275
  /*
 
16276
    If the first table is a semi-join nest, swap it with something that is
 
16277
    not a semi-join nest.
 
16278
  */
 
16279
  if ((*table)->sj_inner_tables)
 
16280
  {
 
16281
    TableList **end= table + tables->elements;
 
16282
    for (TableList **t2= table; t2!=end; t2++)
 
16283
    {
 
16284
      if (!(*t2)->sj_inner_tables)
 
16285
      {
 
16286
        TableList *tmp= *t2;
 
16287
        *t2= *table;
 
16288
        *table= tmp;
 
16289
        break;
 
16290
      }
 
16291
    }
 
16292
  }
6587
16293
  assert(tables->elements >= 1);
6588
16294
  print_table_array(session, str, table, table + tables->elements);
6589
16295
}
6590
16296
 
 
16297
/**
 
16298
  Print table as it should be in join list.
 
16299
 
 
16300
  @param str   string where table should be printed
 
16301
*/
 
16302
void TableList::print(Session *session, String *str, enum_query_type query_type)
 
16303
{
 
16304
  if (nested_join)
 
16305
  {
 
16306
    str->append('(');
 
16307
    print_join(session, str, &nested_join->join_list, query_type);
 
16308
    str->append(')');
 
16309
  }
 
16310
  else
 
16311
  {
 
16312
    const char *cmp_name;                         // Name to compare with alias
 
16313
    if (derived)
 
16314
    {
 
16315
      // A derived table
 
16316
      str->append('(');
 
16317
      derived->print(str, query_type);
 
16318
      str->append(')');
 
16319
      cmp_name= "";                               // Force printing of alias
 
16320
    }
 
16321
    else
 
16322
    {
 
16323
      // A normal table
 
16324
      {
 
16325
        str->append_identifier(db, db_length);
 
16326
        str->append('.');
 
16327
      }
 
16328
      if (schema_table)
 
16329
      {
 
16330
        str->append_identifier(schema_table_name, strlen(schema_table_name));
 
16331
        cmp_name= schema_table_name;
 
16332
      }
 
16333
      else
 
16334
      {
 
16335
        str->append_identifier(table_name, table_name_length);
 
16336
        cmp_name= table_name;
 
16337
      }
 
16338
    }
 
16339
    if (my_strcasecmp(table_alias_charset, cmp_name, alias))
 
16340
    {
 
16341
 
 
16342
      if (alias && alias[0])
 
16343
      {
 
16344
        str->append(' ');
 
16345
 
 
16346
        string t_alias(alias);
 
16347
        if (lower_case_table_names== 1)
 
16348
          transform(t_alias.begin(), t_alias.end(),
 
16349
                    t_alias.begin(), ::tolower);
 
16350
 
 
16351
        str->append_identifier(t_alias.c_str(), t_alias.length());
 
16352
      }
 
16353
 
 
16354
    }
 
16355
 
 
16356
    if (index_hints)
 
16357
    {
 
16358
      List_iterator<Index_hint> it(*index_hints);
 
16359
      Index_hint *hint;
 
16360
 
 
16361
      while ((hint= it++))
 
16362
      {
 
16363
        str->append (STRING_WITH_LEN(" "));
 
16364
        hint->print (session, str);
 
16365
      }
 
16366
    }
 
16367
  }
 
16368
}
 
16369
 
 
16370
 
6591
16371
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
6592
16372
{
6593
16373
  /* QQ: session may not be set for sub queries, but this should be fixed */
6599
16379
  /* First add options */
6600
16380
  if (options & SELECT_STRAIGHT_JOIN)
6601
16381
    str->append(STRING_WITH_LEN("straight_join "));
 
16382
  if ((session->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
 
16383
      (this == &session->lex->select_lex))
 
16384
    str->append(STRING_WITH_LEN("high_priority "));
6602
16385
  if (options & SELECT_DISTINCT)
6603
16386
    str->append(STRING_WITH_LEN("distinct "));
6604
16387
  if (options & SELECT_SMALL_RESULT)
6699
16482
  // PROCEDURE unsupported here
6700
16483
}
6701
16484
 
 
16485
 
 
16486
/**
 
16487
  change select_result object of JOIN.
 
16488
 
 
16489
  @param res            new select_result object
 
16490
 
 
16491
  @retval
 
16492
    false   OK
 
16493
  @retval
 
16494
    true    error
 
16495
*/
 
16496
 
 
16497
bool JOIN::change_result(select_result *res)
 
16498
{
 
16499
  result= res;
 
16500
  if (result->prepare(fields_list, select_lex->master_unit()))
 
16501
  {
 
16502
    return(true);
 
16503
  }
 
16504
  return(false);
 
16505
}
 
16506
 
6702
16507
/**
6703
16508
  @} (end of group Query_Optimizer)
6704
16509
*/
6705
 
 
6706
 
} /* namespace drizzled */