~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Jay Pipes
  • Date: 2009-03-16 15:20:27 UTC
  • mto: (934.3.7 mordred)
  • mto: This revision was merged to the branch mainline in revision 938.
  • Revision ID: jpipes@serialcoder-20090316152027-njlreaim8vxqta6c
Fixes ENUM field type to throw an error on bad data input.  0 is now not
allowed on insertion.  MySQL allows 0, in the manual it states 0 is "the
null string error index" whatever that means.  Drizzle doesn't allow it.

Corrected test cases.

Also cleans up indentation on JOIN::exec() which was bothering me.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
/**
17
17
  @file
18
18
 
19
19
  @brief
20
 
  select_query and join optimization
 
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
#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>
 
32
#include <drizzled/error.h>
 
33
#include <drizzled/gettext.h>
 
34
#include <drizzled/util/test.h>
 
35
#include <drizzled/name_resolution_context_state.h>
 
36
#include <drizzled/nested_join.h>
 
37
#include <drizzled/probes.h>
 
38
#include <drizzled/show.h>
 
39
#include <drizzled/item/cache.h>
 
40
#include <drizzled/item/cmpfunc.h>
 
41
#include <drizzled/item/copy_string.h>
 
42
#include <drizzled/item/uint.h>
 
43
#include <drizzled/cached_item.h>
 
44
#include <drizzled/sql_base.h>
 
45
#include <drizzled/field/blob.h>
 
46
#include <drizzled/check_stack_overrun.h>
 
47
#include <drizzled/lock.h>
 
48
#include <drizzled/item/outer_ref.h>
26
49
 
27
50
#include <string>
28
 
#include <iostream>
29
 
#include <algorithm>
30
 
#include <vector>
31
 
 
32
 
#include "drizzled/sql_select.h" /* include join.h */
33
 
 
34
 
#include "drizzled/error.h"
35
 
#include "drizzled/gettext.h"
36
 
#include "drizzled/util/test.h"
37
 
#include "drizzled/name_resolution_context_state.h"
38
 
#include "drizzled/nested_join.h"
39
 
#include "drizzled/probes.h"
40
 
#include "drizzled/show.h"
41
 
#include "drizzled/item/cache.h"
42
 
#include "drizzled/item/cmpfunc.h"
43
 
#include "drizzled/item/copy_string.h"
44
 
#include "drizzled/item/uint.h"
45
 
#include "drizzled/cached_item.h"
46
 
#include "drizzled/sql_base.h"
47
 
#include "drizzled/field/blob.h"
48
 
#include "drizzled/check_stack_overrun.h"
49
 
#include "drizzled/lock.h"
50
 
#include "drizzled/item/outer_ref.h"
51
 
#include "drizzled/index_hint.h"
52
 
#include "drizzled/records.h"
53
 
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
#include "drizzled/plugin/storage_engine.h"
56
 
 
57
 
#include "drizzled/sql_union.h"
58
 
#include "drizzled/optimizer/key_field.h"
59
 
#include "drizzled/optimizer/position.h"
60
 
#include "drizzled/optimizer/sargable_param.h"
61
 
#include "drizzled/optimizer/key_use.h"
62
 
#include "drizzled/optimizer/range.h"
63
 
#include "drizzled/optimizer/quick_range_select.h"
64
 
#include "drizzled/optimizer/quick_ror_intersect_select.h"
65
 
 
66
 
#include "drizzled/filesort.h"
67
51
 
68
52
using namespace std;
69
53
 
70
 
namespace drizzled
71
 
{
72
 
 
73
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
 
54
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
 
55
                              "MAYBE_REF","ALL","range","index",
 
56
                              "ref_or_null","unique_subquery","index_subquery",
 
57
                              "index_merge"
 
58
};
 
59
 
 
60
struct st_sargable_param;
 
61
 
 
62
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
 
63
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
 
64
                                 DYNAMIC_ARRAY *keyuse);
 
65
static bool update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,
 
66
                                JOIN_TAB *join_tab,
 
67
                                uint32_t tables, COND *conds,
 
68
                                COND_EQUAL *cond_equal,
 
69
                                table_map table_map, Select_Lex *select_lex,
 
70
                                st_sargable_param **sargables);
 
71
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
 
72
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
 
73
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
74
                               table_map used_tables);
 
75
static bool choose_plan(JOIN *join,table_map join_tables);
 
76
 
 
77
static void best_access_path(JOIN *join, JOIN_TAB *s, Session *session,
 
78
                             table_map remaining_tables, uint32_t idx,
 
79
                             double record_count, double read_time);
 
80
static void optimize_straight_join(JOIN *join, table_map join_tables);
 
81
static bool greedy_search(JOIN *join, table_map remaining_tables,
 
82
                             uint32_t depth, uint32_t prune_level);
 
83
static bool best_extension_by_limited_search(JOIN *join,
 
84
                                             table_map remaining_tables,
 
85
                                             uint32_t idx, double record_count,
 
86
                                             double read_time, uint32_t depth,
 
87
                                             uint32_t prune_level);
 
88
static uint32_t determine_search_depth(JOIN* join);
 
89
extern "C" int join_tab_cmp(const void* ptr1, const void* ptr2);
 
90
extern "C" int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
 
91
/*
 
92
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
 
93
  tested and approved.
 
94
*/
 
95
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index,
 
96
                      double record_count,double read_time);
 
97
static uint32_t cache_record_length(JOIN *join,uint32_t index);
 
98
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
 
99
static bool get_best_combination(JOIN *join);
 
100
static store_key *get_store_key(Session *session,
 
101
                                KEYUSE *keyuse, table_map used_tables,
 
102
                                KEY_PART_INFO *key_part, unsigned char *key_buff,
 
103
                                uint32_t maybe_null);
 
104
static bool make_simple_join(JOIN *join,Table *tmp_table);
 
105
static void make_outerjoin_info(JOIN *join);
 
106
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
 
107
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
 
108
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
 
109
static void update_depend_map(JOIN *join);
 
110
static void update_depend_map(JOIN *join, order_st *order);
 
111
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond,
 
112
                                  bool change_list, bool *simple_order);
 
113
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
 
114
                            List<Item> &fields, bool send_row,
 
115
                            uint64_t select_options, const char *info,
 
116
                            Item *having);
74
117
static COND *build_equal_items(Session *session, COND *cond,
75
118
                               COND_EQUAL *inherited,
76
119
                               List<TableList> *join_list,
77
120
                               COND_EQUAL **cond_equal_ref);
78
 
 
 
121
static COND* substitute_for_best_equal_field(COND *cond,
 
122
                                             COND_EQUAL *cond_equal,
 
123
                                             void *table_join_idx);
 
124
static COND *simplify_joins(JOIN *join, List<TableList> *join_list,
 
125
                            COND *conds, bool top, bool in_sj);
 
126
static bool check_interleaving_with_nj(JOIN_TAB *last, JOIN_TAB *next);
 
127
static void restore_prev_nj_state(JOIN_TAB *last);
 
128
static void reset_nj_counters(List<TableList> *join_list);
 
129
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
 
130
                                          uint32_t first_unused);
 
131
 
 
132
static
 
133
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab);
 
134
static void restore_prev_sj_state(const table_map remaining_tables,
 
135
                                  const JOIN_TAB *tab);
 
136
 
 
137
static COND *optimize_cond(JOIN *join, COND *conds,
 
138
                           List<TableList> *join_list,
 
139
                           Item::cond_result *cond_value);
 
140
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
 
141
static int do_select(JOIN *join,List<Item> *fields,Table *tmp_table);
 
142
 
 
143
static enum_nested_loop_state
 
144
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
 
145
                     int error);
 
146
static enum_nested_loop_state
 
147
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab);
 
148
static enum_nested_loop_state
 
149
flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last);
 
150
static enum_nested_loop_state
 
151
end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
152
static enum_nested_loop_state
 
153
end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
154
static enum_nested_loop_state
 
155
end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
156
static enum_nested_loop_state
 
157
end_unique_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
 
158
 
 
159
static int join_read_const_table(JOIN_TAB *tab, POSITION *pos);
 
160
static int join_read_system(JOIN_TAB *tab);
 
161
static int join_read_const(JOIN_TAB *tab);
 
162
static int join_read_key(JOIN_TAB *tab);
 
163
static int join_read_always_key(JOIN_TAB *tab);
 
164
static int join_read_last_key(JOIN_TAB *tab);
 
165
static int join_no_more_records(READ_RECORD *info);
 
166
static int join_read_next(READ_RECORD *info);
 
167
static int join_read_next_different(READ_RECORD *info);
 
168
static int join_init_quick_read_record(JOIN_TAB *tab);
 
169
static int test_if_quick_select(JOIN_TAB *tab);
 
170
static int join_init_read_record(JOIN_TAB *tab);
 
171
static int join_read_first(JOIN_TAB *tab);
 
172
static int join_read_next_same(READ_RECORD *info);
 
173
static int join_read_next_same_diff(READ_RECORD *info);
 
174
static int join_read_last(JOIN_TAB *tab);
 
175
static int join_read_prev_same(READ_RECORD *info);
 
176
static int join_read_prev(READ_RECORD *info);
 
177
int join_read_always_key_or_null(JOIN_TAB *tab);
 
178
int join_read_next_same_or_null(READ_RECORD *info);
 
179
static COND *make_cond_for_table(COND *cond,table_map table,
 
180
                                 table_map used_table,
 
181
                                 bool exclude_expensive_cond);
79
182
static Item* part_of_refkey(Table *form,Field *field);
80
 
static bool cmp_buffer_with_ref(JoinTable *tab);
81
 
static void change_cond_ref_to_const(Session *session,
82
 
                                     list<COND_CMP>& save_list,
83
 
                                     Item *and_father,
84
 
                                     Item *cond,
85
 
                                     Item *field,
86
 
                                     Item *value);
87
 
static bool copy_blobs(Field **ptr);
 
183
static bool test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,
 
184
                                    ha_rows select_limit, bool no_changes,
 
185
                                    const key_map *map);
 
186
static bool list_contains_unique_index(Table *table,
 
187
                          bool (*find_func) (Field *, void *), void *data);
 
188
static bool find_field_in_item_list (Field *field, void *data);
 
189
static bool find_field_in_order_list (Field *field, void *data);
 
190
static int create_sort_index(Session *session, JOIN *join, order_st *order,
 
191
                             ha_rows filesort_limit, ha_rows select_limit,
 
192
                             bool is_order_by);
 
193
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
 
194
                             Item *having);
 
195
static int remove_dup_with_compare(Session *session, Table *entry, Field **field,
 
196
                                   uint32_t offset, Item *having);
 
197
static int remove_dup_with_hash_index(Session *session,Table *table,
 
198
                                      uint32_t field_count, Field **first_field,
 
199
                                      uint32_t key_length, Item *having);
 
200
static int join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count);
 
201
static uint32_t used_blob_length(CACHE_FIELD **ptr);
 
202
static bool store_record_in_cache(JOIN_CACHE *cache);
 
203
static void reset_cache_read(JOIN_CACHE *cache);
 
204
static void reset_cache_write(JOIN_CACHE *cache);
 
205
static void read_cached_record(JOIN_TAB *tab);
 
206
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
 
207
static order_st *create_distinct_group(Session *session, Item **ref_pointer_array,
 
208
                                    order_st *order, List<Item> &fields,
 
209
                                    List<Item> &all_fields,
 
210
                                    bool *all_order_by_fields_used);
 
211
static bool test_if_subpart(order_st *a,order_st *b);
 
212
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
 
213
static void calc_group_buffer(JOIN *join,order_st *group);
 
214
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
 
215
static bool alloc_group_fields(JOIN *join,order_st *group);
 
216
// Create list for using with tempory table
 
217
static bool change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
 
218
                                     List<Item> &new_list1,
 
219
                                     List<Item> &new_list2,
 
220
                                     uint32_t elements, List<Item> &items);
 
221
// Create list for using with tempory table
 
222
static bool change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
 
223
                                      List<Item> &new_list1,
 
224
                                      List<Item> &new_list2,
 
225
                                      uint32_t elements, List<Item> &items);
 
226
static void init_tmptable_sum_functions(Item_sum **func);
 
227
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
 
228
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
 
229
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab);
 
230
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr);
 
231
static bool init_sum_functions(Item_sum **func, Item_sum **end);
 
232
static bool update_sum_func(Item_sum **func);
 
233
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
 
234
                            bool distinct, const char *message=NULL);
 
235
static Item *remove_additional_cond(Item* conds);
 
236
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
 
237
static bool test_if_ref(Item_field *left_item,Item *right_item);
 
238
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
 
239
                                       Item *new_cond, bool fix_fields);
88
240
 
89
241
static bool eval_const_cond(COND *cond)
90
242
{
91
243
    return ((Item_func*) cond)->val_int() ? true : false;
92
244
}
93
245
 
 
246
 
94
247
/*
95
248
  This is used to mark equalities that were made from i-th IN-equality.
96
249
  We limit semi-join InsideOut optimization to handling max 64 inequalities,
99
252
const char *subq_sj_cond_name=
100
253
  "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
101
254
 
102
 
static bool copy_blobs(Field **ptr)
 
255
static bool bitmap_covers(const table_map x, const table_map y)
103
256
{
104
 
  for (; *ptr ; ptr++)
105
 
  {
106
 
    if ((*ptr)->flags & BLOB_FLAG)
107
 
      if (((Field_blob *) (*ptr))->copy())
108
 
        return 1;                               // Error
109
 
  }
110
 
  return 0;
 
257
  return !test(y & ~x);
111
258
}
112
259
 
113
260
/**
114
261
  This handles SELECT with and without UNION.
115
262
*/
 
263
 
116
264
bool handle_select(Session *session, LEX *lex, select_result *result,
117
265
                   uint64_t setup_tables_done_option)
118
266
{
119
267
  bool res;
120
 
  register Select_Lex *select_lex= &lex->select_lex;
121
 
  DRIZZLE_SELECT_START(session->getQueryString()->c_str());
 
268
  register Select_Lex *select_lex = &lex->select_lex;
 
269
  DRIZZLE_SELECT_START();
122
270
 
123
271
  if (select_lex->master_unit()->is_union() ||
124
272
      select_lex->master_unit()->fake_select_lex)
125
 
  {
126
 
    res= drizzle_union(session, lex, result, &lex->unit,
127
 
                       setup_tables_done_option);
128
 
  }
 
273
    res= mysql_union(session, lex, result, &lex->unit, setup_tables_done_option);
129
274
  else
130
275
  {
131
276
    Select_Lex_Unit *unit= &lex->unit;
132
277
    unit->set_limit(unit->global_parameters);
133
278
    session->session_marker= 0;
134
279
    /*
135
 
      'options' of select_query will be set in JOIN, as far as JOIN for
 
280
      'options' of mysql_select will be set in JOIN, as far as JOIN for
136
281
      every PS/SP execution new, we will not need reset this flag if
137
282
      setup_tables_done_option changed for next rexecution
138
283
    */
139
 
    res= select_query(session,
140
 
                      &select_lex->ref_pointer_array,
 
284
    res= mysql_select(session, &select_lex->ref_pointer_array,
141
285
                      (TableList*) select_lex->table_list.first,
142
 
                      select_lex->with_wild,
143
 
                      select_lex->item_list,
 
286
                      select_lex->with_wild, select_lex->item_list,
144
287
                      select_lex->where,
145
288
                      select_lex->order_list.elements +
146
289
                      select_lex->group_list.elements,
147
 
                      (Order*) select_lex->order_list.first,
148
 
                      (Order*) select_lex->group_list.first,
 
290
                      (order_st*) select_lex->order_list.first,
 
291
                      (order_st*) select_lex->group_list.first,
149
292
                      select_lex->having,
150
293
                      select_lex->options | session->options |
151
294
                      setup_tables_done_option,
155
298
  if (unlikely(res))
156
299
    result->abort();
157
300
 
158
 
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
159
 
  return res;
 
301
  DRIZZLE_SELECT_END();
 
302
  return(res);
160
303
}
161
304
 
 
305
 
162
306
/*
163
307
  Fix fields referenced from inner selects.
164
308
 
199
343
    true  an error occured
200
344
    false ok
201
345
*/
202
 
bool fix_inner_refs(Session *session, 
203
 
                    List<Item> &all_fields, 
204
 
                    Select_Lex *select, 
205
 
                    Item **ref_pointer_array)
 
346
 
 
347
bool
 
348
fix_inner_refs(Session *session, List<Item> &all_fields, Select_Lex *select,
 
349
                 Item **ref_pointer_array)
206
350
{
207
351
  Item_outer_ref *ref;
208
352
  bool res= false;
269
413
  return res;
270
414
}
271
415
 
 
416
/**
 
417
  Function to setup clauses without sum functions.
 
418
*/
 
419
inline int setup_without_group(Session *session, Item **ref_pointer_array,
 
420
                               TableList *tables,
 
421
                               TableList *leaves,
 
422
                               List<Item> &fields,
 
423
                               List<Item> &all_fields,
 
424
                               COND **conds,
 
425
                               order_st *order,
 
426
                               order_st *group, bool *hidden_group_fields)
 
427
{
 
428
  int res;
 
429
  nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
 
430
 
 
431
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
 
432
  res= setup_conds(session, tables, leaves, conds);
 
433
 
 
434
  session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
 
435
  res= res || setup_order(session, ref_pointer_array, tables, fields, all_fields,
 
436
                          order);
 
437
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
 
438
  res= res || setup_group(session, ref_pointer_array, tables, fields, all_fields,
 
439
                          group, hidden_group_fields);
 
440
  session->lex->allow_sum_func= save_allow_sum_func;
 
441
  return(res);
 
442
}
 
443
 
272
444
/*****************************************************************************
273
445
  Check fields, find best join, do the select and output fields.
274
 
  select_query assumes that all tables are already opened
 
446
  mysql_select assumes that all tables are already opened
275
447
*****************************************************************************/
276
448
 
 
449
/**
 
450
  Prepare of whole select (including sub queries in future).
 
451
 
 
452
  @todo
 
453
    Add check of calculation of GROUP functions and fields:
 
454
    SELECT COUNT(*)+table.col1 from table1;
 
455
 
 
456
  @retval
 
457
    -1   on error
 
458
  @retval
 
459
    0   on success
 
460
*/
 
461
int
 
462
JOIN::prepare(Item ***rref_pointer_array,
 
463
              TableList *tables_init,
 
464
              uint32_t wild_num, COND *conds_init, uint32_t og_num,
 
465
              order_st *order_init, order_st *group_init,
 
466
              Item *having_init,
 
467
              Select_Lex *select_lex_arg,
 
468
              Select_Lex_Unit *unit_arg)
 
469
{
 
470
  // to prevent double initialization on EXPLAIN
 
471
  if (optimized)
 
472
    return(0);
 
473
 
 
474
  conds= conds_init;
 
475
  order= order_init;
 
476
  group_list= group_init;
 
477
  having= having_init;
 
478
  tables_list= tables_init;
 
479
  select_lex= select_lex_arg;
 
480
  select_lex->join= this;
 
481
  join_list= &select_lex->top_join_list;
 
482
  union_part= unit_arg->is_union();
 
483
 
 
484
  session->lex->current_select->is_item_list_lookup= 1;
 
485
  /*
 
486
    If we have already executed SELECT, then it have not sense to prevent
 
487
    its table from update (see unique_table())
 
488
  */
 
489
  if (session->derived_tables_processing)
 
490
    select_lex->exclude_from_table_unique_test= true;
 
491
 
 
492
  /* Check that all tables, fields, conds and order are ok */
 
493
 
 
494
  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
 
495
      setup_tables_and_check_access(session, &select_lex->context, join_list,
 
496
                                    tables_list, &select_lex->leaf_tables,
 
497
                                    false))
 
498
      return(-1);
 
499
 
 
500
  TableList *table_ptr;
 
501
  for (table_ptr= select_lex->leaf_tables;
 
502
       table_ptr;
 
503
       table_ptr= table_ptr->next_leaf)
 
504
    tables++;
 
505
 
 
506
  if (setup_wild(session, tables_list, fields_list, &all_fields, wild_num) ||
 
507
      select_lex->setup_ref_array(session, og_num) ||
 
508
      setup_fields(session, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
 
509
                   &all_fields, 1) ||
 
510
      setup_without_group(session, (*rref_pointer_array), tables_list,
 
511
                          select_lex->leaf_tables, fields_list,
 
512
                          all_fields, &conds, order, group_list,
 
513
                          &hidden_group_fields))
 
514
    return(-1);                         /* purecov: inspected */
 
515
 
 
516
  ref_pointer_array= *rref_pointer_array;
 
517
 
 
518
  if (having)
 
519
  {
 
520
    nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
521
    session->where="having clause";
 
522
    session->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
 
523
    select_lex->having_fix_field= 1;
 
524
    bool having_fix_rc= (!having->fixed &&
 
525
                         (having->fix_fields(session, &having) ||
 
526
                          having->check_cols(1)));
 
527
    select_lex->having_fix_field= 0;
 
528
    if (having_fix_rc || session->is_error())
 
529
      return(-1);                               /* purecov: inspected */
 
530
    session->lex->allow_sum_func= save_allow_sum_func;
 
531
  }
 
532
 
 
533
  {
 
534
    Item_subselect *subselect;
 
535
    Item_in_subselect *in_subs= NULL;
 
536
    /*
 
537
      Are we in a subquery predicate?
 
538
      TODO: the block below will be executed for every PS execution without need.
 
539
    */
 
540
    if ((subselect= select_lex->master_unit()->item))
 
541
    {
 
542
      bool do_semijoin= !test(session->variables.optimizer_switch &
 
543
                              OPTIMIZER_SWITCH_NO_SEMIJOIN);
 
544
      if (subselect->substype() == Item_subselect::IN_SUBS)
 
545
        in_subs= (Item_in_subselect*)subselect;
 
546
 
 
547
      /*
 
548
        Check if we're in subquery that is a candidate for flattening into a
 
549
        semi-join (which is done done in flatten_subqueries()). The
 
550
        requirements are:
 
551
          1. Subquery predicate is an IN/=ANY subq predicate
 
552
          2. Subquery is a single SELECT (not a UNION)
 
553
          3. Subquery does not have GROUP BY or order_st BY
 
554
          4. Subquery does not use aggregate functions or HAVING
 
555
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
 
556
          6. No execution method was already chosen (by a prepared statement).
 
557
 
 
558
          (*). We are not in a subquery of a single table UPDATE/DELETE that
 
559
               doesn't have a JOIN (TODO: We should handle this at some
 
560
               point by switching to multi-table UPDATE/DELETE)
 
561
 
 
562
          (**). We're not in a confluent table-less subquery, like
 
563
                "SELECT 1".
 
564
      */
 
565
      if (in_subs &&                                                    // 1
 
566
          !select_lex->master_unit()->first_select()->next_select() &&  // 2
 
567
          !select_lex->group_list.elements && !order &&                 // 3
 
568
          !having && !select_lex->with_sum_func &&                      // 4
 
569
          session->session_marker &&                                            // 5
 
570
          select_lex->outer_select()->join &&                           // (*)
 
571
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**)
 
572
          do_semijoin &&
 
573
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
 
574
      {
 
575
        {
 
576
          if (!in_subs->left_expr->fixed &&
 
577
               in_subs->left_expr->fix_fields(session, &in_subs->left_expr))
 
578
          {
 
579
            return(-1);
 
580
          }
 
581
          /*
 
582
            Check that the right part of the subselect contains no more than one
 
583
            column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
 
584
          */
 
585
          if (subselect->substype() == Item_subselect::IN_SUBS &&
 
586
             (select_lex->item_list.elements !=
 
587
              ((Item_in_subselect*)subselect)->left_expr->cols()))
 
588
          {
 
589
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
 
590
            return(-1);
 
591
          }
 
592
        }
 
593
 
 
594
        /* Register the subquery for further processing */
 
595
        select_lex->outer_select()->join->sj_subselects.append(session->mem_root, in_subs);
 
596
        in_subs->expr_join_nest= (TableList*)session->session_marker;
 
597
      }
 
598
      else
 
599
      {
 
600
        bool do_materialize= !test(session->variables.optimizer_switch &
 
601
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
 
602
        /*
 
603
          Check if the subquery predicate can be executed via materialization.
 
604
          The required conditions are:
 
605
          1. Subquery predicate is an IN/=ANY subq predicate
 
606
          2. Subquery is a single SELECT (not a UNION)
 
607
          3. Subquery is not a table-less query. In this case there is no
 
608
             point in materializing.
 
609
          4. Subquery predicate is a top-level predicate
 
610
             (this implies it is not negated)
 
611
             TODO: this is a limitation that should be lifeted once we
 
612
             implement correct NULL semantics (WL#3830)
 
613
          5. Subquery is non-correlated
 
614
             TODO:
 
615
             This is an overly restrictive condition. It can be extended to:
 
616
             (Subquery is non-correlated ||
 
617
              Subquery is correlated to any query outer to IN predicate ||
 
618
              (Subquery is correlated to the immediate outer query &&
 
619
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
 
620
               aggregate functions) && subquery predicate is not under "NOT IN"))
 
621
          6. No execution method was already chosen (by a prepared statement).
 
622
 
 
623
          (*) The subquery must be part of a SELECT statement. The current
 
624
               condition also excludes multi-table update statements.
 
625
 
 
626
          We have to determine whether we will perform subquery materialization
 
627
          before calling the IN=>EXISTS transformation, so that we know whether to
 
628
          perform the whole transformation or only that part of it which wraps
 
629
          Item_in_subselect in an Item_in_optimizer.
 
630
        */
 
631
        if (do_materialize &&
 
632
            in_subs  &&                                                   // 1
 
633
            !select_lex->master_unit()->first_select()->next_select() &&  // 2
 
634
            select_lex->master_unit()->first_select()->leaf_tables &&     // 3
 
635
            session->lex->sql_command == SQLCOM_SELECT)                       // *
 
636
        {
 
637
          if (in_subs->is_top_level_item() &&                             // 4
 
638
              !in_subs->is_correlated &&                                  // 5
 
639
              in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED) // 6
 
640
            in_subs->exec_method= Item_in_subselect::MATERIALIZATION;
 
641
        }
 
642
 
 
643
        Item_subselect::trans_res trans_res;
 
644
        if ((trans_res= subselect->select_transformer(this)) !=
 
645
            Item_subselect::RES_OK)
 
646
        {
 
647
          return((trans_res == Item_subselect::RES_ERROR));
 
648
        }
 
649
      }
 
650
    }
 
651
  }
 
652
 
 
653
  if (order)
 
654
  {
 
655
    order_st *ord;
 
656
    for (ord= order; ord; ord= ord->next)
 
657
    {
 
658
      Item *item= *ord->item;
 
659
      if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
 
660
        item->split_sum_func(session, ref_pointer_array, all_fields);
 
661
    }
 
662
  }
 
663
 
 
664
  if (having && having->with_sum_func)
 
665
    having->split_sum_func(session, ref_pointer_array, all_fields,
 
666
                           &having, true);
 
667
  if (select_lex->inner_sum_func_list)
 
668
  {
 
669
    Item_sum *end=select_lex->inner_sum_func_list;
 
670
    Item_sum *item_sum= end;
 
671
    do
 
672
    {
 
673
      item_sum= item_sum->next;
 
674
      item_sum->split_sum_func(session, ref_pointer_array,
 
675
                               all_fields, item_sum->ref_by, false);
 
676
    } while (item_sum != end);
 
677
  }
 
678
 
 
679
  if (select_lex->inner_refs_list.elements &&
 
680
      fix_inner_refs(session, all_fields, select_lex, ref_pointer_array))
 
681
    return(-1);
 
682
 
 
683
  /*
 
684
    Check if there are references to un-aggregated columns when computing
 
685
    aggregate functions with implicit grouping (there is no GROUP BY).
 
686
 
 
687
    MODE_ONLY_FULL_GROUP_BY is enabled here by default
 
688
  */
 
689
  if (!group_list && select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED))
 
690
  {
 
691
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
 
692
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
 
693
    return(-1);
 
694
  }
 
695
  {
 
696
    /* Caclulate the number of groups */
 
697
    send_group_parts= 0;
 
698
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
699
      send_group_parts++;
 
700
  }
 
701
 
 
702
  if (error)
 
703
    goto err;                                   /* purecov: inspected */
 
704
 
 
705
  if (result && result->prepare(fields_list, unit_arg))
 
706
    goto err;                                   /* purecov: inspected */
 
707
 
 
708
  /* Init join struct */
 
709
  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
 
710
  ref_pointer_array_size= all_fields.elements*sizeof(Item*);
 
711
  this->group= group_list != 0;
 
712
  unit= unit_arg;
 
713
 
 
714
#ifdef RESTRICTED_GROUP
 
715
  if (sum_func_count && !group_list && (func_count || field_count))
 
716
  {
 
717
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
 
718
    goto err;
 
719
  }
 
720
#endif
 
721
  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
 
722
    goto err;
 
723
  if (alloc_func_list())
 
724
    goto err;
 
725
 
 
726
  return(0); // All OK
 
727
 
 
728
err:
 
729
  return(-1);                           /* purecov: inspected */
 
730
}
 
731
 
 
732
 
 
733
/*
 
734
  Remove the predicates pushed down into the subquery
 
735
 
 
736
  SYNOPSIS
 
737
    JOIN::remove_subq_pushed_predicates()
 
738
      where   IN  Must be NULL
 
739
              OUT The remaining WHERE condition, or NULL
 
740
 
 
741
  DESCRIPTION
 
742
    Given that this join will be executed using (unique|index)_subquery,
 
743
    without "checking NULL", remove the predicates that were pushed down
 
744
    into the subquery.
 
745
 
 
746
    If the subquery compares scalar values, we can remove the condition that
 
747
    was wrapped into trig_cond (it will be checked when needed by the subquery
 
748
    engine)
 
749
 
 
750
    If the subquery compares row values, we need to keep the wrapped
 
751
    equalities in the WHERE clause: when the left (outer) tuple has both NULL
 
752
    and non-NULL values, we'll do a full table scan and will rely on the
 
753
    equalities corresponding to non-NULL parts of left tuple to filter out
 
754
    non-matching records.
 
755
 
 
756
    TODO: We can remove the equalities that will be guaranteed to be true by the
 
757
    fact that subquery engine will be using index lookup. This must be done only
 
758
    for cases where there are no conversion errors of significance, e.g. 257
 
759
    that is searched in a byte. But this requires homogenization of the return
 
760
    codes of all Field*::store() methods.
 
761
*/
 
762
 
 
763
void JOIN::remove_subq_pushed_predicates(Item **where)
 
764
{
 
765
  if (conds->type() == Item::FUNC_ITEM &&
 
766
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
 
767
      ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
 
768
      ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM &&
 
769
      test_if_ref ((Item_field *)((Item_func *)conds)->arguments()[1],
 
770
                   ((Item_func *)conds)->arguments()[0]))
 
771
  {
 
772
    *where= 0;
 
773
    return;
 
774
  }
 
775
}
 
776
 
 
777
 
277
778
/*
278
779
  Index lookup-based subquery: save some flags for EXPLAIN output
279
780
 
292
793
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
293
794
    and set appropriate flags in join_tab->packed_info.
294
795
*/
295
 
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
 
796
 
 
797
static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
296
798
{
297
799
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
298
 
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
 
800
  if (join_tab->table->covering_keys.is_set(join_tab->ref.key))
299
801
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
300
802
  if (where)
301
803
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
309
811
  }
310
812
}
311
813
 
 
814
 
 
815
 
 
816
 
 
817
/*
 
818
  Check if the table's rowid is included in the temptable
 
819
 
 
820
  SYNOPSIS
 
821
    sj_table_is_included()
 
822
      join      The join
 
823
      join_tab  The table to be checked
 
824
 
 
825
  DESCRIPTION
 
826
    SemiJoinDuplicateElimination: check the table's rowid should be included
 
827
    in the temptable. This is so if
 
828
 
 
829
    1. The table is not embedded within some semi-join nest
 
830
    2. The has been pulled out of a semi-join nest, or
 
831
 
 
832
    3. The table is functionally dependent on some previous table
 
833
 
 
834
    [4. This is also true for constant tables that can't be
 
835
        NULL-complemented but this function is not called for such tables]
 
836
 
 
837
  RETURN
 
838
    true  - Include table's rowid
 
839
    false - Don't
 
840
*/
 
841
 
 
842
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab)
 
843
{
 
844
  if (join_tab->emb_sj_nest)
 
845
    return false;
 
846
 
 
847
  /* Check if this table is functionally dependent on the tables that
 
848
     are within the same outer join nest
 
849
  */
 
850
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
 
851
  if (join_tab->type == JT_EQ_REF)
 
852
  {
 
853
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
 
854
    uint32_t idx;
 
855
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
 
856
    {
 
857
      JOIN_TAB *ref_tab= join->join_tab + idx;
 
858
      if (embedding == ref_tab->table->pos_in_table_list->embedding)
 
859
        return true;
 
860
    }
 
861
    /* Ok, functionally dependent */
 
862
    return false;
 
863
  }
 
864
  /* Not functionally dependent => need to include*/
 
865
  return true;
 
866
}
 
867
 
 
868
 
 
869
/*
 
870
  Setup the strategies to eliminate semi-join duplicates.
 
871
 
 
872
  SYNOPSIS
 
873
    setup_semijoin_dups_elimination()
 
874
      join           Join to process
 
875
      options        Join options (needed to see if join buffering will be
 
876
                     used or not)
 
877
      no_jbuf_after  Another bit of information re where join buffering will
 
878
                     be used.
 
879
 
 
880
  DESCRIPTION
 
881
    Setup the strategies to eliminate semi-join duplicates. ATM there are 3
 
882
    strategies:
 
883
 
 
884
    1. DuplicateWeedout (use of temptable to remove duplicates based on rowids
 
885
                         of row combinations)
 
886
    2. FirstMatch (pick only the 1st matching row combination of inner tables)
 
887
    3. InsideOut (scanning the sj-inner table in a way that groups duplicates
 
888
                  together and picking the 1st one)
 
889
 
 
890
    The join order has "duplicate-generating ranges", and every range is
 
891
    served by one strategy or a combination of FirstMatch with with some
 
892
    other strategy.
 
893
 
 
894
    "Duplicate-generating range" is defined as a range within the join order
 
895
    that contains all of the inner tables of a semi-join. All ranges must be
 
896
    disjoint, if tables of several semi-joins are interleaved, then the ranges
 
897
    are joined together, which is equivalent to converting
 
898
      SELECT ... WHERE oe1 IN (SELECT ie1 ...) AND oe2 IN (SELECT ie2 )
 
899
    to
 
900
      SELECT ... WHERE (oe1, oe2) IN (SELECT ie1, ie2 ... ...)
 
901
    .
 
902
 
 
903
    Applicability conditions are as follows:
 
904
 
 
905
    DuplicateWeedout strategy
 
906
    ~~~~~~~~~~~~~~~~~~~~~~~~~
 
907
 
 
908
      (ot|nt)*  [ it ((it|ot|nt)* (it|ot))]  (nt)*
 
909
      +------+  +=========================+  +---+
 
910
        (1)                 (2)               (3)
 
911
 
 
912
       (1) - Prefix of OuterTables (those that participate in
 
913
             IN-equality and/or are correlated with subquery) and outer
 
914
             Noncorrelated Tables.
 
915
       (2) - The handled range. The range starts with the first sj-inner
 
916
             table, and covers all sj-inner and outer tables
 
917
             Within the range,  Inner, Outer, outer Noncorrelated tables
 
918
             may follow in any order.
 
919
       (3) - The suffix of outer Noncorrelated tables.
 
920
 
 
921
    FirstMatch strategy
 
922
    ~~~~~~~~~~~~~~~~~~~
 
923
 
 
924
      (ot|nt)*  [ it ((it|nt)* it) ]  (nt)*
 
925
      +------+  +==================+  +---+
 
926
        (1)             (2)          (3)
 
927
 
 
928
      (1) - Prefix of outer and non-correlated tables
 
929
      (2) - The handled range, which may contain only inner and
 
930
            non-correlated tables.
 
931
      (3) - The suffix of outer Noncorrelated tables.
 
932
 
 
933
    InsideOut strategy
 
934
    ~~~~~~~~~~~~~~~~~~
 
935
 
 
936
     (ot|ct|nt) [ insideout_tbl (ot|nt|it)* it ]  (ot|nt)*
 
937
     +--------+   +===========+ +=============+   +------+
 
938
        (1)           (2)          (3)              (4)
 
939
 
 
940
      (1) - Prefix that may contain any outer tables. The prefix must contain
 
941
            all the non-trivially correlated outer tables. (non-trivially means
 
942
            that the correlation is not just through the IN-equality).
 
943
 
 
944
      (2) - Inner table for which the InsideOut scan is performed.
 
945
 
 
946
      (3) - The remainder of the duplicate-generating range. It is served by
 
947
            application of FirstMatch strategy, with the exception that
 
948
            outer IN-correlated tables are considered to be non-correlated.
 
949
 
 
950
      (4) - THe suffix of outer and outer non-correlated tables.
 
951
 
 
952
    If several strategies are applicable, their relative priorities are:
 
953
      1. InsideOut
 
954
      2. FirstMatch
 
955
      3. DuplicateWeedout
 
956
 
 
957
    This function walks over the join order and sets up the strategies by
 
958
    setting appropriate members in join_tab structures.
 
959
 
 
960
  RETURN
 
961
    false  OK
 
962
    true   Out of memory error
 
963
*/
 
964
 
 
965
static
 
966
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
967
{
 
968
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
969
  struct {
 
970
    /*
 
971
      0 - invalid (EOF marker),
 
972
      1 - InsideOut,
 
973
      2 - Temptable (maybe confluent),
 
974
      3 - Temptable with join buffering
 
975
    */
 
976
    uint32_t strategy;
 
977
    uint32_t start_idx; /* Left range bound */
 
978
    uint32_t end_idx;   /* Right range bound */
 
979
    /*
 
980
      For Temptable strategy: Bitmap of all outer and correlated tables from
 
981
      all involved join nests.
 
982
    */
 
983
    table_map outer_tables;
 
984
  } dups_ranges [MAX_TABLES];
 
985
 
 
986
  TableList *emb_insideout_nest= NULL;
 
987
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
 
988
                               tables) whose ranges we're in */
 
989
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
 
990
  table_map range_start_map= 0; /* table_map at current range start */
 
991
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
 
992
  int cur_range= 0;
 
993
  uint32_t i;
 
994
 
 
995
  /*
 
996
    First pass: locate the duplicate-generating ranges and pick the strategies.
 
997
  */
 
998
  for (i=join->const_tables ; i < join->tables ; i++)
 
999
  {
 
1000
    JOIN_TAB *tab=join->join_tab+i;
 
1001
    Table *table=tab->table;
 
1002
    cur_map |= table->map;
 
1003
 
 
1004
    if (tab->emb_sj_nest) // Encountered an sj-inner table
 
1005
    {
 
1006
      if (!emb_sj_map)
 
1007
      {
 
1008
        dups_ranges[cur_range].start_idx= i;
 
1009
        range_start_map= cur_map & ~table->map;
 
1010
        /*
 
1011
          Remember if this is a possible start of range that is covered by
 
1012
          the InsideOut strategy (the reason that it is not covered could
 
1013
          be that it overlaps with anther semi-join's range. we don't
 
1014
          support InsideOut for joined ranges)
 
1015
        */
 
1016
        if (join->best_positions[i].use_insideout_scan)
 
1017
          emb_insideout_nest= tab->emb_sj_nest;
 
1018
      }
 
1019
 
 
1020
      emb_sj_map |= tab->emb_sj_nest->sj_inner_tables;
 
1021
      emb_outer_tables |= tab->emb_sj_nest->nested_join->sj_depends_on;
 
1022
 
 
1023
      if (tab->emb_sj_nest != emb_insideout_nest)
 
1024
      {
 
1025
        /*
 
1026
          Two different semi-joins interleave. This cannot be handled by
 
1027
          InsideOut strategy.
 
1028
        */
 
1029
        emb_insideout_nest= NULL;
 
1030
      }
 
1031
    }
 
1032
 
 
1033
    if (emb_sj_map) /* We're in duplicate-generating range */
 
1034
    {
 
1035
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
1036
          tab->type == JT_ALL && tab->use_quick != 2 && !tab->first_inner &&
 
1037
          i <= no_jbuf_after && !dealing_with_jbuf)
 
1038
      {
 
1039
        /*
 
1040
          This table uses join buffering, which makes use of FirstMatch or
 
1041
          InsideOut strategies impossible for the current and (we assume)
 
1042
          preceding duplicate-producing ranges.
 
1043
          That is, for the join order:
 
1044
 
 
1045
              x x [ x  x]  x  [x x x]  x  [x x X*  x] x
 
1046
                  |     |     |     |          | \
 
1047
                  +-----+     +-----+          |  join buffering use
 
1048
                     r1          r2         we're here
 
1049
 
 
1050
          we'll have to remove r1 and r2 and use duplicate-elimination
 
1051
          strategy that spans all the tables, starting from the very 1st
 
1052
          one.
 
1053
        */
 
1054
        dealing_with_jbuf= true;
 
1055
        emb_insideout_nest= false;
 
1056
 
 
1057
        /*
 
1058
          Absorb all preceding duplicate-eliminating ranges. Their strategies
 
1059
          do not matter:
 
1060
        */
 
1061
        for (int prev_range= 0; prev_range < cur_range; prev_range++)
 
1062
        {
 
1063
          dups_ranges[cur_range].outer_tables |=
 
1064
            dups_ranges[prev_range].outer_tables;
 
1065
        }
 
1066
        dups_ranges[0].start_idx= 0; /* Will need to start from the 1st table */
 
1067
        dups_ranges[0].outer_tables= dups_ranges[cur_range].outer_tables;
 
1068
        cur_range=  0;
 
1069
      }
 
1070
 
 
1071
      /*
 
1072
        Check if we are at the end of duplicate-producing range. We are if
 
1073
 
 
1074
        1. It's an InsideOut range (which presumes all correlated tables are
 
1075
           in the prefix), and all inner tables are in the join order prefix,
 
1076
           or
 
1077
        2. It's a DuplicateElimination range (possibly covering several
 
1078
           SJ-nests), and all inner, outer, and correlated tables of all
 
1079
           sj-nests are in the join order prefix.
 
1080
      */
 
1081
      bool end_of_range= false;
 
1082
      if (emb_insideout_nest &&
 
1083
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
 
1084
      {
 
1085
        /* Save that this range is handled with InsideOut: */
 
1086
        dups_ranges[cur_range].strategy= 1;
 
1087
        end_of_range= true;
 
1088
      }
 
1089
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
 
1090
      {
 
1091
        /*
 
1092
          This is a complete range to be handled with either DuplicateWeedout
 
1093
          or FirstMatch
 
1094
        */
 
1095
        dups_ranges[cur_range].strategy= dealing_with_jbuf? 3 : 2;
 
1096
        /*
 
1097
          This will hold tables from within the range that need to be put
 
1098
          into the join buffer before we can use the FirstMatch on its tail.
 
1099
        */
 
1100
        dups_ranges[cur_range].outer_tables= emb_outer_tables &
 
1101
                                             ~range_start_map;
 
1102
        end_of_range= true;
 
1103
      }
 
1104
 
 
1105
      if (end_of_range)
 
1106
      {
 
1107
        dups_ranges[cur_range].end_idx= i+1;
 
1108
        emb_sj_map= emb_outer_tables= 0;
 
1109
        emb_insideout_nest= NULL;
 
1110
        dealing_with_jbuf= false;
 
1111
        dups_ranges[++cur_range].strategy= 0;
 
1112
      }
 
1113
    }
 
1114
  }
 
1115
 
 
1116
  Session *session= join->session;
 
1117
  SJ_TMP_TABLE **next_sjtbl_ptr= &join->sj_tmp_tables;
 
1118
  /*
 
1119
    Second pass: setup the chosen strategies
 
1120
  */
 
1121
  for (int j= 0; j < cur_range; j++)
 
1122
  {
 
1123
    JOIN_TAB *tab=join->join_tab + dups_ranges[j].start_idx;
 
1124
    JOIN_TAB *jump_to;
 
1125
    if (dups_ranges[j].strategy == 1)  // InsideOut strategy
 
1126
    {
 
1127
      tab->insideout_match_tab= join->join_tab + dups_ranges[j].end_idx - 1;
 
1128
      jump_to= tab++;
 
1129
    }
 
1130
    else // DuplicateWeedout strategy
 
1131
    {
 
1132
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
 
1133
      table_map weed_cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
1134
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
 
1135
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
 
1136
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
 
1137
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
 
1138
      JOIN_TAB *last_outer_tab= tab - 1;
 
1139
      /*
 
1140
        Walk through the range and remember
 
1141
         - tables that need their rowids to be put into temptable
 
1142
         - the last outer table
 
1143
      */
 
1144
      for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
1145
      {
 
1146
        if (sj_table_is_included(join, tab))
 
1147
        {
 
1148
          last_tab->join_tab= tab;
 
1149
          last_tab->rowid_offset= jt_rowid_offset;
 
1150
          jt_rowid_offset += tab->table->file->ref_length;
 
1151
          if (tab->table->maybe_null)
 
1152
          {
 
1153
            last_tab->null_byte= jt_null_bits / 8;
 
1154
            last_tab->null_bit= jt_null_bits++;
 
1155
          }
 
1156
          last_tab++;
 
1157
          tab->table->prepare_for_position();
 
1158
          tab->rowid_keep_flags= rowid_keep_flags;
 
1159
        }
 
1160
        weed_cur_map |= tab->table->map;
 
1161
        if (!tab->emb_sj_nest && bitmap_covers(weed_cur_map,
 
1162
                                               dups_ranges[j].outer_tables))
 
1163
          last_outer_tab= tab;
 
1164
      }
 
1165
 
 
1166
      if (jt_rowid_offset) /* Temptable has at least one rowid */
 
1167
      {
 
1168
        SJ_TMP_TABLE *sjtbl;
 
1169
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
 
1170
        if (!(sjtbl= (SJ_TMP_TABLE*)session->alloc(sizeof(SJ_TMP_TABLE))) ||
 
1171
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) session->alloc(tabs_size)))
 
1172
          return(true);
 
1173
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
 
1174
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
 
1175
        sjtbl->rowid_len= jt_rowid_offset;
 
1176
        sjtbl->null_bits= jt_null_bits;
 
1177
        sjtbl->null_bytes= (jt_null_bits + 7)/8;
 
1178
 
 
1179
        *next_sjtbl_ptr= sjtbl;
 
1180
        next_sjtbl_ptr= &(sjtbl->next);
 
1181
        sjtbl->next= NULL;
 
1182
 
 
1183
        sjtbl->tmp_table=
 
1184
          create_duplicate_weedout_tmp_table(session,
 
1185
                                             sjtbl->rowid_len +
 
1186
                                             sjtbl->null_bytes,
 
1187
                                             sjtbl);
 
1188
 
 
1189
        join->join_tab[dups_ranges[j].start_idx].flush_weedout_table= sjtbl;
 
1190
        join->join_tab[dups_ranges[j].end_idx - 1].check_weed_out_table= sjtbl;
 
1191
      }
 
1192
      tab= last_outer_tab + 1;
 
1193
      jump_to= last_outer_tab;
 
1194
    }
 
1195
 
 
1196
    /* Create the FirstMatch tail */
 
1197
    for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
 
1198
    {
 
1199
      if (tab->emb_sj_nest)
 
1200
        tab->do_firstmatch= jump_to;
 
1201
      else
 
1202
        jump_to= tab;
 
1203
    }
 
1204
  }
 
1205
  return(false);
 
1206
}
 
1207
 
 
1208
 
 
1209
static void cleanup_sj_tmp_tables(JOIN *join)
 
1210
{
 
1211
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl;
 
1212
       sj_tbl= sj_tbl->next)
 
1213
  {
 
1214
    if (sj_tbl->tmp_table)
 
1215
    {
 
1216
      sj_tbl->tmp_table->free_tmp_table(join->session);
 
1217
    }
 
1218
  }
 
1219
  join->sj_tmp_tables= NULL;
 
1220
}
 
1221
 
 
1222
uint32_t make_join_orderinfo(JOIN *join);
 
1223
 
 
1224
/**
 
1225
  global select optimisation.
 
1226
 
 
1227
  @note
 
1228
    error code saved in field 'error'
 
1229
 
 
1230
  @retval
 
1231
    0   success
 
1232
  @retval
 
1233
    1   error
 
1234
*/
 
1235
 
 
1236
int
 
1237
JOIN::optimize()
 
1238
{
 
1239
  // to prevent double initialization on EXPLAIN
 
1240
  if (optimized)
 
1241
    return(0);
 
1242
  optimized= 1;
 
1243
 
 
1244
  session->set_proc_info("optimizing");
 
1245
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
 
1246
              unit->select_limit_cnt);
 
1247
  /* select_limit is used to decide if we are likely to scan the whole table */
 
1248
  select_limit= unit->select_limit_cnt;
 
1249
  if (having || (select_options & OPTION_FOUND_ROWS))
 
1250
    select_limit= HA_POS_ERROR;
 
1251
  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
 
1252
  // Ignore errors of execution if option IGNORE present
 
1253
  if (session->lex->ignore)
 
1254
    session->lex->current_select->no_error= 1;
 
1255
 
 
1256
#ifdef HAVE_REF_TO_FIELDS                       // Not done yet
 
1257
  /* Add HAVING to WHERE if possible */
 
1258
  if (having && !group_list && !sum_func_count)
 
1259
  {
 
1260
    if (!conds)
 
1261
    {
 
1262
      conds= having;
 
1263
      having= 0;
 
1264
    }
 
1265
    else if ((conds=new Item_cond_and(conds,having)))
 
1266
    {
 
1267
      /*
 
1268
        Item_cond_and can't be fixed after creation, so we do not check
 
1269
        conds->fixed
 
1270
      */
 
1271
      conds->fix_fields(session, &conds);
 
1272
      conds->change_ref_to_fields(session, tables_list);
 
1273
      conds->top_level_item();
 
1274
      having= 0;
 
1275
    }
 
1276
  }
 
1277
#endif
 
1278
 
 
1279
  /* Convert all outer joins to inner joins if possible */
 
1280
  conds= simplify_joins(this, join_list, conds, true, false);
 
1281
  build_bitmap_for_nested_joins(join_list, 0);
 
1282
 
 
1283
  conds= optimize_cond(this, conds, join_list, &cond_value);
 
1284
  if (session->is_error())
 
1285
  {
 
1286
    error= 1;
 
1287
    return(1);
 
1288
  }
 
1289
 
 
1290
  {
 
1291
    having= optimize_cond(this, having, join_list, &having_value);
 
1292
    if (session->is_error())
 
1293
    {
 
1294
      error= 1;
 
1295
      return(1);
 
1296
    }
 
1297
    if (select_lex->where)
 
1298
      select_lex->cond_value= cond_value;
 
1299
    if (select_lex->having)
 
1300
      select_lex->having_value= having_value;
 
1301
 
 
1302
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE ||
 
1303
        (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
 
1304
    {                                           /* Impossible cond */
 
1305
      zero_result_cause=  having_value == Item::COND_FALSE ?
 
1306
                           "Impossible HAVING" : "Impossible WHERE";
 
1307
      error= 0;
 
1308
      return(0);
 
1309
    }
 
1310
  }
 
1311
 
 
1312
  /* Optimize count(*), cmin() and cmax() */
 
1313
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
 
1314
  {
 
1315
    int res;
 
1316
    /*
 
1317
      opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
 
1318
      to the WHERE conditions,
 
1319
      or 1 if all items were resolved,
 
1320
      or 0, or an error number HA_ERR_...
 
1321
    */
 
1322
    if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
 
1323
    {
 
1324
      if (res == HA_ERR_KEY_NOT_FOUND)
 
1325
      {
 
1326
        zero_result_cause= "No matching min/max row";
 
1327
        error=0;
 
1328
        return(0);
 
1329
      }
 
1330
      if (res > 1)
 
1331
      {
 
1332
        error= res;
 
1333
        return(1);
 
1334
      }
 
1335
      if (res < 0)
 
1336
      {
 
1337
        zero_result_cause= "No matching min/max row";
 
1338
        error=0;
 
1339
        return(0);
 
1340
      }
 
1341
      zero_result_cause= "Select tables optimized away";
 
1342
      tables_list= 0;                           // All tables resolved
 
1343
      /*
 
1344
        Extract all table-independent conditions and replace the WHERE
 
1345
        clause with them. All other conditions were computed by opt_sum_query
 
1346
        and the MIN/MAX/COUNT function(s) have been replaced by constants,
 
1347
        so there is no need to compute the whole WHERE clause again.
 
1348
        Notice that make_cond_for_table() will always succeed to remove all
 
1349
        computed conditions, because opt_sum_query() is applicable only to
 
1350
        conjunctions.
 
1351
        Preserve conditions for EXPLAIN.
 
1352
      */
 
1353
      if (conds && !(session->lex->describe & DESCRIBE_EXTENDED))
 
1354
      {
 
1355
        COND *table_independent_conds=
 
1356
          make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
 
1357
        conds= table_independent_conds;
 
1358
      }
 
1359
    }
 
1360
  }
 
1361
  if (!tables_list)
 
1362
  {
 
1363
    error= 0;
 
1364
    return(0);
 
1365
  }
 
1366
  error= -1;                                    // Error is sent to client
 
1367
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
 
1368
 
 
1369
  /* Calculate how to do the join */
 
1370
  session->set_proc_info("statistics");
 
1371
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
 
1372
      session->is_fatal_error)
 
1373
  {
 
1374
    return(1);
 
1375
  }
 
1376
 
 
1377
  /* Remove distinct if only const tables */
 
1378
  select_distinct= select_distinct && (const_tables != tables);
 
1379
  session->set_proc_info("preparing");
 
1380
  if (result->initialize_tables(this))
 
1381
  {
 
1382
    return(1);                          // error == -1
 
1383
  }
 
1384
  if (const_table_map != found_const_table_map &&
 
1385
      !(select_options & SELECT_DESCRIBE) &&
 
1386
      (!conds ||
 
1387
       !(conds->used_tables() & RAND_TABLE_BIT) ||
 
1388
       select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
 
1389
  {
 
1390
    zero_result_cause= "no matching row in const table";
 
1391
    error= 0;
 
1392
    return(0);
 
1393
  }
 
1394
  if (!(session->options & OPTION_BIG_SELECTS) &&
 
1395
      best_read > (double) session->variables.max_join_size &&
 
1396
      !(select_options & SELECT_DESCRIBE))
 
1397
  {                                             /* purecov: inspected */
 
1398
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
 
1399
    error= -1;
 
1400
    return(1);
 
1401
  }
 
1402
  if (const_tables && !session->locked_tables &&
 
1403
      !(select_options & SELECT_NO_UNLOCK))
 
1404
    mysql_unlock_some_tables(session, table, const_tables);
 
1405
  if (!conds && outer_join)
 
1406
  {
 
1407
    /* Handle the case where we have an OUTER JOIN without a WHERE */
 
1408
    conds=new Item_int((int64_t) 1,1);  // Always true
 
1409
  }
 
1410
  select= make_select(*table, const_table_map,
 
1411
                      const_table_map, conds, 1, &error);
 
1412
  if (error)
 
1413
  {                                             /* purecov: inspected */
 
1414
    error= -1;                                  /* purecov: inspected */
 
1415
    return(1);
 
1416
  }
 
1417
 
 
1418
  reset_nj_counters(join_list);
 
1419
  make_outerjoin_info(this);
 
1420
 
 
1421
  /*
 
1422
    Among the equal fields belonging to the same multiple equality
 
1423
    choose the one that is to be retrieved first and substitute
 
1424
    all references to these in where condition for a reference for
 
1425
    the selected field.
 
1426
  */
 
1427
  if (conds)
 
1428
  {
 
1429
    conds= substitute_for_best_equal_field(conds, cond_equal, map2table);
 
1430
    conds->update_used_tables();
 
1431
  }
 
1432
 
 
1433
  /*
 
1434
    Permorm the the optimization on fields evaluation mentioned above
 
1435
    for all on expressions.
 
1436
  */
 
1437
  for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
 
1438
  {
 
1439
    if (*tab->on_expr_ref)
 
1440
    {
 
1441
      *tab->on_expr_ref= substitute_for_best_equal_field(*tab->on_expr_ref,
 
1442
                                                         tab->cond_equal,
 
1443
                                                         map2table);
 
1444
      (*tab->on_expr_ref)->update_used_tables();
 
1445
    }
 
1446
  }
 
1447
 
 
1448
  if (conds &&!outer_join && const_table_map != found_const_table_map &&
 
1449
      (select_options & SELECT_DESCRIBE) &&
 
1450
      select_lex->master_unit() == &session->lex->unit) // upper level SELECT
 
1451
  {
 
1452
    conds=new Item_int((int64_t) 0,1);  // Always false
 
1453
  }
 
1454
  if (make_join_select(this, select, conds))
 
1455
  {
 
1456
    zero_result_cause=
 
1457
      "Impossible WHERE noticed after reading const tables";
 
1458
    return(0);                          // error == 0
 
1459
  }
 
1460
 
 
1461
  error= -1;                                    /* if goto err */
 
1462
 
 
1463
  /* Optimize distinct away if possible */
 
1464
  {
 
1465
    order_st *org_order= order;
 
1466
    order=remove_constants(this, order,conds,1, &simple_order);
 
1467
    if (session->is_error())
 
1468
    {
 
1469
      error= 1;
 
1470
      return(1);
 
1471
    }
 
1472
 
 
1473
    /*
 
1474
      If we are using order_st BY NULL or order_st BY const_expression,
 
1475
      return result in any order (even if we are using a GROUP BY)
 
1476
    */
 
1477
    if (!order && org_order)
 
1478
      skip_sort_order= 1;
 
1479
  }
 
1480
  /*
 
1481
     Check if we can optimize away GROUP BY/DISTINCT.
 
1482
     We can do that if there are no aggregate functions, the
 
1483
     fields in DISTINCT clause (if present) and/or columns in GROUP BY
 
1484
     (if present) contain direct references to all key parts of
 
1485
     an unique index (in whatever order) and if the key parts of the
 
1486
     unique index cannot contain NULLs.
 
1487
     Note that the unique keys for DISTINCT and GROUP BY should not
 
1488
     be the same (as long as they are unique).
 
1489
 
 
1490
     The FROM clause must contain a single non-constant table.
 
1491
  */
 
1492
  if (tables - const_tables == 1 && (group_list || select_distinct) &&
 
1493
      !tmp_table_param.sum_func_count &&
 
1494
      (!join_tab[const_tables].select ||
 
1495
       !join_tab[const_tables].select->quick ||
 
1496
       join_tab[const_tables].select->quick->get_type() !=
 
1497
       QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
 
1498
  {
 
1499
    if (group_list &&
 
1500
       list_contains_unique_index(join_tab[const_tables].table,
 
1501
                                 find_field_in_order_list,
 
1502
                                 (void *) group_list))
 
1503
    {
 
1504
      /*
 
1505
        We have found that grouping can be removed since groups correspond to
 
1506
        only one row anyway, but we still have to guarantee correct result
 
1507
        order. The line below effectively rewrites the query from GROUP BY
 
1508
        <fields> to order_st BY <fields>. There are two exceptions:
 
1509
        - if skip_sort_order is set (see above), then we can simply skip
 
1510
          GROUP BY;
 
1511
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
 
1512
          with the GROUP BY ones, i.e. either one is a prefix of another.
 
1513
          We only check if the order_st BY is a prefix of GROUP BY. In this case
 
1514
          test_if_subpart() copies the ASC/DESC attributes from the original
 
1515
          order_st BY fields.
 
1516
          If GROUP BY is a prefix of order_st BY, then it is safe to leave
 
1517
          'order' as is.
 
1518
       */
 
1519
      if (!order || test_if_subpart(group_list, order))
 
1520
          order= skip_sort_order ? 0 : group_list;
 
1521
      /*
 
1522
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be
 
1523
        rewritten to IGNORE INDEX FOR order_st BY(fields).
 
1524
      */
 
1525
      join_tab->table->keys_in_use_for_order_by=
 
1526
        join_tab->table->keys_in_use_for_group_by;
 
1527
      group_list= 0;
 
1528
      group= 0;
 
1529
    }
 
1530
    if (select_distinct &&
 
1531
       list_contains_unique_index(join_tab[const_tables].table,
 
1532
                                 find_field_in_item_list,
 
1533
                                 (void *) &fields_list))
 
1534
    {
 
1535
      select_distinct= 0;
 
1536
    }
 
1537
  }
 
1538
  if (group_list || tmp_table_param.sum_func_count)
 
1539
  {
 
1540
    if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
 
1541
      select_distinct=0;
 
1542
  }
 
1543
  else if (select_distinct && tables - const_tables == 1)
 
1544
  {
 
1545
    /*
 
1546
      We are only using one table. In this case we change DISTINCT to a
 
1547
      GROUP BY query if:
 
1548
      - The GROUP BY can be done through indexes (no sort) and the order_st
 
1549
        BY only uses selected fields.
 
1550
        (In this case we can later optimize away GROUP BY and order_st BY)
 
1551
      - We are scanning the whole table without LIMIT
 
1552
        This can happen if:
 
1553
        - We are using CALC_FOUND_ROWS
 
1554
        - We are using an order_st BY that can't be optimized away.
 
1555
 
 
1556
      We don't want to use this optimization when we are using LIMIT
 
1557
      because in this case we can just create a temporary table that
 
1558
      holds LIMIT rows and stop when this table is full.
 
1559
    */
 
1560
    JOIN_TAB *tab= &join_tab[const_tables];
 
1561
    bool all_order_fields_used;
 
1562
    if (order)
 
1563
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
 
1564
        &tab->table->keys_in_use_for_order_by);
 
1565
    if ((group_list=create_distinct_group(session, select_lex->ref_pointer_array,
 
1566
                                          order, fields_list, all_fields,
 
1567
                                          &all_order_fields_used)))
 
1568
    {
 
1569
      bool skip_group= (skip_sort_order &&
 
1570
        test_if_skip_sort_order(tab, group_list, select_limit, 1,
 
1571
                                &tab->table->keys_in_use_for_group_by) != 0);
 
1572
      count_field_types(select_lex, &tmp_table_param, all_fields, 0);
 
1573
      if ((skip_group && all_order_fields_used) ||
 
1574
          select_limit == HA_POS_ERROR ||
 
1575
          (order && !skip_sort_order))
 
1576
      {
 
1577
        /*  Change DISTINCT to GROUP BY */
 
1578
        select_distinct= 0;
 
1579
        no_order= !order;
 
1580
        if (all_order_fields_used)
 
1581
        {
 
1582
          if (order && skip_sort_order)
 
1583
          {
 
1584
            /*
 
1585
              Force MySQL to read the table in sorted order to get result in
 
1586
              order_st BY order.
 
1587
            */
 
1588
            tmp_table_param.quick_group=0;
 
1589
          }
 
1590
          order=0;
 
1591
        }
 
1592
        group=1;                                // For end_write_group
 
1593
      }
 
1594
      else
 
1595
        group_list= 0;
 
1596
    }
 
1597
    else if (session->is_fatal_error)                   // End of memory
 
1598
      return(1);
 
1599
  }
 
1600
  simple_group= 0;
 
1601
  {
 
1602
    order_st *old_group_list;
 
1603
    group_list= remove_constants(this, (old_group_list= group_list), conds,
 
1604
                                 rollup.state == ROLLUP::STATE_NONE,
 
1605
                                 &simple_group);
 
1606
    if (session->is_error())
 
1607
    {
 
1608
      error= 1;
 
1609
      return(1);
 
1610
    }
 
1611
    if (old_group_list && !group_list)
 
1612
      select_distinct= 0;
 
1613
  }
 
1614
  if (!group_list && group)
 
1615
  {
 
1616
    order=0;                                    // The output has only one row
 
1617
    simple_order=1;
 
1618
    select_distinct= 0;                       // No need in distinct for 1 row
 
1619
    group_optimized_away= 1;
 
1620
  }
 
1621
 
 
1622
  calc_group_buffer(this, group_list);
 
1623
  send_group_parts= tmp_table_param.group_parts; /* Save org parts */
 
1624
 
 
1625
  if (test_if_subpart(group_list, order) ||
 
1626
      (!group_list && tmp_table_param.sum_func_count))
 
1627
    order=0;
 
1628
 
 
1629
  // Can't use sort on head table if using row cache
 
1630
  if (full_join)
 
1631
  {
 
1632
    if (group_list)
 
1633
      simple_group=0;
 
1634
    if (order)
 
1635
      simple_order=0;
 
1636
  }
 
1637
 
 
1638
  /*
 
1639
    Check if we need to create a temporary table.
 
1640
    This has to be done if all tables are not already read (const tables)
 
1641
    and one of the following conditions holds:
 
1642
    - We are using DISTINCT (simple distinct's are already optimized away)
 
1643
    - We are using an order_st BY or GROUP BY on fields not in the first table
 
1644
    - We are using different order_st BY and GROUP BY orders
 
1645
    - The user wants us to buffer the result.
 
1646
  */
 
1647
  need_tmp= (const_tables != tables &&
 
1648
             ((select_distinct || !simple_order || !simple_group) ||
 
1649
              (group_list && order) ||
 
1650
              test(select_options & OPTION_BUFFER_RESULT)));
 
1651
 
 
1652
  uint32_t no_jbuf_after= make_join_orderinfo(this);
 
1653
  uint64_t select_opts_for_readinfo=
 
1654
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
 
1655
 
 
1656
  sj_tmp_tables= NULL;
 
1657
  if (!select_lex->sj_nests.is_empty())
 
1658
    setup_semijoin_dups_elimination(this, select_opts_for_readinfo,
 
1659
                                    no_jbuf_after);
 
1660
 
 
1661
  // No cache for MATCH == 'Don't use join buffering when we use MATCH'.
 
1662
  if (make_join_readinfo(this, select_opts_for_readinfo, no_jbuf_after))
 
1663
    return(1);
 
1664
 
 
1665
  /* Create all structures needed for materialized subquery execution. */
 
1666
  if (setup_subquery_materialization())
 
1667
    return(1);
 
1668
 
 
1669
  /*
 
1670
    is this simple IN subquery?
 
1671
  */
 
1672
  if (!group_list && !order &&
 
1673
      unit->item && unit->item->substype() == Item_subselect::IN_SUBS &&
 
1674
      tables == 1 && conds &&
 
1675
      !unit->is_union())
 
1676
  {
 
1677
    if (!having)
 
1678
    {
 
1679
      Item *where= conds;
 
1680
      if (join_tab[0].type == JT_EQ_REF &&
 
1681
          join_tab[0].ref.items[0]->name == in_left_expr_name)
 
1682
      {
 
1683
        remove_subq_pushed_predicates(&where);
 
1684
        save_index_subquery_explain_info(join_tab, where);
 
1685
        join_tab[0].type= JT_UNIQUE_SUBQUERY;
 
1686
        error= 0;
 
1687
        return(unit->item->
 
1688
                    change_engine(new
 
1689
                                  subselect_uniquesubquery_engine(session,
 
1690
                                                                  join_tab,
 
1691
                                                                  unit->item,
 
1692
                                                                  where)));
 
1693
      }
 
1694
      else if (join_tab[0].type == JT_REF &&
 
1695
               join_tab[0].ref.items[0]->name == in_left_expr_name)
 
1696
      {
 
1697
        remove_subq_pushed_predicates(&where);
 
1698
        save_index_subquery_explain_info(join_tab, where);
 
1699
        join_tab[0].type= JT_INDEX_SUBQUERY;
 
1700
        error= 0;
 
1701
        return(unit->item->
 
1702
                    change_engine(new
 
1703
                                  subselect_indexsubquery_engine(session,
 
1704
                                                                 join_tab,
 
1705
                                                                 unit->item,
 
1706
                                                                 where,
 
1707
                                                                 NULL,
 
1708
                                                                 0)));
 
1709
      }
 
1710
    } else if (join_tab[0].type == JT_REF_OR_NULL &&
 
1711
               join_tab[0].ref.items[0]->name == in_left_expr_name &&
 
1712
               having->name == in_having_cond)
 
1713
    {
 
1714
      join_tab[0].type= JT_INDEX_SUBQUERY;
 
1715
      error= 0;
 
1716
      conds= remove_additional_cond(conds);
 
1717
      save_index_subquery_explain_info(join_tab, conds);
 
1718
      return(unit->item->
 
1719
                  change_engine(new subselect_indexsubquery_engine(session,
 
1720
                                                                   join_tab,
 
1721
                                                                   unit->item,
 
1722
                                                                   conds,
 
1723
                                                                   having,
 
1724
                                                                   1)));
 
1725
    }
 
1726
 
 
1727
  }
 
1728
  /*
 
1729
    Need to tell handlers that to play it safe, it should fetch all
 
1730
    columns of the primary key of the tables: this is because MySQL may
 
1731
    build row pointers for the rows, and for all columns of the primary key
 
1732
    the read set has not necessarily been set by the server code.
 
1733
  */
 
1734
  if (need_tmp || select_distinct || group_list || order)
 
1735
  {
 
1736
    for (uint32_t i = const_tables; i < tables; i++)
 
1737
      join_tab[i].table->prepare_for_position();
 
1738
  }
 
1739
 
 
1740
  if (const_tables != tables)
 
1741
  {
 
1742
    /*
 
1743
      Because filesort always does a full table scan or a quick range scan
 
1744
      we must add the removed reference to the select for the table.
 
1745
      We only need to do this when we have a simple_order or simple_group
 
1746
      as in other cases the join is done before the sort.
 
1747
    */
 
1748
    if ((order || group_list) &&
 
1749
        (join_tab[const_tables].type != JT_ALL) &&
 
1750
        (join_tab[const_tables].type != JT_REF_OR_NULL) &&
 
1751
        ((order && simple_order) || (group_list && simple_group)))
 
1752
    {
 
1753
      if (add_ref_to_table_cond(session,&join_tab[const_tables])) {
 
1754
        return(1);
 
1755
      }
 
1756
    }
 
1757
 
 
1758
    if (!(select_options & SELECT_BIG_RESULT) &&
 
1759
        ((group_list &&
 
1760
          (!simple_group ||
 
1761
           !test_if_skip_sort_order(&join_tab[const_tables], group_list,
 
1762
                                    unit->select_limit_cnt, 0,
 
1763
                                    &join_tab[const_tables].table->
 
1764
                                    keys_in_use_for_group_by))) ||
 
1765
         select_distinct) &&
 
1766
        tmp_table_param.quick_group)
 
1767
    {
 
1768
      need_tmp=1; simple_order=simple_group=0;  // Force tmp table without sort
 
1769
    }
 
1770
    if (order)
 
1771
    {
 
1772
      /*
 
1773
        Force using of tmp table if sorting by a SP or UDF function due to
 
1774
        their expensive and probably non-deterministic nature.
 
1775
      */
 
1776
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
1777
      {
 
1778
        Item *item= *tmp_order->item;
 
1779
        if (item->is_expensive())
 
1780
        {
 
1781
          /* Force tmp table without sort */
 
1782
          need_tmp=1; simple_order=simple_group=0;
 
1783
          break;
 
1784
        }
 
1785
      }
 
1786
    }
 
1787
  }
 
1788
 
 
1789
  tmp_having= having;
 
1790
  if (select_options & SELECT_DESCRIBE)
 
1791
  {
 
1792
    error= 0;
 
1793
    return(0);
 
1794
  }
 
1795
  having= 0;
 
1796
 
 
1797
  /*
 
1798
    The loose index scan access method guarantees that all grouping or
 
1799
    duplicate row elimination (for distinct) is already performed
 
1800
    during data retrieval, and that all MIN/MAX functions are already
 
1801
    computed for each group. Thus all MIN/MAX functions should be
 
1802
    treated as regular functions, and there is no need to perform
 
1803
    grouping in the main execution loop.
 
1804
    Notice that currently loose index scan is applicable only for
 
1805
    single table queries, thus it is sufficient to test only the first
 
1806
    join_tab element of the plan for its access method.
 
1807
  */
 
1808
  if (join_tab->is_using_loose_index_scan())
 
1809
    tmp_table_param.precomputed_group_by= true;
 
1810
 
 
1811
  /* Create a tmp table if distinct or if the sort is too complicated */
 
1812
  if (need_tmp)
 
1813
  {
 
1814
    session->set_proc_info("Creating tmp table");
 
1815
 
 
1816
    init_items_ref_array();
 
1817
 
 
1818
    tmp_table_param.hidden_field_count= (all_fields.elements -
 
1819
                                         fields_list.elements);
 
1820
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
 
1821
                                                             (order_st*) 0);
 
1822
    /*
 
1823
      Pushing LIMIT to the temporary table creation is not applicable
 
1824
      when there is order_st BY or GROUP BY or there is no GROUP BY, but
 
1825
      there are aggregate functions, because in all these cases we need
 
1826
      all result rows.
 
1827
    */
 
1828
    ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
 
1829
                             !tmp_group &&
 
1830
                             !session->lex->current_select->with_sum_func) ?
 
1831
                            select_limit : HA_POS_ERROR;
 
1832
 
 
1833
    if (!(exec_tmp_table1=
 
1834
          create_tmp_table(session, &tmp_table_param, all_fields,
 
1835
                           tmp_group,
 
1836
                           group_list ? 0 : select_distinct,
 
1837
                           group_list && simple_group,
 
1838
                           select_options,
 
1839
                           tmp_rows_limit,
 
1840
                           (char *) "")))
 
1841
                {
 
1842
      return(1);
 
1843
    }
 
1844
 
 
1845
    /*
 
1846
      We don't have to store rows in temp table that doesn't match HAVING if:
 
1847
      - we are sorting the table and writing complete group rows to the
 
1848
        temp table.
 
1849
      - We are using DISTINCT without resolving the distinct as a GROUP BY
 
1850
        on all columns.
 
1851
 
 
1852
      If having is not handled here, it will be checked before the row
 
1853
      is sent to the client.
 
1854
    */
 
1855
    if (tmp_having &&
 
1856
        (sort_and_group || (exec_tmp_table1->distinct && !group_list)))
 
1857
      having= tmp_having;
 
1858
 
 
1859
    /* if group or order on first table, sort first */
 
1860
    if (group_list && simple_group)
 
1861
    {
 
1862
      session->set_proc_info("Sorting for group");
 
1863
      if (create_sort_index(session, this, group_list,
 
1864
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
 
1865
          alloc_group_fields(this, group_list) ||
 
1866
          make_sum_func_list(all_fields, fields_list, 1) ||
 
1867
          setup_sum_funcs(session, sum_funcs))
 
1868
      {
 
1869
        return(1);
 
1870
      }
 
1871
      group_list=0;
 
1872
    }
 
1873
    else
 
1874
    {
 
1875
      if (make_sum_func_list(all_fields, fields_list, 0) ||
 
1876
          setup_sum_funcs(session, sum_funcs))
 
1877
      {
 
1878
        return(1);
 
1879
      }
 
1880
 
 
1881
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
 
1882
      {
 
1883
        session->set_proc_info("Sorting for order");
 
1884
        if (create_sort_index(session, this, order,
 
1885
                              HA_POS_ERROR, HA_POS_ERROR, true))
 
1886
        {
 
1887
          return(1);
 
1888
        }
 
1889
        order=0;
 
1890
      }
 
1891
    }
 
1892
 
 
1893
    /*
 
1894
      Optimize distinct when used on some of the tables
 
1895
      SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
 
1896
      In this case we can stop scanning t2 when we have found one t1.a
 
1897
    */
 
1898
 
 
1899
    if (exec_tmp_table1->distinct)
 
1900
    {
 
1901
      table_map used_tables= session->used_tables;
 
1902
      JOIN_TAB *last_join_tab= join_tab+tables-1;
 
1903
      do
 
1904
      {
 
1905
        if (used_tables & last_join_tab->table->map)
 
1906
          break;
 
1907
        last_join_tab->not_used_in_distinct=1;
 
1908
      } while (last_join_tab-- != join_tab);
 
1909
      /* Optimize "select distinct b from t1 order by key_part_1 limit #" */
 
1910
      if (order && skip_sort_order)
 
1911
      {
 
1912
        /* Should always succeed */
 
1913
        if (test_if_skip_sort_order(&join_tab[const_tables],
 
1914
                                    order, unit->select_limit_cnt, 0,
 
1915
                                    &join_tab[const_tables].table->
 
1916
                                      keys_in_use_for_order_by))
 
1917
          order=0;
 
1918
      }
 
1919
    }
 
1920
 
 
1921
    /*
 
1922
      If this join belongs to an uncacheable subquery save
 
1923
      the original join
 
1924
    */
 
1925
    if (select_lex->uncacheable && !is_top_level_join() &&
 
1926
        init_save_join_tab())
 
1927
      return(-1);                         /* purecov: inspected */
 
1928
  }
 
1929
 
 
1930
  error= 0;
 
1931
  return(0);
 
1932
}
 
1933
 
 
1934
 
 
1935
/**
 
1936
  Restore values in temporary join.
 
1937
*/
 
1938
void JOIN::restore_tmp()
 
1939
{
 
1940
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
 
1941
}
 
1942
 
 
1943
 
 
1944
int
 
1945
JOIN::reinit()
 
1946
{
 
1947
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
 
1948
                                    select_lex->offset_limit->val_uint() :
 
1949
                                    0UL);
 
1950
 
 
1951
  first_record= 0;
 
1952
 
 
1953
  if (exec_tmp_table1)
 
1954
  {
 
1955
    exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
 
1956
    exec_tmp_table1->file->ha_delete_all_rows();
 
1957
    free_io_cache(exec_tmp_table1);
 
1958
    filesort_free_buffers(exec_tmp_table1,0);
 
1959
  }
 
1960
  if (exec_tmp_table2)
 
1961
  {
 
1962
    exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
 
1963
    exec_tmp_table2->file->ha_delete_all_rows();
 
1964
    free_io_cache(exec_tmp_table2);
 
1965
    filesort_free_buffers(exec_tmp_table2,0);
 
1966
  }
 
1967
  if (items0)
 
1968
    set_items_ref_array(items0);
 
1969
 
 
1970
  if (join_tab_save)
 
1971
    memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);
 
1972
 
 
1973
  if (tmp_join)
 
1974
    restore_tmp();
 
1975
 
 
1976
  /* Reset of sum functions */
 
1977
  if (sum_funcs)
 
1978
  {
 
1979
    Item_sum *func, **func_ptr= sum_funcs;
 
1980
    while ((func= *(func_ptr++)))
 
1981
      func->clear();
 
1982
  }
 
1983
 
 
1984
  return(0);
 
1985
}
 
1986
 
 
1987
/**
 
1988
   @brief Save the original join layout
 
1989
 
 
1990
   @details Saves the original join layout so it can be reused in
 
1991
   re-execution and for EXPLAIN.
 
1992
 
 
1993
   @return Operation status
 
1994
   @retval 0      success.
 
1995
   @retval 1      error occurred.
 
1996
*/
 
1997
 
 
1998
bool
 
1999
JOIN::init_save_join_tab()
 
2000
{
 
2001
  if (!(tmp_join= (JOIN*)session->alloc(sizeof(JOIN))))
 
2002
    return 1;                                  /* purecov: inspected */
 
2003
  error= 0;                                    // Ensure that tmp_join.error= 0
 
2004
  restore_tmp();
 
2005
  return 0;
 
2006
}
 
2007
 
 
2008
 
 
2009
bool
 
2010
JOIN::save_join_tab()
 
2011
{
 
2012
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
 
2013
  {
 
2014
    if (!(join_tab_save= (JOIN_TAB*)session->memdup((unsigned char*) join_tab,
 
2015
                                                sizeof(JOIN_TAB) * tables)))
 
2016
      return 1;
 
2017
  }
 
2018
  return 0;
 
2019
}
 
2020
 
 
2021
 
 
2022
/**
 
2023
  Exec select.
 
2024
 
 
2025
  @todo
 
2026
    Note, that create_sort_index calls test_if_skip_sort_order and may
 
2027
    finally replace sorting with index scan if there is a LIMIT clause in
 
2028
    the query.  It's never shown in EXPLAIN!
 
2029
 
 
2030
  @todo
 
2031
    When can we have here session->net.report_error not zero?
 
2032
*/
 
2033
void JOIN::exec()
 
2034
{
 
2035
  List<Item> *columns_list= &fields_list;
 
2036
  int      tmp_error;
 
2037
 
 
2038
  session->set_proc_info("executing");
 
2039
  error= 0;
 
2040
 
 
2041
  if (!tables_list && (tables || !select_lex->with_sum_func))
 
2042
  {                                           
 
2043
    /* Only test of functions */
 
2044
    if (select_options & SELECT_DESCRIBE)
 
2045
      select_describe(this, false, false, false, (zero_result_cause?zero_result_cause:"No tables used"));
 
2046
    else
 
2047
    {
 
2048
      result->send_fields(*columns_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
 
2049
      /*
 
2050
        We have to test for 'conds' here as the WHERE may not be constant
 
2051
        even if we don't have any tables for prepared statements or if
 
2052
        conds uses something like 'rand()'.
 
2053
      */
 
2054
      if (cond_value != Item::COND_FALSE &&
 
2055
          (!conds || conds->val_int()) &&
 
2056
          (!having || having->val_int()))
 
2057
      {
 
2058
        if (do_send_rows && result->send_data(fields_list))
 
2059
          error= 1;
 
2060
        else
 
2061
        {
 
2062
          error= (int) result->send_eof();
 
2063
          send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 : session->sent_row_count);
 
2064
        }
 
2065
      }
 
2066
      else
 
2067
      {
 
2068
        error= (int) result->send_eof();
 
2069
        send_records= 0;
 
2070
      }
 
2071
    }
 
2072
    /* Single select (without union) always returns 0 or 1 row */
 
2073
    session->limit_found_rows= send_records;
 
2074
    session->examined_row_count= 0;
 
2075
    return;
 
2076
  }
 
2077
  /*
 
2078
    Don't reset the found rows count if there're no tables as
 
2079
    FOUND_ROWS() may be called. Never reset the examined row count here.
 
2080
    It must be accumulated from all join iterations of all join parts.
 
2081
  */
 
2082
  if (tables)
 
2083
    session->limit_found_rows= 0;
 
2084
 
 
2085
  if (zero_result_cause)
 
2086
  {
 
2087
    (void) return_zero_rows(this, result, select_lex->leaf_tables,
 
2088
                            *columns_list,
 
2089
                            send_row_on_empty_set(),
 
2090
                            select_options,
 
2091
                            zero_result_cause,
 
2092
                            having);
 
2093
    return;
 
2094
  }
 
2095
 
 
2096
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) && get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
 
2097
    return;
 
2098
 
 
2099
  if (select_options & SELECT_DESCRIBE)
 
2100
  {
 
2101
    /*
 
2102
      Check if we managed to optimize order_st BY away and don't use temporary
 
2103
      table to resolve order_st BY: in that case, we only may need to do
 
2104
      filesort for GROUP BY.
 
2105
    */
 
2106
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
 
2107
    {
 
2108
      /* Reset 'order' to 'group_list' and reinit variables describing 'order' */
 
2109
      order= group_list;
 
2110
      simple_order= simple_group;
 
2111
      skip_sort_order= 0;
 
2112
    }
 
2113
    if (order && (order != group_list || !(select_options & SELECT_BIG_RESULT)))
 
2114
    {
 
2115
      if (const_tables == tables 
 
2116
        || ((simple_order || skip_sort_order) 
 
2117
          && test_if_skip_sort_order(&join_tab[const_tables], order, select_limit, 0, &join_tab[const_tables].table->keys_in_use_for_query)))
 
2118
      order= 0;
 
2119
    }
 
2120
    having= tmp_having;
 
2121
    select_describe(this, need_tmp, order != 0 && !skip_sort_order,  select_distinct, !tables ? "No tables used" : NULL);
 
2122
    return;
 
2123
  }
 
2124
 
 
2125
  JOIN *curr_join= this;
 
2126
  List<Item> *curr_all_fields= &all_fields;
 
2127
  List<Item> *curr_fields_list= &fields_list;
 
2128
  Table *curr_tmp_table= 0;
 
2129
  /*
 
2130
    Initialize examined rows here because the values from all join parts
 
2131
    must be accumulated in examined_row_count. Hence every join
 
2132
    iteration must count from zero.
 
2133
  */
 
2134
  curr_join->examined_rows= 0;
 
2135
 
 
2136
  /* Create a tmp table if distinct or if the sort is too complicated */
 
2137
  if (need_tmp)
 
2138
  {
 
2139
    if (tmp_join)
 
2140
    {
 
2141
      /*
 
2142
        We are in a non cacheable sub query. Get the saved join structure
 
2143
        after optimization.
 
2144
        (curr_join may have been modified during last exection and we need
 
2145
        to reset it)
 
2146
      */
 
2147
      curr_join= tmp_join;
 
2148
    }
 
2149
    curr_tmp_table= exec_tmp_table1;
 
2150
 
 
2151
    /* Copy data to the temporary table */
 
2152
    session->set_proc_info("Copying to tmp table");
 
2153
    if (! curr_join->sort_and_group && curr_join->const_tables != curr_join->tables)
 
2154
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
 
2155
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
 
2156
    {
 
2157
      error= tmp_error;
 
2158
      return;
 
2159
    }
 
2160
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
 
2161
 
 
2162
    if (curr_join->having)
 
2163
      curr_join->having= curr_join->tmp_having= 0; // Allready done
 
2164
 
 
2165
    /* Change sum_fields reference to calculated fields in tmp_table */
 
2166
    curr_join->all_fields= *curr_all_fields;
 
2167
    if (!items1)
 
2168
    {
 
2169
      items1= items0 + all_fields.elements;
 
2170
      if (sort_and_group || curr_tmp_table->group)
 
2171
      {
 
2172
        if (change_to_use_tmp_fields(session, items1,
 
2173
                  tmp_fields_list1, tmp_all_fields1,
 
2174
                  fields_list.elements, all_fields))
 
2175
          return;
 
2176
      }
 
2177
      else
 
2178
      {
 
2179
        if (change_refs_to_tmp_fields(session, items1,
 
2180
                    tmp_fields_list1, tmp_all_fields1,
 
2181
                    fields_list.elements, all_fields))
 
2182
          return;
 
2183
      }
 
2184
      curr_join->tmp_all_fields1= tmp_all_fields1;
 
2185
      curr_join->tmp_fields_list1= tmp_fields_list1;
 
2186
      curr_join->items1= items1;
 
2187
    }
 
2188
    curr_all_fields= &tmp_all_fields1;
 
2189
    curr_fields_list= &tmp_fields_list1;
 
2190
    curr_join->set_items_ref_array(items1);
 
2191
 
 
2192
    if (sort_and_group || curr_tmp_table->group)
 
2193
    {
 
2194
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count
 
2195
                                             + curr_join->tmp_table_param.func_count;
 
2196
      curr_join->tmp_table_param.sum_func_count= 0;
 
2197
      curr_join->tmp_table_param.func_count= 0;
 
2198
    }
 
2199
    else
 
2200
    {
 
2201
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.func_count;
 
2202
      curr_join->tmp_table_param.func_count= 0;
 
2203
    }
 
2204
 
 
2205
    if (curr_tmp_table->group)
 
2206
    {                                           // Already grouped
 
2207
      if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
 
2208
        curr_join->order= curr_join->group_list;  /* order by group */
 
2209
      curr_join->group_list= 0;
 
2210
    }
 
2211
 
 
2212
    /*
 
2213
      If we have different sort & group then we must sort the data by group
 
2214
      and copy it to another tmp table
 
2215
      This code is also used if we are using distinct something
 
2216
      we haven't been able to store in the temporary table yet
 
2217
      like SEC_TO_TIME(SUM(...)).
 
2218
    */
 
2219
 
 
2220
    if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) 
 
2221
        || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
 
2222
    {                                   /* Must copy to another table */
 
2223
      /* Free first data from old join */
 
2224
      curr_join->join_free();
 
2225
      if (make_simple_join(curr_join, curr_tmp_table))
 
2226
        return;
 
2227
      calc_group_buffer(curr_join, group_list);
 
2228
      count_field_types(select_lex, &curr_join->tmp_table_param,
 
2229
                        curr_join->tmp_all_fields1,
 
2230
                        curr_join->select_distinct && !curr_join->group_list);
 
2231
      curr_join->tmp_table_param.hidden_field_count= curr_join->tmp_all_fields1.elements
 
2232
                                                   - curr_join->tmp_fields_list1.elements;
 
2233
 
 
2234
      if (exec_tmp_table2)
 
2235
        curr_tmp_table= exec_tmp_table2;
 
2236
      else
 
2237
      {
 
2238
        /* group data to new table */
 
2239
 
 
2240
        /*
 
2241
          If the access method is loose index scan then all MIN/MAX
 
2242
          functions are precomputed, and should be treated as regular
 
2243
          functions. See extended comment in JOIN::exec.
 
2244
        */
 
2245
        if (curr_join->join_tab->is_using_loose_index_scan())
 
2246
          curr_join->tmp_table_param.precomputed_group_by= true;
 
2247
 
 
2248
        if (!(curr_tmp_table=
 
2249
              exec_tmp_table2= create_tmp_table(session,
 
2250
                                                &curr_join->tmp_table_param,
 
2251
                                                *curr_all_fields,
 
2252
                                                (order_st*) 0,
 
2253
                                                curr_join->select_distinct &&
 
2254
                                                !curr_join->group_list,
 
2255
                                                1, curr_join->select_options,
 
2256
                                                HA_POS_ERROR,
 
2257
                                                (char *) "")))
 
2258
          return;
 
2259
        curr_join->exec_tmp_table2= exec_tmp_table2;
 
2260
      }
 
2261
      if (curr_join->group_list)
 
2262
      {
 
2263
        session->set_proc_info("Creating sort index");
 
2264
        if (curr_join->join_tab == join_tab && save_join_tab())
 
2265
        {
 
2266
          return;
 
2267
        }
 
2268
        if (create_sort_index(session, curr_join, curr_join->group_list,
 
2269
                  HA_POS_ERROR, HA_POS_ERROR, false) ||
 
2270
            make_group_fields(this, curr_join))
 
2271
        {
 
2272
          return;
 
2273
        }
 
2274
        sortorder= curr_join->sortorder;
 
2275
      }
 
2276
 
 
2277
      session->set_proc_info("Copying to group table");
 
2278
      tmp_error= -1;
 
2279
      if (curr_join != this)
 
2280
      {
 
2281
        if (sum_funcs2)
 
2282
        {
 
2283
          curr_join->sum_funcs= sum_funcs2;
 
2284
          curr_join->sum_funcs_end= sum_funcs_end2;
 
2285
        }
 
2286
        else
 
2287
        {
 
2288
          curr_join->alloc_func_list();
 
2289
          sum_funcs2= curr_join->sum_funcs;
 
2290
          sum_funcs_end2= curr_join->sum_funcs_end;
 
2291
        }
 
2292
      }
 
2293
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, 1, true))
 
2294
        return;
 
2295
      curr_join->group_list= 0;
 
2296
 
 
2297
      if (!curr_join->sort_and_group && (curr_join->const_tables != curr_join->tables))
 
2298
        curr_join->join_tab[curr_join->const_tables].sorted= 0;
 
2299
      
 
2300
      if (setup_sum_funcs(curr_join->session, curr_join->sum_funcs) 
 
2301
        || (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
 
2302
      {
 
2303
        error= tmp_error;
 
2304
        return;
 
2305
      }
 
2306
      end_read_record(&curr_join->join_tab->read_record);
 
2307
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
 
2308
      curr_join->join_tab[0].table= 0;           // Table is freed
 
2309
 
 
2310
      // No sum funcs anymore
 
2311
      if (!items2)
 
2312
      {
 
2313
        items2= items1 + all_fields.elements;
 
2314
        if (change_to_use_tmp_fields(session, items2,
 
2315
                  tmp_fields_list2, tmp_all_fields2,
 
2316
                  fields_list.elements, tmp_all_fields1))
 
2317
          return;
 
2318
        curr_join->tmp_fields_list2= tmp_fields_list2;
 
2319
        curr_join->tmp_all_fields2= tmp_all_fields2;
 
2320
      }
 
2321
      curr_fields_list= &curr_join->tmp_fields_list2;
 
2322
      curr_all_fields= &curr_join->tmp_all_fields2;
 
2323
      curr_join->set_items_ref_array(items2);
 
2324
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count;
 
2325
      curr_join->tmp_table_param.sum_func_count= 0;
 
2326
    }
 
2327
    if (curr_tmp_table->distinct)
 
2328
      curr_join->select_distinct=0;             /* Each row is unique */
 
2329
 
 
2330
    curr_join->join_free();                     /* Free quick selects */
 
2331
    if (curr_join->select_distinct && ! curr_join->group_list)
 
2332
    {
 
2333
      session->set_proc_info("Removing duplicates");
 
2334
      if (curr_join->tmp_having)
 
2335
        curr_join->tmp_having->update_used_tables();
 
2336
 
 
2337
      if (remove_duplicates(curr_join, curr_tmp_table,
 
2338
                            *curr_fields_list, curr_join->tmp_having))
 
2339
        return;
 
2340
      
 
2341
      curr_join->tmp_having=0;
 
2342
      curr_join->select_distinct=0;
 
2343
    }
 
2344
    curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
 
2345
    if (make_simple_join(curr_join, curr_tmp_table))
 
2346
      return;
 
2347
    calc_group_buffer(curr_join, curr_join->group_list);
 
2348
    count_field_types(select_lex, &curr_join->tmp_table_param, *curr_all_fields, 0);
 
2349
 
 
2350
  }
 
2351
 
 
2352
  if (curr_join->group || curr_join->tmp_table_param.sum_func_count)
 
2353
  {
 
2354
    if (make_group_fields(this, curr_join))
 
2355
      return;
 
2356
 
 
2357
    if (! items3)
 
2358
    {
 
2359
      if (! items0)
 
2360
        init_items_ref_array();
 
2361
      items3= ref_pointer_array + (all_fields.elements*4);
 
2362
      setup_copy_fields(session, &curr_join->tmp_table_param,
 
2363
                        items3, tmp_fields_list3, tmp_all_fields3,
 
2364
                        curr_fields_list->elements, *curr_all_fields);
 
2365
      tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
 
2366
      tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
 
2367
      tmp_table_param.save_copy_field_end= curr_join->tmp_table_param.copy_field_end;
 
2368
      curr_join->tmp_all_fields3= tmp_all_fields3;
 
2369
      curr_join->tmp_fields_list3= tmp_fields_list3;
 
2370
    }
 
2371
    else
 
2372
    {
 
2373
      curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
 
2374
      curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
 
2375
      curr_join->tmp_table_param.copy_field_end= tmp_table_param.save_copy_field_end;
 
2376
    }
 
2377
    curr_fields_list= &tmp_fields_list3;
 
2378
    curr_all_fields= &tmp_all_fields3;
 
2379
    curr_join->set_items_ref_array(items3);
 
2380
 
 
2381
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
 
2382
                                      1, true) ||
 
2383
        setup_sum_funcs(curr_join->session, curr_join->sum_funcs) ||
 
2384
        session->is_fatal_error)
 
2385
      return;
 
2386
  }
 
2387
  if (curr_join->group_list || curr_join->order)
 
2388
  {
 
2389
    session->set_proc_info("Sorting result");
 
2390
    /* If we have already done the group, add HAVING to sorted table */
 
2391
    if (curr_join->tmp_having && ! curr_join->group_list &&     ! curr_join->sort_and_group)
 
2392
    {
 
2393
      // Some tables may have been const
 
2394
      curr_join->tmp_having->update_used_tables();
 
2395
      JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
 
2396
      table_map used_tables= (curr_join->const_table_map |
 
2397
                              curr_table->table->map);
 
2398
 
 
2399
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having, used_tables, used_tables, 0);
 
2400
      if (sort_table_cond)
 
2401
      {
 
2402
        if (!curr_table->select)
 
2403
          if (!(curr_table->select= new SQL_SELECT))
 
2404
            return;
 
2405
        if (!curr_table->select->cond)
 
2406
          curr_table->select->cond= sort_table_cond;
 
2407
        else                                    // This should never happen
 
2408
        {
 
2409
          if (!(curr_table->select->cond=
 
2410
          new Item_cond_and(curr_table->select->cond,
 
2411
                sort_table_cond)))
 
2412
            return;
 
2413
          /*
 
2414
            Item_cond_and do not need fix_fields for execution, its parameters
 
2415
            are fixed or do not need fix_fields, too
 
2416
          */
 
2417
          curr_table->select->cond->quick_fix_field();
 
2418
        }
 
2419
        curr_table->select_cond= curr_table->select->cond;
 
2420
        curr_table->select_cond->top_level_item();
 
2421
        curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
 
2422
                    ~ (table_map) 0,
 
2423
                    ~used_tables, 0);
 
2424
      }
 
2425
    }
 
2426
    {
 
2427
      if (group)
 
2428
        curr_join->select_limit= HA_POS_ERROR;
 
2429
      else
 
2430
      {
 
2431
        /*
 
2432
          We can abort sorting after session->select_limit rows if we there is no
 
2433
          WHERE clause for any tables after the sorted one.
 
2434
        */
 
2435
        JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
 
2436
        JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
 
2437
        for (; curr_table < end_table ; curr_table++)
 
2438
        {
 
2439
          /*
 
2440
            table->keyuse is set in the case there was an original WHERE clause
 
2441
            on the table that was optimized away.
 
2442
          */
 
2443
          if (curr_table->select_cond ||
 
2444
              (curr_table->keyuse && !curr_table->first_inner))
 
2445
          {
 
2446
            /* We have to sort all rows */
 
2447
            curr_join->select_limit= HA_POS_ERROR;
 
2448
            break;
 
2449
          }
 
2450
        }
 
2451
      }
 
2452
      if (curr_join->join_tab == join_tab && save_join_tab())
 
2453
        return;
 
2454
      /*
 
2455
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
 
2456
        chose FILESORT to be faster than INDEX SCAN or there is no
 
2457
        suitable index present.
 
2458
        Note, that create_sort_index calls test_if_skip_sort_order and may
 
2459
        finally replace sorting with index scan if there is a LIMIT clause in
 
2460
        the query. XXX: it's never shown in EXPLAIN!
 
2461
        OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
 
2462
      */
 
2463
      if (create_sort_index(session, curr_join,
 
2464
                            curr_join->group_list ?
 
2465
                            curr_join->group_list : curr_join->order,
 
2466
                            curr_join->select_limit,
 
2467
                            (select_options & OPTION_FOUND_ROWS ?
 
2468
                             HA_POS_ERROR : unit->select_limit_cnt),
 
2469
                            curr_join->group_list ? true : false))
 
2470
        return;
 
2471
 
 
2472
      sortorder= curr_join->sortorder;
 
2473
      if (curr_join->const_tables != curr_join->tables &&
 
2474
          !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
 
2475
      {
 
2476
        /*
 
2477
          If no IO cache exists for the first table then we are using an
 
2478
          INDEX SCAN and no filesort. Thus we should not remove the sorted
 
2479
          attribute on the INDEX SCAN.
 
2480
        */
 
2481
        skip_sort_order= 1;
 
2482
      }
 
2483
    }
 
2484
  }
 
2485
  /* XXX: When can we have here session->is_error() not zero? */
 
2486
  if (session->is_error())
 
2487
  {
 
2488
    error= session->is_error();
 
2489
    return;
 
2490
  }
 
2491
  curr_join->having= curr_join->tmp_having;
 
2492
  curr_join->fields= curr_fields_list;
 
2493
 
 
2494
  session->set_proc_info("Sending data");
 
2495
  result->send_fields(*curr_fields_list,
 
2496
                      Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
 
2497
  error= do_select(curr_join, curr_fields_list, NULL);
 
2498
  session->limit_found_rows= curr_join->send_records;
 
2499
 
 
2500
  /* Accumulate the counts from all join iterations of all join parts. */
 
2501
  session->examined_row_count+= curr_join->examined_rows;
 
2502
 
 
2503
  /*
 
2504
    With EXPLAIN EXTENDED we have to restore original ref_array
 
2505
    for a derived table which is always materialized.
 
2506
    Otherwise we would not be able to print the query  correctly.
 
2507
  */
 
2508
  if (items0 && (session->lex->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
 
2509
    set_items_ref_array(items0);
 
2510
 
 
2511
  return;
 
2512
}
 
2513
 
 
2514
/**
 
2515
  Clean up join.
 
2516
 
 
2517
  @return
 
2518
    Return error that hold JOIN.
 
2519
*/
 
2520
int JOIN::destroy()
 
2521
{
 
2522
  select_lex->join= 0;
 
2523
 
 
2524
  if (tmp_join)
 
2525
  {
 
2526
    if (join_tab != tmp_join->join_tab)
 
2527
    {
 
2528
      JOIN_TAB *tab, *end;
 
2529
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
 
2530
        tab->cleanup();
 
2531
    }
 
2532
    tmp_join->tmp_join= 0;
 
2533
    tmp_table_param.copy_field=0;
 
2534
    return(tmp_join->destroy());
 
2535
  }
 
2536
  cond_equal= 0;
 
2537
 
 
2538
  cleanup(1);
 
2539
  if (exec_tmp_table1)
 
2540
    exec_tmp_table1->free_tmp_table(session);
 
2541
  if (exec_tmp_table2)
 
2542
    exec_tmp_table2->free_tmp_table(session);
 
2543
  delete select;
 
2544
  delete_dynamic(&keyuse);
 
2545
  return(error);
 
2546
}
 
2547
 
312
2548
/**
313
2549
  An entry point to single-unit select (a select without UNION).
314
2550
 
315
 
  @param session                  thread Cursor
 
2551
  @param session                  thread handler
316
2552
  @param rref_pointer_array   a reference to ref_pointer_array of
317
2553
                              the top-level select_lex for this query
318
2554
  @param tables               list of all tables used in this query.
328
2564
                              for a, b and c in this list.
329
2565
  @param conds                top level item of an expression representing
330
2566
                              WHERE clause of the top level select
331
 
  @param og_num               total number of ORDER BY and GROUP BY clauses
 
2567
  @param og_num               total number of order_st BY and GROUP BY clauses
332
2568
                              arguments
333
 
  @param order                linked list of ORDER BY agruments
 
2569
  @param order                linked list of order_st BY agruments
334
2570
  @param group                linked list of GROUP BY arguments
335
2571
  @param having               top level item of HAVING expression
336
2572
  @param select_options       select options (BIG_RESULT, etc)
351
2587
  @retval
352
2588
    true   an error
353
2589
*/
354
 
bool select_query(Session *session,
355
 
                  Item ***rref_pointer_array,
356
 
                  TableList *tables, 
357
 
                  uint32_t wild_num, 
358
 
                  List<Item> &fields,
359
 
                  COND *conds, 
360
 
                  uint32_t og_num,  
361
 
                  Order *order,
362
 
                  Order *group,
363
 
                  Item *having, 
364
 
                  uint64_t select_options,
365
 
                  select_result *result, 
366
 
                  Select_Lex_Unit *unit,
367
 
                  Select_Lex *select_lex)
 
2590
 
 
2591
bool
 
2592
mysql_select(Session *session, Item ***rref_pointer_array,
 
2593
             TableList *tables, uint32_t wild_num, List<Item> &fields,
 
2594
             COND *conds, uint32_t og_num,  order_st *order, order_st *group,
 
2595
             Item *having, uint64_t select_options,
 
2596
             select_result *result, Select_Lex_Unit *unit,
 
2597
             Select_Lex *select_lex)
368
2598
{
369
2599
  bool err;
370
2600
  bool free_join= 1;
371
2601
 
372
2602
  select_lex->context.resolve_in_select_list= true;
373
 
  Join *join;
 
2603
  JOIN *join;
374
2604
  if (select_lex->join != 0)
375
2605
  {
376
2606
    join= select_lex->join;
379
2609
      creation
380
2610
    */
381
2611
    if (select_lex->linkage != DERIVED_TABLE_TYPE ||
382
 
        (select_options & SELECT_DESCRIBE))
 
2612
        (select_options & SELECT_DESCRIBE))
383
2613
    {
384
2614
      if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
385
2615
      {
386
 
        //here is EXPLAIN of subselect or derived table
387
 
        if (join->change_result(result))
388
 
        {
389
 
          return(true);
390
 
        }
 
2616
        //here is EXPLAIN of subselect or derived table
 
2617
        if (join->change_result(result))
 
2618
        {
 
2619
          return(true);
 
2620
        }
391
2621
      }
392
2622
      else
393
2623
      {
394
2624
        if ((err= join->prepare(rref_pointer_array, tables, wild_num,
395
2625
                               conds, og_num, order, group, having, select_lex, unit)))
396
 
        {
397
 
          goto err;
398
 
        }
 
2626
        {
 
2627
          goto err;
 
2628
        }
399
2629
      }
400
2630
    }
401
2631
    free_join= 0;
403
2633
  }
404
2634
  else
405
2635
  {
406
 
    if (!(join= new Join(session, fields, select_options, result)))
407
 
      return(true);
 
2636
    if (!(join= new JOIN(session, fields, select_options, result)))
 
2637
        return(true);
408
2638
    session->set_proc_info("init");
409
2639
    session->used_tables=0;                         // Updated by setup_fields
410
2640
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
415
2645
    }
416
2646
  }
417
2647
 
418
 
  err= join->optimize();
419
 
  if (err)
420
 
  {
421
 
    goto err; // 1
 
2648
  if (join->flatten_subqueries())
 
2649
  {
 
2650
    err= 1;
 
2651
    goto err;
 
2652
  }
 
2653
 
 
2654
  if ((err= join->optimize()))
 
2655
  {
 
2656
    goto err;                                   // 1
422
2657
  }
423
2658
 
424
2659
  if (session->lex->describe & DESCRIBE_EXTENDED)
448
2683
  return(join->error);
449
2684
}
450
2685
 
451
 
inline Item *and_items(Item* cond, Item *item)
 
2686
 
 
2687
int subq_sj_candidate_cmp(Item_in_subselect* const *el1,
 
2688
                          Item_in_subselect* const *el2)
 
2689
{
 
2690
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
 
2691
         ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
 
2692
}
 
2693
 
 
2694
 
 
2695
inline Item * and_items(Item* cond, Item *item)
452
2696
{
453
2697
  return (cond? (new Item_cond_and(cond, item)) : item);
454
2698
}
455
2699
 
 
2700
 
 
2701
static TableList *alloc_join_nest(Session *session)
 
2702
{
 
2703
  TableList *tbl;
 
2704
  if (!(tbl= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
 
2705
                                       sizeof(nested_join_st))))
 
2706
    return NULL;
 
2707
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl +
 
2708
                                    ALIGN_SIZE(sizeof(TableList)));
 
2709
  return tbl;
 
2710
}
 
2711
 
 
2712
 
 
2713
void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
2714
{
 
2715
  List_iterator<TableList> it(*tlist);
 
2716
  TableList *table;
 
2717
  while ((table= it++))
 
2718
  {
 
2719
    if (table->on_expr)
 
2720
      table->on_expr->fix_after_pullout(new_parent, &table->on_expr);
 
2721
    if (table->nested_join)
 
2722
      fix_list_after_tbl_changes(new_parent, &table->nested_join->join_list);
 
2723
  }
 
2724
}
 
2725
 
 
2726
 
 
2727
/*
 
2728
  Convert a subquery predicate into a TableList semi-join nest
 
2729
 
 
2730
  SYNOPSIS
 
2731
    convert_subq_to_sj()
 
2732
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON
 
2733
                    clause
 
2734
       subq_pred    Subquery predicate to be converted
 
2735
 
 
2736
  DESCRIPTION
 
2737
    Convert a subquery predicate into a TableList semi-join nest. All the
 
2738
    prerequisites are already checked, so the conversion is always successfull.
 
2739
 
 
2740
    Prepared Statements: the transformation is permanent:
 
2741
     - Changes in TableList structures are naturally permanent
 
2742
     - Item tree changes are performed on statement MEM_ROOT:
 
2743
        = we activate statement MEM_ROOT
 
2744
        = this function is called before the first fix_prepare_information
 
2745
          call.
 
2746
 
 
2747
    This is intended because the criteria for subquery-to-sj conversion remain
 
2748
    constant for the lifetime of the Prepared Statement.
 
2749
 
 
2750
  RETURN
 
2751
    false  OK
 
2752
    true   Out of memory error
 
2753
*/
 
2754
 
 
2755
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
 
2756
{
 
2757
  Select_Lex *parent_lex= parent_join->select_lex;
 
2758
  TableList *emb_tbl_nest= NULL;
 
2759
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
 
2760
  Session *session= parent_join->session;
 
2761
 
 
2762
  /*
 
2763
    1. Find out where to put the predicate into.
 
2764
     Note: for "t1 LEFT JOIN t2" this will be t2, a leaf.
 
2765
  */
 
2766
  if ((void*)subq_pred->expr_join_nest != (void*)1)
 
2767
  {
 
2768
    if (subq_pred->expr_join_nest->nested_join)
 
2769
    {
 
2770
      /*
 
2771
        We're dealing with
 
2772
 
 
2773
          ... [LEFT] JOIN  ( ... ) ON (subquery AND whatever) ...
 
2774
 
 
2775
        The sj-nest will be inserted into the brackets nest.
 
2776
      */
 
2777
      emb_tbl_nest=  subq_pred->expr_join_nest;
 
2778
      emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
2779
    }
 
2780
    else if (!subq_pred->expr_join_nest->outer_join)
 
2781
    {
 
2782
      /*
 
2783
        We're dealing with
 
2784
 
 
2785
          ... INNER JOIN tblX ON (subquery AND whatever) ...
 
2786
 
 
2787
        The sj-nest will be tblX's "sibling", i.e. another child of its
 
2788
        parent. This is ok because tblX is joined as an inner join.
 
2789
      */
 
2790
      emb_tbl_nest= subq_pred->expr_join_nest->embedding;
 
2791
      if (emb_tbl_nest)
 
2792
        emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
2793
    }
 
2794
    else if (!subq_pred->expr_join_nest->nested_join)
 
2795
    {
 
2796
      TableList *outer_tbl= subq_pred->expr_join_nest;
 
2797
      TableList *wrap_nest;
 
2798
      /*
 
2799
        We're dealing with
 
2800
 
 
2801
          ... LEFT JOIN tbl ON (on_expr AND subq_pred) ...
 
2802
 
 
2803
        we'll need to convert it into:
 
2804
 
 
2805
          ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
 
2806
                        |                      |
 
2807
                        |<----- wrap_nest ---->|
 
2808
 
 
2809
        Q:  other subqueries may be pointing to this element. What to do?
 
2810
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
 
2811
            But we'll need to fix other pointers.
 
2812
        A2: Another way: have TableList::next_ptr so the following
 
2813
            subqueries know the table has been nested.
 
2814
        A3: changes in the TableList::outer_join will make everything work
 
2815
            automatically.
 
2816
      */
 
2817
      if (!(wrap_nest= alloc_join_nest(parent_join->session)))
 
2818
      {
 
2819
        return(true);
 
2820
      }
 
2821
      wrap_nest->embedding= outer_tbl->embedding;
 
2822
      wrap_nest->join_list= outer_tbl->join_list;
 
2823
      wrap_nest->alias= (char*) "(sj-wrap)";
 
2824
 
 
2825
      wrap_nest->nested_join->join_list.empty();
 
2826
      wrap_nest->nested_join->join_list.push_back(outer_tbl);
 
2827
 
 
2828
      outer_tbl->embedding= wrap_nest;
 
2829
      outer_tbl->join_list= &wrap_nest->nested_join->join_list;
 
2830
 
 
2831
      /*
 
2832
        wrap_nest will take place of outer_tbl, so move the outer join flag
 
2833
        and on_expr
 
2834
      */
 
2835
      wrap_nest->outer_join= outer_tbl->outer_join;
 
2836
      outer_tbl->outer_join= 0;
 
2837
 
 
2838
      wrap_nest->on_expr= outer_tbl->on_expr;
 
2839
      outer_tbl->on_expr= NULL;
 
2840
 
 
2841
      List_iterator<TableList> li(*wrap_nest->join_list);
 
2842
      TableList *tbl;
 
2843
      while ((tbl= li++))
 
2844
      {
 
2845
        if (tbl == outer_tbl)
 
2846
        {
 
2847
          li.replace(wrap_nest);
 
2848
          break;
 
2849
        }
 
2850
      }
 
2851
      /*
 
2852
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the
 
2853
        semi-join nest into it
 
2854
      */
 
2855
      emb_join_list= &wrap_nest->nested_join->join_list;
 
2856
      emb_tbl_nest=  wrap_nest;
 
2857
    }
 
2858
  }
 
2859
 
 
2860
  TableList *sj_nest;
 
2861
  nested_join_st *nested_join;
 
2862
  if (!(sj_nest= alloc_join_nest(parent_join->session)))
 
2863
  {
 
2864
    return(true);
 
2865
  }
 
2866
  nested_join= sj_nest->nested_join;
 
2867
 
 
2868
  sj_nest->join_list= emb_join_list;
 
2869
  sj_nest->embedding= emb_tbl_nest;
 
2870
  sj_nest->alias= (char*) "(sj-nest)";
 
2871
  /* Nests do not participate in those 'chains', so: */
 
2872
  /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
 
2873
  emb_join_list->push_back(sj_nest);
 
2874
 
 
2875
  /*
 
2876
    nested_join->used_tables and nested_join->not_null_tables are
 
2877
    initialized in simplify_joins().
 
2878
  */
 
2879
 
 
2880
  /*
 
2881
    2. Walk through subquery's top list and set 'embedding' to point to the
 
2882
       sj-nest.
 
2883
  */
 
2884
  Select_Lex *subq_lex= subq_pred->unit->first_select();
 
2885
  nested_join->join_list.empty();
 
2886
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
 
2887
  TableList *tl, *last_leaf;
 
2888
  while ((tl= li++))
 
2889
  {
 
2890
    tl->embedding= sj_nest;
 
2891
    tl->join_list= &nested_join->join_list;
 
2892
    nested_join->join_list.push_back(tl);
 
2893
  }
 
2894
 
 
2895
  /*
 
2896
    Reconnect the next_leaf chain.
 
2897
    TODO: Do we have to put subquery's tables at the end of the chain?
 
2898
          Inserting them at the beginning would be a bit faster.
 
2899
    NOTE: We actually insert them at the front! That's because the order is
 
2900
          reversed in this list.
 
2901
  */
 
2902
  for (tl= parent_lex->leaf_tables; tl->next_leaf; tl= tl->next_leaf) {};
 
2903
  tl->next_leaf= subq_lex->leaf_tables;
 
2904
  last_leaf= tl;
 
2905
 
 
2906
  /*
 
2907
    Same as above for next_local chain
 
2908
    (a theory: a next_local chain always starts with ::leaf_tables
 
2909
     because view's tables are inserted after the view)
 
2910
  */
 
2911
  for (tl= parent_lex->leaf_tables; tl->next_local; tl= tl->next_local) {};
 
2912
  tl->next_local= subq_lex->leaf_tables;
 
2913
 
 
2914
  /* A theory: no need to re-connect the next_global chain */
 
2915
 
 
2916
  /* 3. Remove the original subquery predicate from the WHERE/ON */
 
2917
 
 
2918
  // The subqueries were replaced for Item_int(1) earlier
 
2919
  subq_pred->exec_method= Item_in_subselect::SEMI_JOIN; // for subsequent executions
 
2920
  /*TODO: also reset the 'with_subselect' there. */
 
2921
 
 
2922
  /* n. Adjust the parent_join->tables counter */
 
2923
  uint32_t table_no= parent_join->tables;
 
2924
  /* n. Walk through child's tables and adjust table->map */
 
2925
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
 
2926
  {
 
2927
    tl->table->tablenr= table_no;
 
2928
    tl->table->map= ((table_map)1) << table_no;
 
2929
    Select_Lex *old_sl= tl->select_lex;
 
2930
    tl->select_lex= parent_join->select_lex;
 
2931
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
 
2932
      emb->select_lex= parent_join->select_lex;
 
2933
  }
 
2934
  parent_join->tables += subq_lex->join->tables;
 
2935
 
 
2936
  /*
 
2937
    Put the subquery's WHERE into semi-join's sj_on_expr
 
2938
    Add the subquery-induced equalities too.
 
2939
  */
 
2940
  Select_Lex *save_lex= session->lex->current_select;
 
2941
  session->lex->current_select=subq_lex;
 
2942
  if (!subq_pred->left_expr->fixed &&
 
2943
       subq_pred->left_expr->fix_fields(session, &subq_pred->left_expr))
 
2944
    return(true);
 
2945
  session->lex->current_select=save_lex;
 
2946
 
 
2947
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
 
2948
  sj_nest->nested_join->sj_depends_on=  subq_pred->used_tables() |
 
2949
                                        subq_pred->left_expr->used_tables();
 
2950
  sj_nest->sj_on_expr= subq_lex->where;
 
2951
 
 
2952
  /*
 
2953
    Create the IN-equalities and inject them into semi-join's ON expression.
 
2954
    Additionally, for InsideOut strategy
 
2955
     - Record the number of IN-equalities.
 
2956
     - Create list of pointers to (oe1, ..., ieN). We'll need the list to
 
2957
       see which of the expressions are bound and which are not (for those
 
2958
       we'll produce a distinct stream of (ie_i1,...ie_ik).
 
2959
 
 
2960
       (TODO: can we just create a list of pointers and hope the expressions
 
2961
       will not substitute themselves on fix_fields()? or we need to wrap
 
2962
       them into Item_direct_view_refs and store pointers to those. The
 
2963
       pointers to Item_direct_view_refs are guaranteed to be stable as
 
2964
       Item_direct_view_refs doesn't substitute itself with anything in
 
2965
       Item_direct_view_ref::fix_fields.
 
2966
  */
 
2967
  sj_nest->sj_in_exprs= subq_pred->left_expr->cols();
 
2968
  sj_nest->nested_join->sj_outer_expr_list.empty();
 
2969
 
 
2970
  if (subq_pred->left_expr->cols() == 1)
 
2971
  {
 
2972
    nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr);
 
2973
 
 
2974
    Item *item_eq= new Item_func_eq(subq_pred->left_expr,
 
2975
                                    subq_lex->ref_pointer_array[0]);
 
2976
    item_eq->name= (char*)subq_sj_cond_name;
 
2977
    sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
2978
  }
 
2979
  else
 
2980
  {
 
2981
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
 
2982
    {
 
2983
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
 
2984
                                                element_index(i));
 
2985
      Item *item_eq=
 
2986
        new Item_func_eq(subq_pred->left_expr->element_index(i),
 
2987
                         subq_lex->ref_pointer_array[i]);
 
2988
      item_eq->name= (char*)subq_sj_cond_name + (i % 64);
 
2989
      sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
2990
    }
 
2991
  }
 
2992
  /* Fix the created equality and AND */
 
2993
  sj_nest->sj_on_expr->fix_fields(parent_join->session, &sj_nest->sj_on_expr);
 
2994
 
 
2995
  /*
 
2996
    Walk through sj nest's WHERE and ON expressions and call
 
2997
    item->fix_table_changes() for all items.
 
2998
  */
 
2999
  sj_nest->sj_on_expr->fix_after_pullout(parent_lex, &sj_nest->sj_on_expr);
 
3000
  fix_list_after_tbl_changes(parent_lex, &sj_nest->nested_join->join_list);
 
3001
 
 
3002
 
 
3003
  /* Unlink the child select_lex so it doesn't show up in EXPLAIN: */
 
3004
  subq_lex->master_unit()->exclude_level();
 
3005
 
 
3006
  /* Inject sj_on_expr into the parent's WHERE or ON */
 
3007
  if (emb_tbl_nest)
 
3008
  {
 
3009
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr,
 
3010
                                     sj_nest->sj_on_expr);
 
3011
    emb_tbl_nest->on_expr->fix_fields(parent_join->session, &emb_tbl_nest->on_expr);
 
3012
  }
 
3013
  else
 
3014
  {
 
3015
    /* Inject into the WHERE */
 
3016
    parent_join->conds= and_items(parent_join->conds, sj_nest->sj_on_expr);
 
3017
    parent_join->conds->fix_fields(parent_join->session, &parent_join->conds);
 
3018
    parent_join->select_lex->where= parent_join->conds;
 
3019
  }
 
3020
 
 
3021
  return(false);
 
3022
}
 
3023
 
 
3024
 
 
3025
/*
 
3026
  Convert candidate subquery predicates to semi-joins
 
3027
 
 
3028
  SYNOPSIS
 
3029
    JOIN::flatten_subqueries()
 
3030
 
 
3031
  DESCRIPTION
 
3032
    Convert candidate subquery predicates to semi-joins.
 
3033
 
 
3034
  RETURN
 
3035
    false  OK
 
3036
    true   Error
 
3037
*/
 
3038
 
 
3039
bool JOIN::flatten_subqueries()
 
3040
{
 
3041
  Item_in_subselect **in_subq;
 
3042
  Item_in_subselect **in_subq_end;
 
3043
 
 
3044
  if (sj_subselects.elements() == 0)
 
3045
    return(false);
 
3046
 
 
3047
  /* 1. Fix children subqueries */
 
3048
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
 
3049
       in_subq != in_subq_end; in_subq++)
 
3050
  {
 
3051
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
3052
    child_join->outer_tables = child_join->tables;
 
3053
    if (child_join->flatten_subqueries())
 
3054
      return(true);
 
3055
    (*in_subq)->sj_convert_priority=
 
3056
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
 
3057
  }
 
3058
  
 
3059
  bool outer_join_disable_semi_join= false;
 
3060
  /*
 
3061
   * Temporary measure: disable semi-joins when they are together with outer
 
3062
   * joins.
 
3063
   *
 
3064
   * @see LP Bug #314911
 
3065
   */
 
3066
  for (TableList *tbl= select_lex->leaf_tables; tbl; tbl=tbl->next_leaf)
 
3067
  {
 
3068
    TableList *embedding= tbl->embedding;
 
3069
    if (tbl->on_expr || (tbl->embedding && !(embedding->sj_on_expr && 
 
3070
                                            !embedding->embedding)))
 
3071
    {
 
3072
      in_subq= sj_subselects.front();
 
3073
      outer_join_disable_semi_join= true;
 
3074
    }
 
3075
  }
 
3076
 
 
3077
  if (! outer_join_disable_semi_join)
 
3078
  {
 
3079
    /*
 
3080
      2. Pick which subqueries to convert:
 
3081
        sort the subquery array
 
3082
        - prefer correlated subqueries over uncorrelated;
 
3083
        - prefer subqueries that have greater number of outer tables;
 
3084
    */
 
3085
    sj_subselects.sort(subq_sj_candidate_cmp);
 
3086
    // #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
 
3087
    /* Replace all subqueries to be flattened with Item_int(1) */
 
3088
    for (in_subq= sj_subselects.front();
 
3089
        in_subq != in_subq_end &&
 
3090
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
3091
        in_subq++)
 
3092
    {
 
3093
      if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
 
3094
        return(true);
 
3095
    }
 
3096
 
 
3097
    for (in_subq= sj_subselects.front();
 
3098
        in_subq != in_subq_end &&
 
3099
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
3100
        in_subq++)
 
3101
    {
 
3102
      if (convert_subq_to_sj(this, *in_subq))
 
3103
        return(true);
 
3104
    }
 
3105
  }
 
3106
 
 
3107
  /* 3. Finalize those we didn't convert */
 
3108
  for (; in_subq!= in_subq_end; in_subq++)
 
3109
  {
 
3110
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
 
3111
    Item_subselect::trans_res res;
 
3112
    (*in_subq)->changed= 0;
 
3113
    (*in_subq)->fixed= 0;
 
3114
    res= (*in_subq)->select_transformer(child_join);
 
3115
    if (res == Item_subselect::RES_ERROR)
 
3116
      return(true);
 
3117
 
 
3118
    (*in_subq)->changed= 1;
 
3119
    (*in_subq)->fixed= 1;
 
3120
 
 
3121
    Item *substitute= (*in_subq)->substitution;
 
3122
    bool do_fix_fields= !(*in_subq)->substitution->fixed;
 
3123
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
 
3124
      return(true);
 
3125
 
 
3126
    //if ((*in_subq)->fix_fields(session, (*in_subq)->ref_ptr))
 
3127
    //  return(true);
 
3128
  }
 
3129
  sj_subselects.clear();
 
3130
  return(false);
 
3131
}
 
3132
 
 
3133
/**
 
3134
  Setup for execution all subqueries of a query, for which the optimizer
 
3135
  chose hash semi-join.
 
3136
 
 
3137
  @details Iterate over all subqueries of the query, and if they are under an
 
3138
  IN predicate, and the optimizer chose to compute it via hash semi-join:
 
3139
  - try to initialize all data structures needed for the materialized execution
 
3140
    of the IN predicate,
 
3141
  - if this fails, then perform the IN=>EXISTS transformation which was
 
3142
    previously blocked during JOIN::prepare.
 
3143
 
 
3144
  This method is part of the "code generation" query processing phase.
 
3145
 
 
3146
  This phase must be called after substitute_for_best_equal_field() because
 
3147
  that function may replace items with other items from a multiple equality,
 
3148
  and we need to reference the correct items in the index access method of the
 
3149
  IN predicate.
 
3150
 
 
3151
  @return Operation status
 
3152
  @retval false     success.
 
3153
  @retval true      error occurred.
 
3154
*/
 
3155
bool JOIN::setup_subquery_materialization()
 
3156
{
 
3157
  for (Select_Lex_Unit *un= select_lex->first_inner_unit(); un;
 
3158
       un= un->next_unit())
 
3159
  {
 
3160
    for (Select_Lex *sl= un->first_select(); sl; sl= sl->next_select())
 
3161
    {
 
3162
      Item_subselect *subquery_predicate= sl->master_unit()->item;
 
3163
      if (subquery_predicate &&
 
3164
          subquery_predicate->substype() == Item_subselect::IN_SUBS)
 
3165
      {
 
3166
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
 
3167
        if (in_subs->exec_method == Item_in_subselect::MATERIALIZATION &&
 
3168
            in_subs->setup_engine())
 
3169
          return true;
 
3170
      }
 
3171
    }
 
3172
  }
 
3173
  return false;
 
3174
}
 
3175
 
 
3176
 
 
3177
/*
 
3178
  Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
3179
 
 
3180
  SYNOPSIS
 
3181
    find_eq_ref_candidate()
 
3182
      table             Table to be checked
 
3183
      sj_inner_tables   Bitmap of inner tables. eq_ref(inner_table) doesn't
 
3184
                        count.
 
3185
 
 
3186
  DESCRIPTION
 
3187
    Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
3188
 
 
3189
  TODO
 
3190
    Check again if it is feasible to factor common parts with constant table
 
3191
    search
 
3192
 
 
3193
  RETURN
 
3194
    true  - There exists an eq_ref(outer-tables) candidate
 
3195
    false - Otherwise
 
3196
*/
 
3197
 
 
3198
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
 
3199
{
 
3200
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
 
3201
  uint32_t key;
 
3202
 
 
3203
  if (keyuse)
 
3204
  {
 
3205
    while (1) /* For each key */
 
3206
    {
 
3207
      key= keyuse->key;
 
3208
      KEY *keyinfo= table->key_info + key;
 
3209
      key_part_map bound_parts= 0;
 
3210
      if ((keyinfo->flags & HA_NOSAME) == HA_NOSAME)
 
3211
      {
 
3212
        do  /* For all equalities on all key parts */
 
3213
        {
 
3214
          /* Check if this is "t.keypart = expr(outer_tables) */
 
3215
          if (!(keyuse->used_tables & sj_inner_tables) &&
 
3216
              !(keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL))
 
3217
          {
 
3218
            bound_parts |= 1 << keyuse->keypart;
 
3219
          }
 
3220
          keyuse++;
 
3221
        } while (keyuse->key == key && keyuse->table == table);
 
3222
 
 
3223
        if (bound_parts == PREV_BITS(uint, keyinfo->key_parts))
 
3224
          return true;
 
3225
        if (keyuse->table != table)
 
3226
          return false;
 
3227
      }
 
3228
      else
 
3229
      {
 
3230
        do
 
3231
        {
 
3232
          keyuse++;
 
3233
          if (keyuse->table != table)
 
3234
            return false;
 
3235
        }
 
3236
        while (keyuse->key == key);
 
3237
      }
 
3238
    }
 
3239
  }
 
3240
  return false;
 
3241
}
 
3242
 
 
3243
 
 
3244
/*
 
3245
  Pull tables out of semi-join nests, if possible
 
3246
 
 
3247
  SYNOPSIS
 
3248
    pull_out_semijoin_tables()
 
3249
      join  The join where to do the semi-join flattening
 
3250
 
 
3251
  DESCRIPTION
 
3252
    Try to pull tables out of semi-join nests.
 
3253
 
 
3254
    PRECONDITIONS
 
3255
    When this function is called, the join may have several semi-join nests
 
3256
    (possibly within different semi-join nests), but it is guaranteed that
 
3257
    one semi-join nest does not contain another.
 
3258
 
 
3259
    ACTION
 
3260
    A table can be pulled out of the semi-join nest if
 
3261
     - It is a constant table
 
3262
     - It is accessed
 
3263
 
 
3264
    POSTCONDITIONS
 
3265
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
 
3266
       tables)
 
3267
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
 
3268
     * Semi-join nests TableList::sj_inner_tables
 
3269
 
 
3270
    This operation is (and should be) performed at each PS execution since
 
3271
    tables may become/cease to be constant across PS reexecutions.
 
3272
 
 
3273
  RETURN
 
3274
    0 - OK
 
3275
    1 - Out of memory error
 
3276
*/
 
3277
 
 
3278
int pull_out_semijoin_tables(JOIN *join)
 
3279
{
 
3280
  TableList *sj_nest;
 
3281
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
 
3282
 
 
3283
  /* Try pulling out of the each of the semi-joins */
 
3284
  while ((sj_nest= sj_list_it++))
 
3285
  {
 
3286
    /* Action #1: Mark the constant tables to be pulled out */
 
3287
    table_map pulled_tables= 0;
 
3288
 
 
3289
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
 
3290
    TableList *tbl;
 
3291
    while ((tbl= child_li++))
 
3292
    {
 
3293
      if (tbl->table)
 
3294
      {
 
3295
        tbl->table->reginfo.join_tab->emb_sj_nest= sj_nest;
 
3296
        if (tbl->table->map & join->const_table_map)
 
3297
        {
 
3298
          pulled_tables |= tbl->table->map;
 
3299
        }
 
3300
      }
 
3301
    }
 
3302
 
 
3303
    /*
 
3304
      Action #2: Find which tables we can pull out based on
 
3305
      update_ref_and_keys() data. Note that pulling one table out can allow
 
3306
      us to pull out some other tables too.
 
3307
    */
 
3308
    bool pulled_a_table;
 
3309
    do
 
3310
    {
 
3311
      pulled_a_table= false;
 
3312
      child_li.rewind();
 
3313
      while ((tbl= child_li++))
 
3314
      {
 
3315
        if (tbl->table && !(pulled_tables & tbl->table->map))
 
3316
        {
 
3317
          if (find_eq_ref_candidate(tbl->table,
 
3318
                                    sj_nest->nested_join->used_tables &
 
3319
                                    ~pulled_tables))
 
3320
          {
 
3321
            pulled_a_table= true;
 
3322
            pulled_tables |= tbl->table->map;
 
3323
          }
 
3324
        }
 
3325
      }
 
3326
    } while (pulled_a_table);
 
3327
 
 
3328
    child_li.rewind();
 
3329
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
 
3330
    {
 
3331
      (sj_nest)->sj_inner_tables= 0;
 
3332
      while ((tbl= child_li++))
 
3333
      {
 
3334
        if (tbl->table)
 
3335
          tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
3336
      }
 
3337
    }
 
3338
    else
 
3339
    {
 
3340
      /* Record the bitmap of inner tables, mark the inner tables */
 
3341
      table_map inner_tables=(sj_nest)->nested_join->used_tables &
 
3342
                             ~pulled_tables;
 
3343
      (sj_nest)->sj_inner_tables= inner_tables;
 
3344
      while ((tbl= child_li++))
 
3345
      {
 
3346
        if (tbl->table)
 
3347
        {
 
3348
          if (inner_tables & tbl->table->map)
 
3349
            tbl->table->reginfo.join_tab->emb_sj_nest= (sj_nest);
 
3350
          else
 
3351
            tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
 
3352
        }
 
3353
      }
 
3354
    }
 
3355
  }
 
3356
  return(0);
 
3357
}
 
3358
 
456
3359
/*****************************************************************************
457
 
  Create JoinTableS, make a guess about the table types,
 
3360
  Create JOIN_TABS, make a guess about the table types,
458
3361
  Approximate how many records will be used in each table
459
3362
*****************************************************************************/
460
 
ha_rows get_quick_record_count(Session *session, optimizer::SqlSelect *select, Table *table, const key_map *keys,ha_rows limit)
 
3363
 
 
3364
 
 
3365
static ha_rows get_quick_record_count(Session *session, SQL_SELECT *select,
 
3366
                                      Table *table,
 
3367
                                      const key_map *keys,ha_rows limit)
461
3368
{
462
3369
  int error;
463
3370
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
478
3385
  return(HA_POS_ERROR);                 /* This shouldn't happend */
479
3386
}
480
3387
 
 
3388
/*
 
3389
   This structure is used to collect info on potentially sargable
 
3390
   predicates in order to check whether they become sargable after
 
3391
   reading const tables.
 
3392
   We form a bitmap of indexes that can be used for sargable predicates.
 
3393
   Only such indexes are involved in range analysis.
 
3394
*/
 
3395
typedef struct st_sargable_param
 
3396
{
 
3397
  Field *field;              /* field against which to check sargability */
 
3398
  Item **arg_value;          /* values of potential keys for lookups     */
 
3399
  uint32_t num_values;           /* number of values in the above array      */
 
3400
} SARGABLE_PARAM;
 
3401
 
 
3402
/**
 
3403
  Calculate the best possible join and initialize the join structure.
 
3404
 
 
3405
  @retval
 
3406
    0   ok
 
3407
  @retval
 
3408
    1   Fatal error
 
3409
*/
 
3410
 
 
3411
static bool
 
3412
make_join_statistics(JOIN *join, TableList *tables, COND *conds,
 
3413
                     DYNAMIC_ARRAY *keyuse_array)
 
3414
{
 
3415
  int error;
 
3416
  Table *table;
 
3417
  uint32_t i,table_count,const_count,key;
 
3418
  table_map found_const_table_map, all_table_map, found_ref, refs;
 
3419
  key_map const_ref, eq_part;
 
3420
  Table **table_vector;
 
3421
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
 
3422
  KEYUSE *keyuse,*start_keyuse;
 
3423
  table_map outer_join=0;
 
3424
  SARGABLE_PARAM *sargables= 0;
 
3425
  JOIN_TAB *stat_vector[MAX_TABLES+1];
 
3426
 
 
3427
  table_count=join->tables;
 
3428
  stat=(JOIN_TAB*) join->session->calloc(sizeof(JOIN_TAB)*table_count);
 
3429
  stat_ref=(JOIN_TAB**) join->session->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
 
3430
  table_vector=(Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
 
3431
  if (!stat || !stat_ref || !table_vector)
 
3432
    return(1);                          // Eom /* purecov: inspected */
 
3433
 
 
3434
  join->best_ref=stat_vector;
 
3435
 
 
3436
  stat_end=stat+table_count;
 
3437
  found_const_table_map= all_table_map=0;
 
3438
  const_count=0;
 
3439
 
 
3440
  for (s= stat, i= 0;
 
3441
       tables;
 
3442
       s++, tables= tables->next_leaf, i++)
 
3443
  {
 
3444
    TableList *embedding= tables->embedding;
 
3445
    stat_vector[i]=s;
 
3446
    s->keys.init();
 
3447
    s->const_keys.init();
 
3448
    s->checked_keys.init();
 
3449
    s->needed_reg.init();
 
3450
    table_vector[i]=s->table=table=tables->table;
 
3451
    table->pos_in_table_list= tables;
 
3452
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
3453
    if(error)
 
3454
    {
 
3455
        table->file->print_error(error, MYF(0));
 
3456
        return(1);
 
3457
    }
 
3458
    table->quick_keys.clear_all();
 
3459
    table->reginfo.join_tab=s;
 
3460
    table->reginfo.not_exists_optimize=0;
 
3461
    memset(table->const_key_parts, 0,
 
3462
           sizeof(key_part_map)*table->s->keys);
 
3463
    all_table_map|= table->map;
 
3464
    s->join=join;
 
3465
    s->info=0;                                  // For describe
 
3466
 
 
3467
    s->dependent= tables->dep_tables;
 
3468
    s->key_dependent= 0;
 
3469
    if (tables->schema_table)
 
3470
      table->file->stats.records= 2;
 
3471
    table->quick_condition_rows= table->file->stats.records;
 
3472
 
 
3473
    s->on_expr_ref= &tables->on_expr;
 
3474
    if (*s->on_expr_ref)
 
3475
    {
 
3476
      /* s is the only inner table of an outer join */
 
3477
      if (!table->file->stats.records && !embedding)
 
3478
      {                                         // Empty table
 
3479
        s->dependent= 0;                        // Ignore LEFT JOIN depend.
 
3480
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
3481
        continue;
 
3482
      }
 
3483
      outer_join|= table->map;
 
3484
      s->embedding_map= 0;
 
3485
      for (;embedding; embedding= embedding->embedding)
 
3486
        s->embedding_map|= embedding->nested_join->nj_map;
 
3487
      continue;
 
3488
    }
 
3489
    if (embedding && !(embedding->sj_on_expr && ! embedding->embedding))
 
3490
    {
 
3491
      /* s belongs to a nested join, maybe to several embedded joins */
 
3492
      s->embedding_map= 0;
 
3493
      do
 
3494
      {
 
3495
        nested_join_st *nested_join= embedding->nested_join;
 
3496
        s->embedding_map|=nested_join->nj_map;
 
3497
        s->dependent|= embedding->dep_tables;
 
3498
        embedding= embedding->embedding;
 
3499
        outer_join|= nested_join->used_tables;
 
3500
      }
 
3501
      while (embedding);
 
3502
      continue;
 
3503
    }
 
3504
    if ((table->file->stats.records <= 1) &&
 
3505
        !s->dependent &&
 
3506
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
 
3507
    {
 
3508
      set_position(join,const_count++,s,(KEYUSE*) 0);
 
3509
    }
 
3510
  }
 
3511
  stat_vector[i]=0;
 
3512
  join->outer_join=outer_join;
 
3513
 
 
3514
  if (join->outer_join)
 
3515
  {
 
3516
    /*
 
3517
       Build transitive closure for relation 'to be dependent on'.
 
3518
       This will speed up the plan search for many cases with outer joins,
 
3519
       as well as allow us to catch illegal cross references/
 
3520
       Warshall's algorithm is used to build the transitive closure.
 
3521
       As we use bitmaps to represent the relation the complexity
 
3522
       of the algorithm is O((number of tables)^2).
 
3523
    */
 
3524
    for (i= 0, s= stat ; i < table_count ; i++, s++)
 
3525
    {
 
3526
      for (uint32_t j= 0 ; j < table_count ; j++)
 
3527
      {
 
3528
        table= stat[j].table;
 
3529
        if (s->dependent & table->map)
 
3530
          s->dependent |= table->reginfo.join_tab->dependent;
 
3531
      }
 
3532
      if (s->dependent)
 
3533
        s->table->maybe_null= 1;
 
3534
    }
 
3535
    /* Catch illegal cross references for outer joins */
 
3536
    for (i= 0, s= stat ; i < table_count ; i++, s++)
 
3537
    {
 
3538
      if (s->dependent & s->table->map)
 
3539
      {
 
3540
        join->tables=0;                 // Don't use join->table
 
3541
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
 
3542
        return(1);
 
3543
      }
 
3544
      s->key_dependent= s->dependent;
 
3545
    }
 
3546
  }
 
3547
 
 
3548
  if (conds || outer_join)
 
3549
    if (update_ref_and_keys(join->session, keyuse_array, stat, join->tables,
 
3550
                            conds, join->cond_equal,
 
3551
                            ~outer_join, join->select_lex, &sargables))
 
3552
      return(1);
 
3553
 
 
3554
  /* Read tables with 0 or 1 rows (system tables) */
 
3555
  join->const_table_map= 0;
 
3556
 
 
3557
  for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
 
3558
       p_pos < p_end ;
 
3559
       p_pos++)
 
3560
  {
 
3561
    int tmp;
 
3562
    s= p_pos->table;
 
3563
    s->type=JT_SYSTEM;
 
3564
    join->const_table_map|=s->table->map;
 
3565
    if ((tmp=join_read_const_table(s, p_pos)))
 
3566
    {
 
3567
      if (tmp > 0)
 
3568
        return(1);                      // Fatal error
 
3569
    }
 
3570
    else
 
3571
      found_const_table_map|= s->table->map;
 
3572
  }
 
3573
 
 
3574
  /* loop until no more const tables are found */
 
3575
  int ref_changed;
 
3576
  do
 
3577
  {
 
3578
  more_const_tables_found:
 
3579
    ref_changed = 0;
 
3580
    found_ref=0;
 
3581
 
 
3582
    /*
 
3583
      We only have to loop from stat_vector + const_count as
 
3584
      set_position() will move all const_tables first in stat_vector
 
3585
    */
 
3586
 
 
3587
    for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
 
3588
    {
 
3589
      table=s->table;
 
3590
 
 
3591
      /*
 
3592
        If equi-join condition by a key is null rejecting and after a
 
3593
        substitution of a const table the key value happens to be null
 
3594
        then we can state that there are no matches for this equi-join.
 
3595
      */
 
3596
      if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
 
3597
      {
 
3598
        /*
 
3599
          When performing an outer join operation if there are no matching rows
 
3600
          for the single row of the outer table all the inner tables are to be
 
3601
          null complemented and thus considered as constant tables.
 
3602
          Here we apply this consideration to the case of outer join operations
 
3603
          with a single inner table only because the case with nested tables
 
3604
          would require a more thorough analysis.
 
3605
          TODO. Apply single row substitution to null complemented inner tables
 
3606
          for nested outer join operations.
 
3607
        */
 
3608
        while (keyuse->table == table)
 
3609
        {
 
3610
          if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
 
3611
              keyuse->val->is_null() && keyuse->null_rejecting)
 
3612
          {
 
3613
            s->type= JT_CONST;
 
3614
            mark_as_null_row(table);
 
3615
            found_const_table_map|= table->map;
 
3616
            join->const_table_map|= table->map;
 
3617
            set_position(join,const_count++,s,(KEYUSE*) 0);
 
3618
            goto more_const_tables_found;
 
3619
           }
 
3620
          keyuse++;
 
3621
        }
 
3622
      }
 
3623
 
 
3624
      if (s->dependent)                         // If dependent on some table
 
3625
      {
 
3626
        // All dep. must be constants
 
3627
        if (s->dependent & ~(found_const_table_map))
 
3628
          continue;
 
3629
        if (table->file->stats.records <= 1L &&
 
3630
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
3631
            !table->pos_in_table_list->embedding)
 
3632
        {                                       // system table
 
3633
          int tmp= 0;
 
3634
          s->type=JT_SYSTEM;
 
3635
          join->const_table_map|=table->map;
 
3636
          set_position(join,const_count++,s,(KEYUSE*) 0);
 
3637
          if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
 
3638
          {
 
3639
            if (tmp > 0)
 
3640
              return(1);                        // Fatal error
 
3641
          }
 
3642
          else
 
3643
            found_const_table_map|= table->map;
 
3644
          continue;
 
3645
        }
 
3646
      }
 
3647
      /* check if table can be read by key or table only uses const refs */
 
3648
      if ((keyuse=s->keyuse))
 
3649
      {
 
3650
        s->type= JT_REF;
 
3651
        while (keyuse->table == table)
 
3652
        {
 
3653
          start_keyuse=keyuse;
 
3654
          key=keyuse->key;
 
3655
          s->keys.set_bit(key);               // QQ: remove this ?
 
3656
 
 
3657
          refs=0;
 
3658
          const_ref.clear_all();
 
3659
          eq_part.clear_all();
 
3660
          do
 
3661
          {
 
3662
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
 
3663
            {
 
3664
              if (!((~found_const_table_map) & keyuse->used_tables))
 
3665
                const_ref.set_bit(keyuse->keypart);
 
3666
              else
 
3667
                refs|=keyuse->used_tables;
 
3668
              eq_part.set_bit(keyuse->keypart);
 
3669
            }
 
3670
            keyuse++;
 
3671
          } while (keyuse->table == table && keyuse->key == key);
 
3672
 
 
3673
          if (eq_part.is_prefix(table->key_info[key].key_parts) &&
 
3674
              !table->pos_in_table_list->embedding)
 
3675
          {
 
3676
            if ((table->key_info[key].flags & (HA_NOSAME))
 
3677
                 == HA_NOSAME)
 
3678
            {
 
3679
              if (const_ref == eq_part)
 
3680
              {                                 // Found everything for ref.
 
3681
                int tmp;
 
3682
                ref_changed = 1;
 
3683
                s->type= JT_CONST;
 
3684
                join->const_table_map|=table->map;
 
3685
                set_position(join,const_count++,s,start_keyuse);
 
3686
                if (create_ref_for_key(join, s, start_keyuse,
 
3687
                                       found_const_table_map))
 
3688
                  return(1);
 
3689
                if ((tmp=join_read_const_table(s,
 
3690
                                               join->positions+const_count-1)))
 
3691
                {
 
3692
                  if (tmp > 0)
 
3693
                    return(1);                  // Fatal error
 
3694
                }
 
3695
                else
 
3696
                  found_const_table_map|= table->map;
 
3697
                break;
 
3698
              }
 
3699
              else
 
3700
                found_ref|= refs;      // Table is const if all refs are const
 
3701
            }
 
3702
            else if (const_ref == eq_part)
 
3703
              s->const_keys.set_bit(key);
 
3704
          }
 
3705
        }
 
3706
      }
 
3707
    }
 
3708
  } while (join->const_table_map & found_ref && ref_changed);
 
3709
 
 
3710
  /*
 
3711
    Update info on indexes that can be used for search lookups as
 
3712
    reading const tables may has added new sargable predicates.
 
3713
  */
 
3714
  if (const_count && sargables)
 
3715
  {
 
3716
    for( ; sargables->field ; sargables++)
 
3717
    {
 
3718
      Field *field= sargables->field;
 
3719
      JOIN_TAB *join_tab= field->table->reginfo.join_tab;
 
3720
      key_map possible_keys= field->key_start;
 
3721
      possible_keys.intersect(field->table->keys_in_use_for_query);
 
3722
      bool is_const= 1;
 
3723
      for (uint32_t j=0; j < sargables->num_values; j++)
 
3724
        is_const&= sargables->arg_value[j]->const_item();
 
3725
      if (is_const)
 
3726
        join_tab[0].const_keys.merge(possible_keys);
 
3727
    }
 
3728
  }
 
3729
 
 
3730
  if (pull_out_semijoin_tables(join))
 
3731
    return(true);
 
3732
 
 
3733
  /* Calc how many (possible) matched records in each table */
 
3734
 
 
3735
  for (s=stat ; s < stat_end ; s++)
 
3736
  {
 
3737
    if (s->type == JT_SYSTEM || s->type == JT_CONST)
 
3738
    {
 
3739
      /* Only one matching row */
 
3740
      s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
 
3741
      continue;
 
3742
    }
 
3743
    /* Approximate found rows and time to read them */
 
3744
    s->found_records=s->records=s->table->file->stats.records;
 
3745
    s->read_time=(ha_rows) s->table->file->scan_time();
 
3746
 
 
3747
    /*
 
3748
      Set a max range of how many seeks we can expect when using keys
 
3749
      This is can't be to high as otherwise we are likely to use
 
3750
      table scan.
 
3751
    */
 
3752
    s->worst_seeks= cmin((double) s->found_records / 10,
 
3753
                        (double) s->read_time*3);
 
3754
    if (s->worst_seeks < 2.0)                   // Fix for small tables
 
3755
      s->worst_seeks=2.0;
 
3756
 
 
3757
    /*
 
3758
      Add to stat->const_keys those indexes for which all group fields or
 
3759
      all select distinct fields participate in one index.
 
3760
    */
 
3761
    add_group_and_distinct_keys(join, s);
 
3762
 
 
3763
    if (!s->const_keys.is_clear_all() &&
 
3764
        !s->table->pos_in_table_list->embedding)
 
3765
    {
 
3766
      ha_rows records;
 
3767
      SQL_SELECT *select;
 
3768
      select= make_select(s->table, found_const_table_map,
 
3769
                          found_const_table_map,
 
3770
                          *s->on_expr_ref ? *s->on_expr_ref : conds,
 
3771
                          1, &error);
 
3772
      if (!select)
 
3773
        return(1);
 
3774
      records= get_quick_record_count(join->session, select, s->table,
 
3775
                                      &s->const_keys, join->row_limit);
 
3776
      s->quick=select->quick;
 
3777
      s->needed_reg=select->needed_reg;
 
3778
      select->quick=0;
 
3779
      if (records == 0 && s->table->reginfo.impossible_range)
 
3780
      {
 
3781
        /*
 
3782
          Impossible WHERE or ON expression
 
3783
          In case of ON, we mark that the we match one empty NULL row.
 
3784
          In case of WHERE, don't set found_const_table_map to get the
 
3785
          caller to abort with a zero row result.
 
3786
        */
 
3787
        join->const_table_map|= s->table->map;
 
3788
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
3789
        s->type= JT_CONST;
 
3790
        if (*s->on_expr_ref)
 
3791
        {
 
3792
          /* Generate empty row */
 
3793
          s->info= "Impossible ON condition";
 
3794
          found_const_table_map|= s->table->map;
 
3795
          s->type= JT_CONST;
 
3796
          mark_as_null_row(s->table);           // All fields are NULL
 
3797
        }
 
3798
      }
 
3799
      if (records != HA_POS_ERROR)
 
3800
      {
 
3801
        s->found_records=records;
 
3802
        s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
 
3803
      }
 
3804
      delete select;
 
3805
    }
 
3806
  }
 
3807
 
 
3808
  join->join_tab=stat;
 
3809
  join->map2table=stat_ref;
 
3810
  join->table= join->all_tables=table_vector;
 
3811
  join->const_tables=const_count;
 
3812
  join->found_const_table_map=found_const_table_map;
 
3813
 
 
3814
  /* Find an optimal join order of the non-constant tables. */
 
3815
  if (join->const_tables != join->tables)
 
3816
  {
 
3817
    optimize_keyuse(join, keyuse_array);
 
3818
    if (choose_plan(join, all_table_map & ~join->const_table_map))
 
3819
      return(true);
 
3820
  }
 
3821
  else
 
3822
  {
 
3823
    memcpy(join->best_positions, join->positions,
 
3824
           sizeof(POSITION)*join->const_tables);
 
3825
    join->best_read=1.0;
 
3826
  }
 
3827
  /* Generate an execution plan from the found optimal join order. */
 
3828
  return(join->session->killed || get_best_combination(join));
 
3829
}
 
3830
 
 
3831
 
481
3832
/*****************************************************************************
482
3833
  Check with keys are used and with tables references with tables
483
3834
  Updates in stat:
486
3837
          keyuse     Pointer to possible keys
487
3838
*****************************************************************************/
488
3839
 
 
3840
/// Used when finding key fields
 
3841
typedef struct key_field_t {
 
3842
  Field         *field;
 
3843
  Item          *val;                   ///< May be empty if diff constant
 
3844
  uint          level;
 
3845
  uint          optimize; // KEY_OPTIMIZE_*
 
3846
  bool          eq_func;
 
3847
  /**
 
3848
    If true, the condition this struct represents will not be satisfied
 
3849
    when val IS NULL.
 
3850
  */
 
3851
  bool          null_rejecting;
 
3852
  bool          *cond_guard; /* See KEYUSE::cond_guard */
 
3853
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
 
3854
} KEY_FIELD;
 
3855
 
 
3856
/**
 
3857
  Merge new key definitions to old ones, remove those not used in both.
 
3858
 
 
3859
  This is called for OR between different levels.
 
3860
 
 
3861
  To be able to do 'ref_or_null' we merge a comparison of a column
 
3862
  and 'column IS NULL' to one test.  This is useful for sub select queries
 
3863
  that are internally transformed to something like:.
 
3864
 
 
3865
  @code
 
3866
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
 
3867
  @endcode
 
3868
 
 
3869
  KEY_FIELD::null_rejecting is processed as follows: @n
 
3870
  result has null_rejecting=true if it is set for both ORed references.
 
3871
  for example:
 
3872
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
 
3873
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
 
3874
 
 
3875
  @todo
 
3876
    The result of this is that we're missing some 'ref' accesses.
 
3877
    OptimizerTeam: Fix this
 
3878
*/
 
3879
 
 
3880
static KEY_FIELD *
 
3881
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
 
3882
                 uint32_t and_level)
 
3883
{
 
3884
  if (start == new_fields)
 
3885
    return start;                               // Impossible or
 
3886
  if (new_fields == end)
 
3887
    return start;                               // No new fields, skip all
 
3888
 
 
3889
  KEY_FIELD *first_free=new_fields;
 
3890
 
 
3891
  /* Mark all found fields in old array */
 
3892
  for (; new_fields != end ; new_fields++)
 
3893
  {
 
3894
    for (KEY_FIELD *old=start ; old != first_free ; old++)
 
3895
    {
 
3896
      if (old->field == new_fields->field)
 
3897
      {
 
3898
        /*
 
3899
          NOTE: below const_item() call really works as "!used_tables()", i.e.
 
3900
          it can return false where it is feasible to make it return true.
 
3901
 
 
3902
          The cause is as follows: Some of the tables are already known to be
 
3903
          const tables (the detection code is in make_join_statistics(),
 
3904
          above the update_ref_and_keys() call), but we didn't propagate
 
3905
          information about this: Table::const_table is not set to true, and
 
3906
          Item::update_used_tables() hasn't been called for each item.
 
3907
          The result of this is that we're missing some 'ref' accesses.
 
3908
          TODO: OptimizerTeam: Fix this
 
3909
        */
 
3910
        if (!new_fields->val->const_item())
 
3911
        {
 
3912
          /*
 
3913
            If the value matches, we can use the key reference.
 
3914
            If not, we keep it until we have examined all new values
 
3915
          */
 
3916
          if (old->val->eq(new_fields->val, old->field->binary()))
 
3917
          {
 
3918
            old->level= and_level;
 
3919
            old->optimize= ((old->optimize & new_fields->optimize &
 
3920
                             KEY_OPTIMIZE_EXISTS) |
 
3921
                            ((old->optimize | new_fields->optimize) &
 
3922
                             KEY_OPTIMIZE_REF_OR_NULL));
 
3923
            old->null_rejecting= (old->null_rejecting &&
 
3924
                                  new_fields->null_rejecting);
 
3925
          }
 
3926
        }
 
3927
        else if (old->eq_func && new_fields->eq_func &&
 
3928
                 old->val->eq_by_collation(new_fields->val,
 
3929
                                           old->field->binary(),
 
3930
                                           old->field->charset()))
 
3931
 
 
3932
        {
 
3933
          old->level= and_level;
 
3934
          old->optimize= ((old->optimize & new_fields->optimize &
 
3935
                           KEY_OPTIMIZE_EXISTS) |
 
3936
                          ((old->optimize | new_fields->optimize) &
 
3937
                           KEY_OPTIMIZE_REF_OR_NULL));
 
3938
          old->null_rejecting= (old->null_rejecting &&
 
3939
                                new_fields->null_rejecting);
 
3940
        }
 
3941
        else if (old->eq_func && new_fields->eq_func &&
 
3942
                 ((old->val->const_item() && old->val->is_null()) ||
 
3943
                  new_fields->val->is_null()))
 
3944
        {
 
3945
          /* field = expression OR field IS NULL */
 
3946
          old->level= and_level;
 
3947
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
 
3948
          /*
 
3949
            Remember the NOT NULL value unless the value does not depend
 
3950
            on other tables.
 
3951
          */
 
3952
          if (!old->val->used_tables() && old->val->is_null())
 
3953
            old->val= new_fields->val;
 
3954
          /* The referred expression can be NULL: */
 
3955
          old->null_rejecting= 0;
 
3956
        }
 
3957
        else
 
3958
        {
 
3959
          /*
 
3960
            We are comparing two different const.  In this case we can't
 
3961
            use a key-lookup on this so it's better to remove the value
 
3962
            and let the range optimzier handle it
 
3963
          */
 
3964
          if (old == --first_free)              // If last item
 
3965
            break;
 
3966
          *old= *first_free;                    // Remove old value
 
3967
          old--;                                // Retry this value
 
3968
        }
 
3969
      }
 
3970
    }
 
3971
  }
 
3972
  /* Remove all not used items */
 
3973
  for (KEY_FIELD *old=start ; old != first_free ;)
 
3974
  {
 
3975
    if (old->level != and_level)
 
3976
    {                                           // Not used in all levels
 
3977
      if (old == --first_free)
 
3978
        break;
 
3979
      *old= *first_free;                        // Remove old value
 
3980
      continue;
 
3981
    }
 
3982
    old++;
 
3983
  }
 
3984
  return first_free;
 
3985
}
 
3986
 
 
3987
 
 
3988
/**
 
3989
  Add a possible key to array of possible keys if it's usable as a key
 
3990
 
 
3991
    @param key_fields      Pointer to add key, if usable
 
3992
    @param and_level       And level, to be stored in KEY_FIELD
 
3993
    @param cond            Condition predicate
 
3994
    @param field           Field used in comparision
 
3995
    @param eq_func         True if we used =, <=> or IS NULL
 
3996
    @param value           Value used for comparison with field
 
3997
    @param usable_tables   Tables which can be used for key optimization
 
3998
    @param sargables       IN/OUT Array of found sargable candidates
 
3999
 
 
4000
  @note
 
4001
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
 
4002
    table, we store this to be able to do not exists optimization later.
 
4003
 
 
4004
  @returns
 
4005
    *key_fields is incremented if we stored a key in the array
 
4006
*/
 
4007
 
 
4008
static void
 
4009
add_key_field(KEY_FIELD **key_fields,uint32_t and_level, Item_func *cond,
 
4010
              Field *field, bool eq_func, Item **value, uint32_t num_values,
 
4011
              table_map usable_tables, SARGABLE_PARAM **sargables)
 
4012
{
 
4013
  uint32_t exists_optimize= 0;
 
4014
  if (!(field->flags & PART_KEY_FLAG))
 
4015
  {
 
4016
    // Don't remove column IS NULL on a LEFT JOIN table
 
4017
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
4018
        !field->table->maybe_null || field->null_ptr)
 
4019
      return;                                   // Not a key. Skip it
 
4020
    exists_optimize= KEY_OPTIMIZE_EXISTS;
 
4021
    assert(num_values == 1);
 
4022
  }
 
4023
  else
 
4024
  {
 
4025
    table_map used_tables=0;
 
4026
    bool optimizable=0;
 
4027
    for (uint32_t i=0; i<num_values; i++)
 
4028
    {
 
4029
      used_tables|=(value[i])->used_tables();
 
4030
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
 
4031
        optimizable=1;
 
4032
    }
 
4033
    if (!optimizable)
 
4034
      return;
 
4035
    if (!(usable_tables & field->table->map))
 
4036
    {
 
4037
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
4038
          !field->table->maybe_null || field->null_ptr)
 
4039
        return;                                 // Can't use left join optimize
 
4040
      exists_optimize= KEY_OPTIMIZE_EXISTS;
 
4041
    }
 
4042
    else
 
4043
    {
 
4044
      JOIN_TAB *stat=field->table->reginfo.join_tab;
 
4045
      key_map possible_keys=field->key_start;
 
4046
      possible_keys.intersect(field->table->keys_in_use_for_query);
 
4047
      stat[0].keys.merge(possible_keys);             // Add possible keys
 
4048
 
 
4049
      /*
 
4050
        Save the following cases:
 
4051
        Field op constant
 
4052
        Field LIKE constant where constant doesn't start with a wildcard
 
4053
        Field = field2 where field2 is in a different table
 
4054
        Field op formula
 
4055
        Field IS NULL
 
4056
        Field IS NOT NULL
 
4057
         Field BETWEEN ...
 
4058
         Field IN ...
 
4059
      */
 
4060
      stat[0].key_dependent|=used_tables;
 
4061
 
 
4062
      bool is_const=1;
 
4063
      for (uint32_t i=0; i<num_values; i++)
 
4064
      {
 
4065
        if (!(is_const&= value[i]->const_item()))
 
4066
          break;
 
4067
      }
 
4068
      if (is_const)
 
4069
        stat[0].const_keys.merge(possible_keys);
 
4070
      else if (!eq_func)
 
4071
      {
 
4072
        /*
 
4073
          Save info to be able check whether this predicate can be
 
4074
          considered as sargable for range analisis after reading const tables.
 
4075
          We do not save info about equalities as update_const_equal_items
 
4076
          will take care of updating info on keys from sargable equalities.
 
4077
        */
 
4078
        (*sargables)--;
 
4079
        (*sargables)->field= field;
 
4080
        (*sargables)->arg_value= value;
 
4081
        (*sargables)->num_values= num_values;
 
4082
      }
 
4083
      /*
 
4084
        We can't always use indexes when comparing a string index to a
 
4085
        number. cmp_type() is checked to allow compare of dates to numbers.
 
4086
        eq_func is NEVER true when num_values > 1
 
4087
       */
 
4088
      if (!eq_func)
 
4089
      {
 
4090
        /*
 
4091
          Additional optimization: if we're processing
 
4092
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
 
4093
          "t.key = c1".
 
4094
          TODO: This is a very limited fix. A more generic fix is possible.
 
4095
          There are 2 options:
 
4096
          A) Make equality propagation code be able to handle BETWEEN
 
4097
             (including cases like t1.key BETWEEN t2.key AND t3.key)
 
4098
          B) Make range optimizer to infer additional "t.key = c" equalities
 
4099
             and use them in equality propagation process (see details in
 
4100
             OptimizerKBAndTodo)
 
4101
        */
 
4102
        if ((cond->functype() != Item_func::BETWEEN) ||
 
4103
            ((Item_func_between*) cond)->negated ||
 
4104
            !value[0]->eq(value[1], field->binary()))
 
4105
          return;
 
4106
        eq_func= true;
 
4107
      }
 
4108
 
 
4109
      if (field->result_type() == STRING_RESULT)
 
4110
      {
 
4111
        if ((*value)->result_type() != STRING_RESULT)
 
4112
        {
 
4113
          if (field->cmp_type() != (*value)->result_type())
 
4114
            return;
 
4115
        }
 
4116
        else
 
4117
        {
 
4118
          /*
 
4119
            We can't use indexes if the effective collation
 
4120
            of the operation differ from the field collation.
 
4121
          */
 
4122
          if (field->cmp_type() == STRING_RESULT &&
 
4123
              ((Field_str*)field)->charset() != cond->compare_collation())
 
4124
            return;
 
4125
        }
 
4126
      }
 
4127
    }
 
4128
  }
 
4129
  /*
 
4130
    For the moment eq_func is always true. This slot is reserved for future
 
4131
    extensions where we want to remembers other things than just eq comparisons
 
4132
  */
 
4133
  assert(eq_func);
 
4134
  /* Store possible eq field */
 
4135
  (*key_fields)->field=         field;
 
4136
  (*key_fields)->eq_func=       eq_func;
 
4137
  (*key_fields)->val=           *value;
 
4138
  (*key_fields)->level=         and_level;
 
4139
  (*key_fields)->optimize=      exists_optimize;
 
4140
  /*
 
4141
    If the condition has form "tbl.keypart = othertbl.field" and
 
4142
    othertbl.field can be NULL, there will be no matches if othertbl.field
 
4143
    has NULL value.
 
4144
    We use null_rejecting in add_not_null_conds() to add
 
4145
    'othertbl.field IS NOT NULL' to tab->select_cond.
 
4146
  */
 
4147
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
 
4148
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
 
4149
                                  ((*value)->type() == Item::FIELD_ITEM) &&
 
4150
                                  ((Item_field*)*value)->field->maybe_null());
 
4151
  (*key_fields)->cond_guard= NULL;
 
4152
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name &&
 
4153
                              cond->name < subq_sj_cond_name + 64)?
 
4154
                              cond->name - subq_sj_cond_name: UINT_MAX;
 
4155
  (*key_fields)++;
 
4156
}
 
4157
 
 
4158
/**
 
4159
  Add possible keys to array of possible keys originated from a simple
 
4160
  predicate.
 
4161
 
 
4162
    @param  key_fields     Pointer to add key, if usable
 
4163
    @param  and_level      And level, to be stored in KEY_FIELD
 
4164
    @param  cond           Condition predicate
 
4165
    @param  field          Field used in comparision
 
4166
    @param  eq_func        True if we used =, <=> or IS NULL
 
4167
    @param  value          Value used for comparison with field
 
4168
                           Is NULL for BETWEEN and IN
 
4169
    @param  usable_tables  Tables which can be used for key optimization
 
4170
    @param  sargables      IN/OUT Array of found sargable candidates
 
4171
 
 
4172
  @note
 
4173
    If field items f1 and f2 belong to the same multiple equality and
 
4174
    a key is added for f1, the the same key is added for f2.
 
4175
 
 
4176
  @returns
 
4177
    *key_fields is incremented if we stored a key in the array
 
4178
*/
 
4179
 
 
4180
static void
 
4181
add_key_equal_fields(KEY_FIELD **key_fields, uint32_t and_level,
 
4182
                     Item_func *cond, Item_field *field_item,
 
4183
                     bool eq_func, Item **val,
 
4184
                     uint32_t num_values, table_map usable_tables,
 
4185
                     SARGABLE_PARAM **sargables)
 
4186
{
 
4187
  Field *field= field_item->field;
 
4188
  add_key_field(key_fields, and_level, cond, field,
 
4189
                eq_func, val, num_values, usable_tables, sargables);
 
4190
  Item_equal *item_equal= field_item->item_equal;
 
4191
  if (item_equal)
 
4192
  {
 
4193
    /*
 
4194
      Add to the set of possible key values every substitution of
 
4195
      the field for an equal field included into item_equal
 
4196
    */
 
4197
    Item_equal_iterator it(*item_equal);
 
4198
    Item_field *item;
 
4199
    while ((item= it++))
 
4200
    {
 
4201
      if (!field->eq(item->field))
 
4202
      {
 
4203
        add_key_field(key_fields, and_level, cond, item->field,
 
4204
                      eq_func, val, num_values, usable_tables,
 
4205
                      sargables);
 
4206
      }
 
4207
    }
 
4208
  }
 
4209
}
 
4210
 
 
4211
static void
 
4212
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint32_t *and_level,
 
4213
               COND *cond, table_map usable_tables,
 
4214
               SARGABLE_PARAM **sargables)
 
4215
{
 
4216
  if (cond->type() == Item_func::COND_ITEM)
 
4217
  {
 
4218
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
 
4219
    KEY_FIELD *org_key_fields= *key_fields;
 
4220
 
 
4221
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
4222
    {
 
4223
      Item *item;
 
4224
      while ((item=li++))
 
4225
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
4226
                       sargables);
 
4227
      for (; org_key_fields != *key_fields ; org_key_fields++)
 
4228
        org_key_fields->level= *and_level;
 
4229
    }
 
4230
    else
 
4231
    {
 
4232
      (*and_level)++;
 
4233
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
 
4234
                     sargables);
 
4235
      Item *item;
 
4236
      while ((item=li++))
 
4237
      {
 
4238
        KEY_FIELD *start_key_fields= *key_fields;
 
4239
        (*and_level)++;
 
4240
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
4241
                       sargables);
 
4242
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
 
4243
                                     *key_fields,++(*and_level));
 
4244
      }
 
4245
    }
 
4246
    return;
 
4247
  }
 
4248
 
 
4249
  /*
 
4250
    Subquery optimization: Conditions that are pushed down into subqueries
 
4251
    are wrapped into Item_func_trig_cond. We process the wrapped condition
 
4252
    but need to set cond_guard for KEYUSE elements generated from it.
 
4253
  */
 
4254
  {
 
4255
    if (cond->type() == Item::FUNC_ITEM &&
 
4256
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
 
4257
    {
 
4258
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
 
4259
      if (!join->group_list && !join->order &&
 
4260
          join->unit->item &&
 
4261
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
 
4262
          !join->unit->is_union())
 
4263
      {
 
4264
        KEY_FIELD *save= *key_fields;
 
4265
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
 
4266
                       sargables);
 
4267
        // Indicate that this ref access candidate is for subquery lookup:
 
4268
        for (; save != *key_fields; save++)
 
4269
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
 
4270
      }
 
4271
      return;
 
4272
    }
 
4273
  }
 
4274
 
 
4275
  /* If item is of type 'field op field/constant' add it to key_fields */
 
4276
  if (cond->type() != Item::FUNC_ITEM)
 
4277
    return;
 
4278
  Item_func *cond_func= (Item_func*) cond;
 
4279
  switch (cond_func->select_optimize()) {
 
4280
  case Item_func::OPTIMIZE_NONE:
 
4281
    break;
 
4282
  case Item_func::OPTIMIZE_KEY:
 
4283
  {
 
4284
    Item **values;
 
4285
    // BETWEEN, IN, NE
 
4286
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
 
4287
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
4288
    {
 
4289
      values= cond_func->arguments()+1;
 
4290
      if (cond_func->functype() == Item_func::NE_FUNC &&
 
4291
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
4292
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
4293
        values--;
 
4294
      assert(cond_func->functype() != Item_func::IN_FUNC ||
 
4295
                  cond_func->argument_count() != 2);
 
4296
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4297
                           (Item_field*) (cond_func->key_item()->real_item()),
 
4298
                           0, values,
 
4299
                           cond_func->argument_count()-1,
 
4300
                           usable_tables, sargables);
 
4301
    }
 
4302
    if (cond_func->functype() == Item_func::BETWEEN)
 
4303
    {
 
4304
      values= cond_func->arguments();
 
4305
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
4306
      {
 
4307
        Item_field *field_item;
 
4308
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
 
4309
            &&
 
4310
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
 
4311
        {
 
4312
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
 
4313
          add_key_equal_fields(key_fields, *and_level, cond_func,
 
4314
                               field_item, 0, values, 1, usable_tables,
 
4315
                               sargables);
 
4316
        }
 
4317
      }
 
4318
    }
 
4319
    break;
 
4320
  }
 
4321
  case Item_func::OPTIMIZE_OP:
 
4322
  {
 
4323
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
 
4324
                     cond_func->functype() == Item_func::EQUAL_FUNC);
 
4325
 
 
4326
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
4327
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
4328
    {
 
4329
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4330
                        (Item_field*) (cond_func->arguments()[0])->real_item(),
 
4331
                           equal_func,
 
4332
                           cond_func->arguments()+1, 1, usable_tables,
 
4333
                           sargables);
 
4334
    }
 
4335
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
4336
        cond_func->functype() != Item_func::LIKE_FUNC &&
 
4337
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
 
4338
    {
 
4339
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4340
                       (Item_field*) (cond_func->arguments()[1])->real_item(),
 
4341
                           equal_func,
 
4342
                           cond_func->arguments(),1,usable_tables,
 
4343
                           sargables);
 
4344
    }
 
4345
    break;
 
4346
  }
 
4347
  case Item_func::OPTIMIZE_NULL:
 
4348
    /* column_name IS [NOT] NULL */
 
4349
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
4350
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
4351
    {
 
4352
      Item *tmp=new Item_null;
 
4353
      if (unlikely(!tmp))                       // Should never be true
 
4354
        return;
 
4355
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
4356
                    (Item_field*) (cond_func->arguments()[0])->real_item(),
 
4357
                    cond_func->functype() == Item_func::ISNULL_FUNC,
 
4358
                           &tmp, 1, usable_tables, sargables);
 
4359
    }
 
4360
    break;
 
4361
  case Item_func::OPTIMIZE_EQUAL:
 
4362
    Item_equal *item_equal= (Item_equal *) cond;
 
4363
    Item *const_item= item_equal->get_const();
 
4364
    Item_equal_iterator it(*item_equal);
 
4365
    Item_field *item;
 
4366
    if (const_item)
 
4367
    {
 
4368
      /*
 
4369
        For each field field1 from item_equal consider the equality
 
4370
        field1=const_item as a condition allowing an index access of the table
 
4371
        with field1 by the keys value of field1.
 
4372
      */
 
4373
      while ((item= it++))
 
4374
      {
 
4375
        add_key_field(key_fields, *and_level, cond_func, item->field,
 
4376
                      true, &const_item, 1, usable_tables, sargables);
 
4377
      }
 
4378
    }
 
4379
    else
 
4380
    {
 
4381
      /*
 
4382
        Consider all pairs of different fields included into item_equal.
 
4383
        For each of them (field1, field1) consider the equality
 
4384
        field1=field2 as a condition allowing an index access of the table
 
4385
        with field1 by the keys value of field2.
 
4386
      */
 
4387
      Item_equal_iterator fi(*item_equal);
 
4388
      while ((item= fi++))
 
4389
      {
 
4390
        Field *field= item->field;
 
4391
        while ((item= it++))
 
4392
        {
 
4393
          if (!field->eq(item->field))
 
4394
          {
 
4395
            add_key_field(key_fields, *and_level, cond_func, field,
 
4396
                          true, (Item **) &item, 1, usable_tables,
 
4397
                          sargables);
 
4398
          }
 
4399
        }
 
4400
        it.rewind();
 
4401
      }
 
4402
    }
 
4403
    break;
 
4404
  }
 
4405
}
489
4406
 
490
4407
/**
491
4408
  Add all keys with uses 'field' for some keypart.
492
4409
 
493
4410
  If field->and_level != and_level then only mark key_part as const_part.
494
4411
*/
495
 
uint32_t max_part_bit(key_part_map bits)
 
4412
 
 
4413
static uint
 
4414
max_part_bit(key_part_map bits)
496
4415
{
497
4416
  uint32_t found;
498
4417
  for (found=0; bits & 1 ; found++,bits>>=1) ;
499
4418
  return found;
500
4419
}
501
4420
 
502
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b)
 
4421
static void
 
4422
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
 
4423
{
 
4424
  Field *field=key_field->field;
 
4425
  Table *form= field->table;
 
4426
  KEYUSE keyuse;
 
4427
 
 
4428
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
 
4429
  {
 
4430
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
4431
    {
 
4432
      if (!(form->keys_in_use_for_query.is_set(key)))
 
4433
        continue;
 
4434
 
 
4435
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
 
4436
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
4437
      {
 
4438
        if (field->eq(form->key_info[key].key_part[part].field))
 
4439
        {
 
4440
          keyuse.table= field->table;
 
4441
          keyuse.val =  key_field->val;
 
4442
          keyuse.key =  key;
 
4443
          keyuse.keypart=part;
 
4444
          keyuse.keypart_map= (key_part_map) 1 << part;
 
4445
          keyuse.used_tables=key_field->val->used_tables();
 
4446
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
 
4447
          keyuse.null_rejecting= key_field->null_rejecting;
 
4448
          keyuse.cond_guard= key_field->cond_guard;
 
4449
          keyuse.sj_pred_no= key_field->sj_pred_no;
 
4450
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
4451
        }
 
4452
      }
 
4453
    }
 
4454
  }
 
4455
}
 
4456
 
 
4457
static int
 
4458
sort_keyuse(KEYUSE *a,KEYUSE *b)
503
4459
{
504
4460
  int res;
505
 
  if (a->getTable()->tablenr != b->getTable()->tablenr)
506
 
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
507
 
  if (a->getKey() != b->getKey())
508
 
    return static_cast<int>((a->getKey() - b->getKey()));
509
 
  if (a->getKeypart() != b->getKeypart())
510
 
    return static_cast<int>((a->getKeypart() - b->getKeypart()));
 
4461
  if (a->table->tablenr != b->table->tablenr)
 
4462
    return (int) (a->table->tablenr - b->table->tablenr);
 
4463
  if (a->key != b->key)
 
4464
    return (int) (a->key - b->key);
 
4465
  if (a->keypart != b->keypart)
 
4466
    return (int) (a->keypart - b->keypart);
511
4467
  // Place const values before other ones
512
 
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
513
 
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
 
4468
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
 
4469
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
514
4470
    return res;
515
4471
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
516
 
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
517
 
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
 
4472
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
 
4473
                (b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
 
4474
}
 
4475
 
 
4476
 
 
4477
/*
 
4478
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
 
4479
 
 
4480
    This function populates KEY_FIELD array with entries generated from the
 
4481
    ON condition of the given nested join, and does the same for nested joins
 
4482
    contained within this nested join.
 
4483
 
 
4484
  @param[in]      nested_join_table   Nested join pseudo-table to process
 
4485
  @param[in,out]  end                 End of the key field array
 
4486
  @param[in,out]  and_level           And-level
 
4487
  @param[in,out]  sargables           Array of found sargable candidates
 
4488
 
 
4489
 
 
4490
  @note
 
4491
    We can add accesses to the tables that are direct children of this nested
 
4492
    join (1), and are not inner tables w.r.t their neighbours (2).
 
4493
 
 
4494
    Example for #1 (outer brackets pair denotes nested join this function is
 
4495
    invoked for):
 
4496
    @code
 
4497
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
 
4498
    @endcode
 
4499
    Example for #2:
 
4500
    @code
 
4501
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
 
4502
    @endcode
 
4503
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
 
4504
    t1 only.
 
4505
    Example #3:
 
4506
    @code
 
4507
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
 
4508
    @endcode
 
4509
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
 
4510
*/
 
4511
 
 
4512
static void add_key_fields_for_nj(JOIN *join, TableList *nested_join_table,
 
4513
                                  KEY_FIELD **end, uint32_t *and_level,
 
4514
                                  SARGABLE_PARAM **sargables)
 
4515
{
 
4516
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
 
4517
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
 
4518
  bool have_another = false;
 
4519
  table_map tables= 0;
 
4520
  TableList *table;
 
4521
  assert(nested_join_table->nested_join);
 
4522
 
 
4523
  while ((table= li++) || (have_another && (li=li2, have_another=false,
 
4524
                                            (table= li++))))
 
4525
  {
 
4526
    if (table->nested_join)
 
4527
    {
 
4528
      if (!table->on_expr)
 
4529
      {
 
4530
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
 
4531
        have_another= true;
 
4532
        li2= li;
 
4533
        li= List_iterator<TableList>(table->nested_join->join_list);
 
4534
      }
 
4535
      else
 
4536
        add_key_fields_for_nj(join, table, end, and_level, sargables);
 
4537
    }
 
4538
    else
 
4539
      if (!table->on_expr)
 
4540
        tables |= table->table->map;
 
4541
  }
 
4542
  if (nested_join_table->on_expr)
 
4543
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
 
4544
                   sargables);
518
4545
}
519
4546
 
520
4547
 
522
4549
  Update keyuse array with all possible keys we can use to fetch rows.
523
4550
 
524
4551
  @param       session
525
 
  @param[out]  keyuse         Put here ordered array of KeyUse structures
 
4552
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
526
4553
  @param       join_tab       Array in tablenr_order
527
4554
  @param       tables         Number of tables in join
528
4555
  @param       cond           WHERE condition (note that the function analyzes
531
4558
                              for which we can make ref access based the WHERE
532
4559
                              clause)
533
4560
  @param       select_lex     current SELECT
534
 
  @param[out]  sargables      std::vector of found sargable candidates
 
4561
  @param[out]  sargables      Array of found sargable candidates
535
4562
 
536
4563
   @retval
537
4564
     0  OK
538
4565
   @retval
539
4566
     1  Out of memory.
540
4567
*/
541
 
bool update_ref_and_keys(Session *session,
542
 
                         DYNAMIC_ARRAY *keyuse,
543
 
                         JoinTable *join_tab,
544
 
                         uint32_t tables,
545
 
                         COND *cond, 
546
 
                         COND_EQUAL *,
547
 
                         table_map normal_tables,
548
 
                         Select_Lex *select_lex,
549
 
                         vector<optimizer::SargableParam> &sargables)
 
4568
 
 
4569
static bool
 
4570
update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
 
4571
                    uint32_t tables, COND *cond, COND_EQUAL *,
 
4572
                    table_map normal_tables, Select_Lex *select_lex,
 
4573
                    SARGABLE_PARAM **sargables)
550
4574
{
551
 
  uint  and_level,found_eq_constant;
552
 
  optimizer::KeyField *key_fields, *end, *field;
 
4575
  uint  and_level,i,found_eq_constant;
 
4576
  KEY_FIELD *key_fields, *end, *field;
553
4577
  uint32_t sz;
554
 
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
 
4578
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
555
4579
 
556
4580
  /*
557
 
    All predicates that are used to fill arrays of KeyField
558
 
    and SargableParam classes have at most 2 arguments
 
4581
    We use the same piece of memory to store both  KEY_FIELD
 
4582
    and SARGABLE_PARAM structure.
 
4583
    KEY_FIELD values are placed at the beginning this memory
 
4584
    while  SARGABLE_PARAM values are put at the end.
 
4585
    All predicates that are used to fill arrays of KEY_FIELD
 
4586
    and SARGABLE_PARAM structures have at most 2 arguments
559
4587
    except BETWEEN predicates that have 3 arguments and
560
4588
    IN predicates.
561
4589
    This any predicate if it's not BETWEEN/IN can be used
562
 
    directly to fill at most 2 array elements, either of KeyField 
563
 
    or SargableParam type. For a BETWEEN predicate 3 elements
 
4590
    directly to fill at most 2 array elements, either of KEY_FIELD
 
4591
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
564
4592
    can be filled as this predicate is considered as
565
4593
    saragable with respect to each of its argument.
566
4594
    An IN predicate can require at most 1 element as currently
570
4598
    can be not more than select_lex->max_equal_elems such
571
4599
    substitutions.
572
4600
  */
573
 
  sz= sizeof(optimizer::KeyField) *
 
4601
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
574
4602
      (((session->lex->current_select->cond_count+1)*2 +
575
4603
        session->lex->current_select->between_count)*m+1);
576
 
  if (! (key_fields= (optimizer::KeyField*) session->getMemRoot()->allocate(sz)))
577
 
    return true;
 
4604
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
 
4605
    return true; /* purecov: inspected */
578
4606
  and_level= 0;
579
4607
  field= end= key_fields;
 
4608
  *sargables= (SARGABLE_PARAM *) key_fields +
 
4609
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
 
4610
  /* set a barrier for the array of SARGABLE_PARAM */
 
4611
  (*sargables)[0].field= 0;
580
4612
 
581
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
 
4613
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
582
4614
    return true;
583
4615
  if (cond)
584
4616
  {
585
4617
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
586
4618
                   sargables);
587
 
    for (; field != end; field++)
 
4619
    for (; field != end ; field++)
588
4620
    {
589
 
      add_key_part(keyuse, field);
 
4621
      add_key_part(keyuse,field);
590
4622
      /* Mark that we can optimize LEFT JOIN */
591
 
      if (field->getValue()->type() == Item::NULL_ITEM &&
592
 
          ! field->getField()->real_maybe_null())
593
 
      {
594
 
        field->getField()->getTable()->reginfo.not_exists_optimize= 1;
595
 
      }
 
4623
      if (field->val->type() == Item::NULL_ITEM &&
 
4624
          !field->field->real_maybe_null())
 
4625
        field->field->table->reginfo.not_exists_optimize=1;
596
4626
    }
597
4627
  }
598
 
  for (uint32_t i= 0; i < tables; i++)
 
4628
  for (i=0 ; i < tables ; i++)
599
4629
  {
600
4630
    /*
601
4631
      Block the creation of keys for inner tables of outer joins.
618
4648
    TableList *table;
619
4649
    while ((table= li++))
620
4650
    {
621
 
      if (table->getNestedJoin())
 
4651
      if (table->nested_join)
622
4652
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
623
4653
                              sargables);
624
4654
    }
639
4669
  */
640
4670
  if (keyuse->elements)
641
4671
  {
642
 
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
 
4672
    KEYUSE key_end,*prev,*save_pos,*use;
643
4673
 
644
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
645
 
                       (qsort_cmp) sort_keyuse);
 
4674
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
 
4675
          (qsort_cmp) sort_keyuse);
646
4676
 
647
4677
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
648
4678
    insert_dynamic(keyuse,(unsigned char*) &key_end);
649
4679
 
650
 
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
 
4680
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
651
4681
    prev= &key_end;
652
 
    found_eq_constant= 0;
 
4682
    found_eq_constant=0;
 
4683
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
653
4684
    {
654
 
      uint32_t i;
655
 
 
656
 
      for (i= 0; i < keyuse->elements-1; i++, use++)
 
4685
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
 
4686
        use->table->const_key_parts[use->key]|= use->keypart_map;
657
4687
      {
658
 
        if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
659
 
          use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
660
 
        if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
661
 
        {
662
 
          if (prev->getKeypart() + 1 < use->getKeypart() || 
663
 
              ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
664
 
            continue;                           /* remove */
665
 
        }
666
 
        else if (use->getKeypart() != 0)                // First found must be 0
667
 
          continue;
 
4688
        if (use->key == prev->key && use->table == prev->table)
 
4689
        {
 
4690
          if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
 
4691
            continue;                           /* remove */
 
4692
        }
 
4693
        else if (use->keypart != 0)             // First found must be 0
 
4694
          continue;
 
4695
      }
668
4696
 
669
 
#ifdef HAVE_VALGRIND
670
 
        /* Valgrind complains about overlapped memcpy when save_pos==use. */
671
 
        if (save_pos != use)
 
4697
#ifdef HAVE_purify
 
4698
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
 
4699
      if (save_pos != use)
672
4700
#endif
673
 
          *save_pos= *use;
674
 
        prev=use;
675
 
        found_eq_constant= ! use->getUsedTables();
676
 
        /* Save ptr to first use */
677
 
        if (! use->getTable()->reginfo.join_tab->keyuse)
678
 
          use->getTable()->reginfo.join_tab->keyuse= save_pos;
679
 
        use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
680
 
        save_pos++;
681
 
      }
682
 
      i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
683
 
      set_dynamic(keyuse, (unsigned char*) &key_end, i);
684
 
      keyuse->elements= i;
 
4701
        *save_pos= *use;
 
4702
      prev=use;
 
4703
      found_eq_constant= !use->used_tables;
 
4704
      /* Save ptr to first use */
 
4705
      if (!use->table->reginfo.join_tab->keyuse)
 
4706
        use->table->reginfo.join_tab->keyuse=save_pos;
 
4707
      use->table->reginfo.join_tab->checked_keys.set_bit(use->key);
 
4708
      save_pos++;
685
4709
    }
 
4710
    i=(uint32_t) (save_pos-(KEYUSE*) keyuse->buffer);
 
4711
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
4712
    keyuse->elements=i;
686
4713
  }
687
4714
  return false;
688
4715
}
690
4717
/**
691
4718
  Update some values in keyuse for faster choose_plan() loop.
692
4719
*/
693
 
void optimize_keyuse(Join *join, DYNAMIC_ARRAY *keyuse_array)
 
4720
 
 
4721
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
694
4722
{
695
 
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
696
 
                                                  0, 
697
 
                                                  optimizer::KeyUse*);
 
4723
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);
698
4724
 
699
4725
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
700
4726
  {
707
4733
      Constant tables are ignored.
708
4734
      To avoid bad matches, we don't make ref_table_rows less than 100.
709
4735
    */
710
 
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
711
 
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
 
4736
    keyuse->ref_table_rows= ~(ha_rows) 0;       // If no ref
 
4737
    if (keyuse->used_tables &
 
4738
        (map= (keyuse->used_tables & ~join->const_table_map &
 
4739
               ~OUTER_REF_TABLE_BIT)))
712
4740
    {
713
4741
      uint32_t tablenr;
714
4742
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
715
4743
      if (map == 1)                     // Only one table
716
4744
      {
717
 
        Table *tmp_table=join->all_tables[tablenr];
718
 
        keyuse->setTableRows(max(tmp_table->cursor->stats.records, (ha_rows)100));
 
4745
        Table *tmp_table=join->all_tables[tablenr];
 
4746
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
719
4747
      }
720
4748
    }
721
4749
    /*
722
4750
      Outer reference (external field) is constant for single executing
723
4751
      of subquery
724
4752
    */
725
 
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
726
 
      keyuse->setTableRows(1);
 
4753
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
 
4754
      keyuse->ref_table_rows= 1;
727
4755
  }
728
4756
}
729
4757
 
745
4773
  @return
746
4774
    None
747
4775
*/
748
 
void add_group_and_distinct_keys(Join *join, JoinTable *join_tab)
 
4776
 
 
4777
static void
 
4778
add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab)
749
4779
{
750
4780
  List<Item_field> indexed_fields;
751
4781
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
752
 
  Order      *cur_group;
 
4782
  order_st      *cur_group;
753
4783
  Item_field *cur_item;
754
4784
  key_map possible_keys(0);
755
4785
 
776
4806
 
777
4807
  /* Intersect the keys of all group fields. */
778
4808
  cur_item= indexed_fields_it++;
779
 
  possible_keys|= cur_item->field->part_of_key;
 
4809
  possible_keys.merge(cur_item->field->part_of_key);
780
4810
  while ((cur_item= indexed_fields_it++))
781
4811
  {
782
 
    possible_keys&= cur_item->field->part_of_key;
783
 
  }
784
 
 
785
 
  if (possible_keys.any())
786
 
    join_tab->const_keys|= possible_keys;
787
 
}
788
 
 
789
 
/**
790
 
  Compare two JoinTable objects based on the number of accessed records.
791
 
 
792
 
  @param ptr1 pointer to first JoinTable object
793
 
  @param ptr2 pointer to second JoinTable object
 
4812
    possible_keys.intersect(cur_item->field->part_of_key);
 
4813
  }
 
4814
 
 
4815
  if (!possible_keys.is_clear_all())
 
4816
    join_tab->const_keys.merge(possible_keys);
 
4817
}
 
4818
 
 
4819
 
 
4820
/*****************************************************************************
 
4821
  Go through all combinations of not marked tables and find the one
 
4822
  which uses least records
 
4823
*****************************************************************************/
 
4824
 
 
4825
/** Save const tables first as used tables. */
 
4826
 
 
4827
static void
 
4828
set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
 
4829
{
 
4830
  join->positions[idx].table= table;
 
4831
  join->positions[idx].key=key;
 
4832
  join->positions[idx].records_read=1.0;        /* This is a const table */
 
4833
  join->positions[idx].ref_depend_map= 0;
 
4834
 
 
4835
  /* Move the const table as down as possible in best_ref */
 
4836
  JOIN_TAB **pos=join->best_ref+idx+1;
 
4837
  JOIN_TAB *next=join->best_ref[idx];
 
4838
  for (;next != table ; pos++)
 
4839
  {
 
4840
    JOIN_TAB *tmp=pos[0];
 
4841
    pos[0]=next;
 
4842
    next=tmp;
 
4843
  }
 
4844
  join->best_ref[idx]=table;
 
4845
}
 
4846
 
 
4847
 
 
4848
/*
 
4849
  Given a semi-join nest, find out which of the IN-equalities are bound
 
4850
 
 
4851
  SYNOPSIS
 
4852
    get_bound_sj_equalities()
 
4853
      sj_nest           Semi-join nest
 
4854
      remaining_tables  Tables that are not yet bound
 
4855
 
 
4856
  DESCRIPTION
 
4857
    Given a semi-join nest, find out which of the IN-equalities have their
 
4858
    left part expression bound (i.e. the said expression doesn't refer to
 
4859
    any of remaining_tables and can be evaluated).
 
4860
 
 
4861
  RETURN
 
4862
    Bitmap of bound IN-equalities.
 
4863
*/
 
4864
 
 
4865
uint64_t get_bound_sj_equalities(TableList *sj_nest,
 
4866
                                  table_map remaining_tables)
 
4867
{
 
4868
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
 
4869
  Item *item;
 
4870
  uint32_t i= 0;
 
4871
  uint64_t res= 0;
 
4872
  while ((item= li++))
 
4873
  {
 
4874
    /*
 
4875
      Q: should this take into account equality propagation and how?
 
4876
      A: If e->outer_side is an Item_field, walk over the equality
 
4877
         class and see if there is an element that is bound?
 
4878
      (this is an optional feature)
 
4879
    */
 
4880
    if (!(item->used_tables() & remaining_tables))
 
4881
    {
 
4882
      res |= 1UL < i;
 
4883
    }
 
4884
  }
 
4885
  return res;
 
4886
}
 
4887
 
 
4888
 
 
4889
/**
 
4890
  Find the best access path for an extension of a partial execution
 
4891
  plan and add this path to the plan.
 
4892
 
 
4893
  The function finds the best access path to table 's' from the passed
 
4894
  partial plan where an access path is the general term for any means to
 
4895
  access the data in 's'. An access path may use either an index or a scan,
 
4896
  whichever is cheaper. The input partial plan is passed via the array
 
4897
  'join->positions' of length 'idx'. The chosen access method for 's' and its
 
4898
  cost are stored in 'join->positions[idx]'.
 
4899
 
 
4900
  @param join             pointer to the structure providing all context info
 
4901
                          for the query
 
4902
  @param s                the table to be joined by the function
 
4903
  @param session              thread for the connection that submitted the query
 
4904
  @param remaining_tables set of tables not included into the partial plan yet
 
4905
  @param idx              the length of the partial plan
 
4906
  @param record_count     estimate for the number of records returned by the
 
4907
                          partial plan
 
4908
  @param read_time        the cost of the partial plan
 
4909
 
 
4910
  @return
 
4911
    None
 
4912
*/
 
4913
 
 
4914
static void
 
4915
best_access_path(JOIN      *join,
 
4916
                 JOIN_TAB  *s,
 
4917
                 Session       *session,
 
4918
                 table_map remaining_tables,
 
4919
                 uint32_t      idx,
 
4920
                 double    record_count,
 
4921
                 double)
 
4922
{
 
4923
  KEYUSE *best_key=         0;
 
4924
  uint32_t best_max_key_part=   0;
 
4925
  bool found_constraint= 0;
 
4926
  double best=              DBL_MAX;
 
4927
  double best_time=         DBL_MAX;
 
4928
  double records=           DBL_MAX;
 
4929
  table_map best_ref_depends_map= 0;
 
4930
  double tmp;
 
4931
  ha_rows rec;
 
4932
  uint32_t best_is_sj_inside_out=    0;
 
4933
 
 
4934
  if (s->keyuse)
 
4935
  {                                            /* Use key if possible */
 
4936
    Table *table= s->table;
 
4937
    KEYUSE *keyuse,*start_key=0;
 
4938
    double best_records= DBL_MAX;
 
4939
    uint32_t max_key_part=0;
 
4940
    uint64_t bound_sj_equalities= 0;
 
4941
    bool try_sj_inside_out= false;
 
4942
    /*
 
4943
      Discover the bound equalites. We need to do this, if
 
4944
        1. The next table is an SJ-inner table, and
 
4945
        2. It is the first table from that semijoin, and
 
4946
        3. We're not within a semi-join range (i.e. all semi-joins either have
 
4947
           all or none of their tables in join_table_map), except
 
4948
           s->emb_sj_nest (which we've just entered).
 
4949
        3. All correlation references from this sj-nest are bound
 
4950
    */
 
4951
    if (s->emb_sj_nest &&                                                 // (1)
 
4952
        s->emb_sj_nest->sj_in_exprs < 64 &&
 
4953
        ((remaining_tables & s->emb_sj_nest->sj_inner_tables) ==           // (2)
 
4954
         s->emb_sj_nest->sj_inner_tables) &&                               // (2)
 
4955
        join->cur_emb_sj_nests == s->emb_sj_nest->sj_inner_tables &&       // (3)
 
4956
        !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables)) // (4)
 
4957
    {
 
4958
      /* This table is an InsideOut scan candidate */
 
4959
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest,
 
4960
                                                   remaining_tables);
 
4961
      try_sj_inside_out= true;
 
4962
    }
 
4963
 
 
4964
    /* Test how we can use keys */
 
4965
    rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE;  // Assumed records/key
 
4966
    for (keyuse=s->keyuse ; keyuse->table == table ;)
 
4967
    {
 
4968
      key_part_map found_part= 0;
 
4969
      table_map found_ref= 0;
 
4970
      uint32_t key= keyuse->key;
 
4971
      KEY *keyinfo= table->key_info+key;
 
4972
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
 
4973
      key_part_map const_part= 0;
 
4974
      /* The or-null keypart in ref-or-null access: */
 
4975
      key_part_map ref_or_null_part= 0;
 
4976
 
 
4977
      /* Calculate how many key segments of the current key we can use */
 
4978
      start_key= keyuse;
 
4979
      uint64_t handled_sj_equalities=0;
 
4980
      key_part_map sj_insideout_map= 0;
 
4981
 
 
4982
      do /* For each keypart */
 
4983
      {
 
4984
        uint32_t keypart= keyuse->keypart;
 
4985
        table_map best_part_found_ref= 0;
 
4986
        double best_prev_record_reads= DBL_MAX;
 
4987
 
 
4988
        do /* For each way to access the keypart */
 
4989
        {
 
4990
 
 
4991
          /*
 
4992
            if 1. expression doesn't refer to forward tables
 
4993
               2. we won't get two ref-or-null's
 
4994
          */
 
4995
          if (!(remaining_tables & keyuse->used_tables) &&
 
4996
              !(ref_or_null_part && (keyuse->optimize &
 
4997
                                     KEY_OPTIMIZE_REF_OR_NULL)))
 
4998
          {
 
4999
            found_part|= keyuse->keypart_map;
 
5000
            if (!(keyuse->used_tables & ~join->const_table_map))
 
5001
              const_part|= keyuse->keypart_map;
 
5002
 
 
5003
            double tmp2= prev_record_reads(join, idx, (found_ref |
 
5004
                                                      keyuse->used_tables));
 
5005
            if (tmp2 < best_prev_record_reads)
 
5006
            {
 
5007
              best_part_found_ref= keyuse->used_tables & ~join->const_table_map;
 
5008
              best_prev_record_reads= tmp2;
 
5009
            }
 
5010
            if (rec > keyuse->ref_table_rows)
 
5011
              rec= keyuse->ref_table_rows;
 
5012
            /*
 
5013
              If there is one 'key_column IS NULL' expression, we can
 
5014
              use this ref_or_null optimisation of this field
 
5015
            */
 
5016
            if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)
 
5017
              ref_or_null_part |= keyuse->keypart_map;
 
5018
          }
 
5019
 
 
5020
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
 
5021
          {
 
5022
            if (!(remaining_tables & keyuse->used_tables))
 
5023
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5024
            else
 
5025
            {
 
5026
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5027
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
 
5028
            }
 
5029
          }
 
5030
 
 
5031
          keyuse++;
 
5032
        } while (keyuse->table == table && keyuse->key == key &&
 
5033
                 keyuse->keypart == keypart);
 
5034
        found_ref|= best_part_found_ref;
 
5035
      } while (keyuse->table == table && keyuse->key == key);
 
5036
 
 
5037
      /*
 
5038
        Assume that that each key matches a proportional part of table.
 
5039
      */
 
5040
      if (!found_part && !handled_sj_equalities)
 
5041
        continue;                               // Nothing usable found
 
5042
 
 
5043
      if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
 
5044
        rec= MATCHING_ROWS_IN_OTHER_TABLE;      // Fix for small tables
 
5045
 
 
5046
      bool sj_inside_out_scan= false;
 
5047
      {
 
5048
        found_constraint= 1;
 
5049
        /*
 
5050
          Check if InsideOut scan is applicable:
 
5051
          1. All IN-equalities are either "bound" or "handled"
 
5052
          2. Index keyparts are
 
5053
             ...
 
5054
        */
 
5055
        if (try_sj_inside_out &&
 
5056
            table->covering_keys.is_set(key) &&
 
5057
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
 
5058
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
 
5059
        {
 
5060
          uint32_t n_fixed_parts= max_part_bit(found_part);
 
5061
          if (n_fixed_parts != keyinfo->key_parts &&
 
5062
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
 
5063
               PREV_BITS(uint, keyinfo->key_parts))
 
5064
          {
 
5065
            /*
 
5066
              Not all parts are fixed. Produce bitmap of remaining bits and
 
5067
              check if all of them are covered.
 
5068
            */
 
5069
            sj_inside_out_scan= true;
 
5070
            if (!n_fixed_parts)
 
5071
            {
 
5072
              /*
 
5073
                It's a confluent ref scan.
 
5074
 
 
5075
                That is, all found KEYUSE elements refer to IN-equalities,
 
5076
                and there is really no ref access because there is no
 
5077
                  t.keypart0 = {bound expression}
 
5078
 
 
5079
                Calculate the cost of complete loose index scan.
 
5080
              */
 
5081
              records= (double)s->table->file->stats.records;
 
5082
 
 
5083
              /* The cost is entire index scan cost (divided by 2) */
 
5084
              best_time= s->table->file->index_only_read_time(key, records);
 
5085
 
 
5086
              /* Now figure how many different keys we will get */
 
5087
              ulong rpc;
 
5088
              if ((rpc= keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5089
                records= records / rpc;
 
5090
              start_key= NULL;
 
5091
            }
 
5092
          }
 
5093
        }
 
5094
 
 
5095
        /*
 
5096
          Check if we found full key
 
5097
        */
 
5098
        if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
 
5099
            !ref_or_null_part)
 
5100
        {                                         /* use eq key */
 
5101
          max_key_part= UINT32_MAX;
 
5102
          if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)
 
5103
          {
 
5104
            tmp = prev_record_reads(join, idx, found_ref);
 
5105
            records=1.0;
 
5106
          }
 
5107
          else
 
5108
          {
 
5109
            if (!found_ref)
 
5110
            {                                     /* We found a const key */
 
5111
              /*
 
5112
                ReuseRangeEstimateForRef-1:
 
5113
                We get here if we've found a ref(const) (c_i are constants):
 
5114
                  "(keypart1=c1) AND ... AND (keypartN=cN)"   [ref_const_cond]
 
5115
 
 
5116
                If range optimizer was able to construct a "range"
 
5117
                access on this index, then its condition "quick_cond" was
 
5118
                eqivalent to ref_const_cond (*), and we can re-use E(#rows)
 
5119
                from the range optimizer.
 
5120
 
 
5121
                Proof of (*): By properties of range and ref optimizers
 
5122
                quick_cond will be equal or tighther than ref_const_cond.
 
5123
                ref_const_cond already covers "smallest" possible interval -
 
5124
                a singlepoint interval over all keyparts. Therefore,
 
5125
                quick_cond is equivalent to ref_const_cond (if it was an
 
5126
                empty interval we wouldn't have got here).
 
5127
              */
 
5128
              if (table->quick_keys.is_set(key))
 
5129
                records= (double) table->quick_rows[key];
 
5130
              else
 
5131
              {
 
5132
                /* quick_range couldn't use key! */
 
5133
                records= (double) s->records/rec;
 
5134
              }
 
5135
            }
 
5136
            else
 
5137
            {
 
5138
              if (!(records=keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5139
              {                                   /* Prefer longer keys */
 
5140
                records=
 
5141
                  ((double) s->records / (double) rec *
 
5142
                   (1.0 +
 
5143
                    ((double) (table->s->max_key_length-keyinfo->key_length) /
 
5144
                     (double) table->s->max_key_length)));
 
5145
                if (records < 2.0)
 
5146
                  records=2.0;               /* Can't be as good as a unique */
 
5147
              }
 
5148
              /*
 
5149
                ReuseRangeEstimateForRef-2:  We get here if we could not reuse
 
5150
                E(#rows) from range optimizer. Make another try:
 
5151
 
 
5152
                If range optimizer produced E(#rows) for a prefix of the ref
 
5153
                access we're considering, and that E(#rows) is lower then our
 
5154
                current estimate, make an adjustment. The criteria of when we
 
5155
                can make an adjustment is a special case of the criteria used
 
5156
                in ReuseRangeEstimateForRef-3.
 
5157
              */
 
5158
              if (table->quick_keys.is_set(key) &&
 
5159
                  const_part & (1 << table->quick_key_parts[key]) &&
 
5160
                  table->quick_n_ranges[key] == 1 &&
 
5161
                  records > (double) table->quick_rows[key])
 
5162
              {
 
5163
                records= (double) table->quick_rows[key];
 
5164
              }
 
5165
            }
 
5166
            /* Limit the number of matched rows */
 
5167
            tmp= records;
 
5168
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5169
            if (table->covering_keys.is_set(key))
 
5170
            {
 
5171
              /* we can use only index tree */
 
5172
              tmp= record_count * table->file->index_only_read_time(key, tmp);
 
5173
            }
 
5174
            else
 
5175
              tmp= record_count*cmin(tmp,s->worst_seeks);
 
5176
          }
 
5177
        }
 
5178
        else
 
5179
        {
 
5180
          /*
 
5181
            Use as much key-parts as possible and a uniq key is better
 
5182
            than a not unique key
 
5183
            Set tmp to (previous record count) * (records / combination)
 
5184
          */
 
5185
          if ((found_part & 1) &&
 
5186
              (!(table->file->index_flags(key, 0, 0) & HA_ONLY_WHOLE_INDEX) ||
 
5187
               found_part == PREV_BITS(uint,keyinfo->key_parts)))
 
5188
          {
 
5189
            max_key_part= max_part_bit(found_part);
 
5190
            /*
 
5191
              ReuseRangeEstimateForRef-3:
 
5192
              We're now considering a ref[or_null] access via
 
5193
              (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR
 
5194
              (same-as-above but with one cond replaced
 
5195
               with "t.keypart_i IS NULL")]  (**)
 
5196
 
 
5197
              Try re-using E(#rows) from "range" optimizer:
 
5198
              We can do so if "range" optimizer used the same intervals as
 
5199
              in (**). The intervals used by range optimizer may be not
 
5200
              available at this point (as "range" access might have choosen to
 
5201
              create quick select over another index), so we can't compare
 
5202
              them to (**). We'll make indirect judgements instead.
 
5203
              The sufficient conditions for re-use are:
 
5204
              (C1) All e_i in (**) are constants, i.e. found_ref==false. (if
 
5205
                   this is not satisfied we have no way to know which ranges
 
5206
                   will be actually scanned by 'ref' until we execute the
 
5207
                   join)
 
5208
              (C2) max #key parts in 'range' access == K == max_key_part (this
 
5209
                   is apparently a necessary requirement)
 
5210
 
 
5211
              We also have a property that "range optimizer produces equal or
 
5212
              tighter set of scan intervals than ref(const) optimizer". Each
 
5213
              of the intervals in (**) are "tightest possible" intervals when
 
5214
              one limits itself to using keyparts 1..K (which we do in #2).
 
5215
              From here it follows that range access used either one, or
 
5216
              both of the (I1) and (I2) intervals:
 
5217
 
 
5218
               (t.keypart1=c1 AND ... AND t.keypartK=eK)  (I1)
 
5219
               (same-as-above but with one cond replaced
 
5220
                with "t.keypart_i IS NULL")               (I2)
 
5221
 
 
5222
              The remaining part is to exclude the situation where range
 
5223
              optimizer used one interval while we're considering
 
5224
              ref-or-null and looking for estimate for two intervals. This
 
5225
              is done by last limitation:
 
5226
 
 
5227
              (C3) "range optimizer used (have ref_or_null?2:1) intervals"
 
5228
            */
 
5229
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
 
5230
                table->quick_key_parts[key] == max_key_part &&          //(C2)
 
5231
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
 
5232
            {
 
5233
              tmp= records= (double) table->quick_rows[key];
 
5234
            }
 
5235
            else
 
5236
            {
 
5237
              /* Check if we have statistic about the distribution */
 
5238
              if ((records= keyinfo->rec_per_key[max_key_part-1]))
 
5239
              {
 
5240
                /*
 
5241
                  Fix for the case where the index statistics is too
 
5242
                  optimistic: If
 
5243
                  (1) We're considering ref(const) and there is quick select
 
5244
                      on the same index,
 
5245
                  (2) and that quick select uses more keyparts (i.e. it will
 
5246
                      scan equal/smaller interval then this ref(const))
 
5247
                  (3) and E(#rows) for quick select is higher then our
 
5248
                      estimate,
 
5249
                  Then
 
5250
                    We'll use E(#rows) from quick select.
 
5251
 
 
5252
                  Q: Why do we choose to use 'ref'? Won't quick select be
 
5253
                  cheaper in some cases ?
 
5254
                  TODO: figure this out and adjust the plan choice if needed.
 
5255
                */
 
5256
                if (!found_ref && table->quick_keys.is_set(key) &&    // (1)
 
5257
                    table->quick_key_parts[key] > max_key_part &&     // (2)
 
5258
                    records < (double)table->quick_rows[key])         // (3)
 
5259
                  records= (double)table->quick_rows[key];
 
5260
 
 
5261
                tmp= records;
 
5262
              }
 
5263
              else
 
5264
              {
 
5265
                /*
 
5266
                  Assume that the first key part matches 1% of the file
 
5267
                  and that the whole key matches 10 (duplicates) or 1
 
5268
                  (unique) records.
 
5269
                  Assume also that more key matches proportionally more
 
5270
                  records
 
5271
                  This gives the formula:
 
5272
                  records = (x * (b-a) + a*c-b)/(c-1)
 
5273
 
 
5274
                  b = records matched by whole key
 
5275
                  a = records matched by first key part (1% of all records?)
 
5276
                  c = number of key parts in key
 
5277
                  x = used key parts (1 <= x <= c)
 
5278
                */
 
5279
                double rec_per_key;
 
5280
                if (!(rec_per_key=(double)
 
5281
                      keyinfo->rec_per_key[keyinfo->key_parts-1]))
 
5282
                  rec_per_key=(double) s->records/rec+1;
 
5283
 
 
5284
                if (!s->records)
 
5285
                  tmp = 0;
 
5286
                else if (rec_per_key/(double) s->records >= 0.01)
 
5287
                  tmp = rec_per_key;
 
5288
                else
 
5289
                {
 
5290
                  double a=s->records*0.01;
 
5291
                  if (keyinfo->key_parts > 1)
 
5292
                    tmp= (max_key_part * (rec_per_key - a) +
 
5293
                          a*keyinfo->key_parts - rec_per_key)/
 
5294
                         (keyinfo->key_parts-1);
 
5295
                  else
 
5296
                    tmp= a;
 
5297
                  set_if_bigger(tmp,1.0);
 
5298
                }
 
5299
                records = (uint32_t) tmp;
 
5300
              }
 
5301
 
 
5302
              if (ref_or_null_part)
 
5303
              {
 
5304
                /* We need to do two key searches to find key */
 
5305
                tmp *= 2.0;
 
5306
                records *= 2.0;
 
5307
              }
 
5308
 
 
5309
              /*
 
5310
                ReuseRangeEstimateForRef-4:  We get here if we could not reuse
 
5311
                E(#rows) from range optimizer. Make another try:
 
5312
 
 
5313
                If range optimizer produced E(#rows) for a prefix of the ref
 
5314
                access we're considering, and that E(#rows) is lower then our
 
5315
                current estimate, make the adjustment.
 
5316
 
 
5317
                The decision whether we can re-use the estimate from the range
 
5318
                optimizer is the same as in ReuseRangeEstimateForRef-3,
 
5319
                applied to first table->quick_key_parts[key] key parts.
 
5320
              */
 
5321
              if (table->quick_keys.is_set(key) &&
 
5322
                  table->quick_key_parts[key] <= max_key_part &&
 
5323
                  const_part & (1 << table->quick_key_parts[key]) &&
 
5324
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
 
5325
                                                     const_part) ? 1 : 0) &&
 
5326
                  records > (double) table->quick_rows[key])
 
5327
              {
 
5328
                tmp= records= (double) table->quick_rows[key];
 
5329
              }
 
5330
            }
 
5331
 
 
5332
            /* Limit the number of matched rows */
 
5333
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5334
            if (table->covering_keys.is_set(key))
 
5335
            {
 
5336
              /* we can use only index tree */
 
5337
              tmp= record_count * table->file->index_only_read_time(key, tmp);
 
5338
            }
 
5339
            else
 
5340
              tmp= record_count * cmin(tmp,s->worst_seeks);
 
5341
          }
 
5342
          else
 
5343
            tmp= best_time;                    // Do nothing
 
5344
        }
 
5345
 
 
5346
        if (sj_inside_out_scan && !start_key)
 
5347
        {
 
5348
          tmp= tmp/2;
 
5349
          if (records)
 
5350
            records= records/2;
 
5351
        }
 
5352
 
 
5353
      }
 
5354
      if (tmp < best_time - records/(double) TIME_FOR_COMPARE)
 
5355
      {
 
5356
        best_time= tmp + records/(double) TIME_FOR_COMPARE;
 
5357
        best= tmp;
 
5358
        best_records= records;
 
5359
        best_key= start_key;
 
5360
        best_max_key_part= max_key_part;
 
5361
        best_ref_depends_map= found_ref;
 
5362
        best_is_sj_inside_out= sj_inside_out_scan;
 
5363
      }
 
5364
    }
 
5365
    records= best_records;
 
5366
  }
 
5367
 
 
5368
  /*
 
5369
    Don't test table scan if it can't be better.
 
5370
    Prefer key lookup if we would use the same key for scanning.
 
5371
 
 
5372
    Don't do a table scan on InnoDB tables, if we can read the used
 
5373
    parts of the row from any of the used index.
 
5374
    This is because table scans uses index and we would not win
 
5375
    anything by using a table scan.
 
5376
 
 
5377
    A word for word translation of the below if-statement in sergefp's
 
5378
    understanding: we check if we should use table scan if:
 
5379
    (1) The found 'ref' access produces more records than a table scan
 
5380
        (or index scan, or quick select), or 'ref' is more expensive than
 
5381
        any of them.
 
5382
    (2) This doesn't hold: the best way to perform table scan is to to perform
 
5383
        'range' access using index IDX, and the best way to perform 'ref'
 
5384
        access is to use the same index IDX, with the same or more key parts.
 
5385
        (note: it is not clear how this rule is/should be extended to
 
5386
        index_merge quick selects)
 
5387
    (3) See above note about InnoDB.
 
5388
    (4) NOT ("FORCE INDEX(...)" is used for table and there is 'ref' access
 
5389
             path, but there is no quick select)
 
5390
        If the condition in the above brackets holds, then the only possible
 
5391
        "table scan" access method is ALL/index (there is no quick select).
 
5392
        Since we have a 'ref' access path, and FORCE INDEX instructs us to
 
5393
        choose it over ALL/index, there is no need to consider a full table
 
5394
        scan.
 
5395
  */
 
5396
  if ((records >= s->found_records || best > s->read_time) &&            // (1)
 
5397
      !(s->quick && best_key && s->quick->index == best_key->key &&      // (2)
 
5398
        best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2)
 
5399
      !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) &&   // (3)
 
5400
        ! s->table->covering_keys.is_clear_all() && best_key && !s->quick) &&// (3)
 
5401
      !(s->table->force_index && best_key && !s->quick))                 // (4)
 
5402
  {                                             // Check full join
 
5403
    ha_rows rnd_records= s->found_records;
 
5404
    /*
 
5405
      If there is a filtering condition on the table (i.e. ref analyzer found
 
5406
      at least one "table.keyXpartY= exprZ", where exprZ refers only to tables
 
5407
      preceding this table in the join order we're now considering), then
 
5408
      assume that 25% of the rows will be filtered out by this condition.
 
5409
 
 
5410
      This heuristic is supposed to force tables used in exprZ to be before
 
5411
      this table in join order.
 
5412
    */
 
5413
    if (found_constraint)
 
5414
      rnd_records-= rnd_records/4;
 
5415
 
 
5416
    /*
 
5417
      If applicable, get a more accurate estimate. Don't use the two
 
5418
      heuristics at once.
 
5419
    */
 
5420
    if (s->table->quick_condition_rows != s->found_records)
 
5421
      rnd_records= s->table->quick_condition_rows;
 
5422
 
 
5423
    /*
 
5424
      Range optimizer never proposes a RANGE if it isn't better
 
5425
      than FULL: so if RANGE is present, it's always preferred to FULL.
 
5426
      Here we estimate its cost.
 
5427
    */
 
5428
    if (s->quick)
 
5429
    {
 
5430
      /*
 
5431
        For each record we:
 
5432
        - read record range through 'quick'
 
5433
        - skip rows which does not satisfy WHERE constraints
 
5434
        TODO:
 
5435
        We take into account possible use of join cache for ALL/index
 
5436
        access (see first else-branch below), but we don't take it into
 
5437
        account here for range/index_merge access. Find out why this is so.
 
5438
      */
 
5439
      tmp= record_count *
 
5440
        (s->quick->read_time +
 
5441
         (s->found_records - rnd_records)/(double) TIME_FOR_COMPARE);
 
5442
    }
 
5443
    else
 
5444
    {
 
5445
      /* Estimate cost of reading table. */
 
5446
      tmp= s->table->file->scan_time();
 
5447
      if (s->table->map & join->outer_join)     // Can't use join cache
 
5448
      {
 
5449
        /*
 
5450
          For each record we have to:
 
5451
          - read the whole table record
 
5452
          - skip rows which does not satisfy join condition
 
5453
        */
 
5454
        tmp= record_count *
 
5455
          (tmp +
 
5456
           (s->records - rnd_records)/(double) TIME_FOR_COMPARE);
 
5457
      }
 
5458
      else
 
5459
      {
 
5460
        /* We read the table as many times as join buffer becomes full. */
 
5461
        tmp*= (1.0 + floor((double) cache_record_length(join,idx) *
 
5462
                           record_count /
 
5463
                           (double) session->variables.join_buff_size));
 
5464
        /*
 
5465
            We don't make full cartesian product between rows in the scanned
 
5466
           table and existing records because we skip all rows from the
 
5467
           scanned table, which does not satisfy join condition when
 
5468
           we read the table (see flush_cached_records for details). Here we
 
5469
           take into account cost to read and skip these records.
 
5470
        */
 
5471
        tmp+= (s->records - rnd_records)/(double) TIME_FOR_COMPARE;
 
5472
      }
 
5473
    }
 
5474
 
 
5475
    /*
 
5476
      We estimate the cost of evaluating WHERE clause for found records
 
5477
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
 
5478
      tmp give us total cost of using Table SCAN
 
5479
    */
 
5480
    if (best == DBL_MAX ||
 
5481
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
 
5482
         best + record_count/(double) TIME_FOR_COMPARE*records))
 
5483
    {
 
5484
      /*
 
5485
        If the table has a range (s->quick is set) make_join_select()
 
5486
        will ensure that this will be used
 
5487
      */
 
5488
      best= tmp;
 
5489
      records= rows2double(rnd_records);
 
5490
      best_key= 0;
 
5491
      /* range/index_merge/ALL/index access method are "independent", so: */
 
5492
      best_ref_depends_map= 0;
 
5493
      best_is_sj_inside_out= false;
 
5494
    }
 
5495
  }
 
5496
 
 
5497
  /* Update the cost information for the current partial plan */
 
5498
  join->positions[idx].records_read= records;
 
5499
  join->positions[idx].read_time=    best;
 
5500
  join->positions[idx].key=          best_key;
 
5501
  join->positions[idx].table=        s;
 
5502
  join->positions[idx].ref_depend_map= best_ref_depends_map;
 
5503
  join->positions[idx].use_insideout_scan= best_is_sj_inside_out;
 
5504
 
 
5505
  if (!best_key &&
 
5506
      idx == join->const_tables &&
 
5507
      s->table == join->sort_by_table &&
 
5508
      join->unit->select_limit_cnt >= records)
 
5509
    join->sort_by_table= (Table*) 1;  // Must use temporary table
 
5510
 
 
5511
  return;
 
5512
}
 
5513
 
 
5514
 
 
5515
/**
 
5516
  Selects and invokes a search strategy for an optimal query plan.
 
5517
 
 
5518
  The function checks user-configurable parameters that control the search
 
5519
  strategy for an optimal plan, selects the search method and then invokes
 
5520
  it. Each specific optimization procedure stores the final optimal plan in
 
5521
  the array 'join->best_positions', and the cost of the plan in
 
5522
  'join->best_read'.
 
5523
 
 
5524
  @param join         pointer to the structure providing all context info for
 
5525
                      the query
 
5526
  @param join_tables  set of the tables in the query
 
5527
 
 
5528
  @todo
 
5529
    'MAX_TABLES+2' denotes the old implementation of find_best before
 
5530
    the greedy version. Will be removed when greedy_search is approved.
 
5531
 
 
5532
  @retval
 
5533
    false       ok
 
5534
  @retval
 
5535
    true        Fatal error
 
5536
*/
 
5537
 
 
5538
static bool
 
5539
choose_plan(JOIN *join, table_map join_tables)
 
5540
{
 
5541
  uint32_t search_depth= join->session->variables.optimizer_search_depth;
 
5542
  uint32_t prune_level=  join->session->variables.optimizer_prune_level;
 
5543
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
 
5544
 
 
5545
  join->cur_embedding_map= 0;
 
5546
  reset_nj_counters(join->join_list);
 
5547
  /*
 
5548
    if (SELECT_STRAIGHT_JOIN option is set)
 
5549
      reorder tables so dependent tables come after tables they depend
 
5550
      on, otherwise keep tables in the order they were specified in the query
 
5551
    else
 
5552
      Apply heuristic: pre-sort all access plans with respect to the number of
 
5553
      records accessed.
 
5554
  */
 
5555
  my_qsort(join->best_ref + join->const_tables,
 
5556
           join->tables - join->const_tables, sizeof(JOIN_TAB*),
 
5557
           straight_join ? join_tab_cmp_straight : join_tab_cmp);
 
5558
  join->cur_emb_sj_nests= 0;
 
5559
  if (straight_join)
 
5560
  {
 
5561
    optimize_straight_join(join, join_tables);
 
5562
  }
 
5563
  else
 
5564
  {
 
5565
    if (search_depth == MAX_TABLES+2)
 
5566
    { /*
 
5567
        TODO: 'MAX_TABLES+2' denotes the old implementation of find_best before
 
5568
        the greedy version. Will be removed when greedy_search is approved.
 
5569
      */
 
5570
      join->best_read= DBL_MAX;
 
5571
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
 
5572
        return(true);
 
5573
    }
 
5574
    else
 
5575
    {
 
5576
      if (search_depth == 0)
 
5577
        /* Automatically determine a reasonable value for 'search_depth' */
 
5578
        search_depth= determine_search_depth(join);
 
5579
      if (greedy_search(join, join_tables, search_depth, prune_level))
 
5580
        return(true);
 
5581
    }
 
5582
  }
 
5583
 
 
5584
  /*
 
5585
    Store the cost of this query into a user variable
 
5586
    Don't update last_query_cost for statements that are not "flat joins" :
 
5587
    i.e. they have subqueries, unions or call stored procedures.
 
5588
    TODO: calculate a correct cost for a query with subqueries and UNIONs.
 
5589
  */
 
5590
  if (join->session->lex->is_single_level_stmt())
 
5591
    join->session->status_var.last_query_cost= join->best_read;
 
5592
  return(false);
 
5593
}
 
5594
 
 
5595
 
 
5596
/**
 
5597
  Compare two JOIN_TAB objects based on the number of accessed records.
 
5598
 
 
5599
  @param ptr1 pointer to first JOIN_TAB object
 
5600
  @param ptr2 pointer to second JOIN_TAB object
794
5601
 
795
5602
  NOTES
796
5603
    The order relation implemented by join_tab_cmp() is not transitive,
810
5617
  @retval
811
5618
    0  if equal
812
5619
*/
 
5620
 
813
5621
int join_tab_cmp(const void* ptr1, const void* ptr2)
814
5622
{
815
 
  JoinTable *jt1= *(JoinTable**) ptr1;
816
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
5623
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
5624
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
817
5625
 
818
5626
  if (jt1->dependent & jt2->table->map)
819
5627
    return 1;
826
5634
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
827
5635
}
828
5636
 
 
5637
 
829
5638
/**
830
5639
  Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN.
831
5640
*/
 
5641
 
832
5642
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
833
5643
{
834
 
  JoinTable *jt1= *(JoinTable**) ptr1;
835
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
5644
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
5645
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
836
5646
 
837
5647
  if (jt1->dependent & jt2->table->map)
838
5648
    return 1;
842
5652
}
843
5653
 
844
5654
/**
 
5655
  Heuristic procedure to automatically guess a reasonable degree of
 
5656
  exhaustiveness for the greedy search procedure.
 
5657
 
 
5658
  The procedure estimates the optimization time and selects a search depth
 
5659
  big enough to result in a near-optimal QEP, that doesn't take too long to
 
5660
  find. If the number of tables in the query exceeds some constant, then
 
5661
  search_depth is set to this constant.
 
5662
 
 
5663
  @param join   pointer to the structure providing all context info for
 
5664
                the query
 
5665
 
 
5666
  @note
 
5667
    This is an extremely simplistic implementation that serves as a stub for a
 
5668
    more advanced analysis of the join. Ideally the search depth should be
 
5669
    determined by learning from previous query optimizations, because it will
 
5670
    depend on the CPU power (and other factors).
 
5671
 
 
5672
  @todo
 
5673
    this value should be determined dynamically, based on statistics:
 
5674
    uint32_t max_tables_for_exhaustive_opt= 7;
 
5675
 
 
5676
  @todo
 
5677
    this value could be determined by some mapping of the form:
 
5678
    depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE]
 
5679
 
 
5680
  @return
 
5681
    A positive integer that specifies the search depth (and thus the
 
5682
    exhaustiveness) of the depth-first search algorithm used by
 
5683
    'greedy_search'.
 
5684
*/
 
5685
 
 
5686
static uint
 
5687
determine_search_depth(JOIN *join)
 
5688
{
 
5689
  uint32_t table_count=  join->tables - join->const_tables;
 
5690
  uint32_t search_depth;
 
5691
  /* TODO: this value should be determined dynamically, based on statistics: */
 
5692
  uint32_t max_tables_for_exhaustive_opt= 7;
 
5693
 
 
5694
  if (table_count <= max_tables_for_exhaustive_opt)
 
5695
    search_depth= table_count+1; // use exhaustive for small number of tables
 
5696
  else
 
5697
    /*
 
5698
      TODO: this value could be determined by some mapping of the form:
 
5699
      depth : table_count -> [max_tables_for_exhaustive_opt..MAX_EXHAUSTIVE]
 
5700
    */
 
5701
    search_depth= max_tables_for_exhaustive_opt; // use greedy search
 
5702
 
 
5703
  return search_depth;
 
5704
}
 
5705
 
 
5706
 
 
5707
/**
 
5708
  Select the best ways to access the tables in a query without reordering them.
 
5709
 
 
5710
    Find the best access paths for each query table and compute their costs
 
5711
    according to their order in the array 'join->best_ref' (thus without
 
5712
    reordering the join tables). The function calls sequentially
 
5713
    'best_access_path' for each table in the query to select the best table
 
5714
    access method. The final optimal plan is stored in the array
 
5715
    'join->best_positions', and the corresponding cost in 'join->best_read'.
 
5716
 
 
5717
  @param join          pointer to the structure providing all context info for
 
5718
                       the query
 
5719
  @param join_tables   set of the tables in the query
 
5720
 
 
5721
  @note
 
5722
    This function can be applied to:
 
5723
    - queries with STRAIGHT_JOIN
 
5724
    - internally to compute the cost of an arbitrary QEP
 
5725
  @par
 
5726
    Thus 'optimize_straight_join' can be used at any stage of the query
 
5727
    optimization process to finalize a QEP as it is.
 
5728
*/
 
5729
 
 
5730
static void
 
5731
optimize_straight_join(JOIN *join, table_map join_tables)
 
5732
{
 
5733
  JOIN_TAB *s;
 
5734
  uint32_t idx= join->const_tables;
 
5735
  double    record_count= 1.0;
 
5736
  double    read_time=    0.0;
 
5737
 
 
5738
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
5739
  {
 
5740
    /* Find the best access method from 's' to the current partial plan */
 
5741
    advance_sj_state(join_tables, s);
 
5742
    best_access_path(join, s, join->session, join_tables, idx,
 
5743
                     record_count, read_time);
 
5744
    /* compute the cost of the new plan extended with 's' */
 
5745
    record_count*= join->positions[idx].records_read;
 
5746
    read_time+=    join->positions[idx].read_time;
 
5747
    join_tables&= ~(s->table->map);
 
5748
    ++idx;
 
5749
  }
 
5750
 
 
5751
  read_time+= record_count / (double) TIME_FOR_COMPARE;
 
5752
  if (join->sort_by_table &&
 
5753
      join->sort_by_table != join->positions[join->const_tables].table->table)
 
5754
    read_time+= record_count;  // We have to make a temp table
 
5755
  memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
5756
  join->best_read= read_time;
 
5757
}
 
5758
 
 
5759
 
 
5760
/**
 
5761
  Find a good, possibly optimal, query execution plan (QEP) by a greedy search.
 
5762
 
 
5763
    The search procedure uses a hybrid greedy/exhaustive search with controlled
 
5764
    exhaustiveness. The search is performed in N = card(remaining_tables)
 
5765
    steps. Each step evaluates how promising is each of the unoptimized tables,
 
5766
    selects the most promising table, and extends the current partial QEP with
 
5767
    that table.  Currenly the most 'promising' table is the one with least
 
5768
    expensive extension.\
 
5769
 
 
5770
    There are two extreme cases:
 
5771
    -# When (card(remaining_tables) < search_depth), the estimate finds the
 
5772
    best complete continuation of the partial QEP. This continuation can be
 
5773
    used directly as a result of the search.
 
5774
    -# When (search_depth == 1) the 'best_extension_by_limited_search'
 
5775
    consideres the extension of the current QEP with each of the remaining
 
5776
    unoptimized tables.
 
5777
 
 
5778
    All other cases are in-between these two extremes. Thus the parameter
 
5779
    'search_depth' controlls the exhaustiveness of the search. The higher the
 
5780
    value, the longer the optimizaton time and possibly the better the
 
5781
    resulting plan. The lower the value, the fewer alternative plans are
 
5782
    estimated, but the more likely to get a bad QEP.
 
5783
 
 
5784
    All intermediate and final results of the procedure are stored in 'join':
 
5785
    - join->positions     : modified for every partial QEP that is explored
 
5786
    - join->best_positions: modified for the current best complete QEP
 
5787
    - join->best_read     : modified for the current best complete QEP
 
5788
    - join->best_ref      : might be partially reordered
 
5789
 
 
5790
    The final optimal plan is stored in 'join->best_positions', and its
 
5791
    corresponding cost in 'join->best_read'.
 
5792
 
 
5793
  @note
 
5794
    The following pseudocode describes the algorithm of 'greedy_search':
 
5795
 
 
5796
    @code
 
5797
    procedure greedy_search
 
5798
    input: remaining_tables
 
5799
    output: pplan;
 
5800
    {
 
5801
      pplan = <>;
 
5802
      do {
 
5803
        (t, a) = best_extension(pplan, remaining_tables);
 
5804
        pplan = concat(pplan, (t, a));
 
5805
        remaining_tables = remaining_tables - t;
 
5806
      } while (remaining_tables != {})
 
5807
      return pplan;
 
5808
    }
 
5809
 
 
5810
  @endcode
 
5811
    where 'best_extension' is a placeholder for a procedure that selects the
 
5812
    most "promising" of all tables in 'remaining_tables'.
 
5813
    Currently this estimate is performed by calling
 
5814
    'best_extension_by_limited_search' to evaluate all extensions of the
 
5815
    current QEP of size 'search_depth', thus the complexity of 'greedy_search'
 
5816
    mainly depends on that of 'best_extension_by_limited_search'.
 
5817
 
 
5818
  @par
 
5819
    If 'best_extension()' == 'best_extension_by_limited_search()', then the
 
5820
    worst-case complexity of this algorithm is <=
 
5821
    O(N*N^search_depth/search_depth). When serch_depth >= N, then the
 
5822
    complexity of greedy_search is O(N!).
 
5823
 
 
5824
  @par
 
5825
    In the future, 'greedy_search' might be extended to support other
 
5826
    implementations of 'best_extension', e.g. some simpler quadratic procedure.
 
5827
 
 
5828
  @param join             pointer to the structure providing all context info
 
5829
                          for the query
 
5830
  @param remaining_tables set of tables not included into the partial plan yet
 
5831
  @param search_depth     controlls the exhaustiveness of the search
 
5832
  @param prune_level      the pruning heuristics that should be applied during
 
5833
                          search
 
5834
 
 
5835
  @retval
 
5836
    false       ok
 
5837
  @retval
 
5838
    true        Fatal error
 
5839
*/
 
5840
 
 
5841
static bool
 
5842
greedy_search(JOIN      *join,
 
5843
              table_map remaining_tables,
 
5844
              uint32_t      search_depth,
 
5845
              uint32_t      prune_level)
 
5846
{
 
5847
  double    record_count= 1.0;
 
5848
  double    read_time=    0.0;
 
5849
  uint32_t      idx= join->const_tables; // index into 'join->best_ref'
 
5850
  uint32_t      best_idx;
 
5851
  uint32_t      size_remain;    // cardinality of remaining_tables
 
5852
  POSITION  best_pos;
 
5853
  JOIN_TAB  *best_table; // the next plan node to be added to the curr QEP
 
5854
 
 
5855
  /* number of tables that remain to be optimized */
 
5856
  size_remain= my_count_bits(remaining_tables);
 
5857
 
 
5858
  do {
 
5859
    /* Find the extension of the current QEP with the lowest cost */
 
5860
    join->best_read= DBL_MAX;
 
5861
    if (best_extension_by_limited_search(join, remaining_tables, idx, record_count,
 
5862
                                         read_time, search_depth, prune_level))
 
5863
      return(true);
 
5864
 
 
5865
    if (size_remain <= search_depth)
 
5866
    {
 
5867
      /*
 
5868
        'join->best_positions' contains a complete optimal extension of the
 
5869
        current partial QEP.
 
5870
      */
 
5871
      return(false);
 
5872
    }
 
5873
 
 
5874
    /* select the first table in the optimal extension as most promising */
 
5875
    best_pos= join->best_positions[idx];
 
5876
    best_table= best_pos.table;
 
5877
    /*
 
5878
      Each subsequent loop of 'best_extension_by_limited_search' uses
 
5879
      'join->positions' for cost estimates, therefore we have to update its
 
5880
      value.
 
5881
    */
 
5882
    join->positions[idx]= best_pos;
 
5883
 
 
5884
    /* find the position of 'best_table' in 'join->best_ref' */
 
5885
    best_idx= idx;
 
5886
    JOIN_TAB *pos= join->best_ref[best_idx];
 
5887
    while (pos && best_table != pos)
 
5888
      pos= join->best_ref[++best_idx];
 
5889
    assert((pos != NULL)); // should always find 'best_table'
 
5890
    /* move 'best_table' at the first free position in the array of joins */
 
5891
    std::swap(join->best_ref[idx], join->best_ref[best_idx]);
 
5892
 
 
5893
    /* compute the cost of the new plan extended with 'best_table' */
 
5894
    record_count*= join->positions[idx].records_read;
 
5895
    read_time+=    join->positions[idx].read_time;
 
5896
 
 
5897
    remaining_tables&= ~(best_table->table->map);
 
5898
    --size_remain;
 
5899
    ++idx;
 
5900
  } while (true);
 
5901
}
 
5902
 
 
5903
 
 
5904
/**
 
5905
  Find a good, possibly optimal, query execution plan (QEP) by a possibly
 
5906
  exhaustive search.
 
5907
 
 
5908
    The procedure searches for the optimal ordering of the query tables in set
 
5909
    'remaining_tables' of size N, and the corresponding optimal access paths to
 
5910
    each table. The choice of a table order and an access path for each table
 
5911
    constitutes a query execution plan (QEP) that fully specifies how to
 
5912
    execute the query.
 
5913
 
 
5914
    The maximal size of the found plan is controlled by the parameter
 
5915
    'search_depth'. When search_depth == N, the resulting plan is complete and
 
5916
    can be used directly as a QEP. If search_depth < N, the found plan consists
 
5917
    of only some of the query tables. Such "partial" optimal plans are useful
 
5918
    only as input to query optimization procedures, and cannot be used directly
 
5919
    to execute a query.
 
5920
 
 
5921
    The algorithm begins with an empty partial plan stored in 'join->positions'
 
5922
    and a set of N tables - 'remaining_tables'. Each step of the algorithm
 
5923
    evaluates the cost of the partial plan extended by all access plans for
 
5924
    each of the relations in 'remaining_tables', expands the current partial
 
5925
    plan with the access plan that results in lowest cost of the expanded
 
5926
    partial plan, and removes the corresponding relation from
 
5927
    'remaining_tables'. The algorithm continues until it either constructs a
 
5928
    complete optimal plan, or constructs an optimal plartial plan with size =
 
5929
    search_depth.
 
5930
 
 
5931
    The final optimal plan is stored in 'join->best_positions'. The
 
5932
    corresponding cost of the optimal plan is in 'join->best_read'.
 
5933
 
 
5934
  @note
 
5935
    The procedure uses a recursive depth-first search where the depth of the
 
5936
    recursion (and thus the exhaustiveness of the search) is controlled by the
 
5937
    parameter 'search_depth'.
 
5938
 
 
5939
  @note
 
5940
    The pseudocode below describes the algorithm of
 
5941
    'best_extension_by_limited_search'. The worst-case complexity of this
 
5942
    algorithm is O(N*N^search_depth/search_depth). When serch_depth >= N, then
 
5943
    the complexity of greedy_search is O(N!).
 
5944
 
 
5945
    @code
 
5946
    procedure best_extension_by_limited_search(
 
5947
      pplan in,             // in, partial plan of tables-joined-so-far
 
5948
      pplan_cost,           // in, cost of pplan
 
5949
      remaining_tables,     // in, set of tables not referenced in pplan
 
5950
      best_plan_so_far,     // in/out, best plan found so far
 
5951
      best_plan_so_far_cost,// in/out, cost of best_plan_so_far
 
5952
      search_depth)         // in, maximum size of the plans being considered
 
5953
    {
 
5954
      for each table T from remaining_tables
 
5955
      {
 
5956
        // Calculate the cost of using table T as above
 
5957
        cost = complex-series-of-calculations;
 
5958
 
 
5959
        // Add the cost to the cost so far.
 
5960
        pplan_cost+= cost;
 
5961
 
 
5962
        if (pplan_cost >= best_plan_so_far_cost)
 
5963
          // pplan_cost already too great, stop search
 
5964
          continue;
 
5965
 
 
5966
        pplan= expand pplan by best_access_method;
 
5967
        remaining_tables= remaining_tables - table T;
 
5968
        if (remaining_tables is not an empty set
 
5969
            and
 
5970
            search_depth > 1)
 
5971
        {
 
5972
          best_extension_by_limited_search(pplan, pplan_cost,
 
5973
                                           remaining_tables,
 
5974
                                           best_plan_so_far,
 
5975
                                           best_plan_so_far_cost,
 
5976
                                           search_depth - 1);
 
5977
        }
 
5978
        else
 
5979
        {
 
5980
          best_plan_so_far_cost= pplan_cost;
 
5981
          best_plan_so_far= pplan;
 
5982
        }
 
5983
      }
 
5984
    }
 
5985
    @endcode
 
5986
 
 
5987
  @note
 
5988
    When 'best_extension_by_limited_search' is called for the first time,
 
5989
    'join->best_read' must be set to the largest possible value (e.g. DBL_MAX).
 
5990
    The actual implementation provides a way to optionally use pruning
 
5991
    heuristic (controlled by the parameter 'prune_level') to reduce the search
 
5992
    space by skipping some partial plans.
 
5993
 
 
5994
  @note
 
5995
    The parameter 'search_depth' provides control over the recursion
 
5996
    depth, and thus the size of the resulting optimal plan.
 
5997
 
 
5998
  @param join             pointer to the structure providing all context info
 
5999
                          for the query
 
6000
  @param remaining_tables set of tables not included into the partial plan yet
 
6001
  @param idx              length of the partial QEP in 'join->positions';
 
6002
                          since a depth-first search is used, also corresponds
 
6003
                          to the current depth of the search tree;
 
6004
                          also an index in the array 'join->best_ref';
 
6005
  @param record_count     estimate for the number of records returned by the
 
6006
                          best partial plan
 
6007
  @param read_time        the cost of the best partial plan
 
6008
  @param search_depth     maximum depth of the recursion and thus size of the
 
6009
                          found optimal plan
 
6010
                          (0 < search_depth <= join->tables+1).
 
6011
  @param prune_level      pruning heuristics that should be applied during
 
6012
                          optimization
 
6013
                          (values: 0 = EXHAUSTIVE, 1 = PRUNE_BY_TIME_OR_ROWS)
 
6014
 
 
6015
  @retval
 
6016
    false       ok
 
6017
  @retval
 
6018
    true        Fatal error
 
6019
*/
 
6020
 
 
6021
static bool
 
6022
best_extension_by_limited_search(JOIN      *join,
 
6023
                                 table_map remaining_tables,
 
6024
                                 uint32_t      idx,
 
6025
                                 double    record_count,
 
6026
                                 double    read_time,
 
6027
                                 uint32_t      search_depth,
 
6028
                                 uint32_t      prune_level)
 
6029
{
 
6030
  Session *session= join->session;
 
6031
  if (session->killed)  // Abort
 
6032
    return(true);
 
6033
 
 
6034
  /*
 
6035
     'join' is a partial plan with lower cost than the best plan so far,
 
6036
     so continue expanding it further with the tables in 'remaining_tables'.
 
6037
  */
 
6038
  JOIN_TAB *s;
 
6039
  double best_record_count= DBL_MAX;
 
6040
  double best_read_time=    DBL_MAX;
 
6041
 
 
6042
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
 
6043
  {
 
6044
    table_map real_table_bit= s->table->map;
 
6045
    if ((remaining_tables & real_table_bit) &&
 
6046
        !(remaining_tables & s->dependent) &&
 
6047
        (!idx || !check_interleaving_with_nj(join->positions[idx-1].table, s)))
 
6048
    {
 
6049
      double current_record_count, current_read_time;
 
6050
      advance_sj_state(remaining_tables, s);
 
6051
 
 
6052
      /*
 
6053
        psergey-insideout-todo:
 
6054
          when best_access_path() detects it could do an InsideOut scan or
 
6055
          some other scan, have it return an insideout scan and a flag that
 
6056
          requests to "fork" this loop iteration. (Q: how does that behave
 
6057
          when the depth is insufficient??)
 
6058
      */
 
6059
      /* Find the best access method from 's' to the current partial plan */
 
6060
      best_access_path(join, s, session, remaining_tables, idx,
 
6061
                       record_count, read_time);
 
6062
      /* Compute the cost of extending the plan with 's' */
 
6063
      current_record_count= record_count * join->positions[idx].records_read;
 
6064
      current_read_time=    read_time + join->positions[idx].read_time;
 
6065
 
 
6066
      /* Expand only partial plans with lower cost than the best QEP so far */
 
6067
      if ((current_read_time +
 
6068
           current_record_count / (double) TIME_FOR_COMPARE) >= join->best_read)
 
6069
      {
 
6070
        restore_prev_nj_state(s);
 
6071
        restore_prev_sj_state(remaining_tables, s);
 
6072
        continue;
 
6073
      }
 
6074
 
 
6075
      /*
 
6076
        Prune some less promising partial plans. This heuristic may miss
 
6077
        the optimal QEPs, thus it results in a non-exhaustive search.
 
6078
      */
 
6079
      if (prune_level == 1)
 
6080
      {
 
6081
        if (best_record_count > current_record_count ||
 
6082
            best_read_time > current_read_time ||
 
6083
            (idx == join->const_tables && s->table == join->sort_by_table)) // 's' is the first table in the QEP
 
6084
        {
 
6085
          if (best_record_count >= current_record_count &&
 
6086
              best_read_time >= current_read_time &&
 
6087
              /* TODO: What is the reasoning behind this condition? */
 
6088
              (!(s->key_dependent & remaining_tables) ||
 
6089
               join->positions[idx].records_read < 2.0))
 
6090
          {
 
6091
            best_record_count= current_record_count;
 
6092
            best_read_time=    current_read_time;
 
6093
          }
 
6094
        }
 
6095
        else
 
6096
        {
 
6097
          restore_prev_nj_state(s);
 
6098
          restore_prev_sj_state(remaining_tables, s);
 
6099
          continue;
 
6100
        }
 
6101
      }
 
6102
 
 
6103
      if ( (search_depth > 1) && (remaining_tables & ~real_table_bit) )
 
6104
      { /* Recursively expand the current partial plan */
 
6105
        std::swap(join->best_ref[idx], *pos);
 
6106
        if (best_extension_by_limited_search(join,
 
6107
                                             remaining_tables & ~real_table_bit,
 
6108
                                             idx + 1,
 
6109
                                             current_record_count,
 
6110
                                             current_read_time,
 
6111
                                             search_depth - 1,
 
6112
                                             prune_level))
 
6113
          return(true);
 
6114
        std::swap(join->best_ref[idx], *pos);
 
6115
      }
 
6116
      else
 
6117
      { /*
 
6118
          'join' is either the best partial QEP with 'search_depth' relations,
 
6119
          or the best complete QEP so far, whichever is smaller.
 
6120
        */
 
6121
        current_read_time+= current_record_count / (double) TIME_FOR_COMPARE;
 
6122
        if (join->sort_by_table &&
 
6123
            join->sort_by_table !=
 
6124
            join->positions[join->const_tables].table->table)
 
6125
          /* We have to make a temp table */
 
6126
          current_read_time+= current_record_count;
 
6127
        if ((search_depth == 1) || (current_read_time < join->best_read))
 
6128
        {
 
6129
          memcpy(join->best_positions, join->positions,
 
6130
                 sizeof(POSITION) * (idx + 1));
 
6131
          join->best_read= current_read_time - 0.001;
 
6132
        }
 
6133
      }
 
6134
      restore_prev_nj_state(s);
 
6135
      restore_prev_sj_state(remaining_tables, s);
 
6136
    }
 
6137
  }
 
6138
  return(false);
 
6139
}
 
6140
 
 
6141
 
 
6142
/**
 
6143
  @todo
 
6144
  - TODO: this function is here only temporarily until 'greedy_search' is
 
6145
  tested and accepted.
 
6146
 
 
6147
  RETURN VALUES
 
6148
    false       ok
 
6149
    true        Fatal error
 
6150
*/
 
6151
static bool
 
6152
find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count,
 
6153
          double read_time)
 
6154
{
 
6155
  Session *session= join->session;
 
6156
  if (session->killed)
 
6157
    return(true);
 
6158
  if (!rest_tables)
 
6159
  {
 
6160
    read_time+=record_count/(double) TIME_FOR_COMPARE;
 
6161
    if (join->sort_by_table &&
 
6162
        join->sort_by_table !=
 
6163
        join->positions[join->const_tables].table->table)
 
6164
      read_time+=record_count;                  // We have to make a temp table
 
6165
    if (read_time < join->best_read)
 
6166
    {
 
6167
      memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
6168
      join->best_read= read_time - 0.001;
 
6169
    }
 
6170
    return(false);
 
6171
  }
 
6172
  if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
 
6173
    return(false);                                      /* Found better before */
 
6174
 
 
6175
  JOIN_TAB *s;
 
6176
  double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
 
6177
  for (JOIN_TAB **pos=join->best_ref+idx ; (s=*pos) ; pos++)
 
6178
  {
 
6179
    table_map real_table_bit=s->table->map;
 
6180
    if ((rest_tables & real_table_bit) && !(rest_tables & s->dependent) &&
 
6181
        (!idx|| !check_interleaving_with_nj(join->positions[idx-1].table, s)))
 
6182
    {
 
6183
      double records, best;
 
6184
      advance_sj_state(rest_tables, s);
 
6185
      best_access_path(join, s, session, rest_tables, idx, record_count,
 
6186
                       read_time);
 
6187
      records= join->positions[idx].records_read;
 
6188
      best= join->positions[idx].read_time;
 
6189
      /*
 
6190
        Go to the next level only if there hasn't been a better key on
 
6191
        this level! This will cut down the search for a lot simple cases!
 
6192
      */
 
6193
      double current_record_count=record_count*records;
 
6194
      double current_read_time=read_time+best;
 
6195
      if (best_record_count > current_record_count ||
 
6196
          best_read_time > current_read_time ||
 
6197
          (idx == join->const_tables && s->table == join->sort_by_table))
 
6198
      {
 
6199
        if (best_record_count >= current_record_count &&
 
6200
            best_read_time >= current_read_time &&
 
6201
            (!(s->key_dependent & rest_tables) || records < 2.0))
 
6202
        {
 
6203
          best_record_count=current_record_count;
 
6204
          best_read_time=current_read_time;
 
6205
        }
 
6206
        std::swap(join->best_ref[idx], *pos);
 
6207
        if (find_best(join,rest_tables & ~real_table_bit,idx+1,
 
6208
                      current_record_count,current_read_time))
 
6209
          return(true);
 
6210
        std::swap(join->best_ref[idx], *pos);
 
6211
      }
 
6212
      restore_prev_nj_state(s);
 
6213
      restore_prev_sj_state(rest_tables, s);
 
6214
      if (join->select_options & SELECT_STRAIGHT_JOIN)
 
6215
        break;                          // Don't test all combinations
 
6216
    }
 
6217
  }
 
6218
  return(false);
 
6219
}
 
6220
 
 
6221
 
 
6222
/**
845
6223
  Find how much space the prevous read not const tables takes in cache.
846
6224
*/
847
 
void calc_used_field_length(Session *, JoinTable *join_tab)
 
6225
 
 
6226
static void calc_used_field_length(Session *, JOIN_TAB *join_tab)
848
6227
{
849
6228
  uint32_t null_fields,blobs,fields,rec_length;
850
6229
  Field **f_ptr,*field;
 
6230
  MY_BITMAP *read_set= join_tab->table->read_set;;
851
6231
 
852
6232
  null_fields= blobs= fields= rec_length=0;
853
 
  for (f_ptr=join_tab->table->getFields() ; (field= *f_ptr) ; f_ptr++)
 
6233
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
854
6234
  {
855
 
    if (field->isReadSet())
 
6235
    if (bitmap_is_set(read_set, field->field_index))
856
6236
    {
857
6237
      uint32_t flags=field->flags;
858
6238
      fields++;
859
6239
      rec_length+=field->pack_length();
860
6240
      if (flags & BLOB_FLAG)
861
 
        blobs++;
 
6241
        blobs++;
862
6242
      if (!(flags & NOT_NULL_FLAG))
863
 
        null_fields++;
 
6243
        null_fields++;
864
6244
    }
865
6245
  }
866
6246
  if (null_fields)
869
6249
    rec_length+=sizeof(bool);
870
6250
  if (blobs)
871
6251
  {
872
 
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
873
 
                                     (join_tab->table->getRecordLength()- rec_length));
874
 
    rec_length+= max((uint32_t)4,blob_length);
875
 
  }
876
 
  join_tab->used_fields= fields;
877
 
  join_tab->used_fieldlength= rec_length;
878
 
  join_tab->used_blobs= blobs;
879
 
}
880
 
 
881
 
StoredKey *get_store_key(Session *session,
882
 
                         optimizer::KeyUse *keyuse,
883
 
                         table_map used_tables,
884
 
                         KeyPartInfo *key_part,
885
 
                         unsigned char *key_buff,
886
 
                         uint32_t maybe_null)
887
 
{
888
 
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
889
 
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
6252
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
 
6253
                             (join_tab->table->getRecordLength()- rec_length));
 
6254
    rec_length+=(uint32_t) cmax((uint32_t)4,blob_length);
 
6255
  }
 
6256
  join_tab->used_fields=fields;
 
6257
  join_tab->used_fieldlength=rec_length;
 
6258
  join_tab->used_blobs=blobs;
 
6259
}
 
6260
 
 
6261
 
 
6262
static uint
 
6263
cache_record_length(JOIN *join,uint32_t idx)
 
6264
{
 
6265
  uint32_t length=0;
 
6266
  JOIN_TAB **pos,**end;
 
6267
  Session *session=join->session;
 
6268
 
 
6269
  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
 
6270
       pos != end ;
 
6271
       pos++)
 
6272
  {
 
6273
    JOIN_TAB *join_tab= *pos;
 
6274
    if (!join_tab->used_fieldlength)            /* Not calced yet */
 
6275
      calc_used_field_length(session, join_tab);
 
6276
    length+=join_tab->used_fieldlength;
 
6277
  }
 
6278
  return length;
 
6279
}
 
6280
 
 
6281
 
 
6282
/*
 
6283
  Get the number of different row combinations for subset of partial join
 
6284
 
 
6285
  SYNOPSIS
 
6286
    prev_record_reads()
 
6287
      join       The join structure
 
6288
      idx        Number of tables in the partial join order (i.e. the
 
6289
                 partial join order is in join->positions[0..idx-1])
 
6290
      found_ref  Bitmap of tables for which we need to find # of distinct
 
6291
                 row combinations.
 
6292
 
 
6293
  DESCRIPTION
 
6294
    Given a partial join order (in join->positions[0..idx-1]) and a subset of
 
6295
    tables within that join order (specified in found_ref), find out how many
 
6296
    distinct row combinations of subset tables will be in the result of the
 
6297
    partial join order.
 
6298
 
 
6299
    This is used as follows: Suppose we have a table accessed with a ref-based
 
6300
    method. The ref access depends on current rows of tables in found_ref.
 
6301
    We want to count # of different ref accesses. We assume two ref accesses
 
6302
    will be different if at least one of access parameters is different.
 
6303
    Example: consider a query
 
6304
 
 
6305
    SELECT * FROM t1, t2, t3 WHERE t1.key=c1 AND t2.key=c2 AND t3.key=t1.field
 
6306
 
 
6307
    and a join order:
 
6308
      t1,  ref access on t1.key=c1
 
6309
      t2,  ref access on t2.key=c2
 
6310
      t3,  ref access on t3.key=t1.field
 
6311
 
 
6312
    For t1: n_ref_scans = 1, n_distinct_ref_scans = 1
 
6313
    For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1
 
6314
    For t3: n_ref_scans = records_read(t1)*records_read(t2)
 
6315
            n_distinct_ref_scans = #records_read(t1)
 
6316
 
 
6317
    The reason for having this function (at least the latest version of it)
 
6318
    is that we need to account for buffering in join execution.
 
6319
 
 
6320
    An edge-case example: if we have a non-first table in join accessed via
 
6321
    ref(const) or ref(param) where there is a small number of different
 
6322
    values of param, then the access will likely hit the disk cache and will
 
6323
    not require any disk seeks.
 
6324
 
 
6325
    The proper solution would be to assume an LRU disk cache of some size,
 
6326
    calculate probability of cache hits, etc. For now we just count
 
6327
    identical ref accesses as one.
 
6328
 
 
6329
  RETURN
 
6330
    Expected number of row combinations
 
6331
*/
 
6332
 
 
6333
static double
 
6334
prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
 
6335
{
 
6336
  double found=1.0;
 
6337
  POSITION *pos_end= join->positions - 1;
 
6338
  for (POSITION *pos= join->positions + idx - 1; pos != pos_end; pos--)
 
6339
  {
 
6340
    if (pos->table->table->map & found_ref)
 
6341
    {
 
6342
      found_ref|= pos->ref_depend_map;
 
6343
      /*
 
6344
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table
 
6345
        with no matching row we will get position[t2].records_read==0.
 
6346
        Actually the size of output is one null-complemented row, therefore
 
6347
        we will use value of 1 whenever we get records_read==0.
 
6348
 
 
6349
        Note
 
6350
        - the above case can't occur if inner part of outer join has more
 
6351
          than one table: table with no matches will not be marked as const.
 
6352
 
 
6353
        - Ideally we should add 1 to records_read for every possible null-
 
6354
          complemented row. We're not doing it because: 1. it will require
 
6355
          non-trivial code and add overhead. 2. The value of records_read
 
6356
          is an inprecise estimate and adding 1 (or, in the worst case,
 
6357
          #max_nested_outer_joins=64-1) will not make it any more precise.
 
6358
      */
 
6359
      if (pos->records_read > DBL_EPSILON)
 
6360
        found*= pos->records_read;
 
6361
    }
 
6362
  }
 
6363
  return found;
 
6364
}
 
6365
 
 
6366
 
 
6367
/**
 
6368
  Set up join struct according to best position.
 
6369
*/
 
6370
 
 
6371
static bool
 
6372
get_best_combination(JOIN *join)
 
6373
{
 
6374
  uint32_t i,tablenr;
 
6375
  table_map used_tables;
 
6376
  JOIN_TAB *join_tab,*j;
 
6377
  KEYUSE *keyuse;
 
6378
  uint32_t table_count;
 
6379
  Session *session=join->session;
 
6380
 
 
6381
  table_count=join->tables;
 
6382
  if (!(join->join_tab=join_tab=
 
6383
        (JOIN_TAB*) session->alloc(sizeof(JOIN_TAB)*table_count)))
 
6384
    return(true);
 
6385
 
 
6386
  join->full_join=0;
 
6387
 
 
6388
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
 
6389
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
 
6390
  {
 
6391
    Table *form;
 
6392
    *j= *join->best_positions[tablenr].table;
 
6393
    form=join->table[tablenr]=j->table;
 
6394
    used_tables|= form->map;
 
6395
    form->reginfo.join_tab=j;
 
6396
    if (!*j->on_expr_ref)
 
6397
      form->reginfo.not_exists_optimize=0;      // Only with LEFT JOIN
 
6398
    if (j->type == JT_CONST)
 
6399
      continue;                                 // Handled in make_join_stat..
 
6400
 
 
6401
    j->ref.key = -1;
 
6402
    j->ref.key_parts=0;
 
6403
 
 
6404
    if (j->type == JT_SYSTEM)
 
6405
      continue;
 
6406
    if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key))
 
6407
    {
 
6408
      j->type=JT_ALL;
 
6409
      if (tablenr != join->const_tables)
 
6410
        join->full_join=1;
 
6411
    }
 
6412
    else if (create_ref_for_key(join, j, keyuse, used_tables))
 
6413
      return(true);                        // Something went wrong
 
6414
  }
 
6415
 
 
6416
  for (i=0 ; i < table_count ; i++)
 
6417
    join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i;
 
6418
  update_depend_map(join);
 
6419
  return(0);
 
6420
}
 
6421
 
 
6422
 
 
6423
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
6424
                               table_map used_tables)
 
6425
{
 
6426
  KEYUSE *keyuse=org_keyuse;
 
6427
  Session  *session= join->session;
 
6428
  uint32_t keyparts,length,key;
 
6429
  Table *table;
 
6430
  KEY *keyinfo;
 
6431
 
 
6432
  /*  Use best key from find_best */
 
6433
  table=j->table;
 
6434
  key=keyuse->key;
 
6435
  keyinfo=table->key_info+key;
 
6436
 
 
6437
  {
 
6438
    keyparts=length=0;
 
6439
    uint32_t found_part_ref_or_null= 0;
 
6440
    /*
 
6441
      Calculate length for the used key
 
6442
      Stop if there is a missing key part or when we find second key_part
 
6443
      with KEY_OPTIMIZE_REF_OR_NULL
 
6444
    */
 
6445
    do
 
6446
    {
 
6447
      if (!(~used_tables & keyuse->used_tables))
 
6448
      {
 
6449
        if (keyparts == keyuse->keypart &&
 
6450
            !(found_part_ref_or_null & keyuse->optimize))
 
6451
        {
 
6452
          keyparts++;
 
6453
          length+= keyinfo->key_part[keyuse->keypart].store_length;
 
6454
          found_part_ref_or_null|= keyuse->optimize;
 
6455
        }
 
6456
      }
 
6457
      keyuse++;
 
6458
    } while (keyuse->table == table && keyuse->key == key);
 
6459
  }
 
6460
 
 
6461
  /* set up fieldref */
 
6462
  keyinfo=table->key_info+key;
 
6463
  j->ref.key_parts=keyparts;
 
6464
  j->ref.key_length=length;
 
6465
  j->ref.key=(int) key;
 
6466
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
 
6467
      !(j->ref.key_copy= (store_key**) session->alloc((sizeof(store_key*) *
 
6468
                                                   (keyparts+1)))) ||
 
6469
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
 
6470
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
 
6471
  {
 
6472
    return(true);
 
6473
  }
 
6474
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
 
6475
  j->ref.key_err=1;
 
6476
  j->ref.null_rejecting= 0;
 
6477
  j->ref.disable_cache= false;
 
6478
  keyuse=org_keyuse;
 
6479
 
 
6480
  store_key **ref_key= j->ref.key_copy;
 
6481
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
 
6482
  bool keyuse_uses_no_tables= true;
 
6483
  {
 
6484
    uint32_t i;
 
6485
    for (i=0 ; i < keyparts ; keyuse++,i++)
 
6486
    {
 
6487
      while (keyuse->keypart != i ||
 
6488
             ((~used_tables) & keyuse->used_tables))
 
6489
        keyuse++;                               /* Skip other parts */
 
6490
 
 
6491
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
 
6492
      j->ref.items[i]=keyuse->val;              // Save for cond removal
 
6493
      j->ref.cond_guards[i]= keyuse->cond_guard;
 
6494
      if (keyuse->null_rejecting)
 
6495
        j->ref.null_rejecting |= 1 << i;
 
6496
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
 
6497
      if (!keyuse->used_tables &&
 
6498
          !(join->select_options & SELECT_DESCRIBE))
 
6499
      {                                 // Compare against constant
 
6500
        store_key_item tmp(session, keyinfo->key_part[i].field,
 
6501
                           key_buff + maybe_null,
 
6502
                           maybe_null ?  key_buff : 0,
 
6503
                           keyinfo->key_part[i].length, keyuse->val);
 
6504
        if (session->is_fatal_error)
 
6505
          return(true);
 
6506
        tmp.copy();
 
6507
      }
 
6508
      else
 
6509
        *ref_key++= get_store_key(session,
 
6510
                                  keyuse,join->const_table_map,
 
6511
                                  &keyinfo->key_part[i],
 
6512
                                  key_buff, maybe_null);
 
6513
      /*
 
6514
        Remember if we are going to use REF_OR_NULL
 
6515
        But only if field _really_ can be null i.e. we force JT_REF
 
6516
        instead of JT_REF_OR_NULL in case if field can't be null
 
6517
      */
 
6518
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
6519
        null_ref_key= key_buff;
 
6520
      key_buff+=keyinfo->key_part[i].store_length;
 
6521
    }
 
6522
  }
 
6523
  *ref_key=0;                           // end_marker
 
6524
  if (j->type == JT_CONST)
 
6525
    j->table->const_table= 1;
 
6526
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
 
6527
           keyparts != keyinfo->key_parts || null_ref_key)
 
6528
  {
 
6529
    /* Must read with repeat */
 
6530
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
 
6531
    j->ref.null_ref_key= null_ref_key;
 
6532
  }
 
6533
  else if (keyuse_uses_no_tables)
 
6534
  {
 
6535
    /*
 
6536
      This happen if we are using a constant expression in the ON part
 
6537
      of an LEFT JOIN.
 
6538
      SELECT * FROM a LEFT JOIN b ON b.key=30
 
6539
      Here we should not mark the table as a 'const' as a field may
 
6540
      have a 'normal' value or a NULL value.
 
6541
    */
 
6542
    j->type=JT_CONST;
 
6543
  }
 
6544
  else
 
6545
    j->type=JT_EQ_REF;
 
6546
  return(0);
 
6547
}
 
6548
 
 
6549
 
 
6550
 
 
6551
static store_key *
 
6552
get_store_key(Session *session, KEYUSE *keyuse, table_map used_tables,
 
6553
              KEY_PART_INFO *key_part, unsigned char *key_buff, uint32_t maybe_null)
 
6554
{
 
6555
  if (!((~used_tables) & keyuse->used_tables))          // if const item
890
6556
  {
891
6557
    return new store_key_const_item(session,
892
6558
                                    key_part->field,
893
6559
                                    key_buff + maybe_null,
894
6560
                                    maybe_null ? key_buff : 0,
895
6561
                                    key_part->length,
896
 
                                    key_use_val);
 
6562
                                    keyuse->val);
897
6563
  }
898
 
  else if (key_use_val->type() == Item::FIELD_ITEM ||
899
 
           (key_use_val->type() == Item::REF_ITEM &&
900
 
            key_use_val->ref_type() == Item_ref::OUTER_REF &&
901
 
            (*(Item_ref**)((Item_ref*)key_use_val)->ref)->ref_type() == Item_ref::DIRECT_REF &&
902
 
            key_use_val->real_item()->type() == Item::FIELD_ITEM))
903
 
  {
 
6564
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
 
6565
           (keyuse->val->type() == Item::REF_ITEM &&
 
6566
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
 
6567
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
 
6568
             Item_ref::DIRECT_REF &&
 
6569
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
904
6570
    return new store_key_field(session,
905
6571
                               key_part->field,
906
6572
                               key_buff + maybe_null,
907
6573
                               maybe_null ? key_buff : 0,
908
6574
                               key_part->length,
909
 
                               ((Item_field*) key_use_val->real_item())->field,
910
 
                               key_use_val->full_name());
911
 
  }
 
6575
                               ((Item_field*) keyuse->val->real_item())->field,
 
6576
                               keyuse->val->full_name());
912
6577
  return new store_key_item(session,
913
6578
                            key_part->field,
914
6579
                            key_buff + maybe_null,
915
6580
                            maybe_null ? key_buff : 0,
916
6581
                            key_part->length,
917
 
                            key_use_val);
 
6582
                            keyuse->val);
918
6583
}
919
6584
 
920
6585
/**
923
6588
  @return
924
6589
    returns 1 if there was some conversion made when the field was stored.
925
6590
*/
926
 
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
 
6591
 
 
6592
bool
 
6593
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
927
6594
{
928
6595
  bool error;
929
 
  Table *table= field->getTable();
 
6596
  Table *table= field->table;
930
6597
  Session *session= table->in_use;
931
6598
  ha_rows cuted_fields=session->cuted_fields;
932
6599
 
933
6600
  /*
934
6601
    we should restore old value of count_cuted_fields because
935
 
    store_val_in_field can be called from insert_query
 
6602
    store_val_in_field can be called from mysql_insert
936
6603
    with select_insert, which make count_cuted_fields= 1
937
6604
   */
938
6605
  enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
942
6609
  return error || cuted_fields != session->cuted_fields;
943
6610
}
944
6611
 
 
6612
 
 
6613
static bool
 
6614
make_simple_join(JOIN *join,Table *tmp_table)
 
6615
{
 
6616
  Table **tableptr;
 
6617
  JOIN_TAB *join_tab;
 
6618
 
 
6619
  /*
 
6620
    Reuse Table * and JOIN_TAB if already allocated by a previous call
 
6621
    to this function through JOIN::exec (may happen for sub-queries).
 
6622
  */
 
6623
  if (!join->table_reexec)
 
6624
  {
 
6625
    if (!(join->table_reexec= (Table**) join->session->alloc(sizeof(Table*))))
 
6626
      return(true);                        /* purecov: inspected */
 
6627
    if (join->tmp_join)
 
6628
      join->tmp_join->table_reexec= join->table_reexec;
 
6629
  }
 
6630
  if (!join->join_tab_reexec)
 
6631
  {
 
6632
    if (!(join->join_tab_reexec=
 
6633
          (JOIN_TAB*) join->session->alloc(sizeof(JOIN_TAB))))
 
6634
      return(true);                        /* purecov: inspected */
 
6635
    if (join->tmp_join)
 
6636
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
 
6637
  }
 
6638
  tableptr= join->table_reexec;
 
6639
  join_tab= join->join_tab_reexec;
 
6640
 
 
6641
  join->join_tab=join_tab;
 
6642
  join->table=tableptr; tableptr[0]=tmp_table;
 
6643
  join->tables=1;
 
6644
  join->const_tables=0;
 
6645
  join->const_table_map=0;
 
6646
  join->tmp_table_param.field_count= join->tmp_table_param.sum_func_count=
 
6647
    join->tmp_table_param.func_count=0;
 
6648
  join->tmp_table_param.copy_field=join->tmp_table_param.copy_field_end=0;
 
6649
  join->first_record=join->sort_and_group=0;
 
6650
  join->send_records=(ha_rows) 0;
 
6651
  join->group=0;
 
6652
  join->row_limit=join->unit->select_limit_cnt;
 
6653
  join->do_send_rows = (join->row_limit) ? 1 : 0;
 
6654
 
 
6655
  join_tab->cache.buff=0;                       /* No caching */
 
6656
  join_tab->table=tmp_table;
 
6657
  join_tab->select=0;
 
6658
  join_tab->select_cond=0;
 
6659
  join_tab->quick=0;
 
6660
  join_tab->type= JT_ALL;                       /* Map through all records */
 
6661
  join_tab->keys.init();
 
6662
  join_tab->keys.set_all();                     /* test everything in quick */
 
6663
  join_tab->info=0;
 
6664
  join_tab->on_expr_ref=0;
 
6665
  join_tab->last_inner= 0;
 
6666
  join_tab->first_unmatched= 0;
 
6667
  join_tab->ref.key = -1;
 
6668
  join_tab->not_used_in_distinct=0;
 
6669
  join_tab->read_first_record= join_init_read_record;
 
6670
  join_tab->join=join;
 
6671
  join_tab->ref.key_parts= 0;
 
6672
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
 
6673
  join_tab->do_firstmatch= NULL;
 
6674
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
 
6675
  tmp_table->status=0;
 
6676
  tmp_table->null_row=0;
 
6677
  return(false);
 
6678
}
 
6679
 
 
6680
 
945
6681
inline void add_cond_and_fix(Item **e1, Item *e2)
946
6682
{
947
6683
  if (*e1)
957
6693
    *e1= e2;
958
6694
}
959
6695
 
960
 
bool create_ref_for_key(Join *join, 
961
 
                        JoinTable *j, 
962
 
                        optimizer::KeyUse *org_keyuse,
963
 
                        table_map used_tables)
964
 
{
965
 
  optimizer::KeyUse *keyuse= org_keyuse;
966
 
  Session  *session= join->session;
967
 
  uint32_t keyparts;
968
 
  uint32_t length;
969
 
  uint32_t key;
970
 
  Table *table= NULL;
971
 
  KeyInfo *keyinfo= NULL;
972
 
 
973
 
  /*  Use best key from find_best */
974
 
  table= j->table;
975
 
  key= keyuse->getKey();
976
 
  keyinfo= table->key_info + key;
977
 
 
978
 
  {
979
 
    keyparts= length= 0;
980
 
    uint32_t found_part_ref_or_null= 0;
981
 
    /*
982
 
      Calculate length for the used key
983
 
      Stop if there is a missing key part or when we find second key_part
984
 
      with KEY_OPTIMIZE_REF_OR_NULL
985
 
    */
986
 
    do
987
 
    {
988
 
      if (! (~used_tables & keyuse->getUsedTables()))
989
 
      {
990
 
        if (keyparts == keyuse->getKeypart() &&
991
 
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
992
 
        {
993
 
          keyparts++;
994
 
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
995
 
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
996
 
        }
997
 
      }
998
 
      keyuse++;
999
 
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
1000
 
  }
1001
 
 
1002
 
  /* set up fieldref */
1003
 
  keyinfo=table->key_info+key;
1004
 
  j->ref.key_parts=keyparts;
1005
 
  j->ref.key_length=length;
1006
 
  j->ref.key=(int) key;
1007
 
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
1008
 
      !(j->ref.key_copy= (StoredKey**) session->getMemRoot()->allocate((sizeof(StoredKey*) *
1009
 
               (keyparts+1)))) ||
1010
 
      !(j->ref.items=    (Item**) session->getMemRoot()->allocate(sizeof(Item*)*keyparts)) ||
1011
 
      !(j->ref.cond_guards= (bool**) session->getMemRoot()->allocate(sizeof(uint*)*keyparts)))
1012
 
  {
1013
 
    return(true);
1014
 
  }
1015
 
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
1016
 
  j->ref.key_err=1;
1017
 
  j->ref.null_rejecting= 0;
1018
 
  j->ref.disable_cache= false;
1019
 
  keyuse=org_keyuse;
1020
 
 
1021
 
  StoredKey **ref_key= j->ref.key_copy;
1022
 
  unsigned char *key_buff= j->ref.key_buff, *null_ref_key= 0;
1023
 
  bool keyuse_uses_no_tables= true;
1024
 
  {
1025
 
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
1026
 
    {
1027
 
      while (keyuse->getKeypart() != i ||
1028
 
             ((~used_tables) & keyuse->getUsedTables()))
1029
 
        keyuse++;       /* Skip other parts */
1030
 
 
1031
 
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1032
 
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
1033
 
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
1034
 
      if (keyuse->isNullRejected())
1035
 
        j->ref.null_rejecting |= 1 << i;
1036
 
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
1037
 
      if (! keyuse->getUsedTables() &&  !(join->select_options & SELECT_DESCRIBE))
1038
 
      {         // Compare against constant
1039
 
        store_key_item tmp(session, keyinfo->key_part[i].field,
1040
 
                           key_buff + maybe_null,
1041
 
                           maybe_null ?  key_buff : 0,
1042
 
                           keyinfo->key_part[i].length, keyuse->getVal());
1043
 
        if (session->is_fatal_error)
1044
 
          return(true);
1045
 
        tmp.copy();
1046
 
      }
1047
 
      else
1048
 
        *ref_key++= get_store_key(session,
1049
 
          keyuse,join->const_table_map,
1050
 
          &keyinfo->key_part[i],
1051
 
          key_buff, maybe_null);
1052
 
      /*
1053
 
        Remember if we are going to use REF_OR_NULL
1054
 
        But only if field _really_ can be null i.e. we force AM_REF
1055
 
        instead of AM_REF_OR_NULL in case if field can't be null
1056
 
      */
1057
 
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1058
 
        null_ref_key= key_buff;
1059
 
      key_buff+=keyinfo->key_part[i].store_length;
1060
 
    }
1061
 
  }
1062
 
  *ref_key= 0;       // end_marker
1063
 
  if (j->type == AM_CONST)
1064
 
    j->table->const_table= 1;
1065
 
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1066
 
           keyparts != keyinfo->key_parts || null_ref_key)
1067
 
  {
1068
 
    /* Must read with repeat */
1069
 
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
1070
 
    j->ref.null_ref_key= null_ref_key;
1071
 
  }
1072
 
  else if (keyuse_uses_no_tables)
1073
 
  {
1074
 
    /*
1075
 
      This happen if we are using a constant expression in the ON part
1076
 
      of an LEFT JOIN.
1077
 
      SELECT * FROM a LEFT JOIN b ON b.key=30
1078
 
      Here we should not mark the table as a 'const' as a field may
1079
 
      have a 'normal' value or a NULL value.
1080
 
    */
1081
 
    j->type= AM_CONST;
1082
 
  }
1083
 
  else
1084
 
    j->type= AM_EQ_REF;
1085
 
  return 0;
1086
 
}
1087
6696
 
1088
6697
/**
1089
6698
  Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions
1129
6738
 
1130
6739
    Implementation overview
1131
6740
      1. update_ref_and_keys() accumulates info about null-rejecting
1132
 
         predicates in in KeyField::null_rejecting
1133
 
      1.1 add_key_part saves these to KeyUse.
1134
 
      2. create_ref_for_key copies them to table_reference_st.
 
6741
         predicates in in KEY_FIELD::null_rejecting
 
6742
      1.1 add_key_part saves these to KEYUSE.
 
6743
      2. create_ref_for_key copies them to TABLE_REF.
1135
6744
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1136
 
         appropiate JoinTable members.
 
6745
         appropiate JOIN_TAB members.
1137
6746
*/
1138
 
void add_not_null_conds(Join *join)
 
6747
 
 
6748
static void add_not_null_conds(JOIN *join)
1139
6749
{
1140
 
  for (uint32_t i= join->const_tables; i < join->tables; i++)
 
6750
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1141
6751
  {
1142
 
    JoinTable *tab=join->join_tab+i;
1143
 
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1144
 
         tab->type == AM_REF_OR_NULL) &&
 
6752
    JOIN_TAB *tab=join->join_tab+i;
 
6753
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
 
6754
         tab->type == JT_REF_OR_NULL) &&
1145
6755
        !tab->table->maybe_null)
1146
6756
    {
1147
6757
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1152
6762
          Item *notnull;
1153
6763
          assert(item->type() == Item::FIELD_ITEM);
1154
6764
          Item_field *not_null_item= (Item_field*)item;
1155
 
          JoinTable *referred_tab= not_null_item->field->getTable()->reginfo.join_tab;
 
6765
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
1156
6766
          /*
1157
6767
            For UPDATE queries such as:
1158
6768
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1193
6803
    -  pointer to the guarded predicate, if success
1194
6804
    -  0, otherwise
1195
6805
*/
1196
 
COND *add_found_match_trig_cond(JoinTable *tab, COND *cond, JoinTable *root_tab)
 
6806
 
 
6807
static COND*
 
6808
add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab)
1197
6809
{
1198
6810
  COND *tmp;
1199
6811
  assert(cond != 0);
1209
6821
  return tmp;
1210
6822
}
1211
6823
 
 
6824
 
 
6825
/**
 
6826
  Fill in outer join related info for the execution plan structure.
 
6827
 
 
6828
    For each outer join operation left after simplification of the
 
6829
    original query the function set up the following pointers in the linear
 
6830
    structure join->join_tab representing the selected execution plan.
 
6831
    The first inner table t0 for the operation is set to refer to the last
 
6832
    inner table tk through the field t0->last_inner.
 
6833
    Any inner table ti for the operation are set to refer to the first
 
6834
    inner table ti->first_inner.
 
6835
    The first inner table t0 for the operation is set to refer to the
 
6836
    first inner table of the embedding outer join operation, if there is any,
 
6837
    through the field t0->first_upper.
 
6838
    The on expression for the outer join operation is attached to the
 
6839
    corresponding first inner table through the field t0->on_expr_ref.
 
6840
    Here ti are structures of the JOIN_TAB type.
 
6841
 
 
6842
  EXAMPLE. For the query:
 
6843
  @code
 
6844
        SELECT * FROM t1
 
6845
                      LEFT JOIN
 
6846
                      (t2, t3 LEFT JOIN t4 ON t3.a=t4.a)
 
6847
                      ON (t1.a=t2.a AND t1.b=t3.b)
 
6848
          WHERE t1.c > 5,
 
6849
  @endcode
 
6850
 
 
6851
    given the execution plan with the table order t1,t2,t3,t4
 
6852
    is selected, the following references will be set;
 
6853
    t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2]
 
6854
    t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2],
 
6855
    on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to
 
6856
    *t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref.
 
6857
 
 
6858
  @param join   reference to the info fully describing the query
 
6859
 
 
6860
  @note
 
6861
    The function assumes that the simplification procedure has been
 
6862
    already applied to the join query (see simplify_joins).
 
6863
    This function can be called only after the execution plan
 
6864
    has been chosen.
 
6865
*/
 
6866
 
 
6867
static void
 
6868
make_outerjoin_info(JOIN *join)
 
6869
{
 
6870
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6871
  {
 
6872
    JOIN_TAB *tab=join->join_tab+i;
 
6873
    Table *table=tab->table;
 
6874
    TableList *tbl= table->pos_in_table_list;
 
6875
    TableList *embedding= tbl->embedding;
 
6876
 
 
6877
    if (tbl->outer_join)
 
6878
    {
 
6879
      /*
 
6880
        Table tab is the only one inner table for outer join.
 
6881
        (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a
 
6882
        is in the query above.)
 
6883
      */
 
6884
      tab->last_inner= tab->first_inner= tab;
 
6885
      tab->on_expr_ref= &tbl->on_expr;
 
6886
      tab->cond_equal= tbl->cond_equal;
 
6887
      if (embedding)
 
6888
        tab->first_upper= embedding->nested_join->first_nested;
 
6889
    }
 
6890
    for ( ; embedding ; embedding= embedding->embedding)
 
6891
    {
 
6892
      /* Ignore sj-nests: */
 
6893
      if (!embedding->on_expr)
 
6894
        continue;
 
6895
      nested_join_st *nested_join= embedding->nested_join;
 
6896
      if (!nested_join->counter_)
 
6897
      {
 
6898
        /*
 
6899
          Table tab is the first inner table for nested_join.
 
6900
          Save reference to it in the nested join structure.
 
6901
        */
 
6902
        nested_join->first_nested= tab;
 
6903
        tab->on_expr_ref= &embedding->on_expr;
 
6904
        tab->cond_equal= tbl->cond_equal;
 
6905
        if (embedding->embedding)
 
6906
          tab->first_upper= embedding->embedding->nested_join->first_nested;
 
6907
      }
 
6908
      if (!tab->first_inner)
 
6909
        tab->first_inner= nested_join->first_nested;
 
6910
      if (++nested_join->counter_ < nested_join->join_list.elements)
 
6911
        break;
 
6912
      /* Table tab is the last inner table for nested join. */
 
6913
      nested_join->first_nested->last_inner= tab;
 
6914
    }
 
6915
  }
 
6916
  return;
 
6917
}
 
6918
 
 
6919
 
 
6920
static bool
 
6921
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
 
6922
{
 
6923
  Session *session= join->session;
 
6924
  if (select)
 
6925
  {
 
6926
    add_not_null_conds(join);
 
6927
    table_map used_tables;
 
6928
    if (cond)                /* Because of QUICK_GROUP_MIN_MAX_SELECT */
 
6929
    {                        /* there may be a select without a cond. */
 
6930
      if (join->tables > 1)
 
6931
        cond->update_used_tables();             // Tablenr may have changed
 
6932
      if (join->const_tables == join->tables &&
 
6933
          session->lex->current_select->master_unit() ==
 
6934
          &session->lex->unit)          // not upper level SELECT
 
6935
        join->const_table_map|=RAND_TABLE_BIT;
 
6936
      {                                         // Check const tables
 
6937
        COND *const_cond=
 
6938
          make_cond_for_table(cond,
 
6939
                              join->const_table_map,
 
6940
                              (table_map) 0, 1);
 
6941
        for (JOIN_TAB *tab= join->join_tab+join->const_tables;
 
6942
             tab < join->join_tab+join->tables ; tab++)
 
6943
        {
 
6944
          if (*tab->on_expr_ref)
 
6945
          {
 
6946
            JOIN_TAB *cond_tab= tab->first_inner;
 
6947
            COND *tmp= make_cond_for_table(*tab->on_expr_ref,
 
6948
                                           join->const_table_map,
 
6949
                                           (  table_map) 0, 0);
 
6950
            if (!tmp)
 
6951
              continue;
 
6952
            tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
 
6953
            if (!tmp)
 
6954
              return(1);
 
6955
            tmp->quick_fix_field();
 
6956
            cond_tab->select_cond= !cond_tab->select_cond ? tmp :
 
6957
                                    new Item_cond_and(cond_tab->select_cond,
 
6958
                                                      tmp);
 
6959
            if (!cond_tab->select_cond)
 
6960
              return(1);
 
6961
            cond_tab->select_cond->quick_fix_field();
 
6962
          }
 
6963
        }
 
6964
        if (const_cond && !const_cond->val_int())
 
6965
        {
 
6966
          return(1);     // Impossible const condition
 
6967
        }
 
6968
      }
 
6969
    }
 
6970
    used_tables=((select->const_tables=join->const_table_map) |
 
6971
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
6972
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6973
    {
 
6974
      JOIN_TAB *tab=join->join_tab+i;
 
6975
      /*
 
6976
        first_inner is the X in queries like:
 
6977
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
 
6978
      */
 
6979
      JOIN_TAB *first_inner_tab= tab->first_inner;
 
6980
      table_map current_map= tab->table->map;
 
6981
      bool use_quick_range=0;
 
6982
      COND *tmp;
 
6983
 
 
6984
      /*
 
6985
        Following force including random expression in last table condition.
 
6986
        It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
 
6987
      */
 
6988
      if (i == join->tables-1)
 
6989
        current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
 
6990
      used_tables|=current_map;
 
6991
 
 
6992
      if (tab->type == JT_REF && tab->quick &&
 
6993
          (uint32_t) tab->ref.key == tab->quick->index &&
 
6994
          tab->ref.key_length < tab->quick->max_used_key_length)
 
6995
      {
 
6996
        /* Range uses longer key;  Use this instead of ref on key */
 
6997
        tab->type=JT_ALL;
 
6998
        use_quick_range=1;
 
6999
        tab->use_quick=1;
 
7000
        tab->ref.key= -1;
 
7001
        tab->ref.key_parts=0;           // Don't use ref key.
 
7002
        join->best_positions[i].records_read= rows2double(tab->quick->records);
 
7003
        /*
 
7004
          We will use join cache here : prevent sorting of the first
 
7005
          table only and sort at the end.
 
7006
        */
 
7007
        if (i != join->const_tables && join->tables > join->const_tables + 1)
 
7008
          join->full_join= 1;
 
7009
      }
 
7010
 
 
7011
      tmp= NULL;
 
7012
      if (cond)
 
7013
        tmp= make_cond_for_table(cond,used_tables,current_map, 0);
 
7014
      if (cond && !tmp && tab->quick)
 
7015
      {                                         // Outer join
 
7016
        if (tab->type != JT_ALL)
 
7017
        {
 
7018
          /*
 
7019
            Don't use the quick method
 
7020
            We come here in the case where we have 'key=constant' and
 
7021
            the test is removed by make_cond_for_table()
 
7022
          */
 
7023
          delete tab->quick;
 
7024
          tab->quick= 0;
 
7025
        }
 
7026
        else
 
7027
        {
 
7028
          /*
 
7029
            Hack to handle the case where we only refer to a table
 
7030
            in the ON part of an OUTER JOIN. In this case we want the code
 
7031
            below to check if we should use 'quick' instead.
 
7032
          */
 
7033
          tmp= new Item_int((int64_t) 1,1);     // Always true
 
7034
        }
 
7035
 
 
7036
      }
 
7037
      if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
 
7038
          tab->type == JT_EQ_REF)
 
7039
      {
 
7040
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
 
7041
                                       session->memdup((unsigned char*) select,
 
7042
                                                   sizeof(*select)));
 
7043
        if (!sel)
 
7044
          return(1);                    // End of memory
 
7045
        /*
 
7046
          If tab is an inner table of an outer join operation,
 
7047
          add a match guard to the pushed down predicate.
 
7048
          The guard will turn the predicate on only after
 
7049
          the first match for outer tables is encountered.
 
7050
        */
 
7051
        if (cond && tmp)
 
7052
        {
 
7053
          /*
 
7054
            Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
 
7055
            a cond, so neutralize the hack above.
 
7056
          */
 
7057
          if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
 
7058
            return(1);
 
7059
          tab->select_cond=sel->cond=tmp;
 
7060
          /* Push condition to storage engine if this is enabled
 
7061
             and the condition is not guarded */
 
7062
          tab->table->file->pushed_cond= NULL;
 
7063
          if (session->variables.engine_condition_pushdown)
 
7064
          {
 
7065
            COND *push_cond=
 
7066
              make_cond_for_table(tmp, current_map, current_map, 0);
 
7067
            if (push_cond)
 
7068
            {
 
7069
              /* Push condition to handler */
 
7070
              if (!tab->table->file->cond_push(push_cond))
 
7071
                tab->table->file->pushed_cond= push_cond;
 
7072
            }
 
7073
          }
 
7074
        }
 
7075
        else
 
7076
          tab->select_cond= sel->cond= NULL;
 
7077
 
 
7078
        sel->head=tab->table;
 
7079
        if (tab->quick)
 
7080
        {
 
7081
          /* Use quick key read if it's a constant and it's not used
 
7082
             with key reading */
 
7083
          if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
 
7084
              && (tab->type != JT_REF || (uint32_t) tab->ref.key == tab->quick->index))
 
7085
          {
 
7086
            sel->quick=tab->quick;              // Use value from get_quick_...
 
7087
            sel->quick_keys.clear_all();
 
7088
            sel->needed_reg.clear_all();
 
7089
          }
 
7090
          else
 
7091
          {
 
7092
            delete tab->quick;
 
7093
          }
 
7094
          tab->quick=0;
 
7095
        }
 
7096
        uint32_t ref_key=(uint32_t) sel->head->reginfo.join_tab->ref.key+1;
 
7097
        if (i == join->const_tables && ref_key)
 
7098
        {
 
7099
          if (!tab->const_keys.is_clear_all() &&
 
7100
              tab->table->reginfo.impossible_range)
 
7101
            return(1);
 
7102
        }
 
7103
        else if (tab->type == JT_ALL && ! use_quick_range)
 
7104
        {
 
7105
          if (!tab->const_keys.is_clear_all() &&
 
7106
              tab->table->reginfo.impossible_range)
 
7107
            return(1);                          // Impossible range
 
7108
          /*
 
7109
            We plan to scan all rows.
 
7110
            Check again if we should use an index.
 
7111
            We could have used an column from a previous table in
 
7112
            the index if we are using limit and this is the first table
 
7113
          */
 
7114
 
 
7115
          if ((cond && (!tab->keys.is_subset(tab->const_keys) && i > 0)) ||
 
7116
              (!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)))
 
7117
          {
 
7118
            /* Join with outer join condition */
 
7119
            COND *orig_cond=sel->cond;
 
7120
            sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
 
7121
 
 
7122
            /*
 
7123
              We can't call sel->cond->fix_fields,
 
7124
              as it will break tab->on_expr if it's AND condition
 
7125
              (fix_fields currently removes extra AND/OR levels).
 
7126
              Yet attributes of the just built condition are not needed.
 
7127
              Thus we call sel->cond->quick_fix_field for safety.
 
7128
            */
 
7129
            if (sel->cond && !sel->cond->fixed)
 
7130
              sel->cond->quick_fix_field();
 
7131
 
 
7132
            if (sel->test_quick_select(session, tab->keys,
 
7133
                                       used_tables & ~ current_map,
 
7134
                                       (join->select_options &
 
7135
                                        OPTION_FOUND_ROWS ?
 
7136
                                        HA_POS_ERROR :
 
7137
                                        join->unit->select_limit_cnt), 0,
 
7138
                                        false) < 0)
 
7139
            {
 
7140
              /*
 
7141
                Before reporting "Impossible WHERE" for the whole query
 
7142
                we have to check isn't it only "impossible ON" instead
 
7143
              */
 
7144
              sel->cond=orig_cond;
 
7145
              if (!*tab->on_expr_ref ||
 
7146
                  sel->test_quick_select(session, tab->keys,
 
7147
                                         used_tables & ~ current_map,
 
7148
                                         (join->select_options &
 
7149
                                          OPTION_FOUND_ROWS ?
 
7150
                                          HA_POS_ERROR :
 
7151
                                          join->unit->select_limit_cnt),0,
 
7152
                                          false) < 0)
 
7153
                return(1);                      // Impossible WHERE
 
7154
            }
 
7155
            else
 
7156
              sel->cond=orig_cond;
 
7157
 
 
7158
            /* Fix for EXPLAIN */
 
7159
            if (sel->quick)
 
7160
              join->best_positions[i].records_read= (double)sel->quick->records;
 
7161
          }
 
7162
          else
 
7163
          {
 
7164
            sel->needed_reg=tab->needed_reg;
 
7165
            sel->quick_keys.clear_all();
 
7166
          }
 
7167
          if (!sel->quick_keys.is_subset(tab->checked_keys) ||
 
7168
              !sel->needed_reg.is_subset(tab->checked_keys))
 
7169
          {
 
7170
            tab->keys=sel->quick_keys;
 
7171
            tab->keys.merge(sel->needed_reg);
 
7172
            tab->use_quick= (!sel->needed_reg.is_clear_all() &&
 
7173
                             (select->quick_keys.is_clear_all() ||
 
7174
                              (select->quick &&
 
7175
                               (select->quick->records >= 100L)))) ?
 
7176
              2 : 1;
 
7177
            sel->read_tables= used_tables & ~current_map;
 
7178
          }
 
7179
          if (i != join->const_tables && tab->use_quick != 2)
 
7180
          {                                     /* Read with cache */
 
7181
            if (cond &&
 
7182
                (tmp=make_cond_for_table(cond,
 
7183
                                         join->const_table_map |
 
7184
                                         current_map,
 
7185
                                         current_map, 0)))
 
7186
            {
 
7187
              tab->cache.select=(SQL_SELECT*)
 
7188
                session->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
7189
              tab->cache.select->cond=tmp;
 
7190
              tab->cache.select->read_tables=join->const_table_map;
 
7191
            }
 
7192
          }
 
7193
        }
 
7194
      }
 
7195
 
 
7196
      /*
 
7197
        Push down conditions from all on expressions.
 
7198
        Each of these conditions are guarded by a variable
 
7199
        that turns if off just before null complemented row for
 
7200
        outer joins is formed. Thus, the condition from an
 
7201
        'on expression' are guaranteed not to be checked for
 
7202
        the null complemented row.
 
7203
      */
 
7204
 
 
7205
      /* First push down constant conditions from on expressions */
 
7206
      for (JOIN_TAB *join_tab= join->join_tab+join->const_tables;
 
7207
           join_tab < join->join_tab+join->tables ; join_tab++)
 
7208
      {
 
7209
        if (*join_tab->on_expr_ref)
 
7210
        {
 
7211
          JOIN_TAB *cond_tab= join_tab->first_inner;
 
7212
          tmp= make_cond_for_table(*join_tab->on_expr_ref,
 
7213
                                   join->const_table_map,
 
7214
                                   (table_map) 0, 0);
 
7215
          if (!tmp)
 
7216
            continue;
 
7217
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
 
7218
          if (!tmp)
 
7219
            return(1);
 
7220
          tmp->quick_fix_field();
 
7221
          cond_tab->select_cond= !cond_tab->select_cond ? tmp :
 
7222
                                    new Item_cond_and(cond_tab->select_cond,tmp);
 
7223
          if (!cond_tab->select_cond)
 
7224
            return(1);
 
7225
          cond_tab->select_cond->quick_fix_field();
 
7226
        }
 
7227
      }
 
7228
 
 
7229
      /* Push down non-constant conditions from on expressions */
 
7230
      JOIN_TAB *last_tab= tab;
 
7231
      while (first_inner_tab && first_inner_tab->last_inner == last_tab)
 
7232
      {
 
7233
        /*
 
7234
          Table tab is the last inner table of an outer join.
 
7235
          An on expression is always attached to it.
 
7236
        */
 
7237
        COND *on_expr= *first_inner_tab->on_expr_ref;
 
7238
 
 
7239
        table_map used_tables2= (join->const_table_map |
 
7240
                                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
 
7241
        for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++)
 
7242
        {
 
7243
          current_map= tab->table->map;
 
7244
          used_tables2|= current_map;
 
7245
          COND *tmp_cond= make_cond_for_table(on_expr, used_tables2,
 
7246
                                              current_map, 0);
 
7247
          if (tmp_cond)
 
7248
          {
 
7249
            JOIN_TAB *cond_tab= tab < first_inner_tab ? first_inner_tab : tab;
 
7250
            /*
 
7251
              First add the guards for match variables of
 
7252
              all embedding outer join operations.
 
7253
            */
 
7254
            if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner,
 
7255
                                                     tmp_cond,
 
7256
                                                     first_inner_tab)))
 
7257
              return(1);
 
7258
            /*
 
7259
              Now add the guard turning the predicate off for
 
7260
              the null complemented row.
 
7261
            */
 
7262
            tmp_cond= new Item_func_trig_cond(tmp_cond,
 
7263
                                              &first_inner_tab->
 
7264
                                              not_null_compl);
 
7265
            if (tmp_cond)
 
7266
              tmp_cond->quick_fix_field();
 
7267
            /* Add the predicate to other pushed down predicates */
 
7268
            cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond :
 
7269
                                  new Item_cond_and(cond_tab->select_cond,
 
7270
                                                    tmp_cond);
 
7271
            if (!cond_tab->select_cond)
 
7272
              return(1);
 
7273
            cond_tab->select_cond->quick_fix_field();
 
7274
          }
 
7275
        }
 
7276
        first_inner_tab= first_inner_tab->first_upper;
 
7277
      }
 
7278
    }
 
7279
  }
 
7280
  return(0);
 
7281
}
 
7282
 
 
7283
 
 
7284
/*
 
7285
  Check if given expression uses only table fields covered by the given index
 
7286
 
 
7287
  SYNOPSIS
 
7288
    uses_index_fields_only()
 
7289
      item           Expression to check
 
7290
      tbl            The table having the index
 
7291
      keyno          The index number
 
7292
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7293
 
 
7294
  DESCRIPTION
 
7295
    Check if given expression only uses fields covered by index #keyno in the
 
7296
    table tbl. The expression can use any fields in any other tables.
 
7297
 
 
7298
    The expression is guaranteed not to be AND or OR - those constructs are
 
7299
    handled outside of this function.
 
7300
 
 
7301
  RETURN
 
7302
    true   Yes
 
7303
    false  No
 
7304
*/
 
7305
 
 
7306
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno,
 
7307
                            bool other_tbls_ok)
 
7308
{
 
7309
  if (item->const_item())
 
7310
    return true;
 
7311
 
 
7312
  /*
 
7313
    Don't push down the triggered conditions. Nested outer joins execution
 
7314
    code may need to evaluate a condition several times (both triggered and
 
7315
    untriggered), and there is no way to put thi
 
7316
    TODO: Consider cloning the triggered condition and using the copies for:
 
7317
      1. push the first copy down, to have most restrictive index condition
 
7318
         possible
 
7319
      2. Put the second copy into tab->select_cond.
 
7320
  */
 
7321
  if (item->type() == Item::FUNC_ITEM &&
 
7322
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
 
7323
    return false;
 
7324
 
 
7325
  if (!(item->used_tables() & tbl->map))
 
7326
    return other_tbls_ok;
 
7327
 
 
7328
  Item::Type item_type= item->type();
 
7329
  switch (item_type) {
 
7330
  case Item::FUNC_ITEM:
 
7331
    {
 
7332
      /* This is a function, apply condition recursively to arguments */
 
7333
      Item_func *item_func= (Item_func*)item;
 
7334
      Item **child;
 
7335
      Item **item_end= (item_func->arguments()) + item_func->argument_count();
 
7336
      for (child= item_func->arguments(); child != item_end; child++)
 
7337
      {
 
7338
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
 
7339
          return false;
 
7340
      }
 
7341
      return true;
 
7342
    }
 
7343
  case Item::COND_ITEM:
 
7344
    {
 
7345
      /* This is a function, apply condition recursively to arguments */
 
7346
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
 
7347
      Item *list_item;
 
7348
      while ((list_item=li++))
 
7349
      {
 
7350
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
 
7351
          return false;
 
7352
      }
 
7353
      return true;
 
7354
    }
 
7355
  case Item::FIELD_ITEM:
 
7356
    {
 
7357
      Item_field *item_field= (Item_field*)item;
 
7358
      if (item_field->field->table != tbl)
 
7359
        return true;
 
7360
      return item_field->field->part_of_key.is_set(keyno);
 
7361
    }
 
7362
  case Item::REF_ITEM:
 
7363
    return uses_index_fields_only(item->real_item(), tbl, keyno,
 
7364
                                  other_tbls_ok);
 
7365
  default:
 
7366
    return false; /* Play it safe, don't push unknown non-const items */
 
7367
  }
 
7368
}
 
7369
 
 
7370
 
1212
7371
#define ICP_COND_USES_INDEX_ONLY 10
1213
7372
 
1214
 
 
1215
 
/**
1216
 
  cleanup JoinTable.
1217
 
*/
1218
 
void JoinTable::cleanup()
 
7373
/*
 
7374
  Get a part of the condition that can be checked using only index fields
 
7375
 
 
7376
  SYNOPSIS
 
7377
    make_cond_for_index()
 
7378
      cond           The source condition
 
7379
      table          The table that is partially available
 
7380
      keyno          The index in the above table. Only fields covered by the index
 
7381
                     are available
 
7382
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7383
 
 
7384
  DESCRIPTION
 
7385
    Get a part of the condition that can be checked when for the given table
 
7386
    we have values only of fields covered by some index. The condition may
 
7387
    refer to other tables, it is assumed that we have values of all of their
 
7388
    fields.
 
7389
 
 
7390
    Example:
 
7391
      make_cond_for_index(
 
7392
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
 
7393
          t2, keyno(t2.key1))
 
7394
      will return
 
7395
        "cond(t1.field) AND cond(t2.key2)"
 
7396
 
 
7397
  RETURN
 
7398
    Index condition, or NULL if no condition could be inferred.
 
7399
*/
 
7400
 
 
7401
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno,
 
7402
                          bool other_tbls_ok)
 
7403
{
 
7404
  if (!cond)
 
7405
    return NULL;
 
7406
  if (cond->type() == Item::COND_ITEM)
 
7407
  {
 
7408
    uint32_t n_marked= 0;
 
7409
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
7410
    {
 
7411
      Item_cond_and *new_cond=new Item_cond_and;
 
7412
      if (!new_cond)
 
7413
        return (COND*) 0;
 
7414
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
7415
      Item *item;
 
7416
      while ((item=li++))
 
7417
      {
 
7418
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
7419
        if (fix)
 
7420
          new_cond->argument_list()->push_back(fix);
 
7421
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
7422
      }
 
7423
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
7424
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
7425
      switch (new_cond->argument_list()->elements) {
 
7426
      case 0:
 
7427
        return (COND*) 0;
 
7428
      case 1:
 
7429
        return new_cond->argument_list()->head();
 
7430
      default:
 
7431
        new_cond->quick_fix_field();
 
7432
        return new_cond;
 
7433
      }
 
7434
    }
 
7435
    else /* It's OR */
 
7436
    {
 
7437
      Item_cond_or *new_cond=new Item_cond_or;
 
7438
      if (!new_cond)
 
7439
        return (COND*) 0;
 
7440
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
7441
      Item *item;
 
7442
      while ((item=li++))
 
7443
      {
 
7444
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
7445
        if (!fix)
 
7446
          return (COND*) 0;
 
7447
        new_cond->argument_list()->push_back(fix);
 
7448
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
7449
      }
 
7450
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
7451
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
7452
      new_cond->quick_fix_field();
 
7453
      new_cond->top_level_item();
 
7454
      return new_cond;
 
7455
    }
 
7456
  }
 
7457
 
 
7458
  if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
 
7459
    return (COND*) 0;
 
7460
  cond->marker= ICP_COND_USES_INDEX_ONLY;
 
7461
  return cond;
 
7462
}
 
7463
 
 
7464
 
 
7465
Item *make_cond_remainder(Item *cond, bool exclude_index)
 
7466
{
 
7467
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
 
7468
    return 0; /* Already checked */
 
7469
 
 
7470
  if (cond->type() == Item::COND_ITEM)
 
7471
  {
 
7472
    table_map tbl_map= 0;
 
7473
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
7474
    {
 
7475
      /* Create new top level AND item */
 
7476
      Item_cond_and *new_cond=new Item_cond_and;
 
7477
      if (!new_cond)
 
7478
        return (COND*) 0;
 
7479
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
7480
      Item *item;
 
7481
      while ((item=li++))
 
7482
      {
 
7483
        Item *fix= make_cond_remainder(item, exclude_index);
 
7484
        if (fix)
 
7485
        {
 
7486
          new_cond->argument_list()->push_back(fix);
 
7487
          tbl_map |= fix->used_tables();
 
7488
        }
 
7489
      }
 
7490
      switch (new_cond->argument_list()->elements) {
 
7491
      case 0:
 
7492
        return (COND*) 0;
 
7493
      case 1:
 
7494
        return new_cond->argument_list()->head();
 
7495
      default:
 
7496
        new_cond->quick_fix_field();
 
7497
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
7498
        return new_cond;
 
7499
      }
 
7500
    }
 
7501
    else /* It's OR */
 
7502
    {
 
7503
      Item_cond_or *new_cond=new Item_cond_or;
 
7504
      if (!new_cond)
 
7505
        return (COND*) 0;
 
7506
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
7507
      Item *item;
 
7508
      while ((item=li++))
 
7509
      {
 
7510
        Item *fix= make_cond_remainder(item, false);
 
7511
        if (!fix)
 
7512
          return (COND*) 0;
 
7513
        new_cond->argument_list()->push_back(fix);
 
7514
        tbl_map |= fix->used_tables();
 
7515
      }
 
7516
      new_cond->quick_fix_field();
 
7517
      ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
7518
      new_cond->top_level_item();
 
7519
      return new_cond;
 
7520
    }
 
7521
  }
 
7522
  return cond;
 
7523
}
 
7524
 
 
7525
 
 
7526
/*
 
7527
  Try to extract and push the index condition
 
7528
 
 
7529
  SYNOPSIS
 
7530
    push_index_cond()
 
7531
      tab            A join tab that has tab->table->file and its condition
 
7532
                     in tab->select_cond
 
7533
      keyno          Index for which extract and push the condition
 
7534
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7535
 
 
7536
  DESCRIPTION
 
7537
    Try to extract and push the index condition down to table handler
 
7538
*/
 
7539
 
 
7540
static void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
 
7541
{
 
7542
  Item *idx_cond;
 
7543
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
 
7544
      tab->join->session->variables.engine_condition_pushdown)
 
7545
  {
 
7546
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
 
7547
                                  other_tbls_ok);
 
7548
 
 
7549
    if (idx_cond)
 
7550
    {
 
7551
      tab->pre_idx_push_select_cond= tab->select_cond;
 
7552
      Item *idx_remainder_cond=
 
7553
        tab->table->file->idx_cond_push(keyno, idx_cond);
 
7554
 
 
7555
      /*
 
7556
        Disable eq_ref's "lookup cache" if we've pushed down an index
 
7557
        condition.
 
7558
        TODO: This check happens to work on current ICP implementations, but
 
7559
        there may exist a compliant implementation that will not work
 
7560
        correctly with it. Sort this out when we stabilize the condition
 
7561
        pushdown APIs.
 
7562
      */
 
7563
      if (idx_remainder_cond != idx_cond)
 
7564
        tab->ref.disable_cache= true;
 
7565
 
 
7566
      Item *row_cond= make_cond_remainder(tab->select_cond, true);
 
7567
 
 
7568
      if (row_cond)
 
7569
      {
 
7570
        if (!idx_remainder_cond)
 
7571
          tab->select_cond= row_cond;
 
7572
        else
 
7573
        {
 
7574
          tab->select_cond= new Item_cond_and(row_cond, idx_remainder_cond);
 
7575
          tab->select_cond->quick_fix_field();
 
7576
          ((Item_cond_and*)tab->select_cond)->used_tables_cache=
 
7577
            row_cond->used_tables() | idx_remainder_cond->used_tables();
 
7578
        }
 
7579
      }
 
7580
      else
 
7581
        tab->select_cond= idx_remainder_cond;
 
7582
      if (tab->select)
 
7583
      {
 
7584
        tab->select->cond= tab->select_cond;
 
7585
      }
 
7586
    }
 
7587
  }
 
7588
  return;
 
7589
}
 
7590
 
 
7591
 
 
7592
 
 
7593
    /*
 
7594
      Determine if the set is already ordered for order_st BY, so it can
 
7595
      disable join cache because it will change the ordering of the results.
 
7596
      Code handles sort table that is at any location (not only first after
 
7597
      the const tables) despite the fact that it's currently prohibited.
 
7598
      We must disable join cache if the first non-const table alone is
 
7599
      ordered. If there is a temp table the ordering is done as a last
 
7600
      operation and doesn't prevent join cache usage.
 
7601
    */
 
7602
uint32_t make_join_orderinfo(JOIN *join)
 
7603
{
 
7604
  uint32_t i;
 
7605
  if (join->need_tmp)
 
7606
    return join->tables;
 
7607
 
 
7608
  for (i=join->const_tables ; i < join->tables ; i++)
 
7609
  {
 
7610
    JOIN_TAB *tab=join->join_tab+i;
 
7611
    Table *table=tab->table;
 
7612
    if ((table == join->sort_by_table &&
 
7613
         (!join->order || join->skip_sort_order)) ||
 
7614
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
 
7615
    {
 
7616
      break;
 
7617
    }
 
7618
  }
 
7619
  return i;
 
7620
}
 
7621
 
 
7622
 
 
7623
/*
 
7624
  Plan refinement stage: do various set ups for the executioner
 
7625
 
 
7626
  SYNOPSIS
 
7627
    make_join_readinfo()
 
7628
      join           Join being processed
 
7629
      options        Join's options (checking for SELECT_DESCRIBE,
 
7630
                     SELECT_NO_JOIN_CACHE)
 
7631
      no_jbuf_after  Don't use join buffering after table with this number.
 
7632
 
 
7633
  DESCRIPTION
 
7634
    Plan refinement stage: do various set ups for the executioner
 
7635
      - set up use of join buffering
 
7636
      - push index conditions
 
7637
      - increment counters
 
7638
      - etc
 
7639
 
 
7640
  RETURN
 
7641
    false - OK
 
7642
    true  - Out of memory
 
7643
*/
 
7644
 
 
7645
static bool
 
7646
make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
7647
{
 
7648
  uint32_t i;
 
7649
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
 
7650
  bool sorted= 1;
 
7651
 
 
7652
  for (i=join->const_tables ; i < join->tables ; i++)
 
7653
  {
 
7654
    JOIN_TAB *tab=join->join_tab+i;
 
7655
    Table *table=tab->table;
 
7656
    bool using_join_cache;
 
7657
    tab->read_record.table= table;
 
7658
    tab->read_record.file=table->file;
 
7659
    tab->next_select=sub_select;                /* normal select */
 
7660
    /*
 
7661
      TODO: don't always instruct first table's ref/range access method to
 
7662
      produce sorted output.
 
7663
    */
 
7664
    tab->sorted= sorted;
 
7665
    sorted= 0;                                  // only first must be sorted
 
7666
    if (tab->insideout_match_tab)
 
7667
    {
 
7668
      if (!(tab->insideout_buf= (unsigned char*)join->session->alloc(tab->table->key_info
 
7669
                                                         [tab->index].
 
7670
                                                         key_length)))
 
7671
        return true;
 
7672
    }
 
7673
    switch (tab->type) {
 
7674
    case JT_SYSTEM:                             // Only happens with left join
 
7675
      table->status=STATUS_NO_RECORD;
 
7676
      tab->read_first_record= join_read_system;
 
7677
      tab->read_record.read_record= join_no_more_records;
 
7678
      break;
 
7679
    case JT_CONST:                              // Only happens with left join
 
7680
      table->status=STATUS_NO_RECORD;
 
7681
      tab->read_first_record= join_read_const;
 
7682
      tab->read_record.read_record= join_no_more_records;
 
7683
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7684
          !table->no_keyread)
 
7685
      {
 
7686
        table->key_read=1;
 
7687
        table->file->extra(HA_EXTRA_KEYREAD);
 
7688
      }
 
7689
      break;
 
7690
    case JT_EQ_REF:
 
7691
      table->status=STATUS_NO_RECORD;
 
7692
      if (tab->select)
 
7693
      {
 
7694
        delete tab->select->quick;
 
7695
        tab->select->quick=0;
 
7696
      }
 
7697
      delete tab->quick;
 
7698
      tab->quick=0;
 
7699
      tab->read_first_record= join_read_key;
 
7700
      tab->read_record.read_record= join_no_more_records;
 
7701
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7702
          !table->no_keyread)
 
7703
      {
 
7704
        table->key_read=1;
 
7705
        table->file->extra(HA_EXTRA_KEYREAD);
 
7706
      }
 
7707
      else
 
7708
        push_index_cond(tab, tab->ref.key, true);
 
7709
      break;
 
7710
    case JT_REF_OR_NULL:
 
7711
    case JT_REF:
 
7712
      table->status=STATUS_NO_RECORD;
 
7713
      if (tab->select)
 
7714
      {
 
7715
        delete tab->select->quick;
 
7716
        tab->select->quick=0;
 
7717
      }
 
7718
      delete tab->quick;
 
7719
      tab->quick=0;
 
7720
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7721
          !table->no_keyread)
 
7722
      {
 
7723
        table->key_read=1;
 
7724
        table->file->extra(HA_EXTRA_KEYREAD);
 
7725
      }
 
7726
      else
 
7727
        push_index_cond(tab, tab->ref.key, true);
 
7728
      if (tab->type == JT_REF)
 
7729
      {
 
7730
        tab->read_first_record= join_read_always_key;
 
7731
        tab->read_record.read_record= tab->insideout_match_tab?
 
7732
           join_read_next_same_diff : join_read_next_same;
 
7733
      }
 
7734
      else
 
7735
      {
 
7736
        tab->read_first_record= join_read_always_key_or_null;
 
7737
        tab->read_record.read_record= join_read_next_same_or_null;
 
7738
      }
 
7739
      break;
 
7740
    case JT_ALL:
 
7741
      /*
 
7742
        If previous table use cache
 
7743
        If the incoming data set is already sorted don't use cache.
 
7744
      */
 
7745
      table->status=STATUS_NO_RECORD;
 
7746
      using_join_cache= false;
 
7747
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
 
7748
          tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
 
7749
          !tab->insideout_match_tab)
 
7750
      {
 
7751
        if ((options & SELECT_DESCRIBE) ||
 
7752
            !join_init_cache(join->session,join->join_tab+join->const_tables,
 
7753
                             i-join->const_tables))
 
7754
        {
 
7755
          using_join_cache= true;
 
7756
          tab[-1].next_select=sub_select_cache; /* Patch previous */
 
7757
        }
 
7758
      }
 
7759
      /* These init changes read_record */
 
7760
      if (tab->use_quick == 2)
 
7761
      {
 
7762
        join->session->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
 
7763
        tab->read_first_record= join_init_quick_read_record;
 
7764
        if (statistics)
 
7765
          status_var_increment(join->session->status_var.select_range_check_count);
 
7766
      }
 
7767
      else
 
7768
      {
 
7769
        tab->read_first_record= join_init_read_record;
 
7770
        if (i == join->const_tables)
 
7771
        {
 
7772
          if (tab->select && tab->select->quick)
 
7773
          {
 
7774
            if (statistics)
 
7775
              status_var_increment(join->session->status_var.select_range_count);
 
7776
          }
 
7777
          else
 
7778
          {
 
7779
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7780
            if (statistics)
 
7781
              status_var_increment(join->session->status_var.select_scan_count);
 
7782
          }
 
7783
        }
 
7784
        else
 
7785
        {
 
7786
          if (tab->select && tab->select->quick)
 
7787
          {
 
7788
            if (statistics)
 
7789
              status_var_increment(join->session->status_var.select_full_range_join_count);
 
7790
          }
 
7791
          else
 
7792
          {
 
7793
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7794
            if (statistics)
 
7795
              status_var_increment(join->session->status_var.select_full_join_count);
 
7796
          }
 
7797
        }
 
7798
        if (!table->no_keyread)
 
7799
        {
 
7800
          if (tab->select && tab->select->quick &&
 
7801
              tab->select->quick->index != MAX_KEY && //not index_merge
 
7802
              table->covering_keys.is_set(tab->select->quick->index))
 
7803
          {
 
7804
            table->key_read=1;
 
7805
            table->file->extra(HA_EXTRA_KEYREAD);
 
7806
          }
 
7807
          else if (!table->covering_keys.is_clear_all() &&
 
7808
                   !(tab->select && tab->select->quick))
 
7809
          {                                     // Only read index tree
 
7810
            if (!tab->insideout_match_tab)
 
7811
            {
 
7812
              /*
 
7813
                See bug #26447: "Using the clustered index for a table scan
 
7814
                is always faster than using a secondary index".
 
7815
              */
 
7816
              if (table->s->primary_key != MAX_KEY &&
 
7817
                  table->file->primary_key_is_clustered())
 
7818
                tab->index= table->s->primary_key;
 
7819
              else
 
7820
                tab->index= table->find_shortest_key(&table->covering_keys);
 
7821
            }
 
7822
            tab->read_first_record= join_read_first;
 
7823
            tab->type=JT_NEXT;          // Read with index_first / index_next
 
7824
          }
 
7825
        }
 
7826
        if (tab->select && tab->select->quick &&
 
7827
            tab->select->quick->index != MAX_KEY && ! tab->table->key_read)
 
7828
          push_index_cond(tab, tab->select->quick->index, !using_join_cache);
 
7829
      }
 
7830
      break;
 
7831
    default:
 
7832
      break;                                    /* purecov: deadcode */
 
7833
    case JT_UNKNOWN:
 
7834
    case JT_MAYBE_REF:
 
7835
      abort();                                  /* purecov: deadcode */
 
7836
    }
 
7837
  }
 
7838
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
 
7839
  return(false);
 
7840
}
 
7841
 
 
7842
 
 
7843
/**
 
7844
  Give error if we some tables are done with a full join.
 
7845
 
 
7846
  This is used by multi_table_update and multi_table_delete when running
 
7847
  in safe mode.
 
7848
 
 
7849
  @param join           Join condition
 
7850
 
 
7851
  @retval
 
7852
    0   ok
 
7853
  @retval
 
7854
    1   Error (full join used)
 
7855
*/
 
7856
 
 
7857
bool error_if_full_join(JOIN *join)
 
7858
{
 
7859
  for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables;
 
7860
       tab < end;
 
7861
       tab++)
 
7862
  {
 
7863
    if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
 
7864
    {
 
7865
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
 
7866
                 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
 
7867
      return(1);
 
7868
    }
 
7869
  }
 
7870
  return(0);
 
7871
}
 
7872
 
 
7873
 
 
7874
/**
 
7875
  cleanup JOIN_TAB.
 
7876
*/
 
7877
 
 
7878
void JOIN_TAB::cleanup()
1219
7879
{
1220
7880
  delete select;
1221
7881
  select= 0;
1222
7882
  delete quick;
1223
7883
  quick= 0;
1224
7884
  if (cache.buff)
1225
 
  {
1226
 
    size_t size= cache.end - cache.buff;
1227
 
    global_join_buffer.sub(size);
1228
7885
    free(cache.buff);
1229
 
  }
1230
7886
  cache.buff= 0;
1231
7887
  limit= 0;
1232
7888
  if (table)
1234
7890
    if (table->key_read)
1235
7891
    {
1236
7892
      table->key_read= 0;
1237
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
7893
      table->file->extra(HA_EXTRA_NO_KEYREAD);
1238
7894
    }
1239
 
    table->cursor->ha_index_or_rnd_end();
 
7895
    table->file->ha_index_or_rnd_end();
1240
7896
    /*
1241
7897
      We need to reset this for next select
1242
7898
      (Tested in part_of_refkey)
1243
7899
    */
1244
7900
    table->reginfo.join_tab= 0;
1245
7901
  }
1246
 
  read_record.end_read_record();
1247
 
}
1248
 
 
1249
 
bool only_eq_ref_tables(Join *join,Order *order,table_map tables)
1250
 
{
1251
 
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1252
 
  {
1253
 
    if (tables & 1 && !eq_ref_table(join, order, *tab))
1254
 
      return 0;
1255
 
  }
1256
 
  return 1;
1257
 
}
1258
 
 
1259
 
/**
1260
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
7902
  end_read_record(&read_record);
 
7903
}
 
7904
 
 
7905
 
 
7906
/**
 
7907
  Partially cleanup JOIN after it has executed: close index or rnd read
 
7908
  (table cursors), free quick selects.
 
7909
 
 
7910
    This function is called in the end of execution of a JOIN, before the used
 
7911
    tables are unlocked and closed.
 
7912
 
 
7913
    For a join that is resolved using a temporary table, the first sweep is
 
7914
    performed against actual tables and an intermediate result is inserted
 
7915
    into the temprorary table.
 
7916
    The last sweep is performed against the temporary table. Therefore,
 
7917
    the base tables and associated buffers used to fill the temporary table
 
7918
    are no longer needed, and this function is called to free them.
 
7919
 
 
7920
    For a join that is performed without a temporary table, this function
 
7921
    is called after all rows are sent, but before EOF packet is sent.
 
7922
 
 
7923
    For a simple SELECT with no subqueries this function performs a full
 
7924
    cleanup of the JOIN and calls mysql_unlock_read_tables to free used base
 
7925
    tables.
 
7926
 
 
7927
    If a JOIN is executed for a subquery or if it has a subquery, we can't
 
7928
    do the full cleanup and need to do a partial cleanup only.
 
7929
    - If a JOIN is not the top level join, we must not unlock the tables
 
7930
    because the outer select may not have been evaluated yet, and we
 
7931
    can't unlock only selected tables of a query.
 
7932
    - Additionally, if this JOIN corresponds to a correlated subquery, we
 
7933
    should not free quick selects and join buffers because they will be
 
7934
    needed for the next execution of the correlated subquery.
 
7935
    - However, if this is a JOIN for a [sub]select, which is not
 
7936
    a correlated subquery itself, but has subqueries, we can free it
 
7937
    fully and also free JOINs of all its subqueries. The exception
 
7938
    is a subquery in SELECT list, e.g: @n
 
7939
    SELECT a, (select cmax(b) from t1) group by c @n
 
7940
    This subquery will not be evaluated at first sweep and its value will
 
7941
    not be inserted into the temporary table. Instead, it's evaluated
 
7942
    when selecting from the temporary table. Therefore, it can't be freed
 
7943
    here even though it's not correlated.
 
7944
 
 
7945
  @todo
 
7946
    Unlock tables even if the join isn't top level select in the tree
 
7947
*/
 
7948
 
 
7949
void JOIN::join_free()
 
7950
{
 
7951
  Select_Lex_Unit *tmp_unit;
 
7952
  Select_Lex *sl;
 
7953
  /*
 
7954
    Optimization: if not EXPLAIN and we are done with the JOIN,
 
7955
    free all tables.
 
7956
  */
 
7957
  bool full= (!select_lex->uncacheable && !session->lex->describe);
 
7958
  bool can_unlock= full;
 
7959
 
 
7960
  cleanup(full);
 
7961
 
 
7962
  for (tmp_unit= select_lex->first_inner_unit();
 
7963
       tmp_unit;
 
7964
       tmp_unit= tmp_unit->next_unit())
 
7965
    for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())
 
7966
    {
 
7967
      Item_subselect *subselect= sl->master_unit()->item;
 
7968
      bool full_local= full && (!subselect || subselect->is_evaluated());
 
7969
      /*
 
7970
        If this join is evaluated, we can fully clean it up and clean up all
 
7971
        its underlying joins even if they are correlated -- they will not be
 
7972
        used any more anyway.
 
7973
        If this join is not yet evaluated, we still must clean it up to
 
7974
        close its table cursors -- it may never get evaluated, as in case of
 
7975
        ... HAVING false OR a IN (SELECT ...))
 
7976
        but all table cursors must be closed before the unlock.
 
7977
      */
 
7978
      sl->cleanup_all_joins(full_local);
 
7979
      /* Can't unlock if at least one JOIN is still needed */
 
7980
      can_unlock= can_unlock && full_local;
 
7981
    }
 
7982
 
 
7983
  /*
 
7984
    We are not using tables anymore
 
7985
    Unlock all tables. We may be in an INSERT .... SELECT statement.
 
7986
  */
 
7987
  if (can_unlock && lock && session->lock &&
 
7988
      !(select_options & SELECT_NO_UNLOCK) &&
 
7989
      !select_lex->subquery_in_having &&
 
7990
      (select_lex == (session->lex->unit.fake_select_lex ?
 
7991
                      session->lex->unit.fake_select_lex : &session->lex->select_lex)))
 
7992
  {
 
7993
    /*
 
7994
      TODO: unlock tables even if the join isn't top level select in the
 
7995
      tree.
 
7996
    */
 
7997
    mysql_unlock_read_tables(session, lock);           // Don't free join->lock
 
7998
    lock= 0;
 
7999
  }
 
8000
 
 
8001
  return;
 
8002
}
 
8003
 
 
8004
 
 
8005
/**
 
8006
  Free resources of given join.
 
8007
 
 
8008
  @param fill   true if we should free all resources, call with full==1
 
8009
                should be last, before it this function can be called with
 
8010
                full==0
 
8011
 
 
8012
  @note
 
8013
    With subquery this function definitely will be called several times,
 
8014
    but even for simple query it can be called several times.
 
8015
*/
 
8016
 
 
8017
void JOIN::cleanup(bool full)
 
8018
{
 
8019
  if (table)
 
8020
  {
 
8021
    JOIN_TAB *tab,*end;
 
8022
    /*
 
8023
      Only a sorted table may be cached.  This sorted table is always the
 
8024
      first non const table in join->table
 
8025
    */
 
8026
    if (tables > const_tables) // Test for not-const tables
 
8027
    {
 
8028
      free_io_cache(table[const_tables]);
 
8029
      filesort_free_buffers(table[const_tables],full);
 
8030
    }
 
8031
 
 
8032
    if (full)
 
8033
    {
 
8034
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
 
8035
        tab->cleanup();
 
8036
      table= 0;
 
8037
    }
 
8038
    else
 
8039
    {
 
8040
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
 
8041
      {
 
8042
        if (tab->table)
 
8043
          tab->table->file->ha_index_or_rnd_end();
 
8044
      }
 
8045
    }
 
8046
    cleanup_sj_tmp_tables(this);//
 
8047
  }
 
8048
  /*
 
8049
    We are not using tables anymore
 
8050
    Unlock all tables. We may be in an INSERT .... SELECT statement.
 
8051
  */
 
8052
  if (full)
 
8053
  {
 
8054
    if (tmp_join)
 
8055
      tmp_table_param.copy_field= 0;
 
8056
    group_fields.delete_elements();
 
8057
    /*
 
8058
      We can't call delete_elements() on copy_funcs as this will cause
 
8059
      problems in free_elements() as some of the elements are then deleted.
 
8060
    */
 
8061
    tmp_table_param.copy_funcs.empty();
 
8062
    /*
 
8063
      If we have tmp_join and 'this' JOIN is not tmp_join and
 
8064
      tmp_table_param.copy_field's  of them are equal then we have to remove
 
8065
      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
 
8066
      be removed in tmp_table_param.cleanup().
 
8067
    */
 
8068
    if (tmp_join &&
 
8069
        tmp_join != this &&
 
8070
        tmp_join->tmp_table_param.copy_field ==
 
8071
        tmp_table_param.copy_field)
 
8072
    {
 
8073
      tmp_join->tmp_table_param.copy_field=
 
8074
        tmp_join->tmp_table_param.save_copy_field= 0;
 
8075
    }
 
8076
    tmp_table_param.cleanup();
 
8077
  }
 
8078
  return;
 
8079
}
 
8080
 
 
8081
 
 
8082
/**
 
8083
  Remove the following expressions from order_st BY and GROUP BY:
1261
8084
  Constant expressions @n
1262
8085
  Expression that only uses tables that are of type EQ_REF and the reference
1263
8086
  is in the order_st list or if all refereed tables are of the above type.
1264
8087
 
1265
8088
  In the following, the X field can be removed:
1266
8089
  @code
1267
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
1268
 
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
 
8090
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
 
8091
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1269
8092
  @endcode
1270
8093
 
1271
8094
  These can't be optimized:
1272
8095
  @code
1273
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
1274
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
1275
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
 
8096
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
 
8097
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
 
8098
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1276
8099
  @endcode
1277
8100
*/
1278
 
bool eq_ref_table(Join *join, Order *start_order, JoinTable *tab)
 
8101
 
 
8102
static bool
 
8103
eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
1279
8104
{
1280
8105
  if (tab->cached_eq_ref_table)                 // If cached
1281
8106
    return tab->eq_ref_table;
1282
8107
  tab->cached_eq_ref_table=1;
1283
8108
  /* We can skip const tables only if not an outer table */
1284
 
  if (tab->type == AM_CONST && !tab->first_inner)
1285
 
    return (tab->eq_ref_table=1);
1286
 
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
 
8109
  if (tab->type == JT_CONST && !tab->first_inner)
 
8110
    return (tab->eq_ref_table=1);               /* purecov: inspected */
 
8111
  if (tab->type != JT_EQ_REF || tab->table->maybe_null)
1287
8112
    return (tab->eq_ref_table=0);               // We must use this
1288
8113
  Item **ref_item=tab->ref.items;
1289
8114
  Item **end=ref_item+tab->ref.key_parts;
1294
8119
  {
1295
8120
    if (! (*ref_item)->const_item())
1296
8121
    {                                           // Not a const ref
1297
 
      Order *order;
 
8122
      order_st *order;
1298
8123
      for (order=start_order ; order ; order=order->next)
1299
8124
      {
1300
 
        if ((*ref_item)->eq(order->item[0],0))
1301
 
          break;
 
8125
        if ((*ref_item)->eq(order->item[0],0))
 
8126
          break;
1302
8127
      }
1303
8128
      if (order)
1304
8129
      {
1305
 
        found++;
1306
 
        assert(!(order->used & map));
1307
 
        order->used|=map;
1308
 
        continue;                               // Used in order_st BY
 
8130
        found++;
 
8131
        assert(!(order->used & map));
 
8132
        order->used|=map;
 
8133
        continue;                               // Used in order_st BY
1309
8134
      }
1310
8135
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
1311
 
        return (tab->eq_ref_table= 0);
 
8136
        return (tab->eq_ref_table=0);
1312
8137
    }
1313
8138
  }
1314
8139
  /* Check that there was no reference to table before sort order */
1320
8145
      continue;
1321
8146
    }
1322
8147
    if (start_order->depend_map & map)
1323
 
      return (tab->eq_ref_table= 0);
1324
 
  }
1325
 
  return tab->eq_ref_table= 1;
1326
 
}
 
8148
      return (tab->eq_ref_table=0);
 
8149
  }
 
8150
  return tab->eq_ref_table=1;
 
8151
}
 
8152
 
 
8153
 
 
8154
static bool
 
8155
only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
 
8156
{
 
8157
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
 
8158
  {
 
8159
    if (tables & 1 && !eq_ref_table(join, order, *tab))
 
8160
      return 0;
 
8161
  }
 
8162
  return 1;
 
8163
}
 
8164
 
 
8165
 
 
8166
/** Update the dependency map for the tables. */
 
8167
 
 
8168
static void update_depend_map(JOIN *join)
 
8169
{
 
8170
  JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables;
 
8171
 
 
8172
  for (; join_tab != end ; join_tab++)
 
8173
  {
 
8174
    TABLE_REF *ref= &join_tab->ref;
 
8175
    table_map depend_map=0;
 
8176
    Item **item=ref->items;
 
8177
    uint32_t i;
 
8178
    for (i=0 ; i < ref->key_parts ; i++,item++)
 
8179
      depend_map|=(*item)->used_tables();
 
8180
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
 
8181
    depend_map&= ~OUTER_REF_TABLE_BIT;
 
8182
    for (JOIN_TAB **tab=join->map2table;
 
8183
         depend_map ;
 
8184
         tab++,depend_map>>=1 )
 
8185
    {
 
8186
      if (depend_map & 1)
 
8187
        ref->depend_map|=(*tab)->ref.depend_map;
 
8188
    }
 
8189
  }
 
8190
}
 
8191
 
 
8192
 
 
8193
/** Update the dependency map for the sort order. */
 
8194
 
 
8195
static void update_depend_map(JOIN *join, order_st *order)
 
8196
{
 
8197
  for (; order ; order=order->next)
 
8198
  {
 
8199
    table_map depend_map;
 
8200
    order->item[0]->update_used_tables();
 
8201
    order->depend_map=depend_map=order->item[0]->used_tables();
 
8202
    // Not item_sum(), RAND() and no reference to table outside of sub select
 
8203
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT))
 
8204
        && !order->item[0]->with_sum_func)
 
8205
    {
 
8206
      for (JOIN_TAB **tab=join->map2table;
 
8207
           depend_map ;
 
8208
           tab++, depend_map>>=1)
 
8209
      {
 
8210
        if (depend_map & 1)
 
8211
          order->depend_map|=(*tab)->ref.depend_map;
 
8212
      }
 
8213
    }
 
8214
  }
 
8215
}
 
8216
 
 
8217
 
 
8218
/**
 
8219
  Remove all constants and check if order_st only contains simple
 
8220
  expressions.
 
8221
 
 
8222
  simple_order is set to 1 if sort_order only uses fields from head table
 
8223
  and the head table is not a LEFT JOIN table.
 
8224
 
 
8225
  @param join                   Join handler
 
8226
  @param first_order            List of SORT or GROUP order
 
8227
  @param cond                   WHERE statement
 
8228
  @param change_list            Set to 1 if we should remove things from list.
 
8229
                               If this is not set, then only simple_order is
 
8230
                               calculated.
 
8231
  @param simple_order           Set to 1 if we are only using simple expressions
 
8232
 
 
8233
  @return
 
8234
    Returns new sort order
 
8235
*/
 
8236
 
 
8237
static order_st *
 
8238
remove_constants(JOIN *join,order_st *first_order, COND *cond,
 
8239
                 bool change_list, bool *simple_order)
 
8240
{
 
8241
  if (join->tables == join->const_tables)
 
8242
    return change_list ? 0 : first_order;               // No need to sort
 
8243
 
 
8244
  order_st *order,**prev_ptr;
 
8245
  table_map first_table= join->join_tab[join->const_tables].table->map;
 
8246
  table_map not_const_tables= ~join->const_table_map;
 
8247
  table_map ref;
 
8248
 
 
8249
  prev_ptr= &first_order;
 
8250
  *simple_order= *join->join_tab[join->const_tables].on_expr_ref ? 0 : 1;
 
8251
 
 
8252
  /* NOTE: A variable of not_const_tables ^ first_table; breaks gcc 2.7 */
 
8253
 
 
8254
  update_depend_map(join, first_order);
 
8255
  for (order=first_order; order ; order=order->next)
 
8256
  {
 
8257
    table_map order_tables=order->item[0]->used_tables();
 
8258
    if (order->item[0]->with_sum_func)
 
8259
      *simple_order=0;                          // Must do a temp table to sort
 
8260
    else if (!(order_tables & not_const_tables))
 
8261
    {
 
8262
      if (order->item[0]->with_subselect)
 
8263
        order->item[0]->val_str(&order->item[0]->str_value);
 
8264
      continue;                                 // skip const item
 
8265
    }
 
8266
    else
 
8267
    {
 
8268
      if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))
 
8269
        *simple_order=0;
 
8270
      else
 
8271
      {
 
8272
        Item *comp_item=0;
 
8273
        if (cond && const_expression_in_where(cond,order->item[0], &comp_item))
 
8274
        {
 
8275
          continue;
 
8276
        }
 
8277
        if ((ref=order_tables & (not_const_tables ^ first_table)))
 
8278
        {
 
8279
          if (!(order_tables & first_table) &&
 
8280
              only_eq_ref_tables(join,first_order, ref))
 
8281
          {
 
8282
            continue;
 
8283
          }
 
8284
          *simple_order=0;                      // Must do a temp table to sort
 
8285
        }
 
8286
      }
 
8287
    }
 
8288
    if (change_list)
 
8289
      *prev_ptr= order;                         // use this entry
 
8290
    prev_ptr= &order->next;
 
8291
  }
 
8292
  if (change_list)
 
8293
    *prev_ptr=0;
 
8294
  if (prev_ptr == &first_order)                 // Nothing to sort/group
 
8295
    *simple_order=1;
 
8296
  return(first_order);
 
8297
}
 
8298
 
 
8299
 
 
8300
static int
 
8301
return_zero_rows(JOIN *join, select_result *result,TableList *tables,
 
8302
                 List<Item> &fields, bool send_row, uint64_t select_options,
 
8303
                 const char *info, Item *having)
 
8304
{
 
8305
  if (select_options & SELECT_DESCRIBE)
 
8306
  {
 
8307
    select_describe(join, false, false, false, info);
 
8308
    return(0);
 
8309
  }
 
8310
 
 
8311
  join->join_free();
 
8312
 
 
8313
  if (send_row)
 
8314
  {
 
8315
    for (TableList *table= tables; table; table= table->next_leaf)
 
8316
      mark_as_null_row(table->table);           // All fields are NULL
 
8317
    if (having && having->val_int() == 0)
 
8318
      send_row=0;
 
8319
  }
 
8320
  if (!(result->send_fields(fields,
 
8321
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)))
 
8322
  {
 
8323
    if (send_row)
 
8324
    {
 
8325
      List_iterator_fast<Item> it(fields);
 
8326
      Item *item;
 
8327
      while ((item= it++))
 
8328
        item->no_rows_in_result();
 
8329
      result->send_data(fields);
 
8330
    }
 
8331
    result->send_eof();                         // Should be safe
 
8332
  }
 
8333
  /* Update results for FOUND_ROWS */
 
8334
  join->session->limit_found_rows= join->session->examined_row_count= 0;
 
8335
  return(0);
 
8336
}
 
8337
 
 
8338
/*
 
8339
  used only in JOIN::clear
 
8340
*/
 
8341
static void clear_tables(JOIN *join)
 
8342
{
 
8343
  /*
 
8344
    must clear only the non-const tables, as const tables
 
8345
    are not re-calculated.
 
8346
  */
 
8347
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
8348
    mark_as_null_row(join->table[i]);           // All fields are NULL
 
8349
}
 
8350
 
 
8351
/*****************************************************************************
 
8352
  Make som simple condition optimization:
 
8353
  If there is a test 'field = const' change all refs to 'field' to 'const'
 
8354
  Remove all dummy tests 'item = item', 'const op const'.
 
8355
  Remove all 'item is NULL', when item can never be null!
 
8356
  item->marker should be 0 for all items on entry
 
8357
  Return in cond_value false if condition is impossible (1 = 2)
 
8358
*****************************************************************************/
 
8359
 
 
8360
class COND_CMP :public ilink {
 
8361
public:
 
8362
  static void *operator new(size_t size)
 
8363
  {
 
8364
    return (void*) sql_alloc((uint32_t) size);
 
8365
  }
 
8366
  static void operator delete(void *, size_t)
 
8367
  { TRASH(ptr, size); }
 
8368
 
 
8369
  Item *and_level;
 
8370
  Item_func *cmp_func;
 
8371
  COND_CMP(Item *a,Item_func *b) :and_level(a),cmp_func(b) {}
 
8372
};
 
8373
 
 
8374
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
 
8375
template class I_List<COND_CMP>;
 
8376
template class I_List_iterator<COND_CMP>;
 
8377
#endif
 
8378
 
1327
8379
 
1328
8380
/**
1329
8381
  Find the multiple equality predicate containing a field.
1343
8395
    - Item_equal for the found multiple equality predicate if a success;
1344
8396
    - NULL otherwise.
1345
8397
*/
1346
 
static Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
 
8398
 
 
8399
Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field,
 
8400
                            bool *inherited_fl)
1347
8401
{
1348
8402
  Item_equal *item= 0;
1349
8403
  bool in_upper_level= false;
1364
8418
  return item;
1365
8419
}
1366
8420
 
 
8421
 
1367
8422
/**
1368
8423
  Check whether an equality can be used to build multiple equalities.
1369
8424
 
1445
8500
  @retval
1446
8501
    false   otherwise
1447
8502
*/
1448
 
static bool check_simple_equality(Item *left_item,
1449
 
                                  Item *right_item,
1450
 
                                  Item *item,
1451
 
                                  COND_EQUAL *cond_equal)
 
8503
 
 
8504
static bool check_simple_equality(Item *left_item, Item *right_item,
 
8505
                                  Item *item, COND_EQUAL *cond_equal)
1452
8506
{
1453
8507
  if (left_item->type() == Item::FIELD_ITEM &&
1454
8508
      right_item->type() == Item::FIELD_ITEM &&
1609
8663
  return false;
1610
8664
}
1611
8665
 
 
8666
 
1612
8667
/**
1613
8668
  Convert row equalities into a conjunction of regular equalities.
1614
8669
 
1634
8689
  @retval
1635
8690
    false   otherwise
1636
8691
*/
1637
 
static bool check_row_equality(Session *session,
1638
 
                               Item *left_row, 
1639
 
                               Item_row *right_row,
1640
 
                               COND_EQUAL *cond_equal,
1641
 
                               List<Item>* eq_list)
 
8692
 
 
8693
static bool check_row_equality(Session *session, Item *left_row, Item_row *right_row,
 
8694
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
1642
8695
{
1643
8696
  uint32_t n= left_row->cols();
1644
8697
  for (uint32_t i= 0 ; i < n; i++)
1675
8728
  return true;
1676
8729
}
1677
8730
 
 
8731
 
1678
8732
/**
1679
8733
  Eliminate row equalities and form multiple equalities predicates.
1680
8734
 
1704
8758
           or, if the equality is neither a simple one nor a row equality,
1705
8759
           or, if the procedure fails by a fatal error.
1706
8760
*/
1707
 
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal, List<Item> *eq_list)
 
8761
 
 
8762
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal,
 
8763
                           List<Item> *eq_list)
1708
8764
{
1709
8765
  if (item->type() == Item::FUNC_ITEM &&
1710
8766
         ((Item_func*) item)->functype() == Item_func::EQ_FUNC)
1727
8783
  return false;
1728
8784
}
1729
8785
 
 
8786
 
1730
8787
/**
1731
8788
  Replace all equality predicates in a condition by multiple equality items.
1732
8789
 
1790
8847
  @return
1791
8848
    pointer to the transformed condition
1792
8849
*/
1793
 
static COND *build_equal_items_for_cond(Session *session, COND *cond, COND_EQUAL *inherited)
 
8850
 
 
8851
static COND *build_equal_items_for_cond(Session *session, COND *cond,
 
8852
                                        COND_EQUAL *inherited)
1794
8853
{
1795
8854
  Item_equal *item_equal;
1796
8855
  COND_EQUAL cond_equal;
1886
8945
        {
1887
8946
          item_equal->fix_length_and_dec();
1888
8947
          item_equal->update_used_tables();
1889
 
        }
 
8948
        }
1890
8949
        else
1891
8950
          item_equal= (Item_equal *) eq_list.pop();
1892
8951
        set_if_bigger(session->lex->current_select->max_equal_elems,
1898
8957
        /*
1899
8958
          Here a new AND level must be created. It can happen only
1900
8959
          when a row equality is processed as a standalone predicate.
1901
 
        */
 
8960
        */
1902
8961
        Item_cond_and *and_cond= new Item_cond_and(eq_list);
1903
8962
        and_cond->quick_fix_field();
1904
8963
        List<Item> *args= and_cond->argument_list();
1932
8991
  return cond;
1933
8992
}
1934
8993
 
 
8994
 
1935
8995
/**
1936
8996
  Build multiple equalities for a condition and all on expressions that
1937
8997
  inherit these multiple equalities.
1986
9046
    can get more freedom in performing join operations.
1987
9047
    Althogh we don't use this property now, it probably makes sense to use
1988
9048
    it in the future.
1989
 
  @param session                      Thread Cursor
 
9049
  @param session                      Thread handler
1990
9050
  @param cond                condition to build the multiple equalities for
1991
9051
  @param inherited           path to all inherited multiple equality items
1992
9052
  @param join_list           list of join tables to which the condition
1997
9057
  @return
1998
9058
    pointer to the transformed condition containing multiple equalities
1999
9059
*/
 
9060
 
2000
9061
static COND *build_equal_items(Session *session, COND *cond,
2001
9062
                               COND_EQUAL *inherited,
2002
9063
                               List<TableList> *join_list,
2034
9095
    {
2035
9096
      if (table->on_expr)
2036
9097
      {
2037
 
        List<TableList> *nested_join_list= table->getNestedJoin() ?
2038
 
          &table->getNestedJoin()->join_list : NULL;
 
9098
        List<TableList> *nested_join_list= table->nested_join ?
 
9099
          &table->nested_join->join_list : NULL;
2039
9100
        /*
2040
9101
          We can modify table->on_expr because its old value will
2041
9102
          be restored before re-execution of PS/SP.
2050
9111
  return cond;
2051
9112
}
2052
9113
 
 
9114
 
2053
9115
/**
2054
9116
  Compare field items by table order in the execution plan.
2055
9117
 
2069
9131
  @retval
2070
9132
    0  otherwise
2071
9133
*/
 
9134
 
2072
9135
static int compare_fields_by_table_order(Item_field *field1,
2073
 
                                         Item_field *field2,
2074
 
                                         void *table_join_idx)
 
9136
                                  Item_field *field2,
 
9137
                                  void *table_join_idx)
2075
9138
{
2076
9139
  int cmp= 0;
2077
9140
  bool outer_ref= 0;
2087
9150
  }
2088
9151
  if (outer_ref)
2089
9152
    return cmp;
2090
 
  JoinTable **idx= (JoinTable **) table_join_idx;
2091
 
  cmp= idx[field2->field->getTable()->tablenr]-idx[field1->field->getTable()->tablenr];
 
9153
  JOIN_TAB **idx= (JOIN_TAB **) table_join_idx;
 
9154
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2092
9155
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2093
9156
}
2094
9157
 
 
9158
 
2095
9159
/**
2096
9160
  Generate minimal set of simple equalities equivalent to a multiple equality.
2097
9161
 
2131
9195
    a pointer to the simple generated equality, if success.
2132
9196
    - 0, otherwise.
2133
9197
*/
2134
 
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels, Item_equal *item_equal)
 
9198
 
 
9199
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels,
 
9200
                                  Item_equal *item_equal)
2135
9201
{
2136
9202
  List<Item> eq_list;
2137
9203
  Item_func_eq *eq_item= 0;
2201
9267
  return cond;
2202
9268
}
2203
9269
 
 
9270
 
2204
9271
/**
2205
9272
  Substitute every field reference in a condition by the best equal field
2206
9273
  and eliminate all multiple equality predicates.
2228
9295
  @return
2229
9296
    The transformed condition
2230
9297
*/
2231
 
COND* substitute_for_best_equal_field(COND *cond, COND_EQUAL *cond_equal, void *table_join_idx)
 
9298
 
 
9299
static COND* substitute_for_best_equal_field(COND *cond,
 
9300
                                             COND_EQUAL *cond_equal,
 
9301
                                             void *table_join_idx)
2232
9302
{
2233
9303
  Item_equal *item_equal;
2234
9304
 
2296
9366
  return cond;
2297
9367
}
2298
9368
 
 
9369
 
2299
9370
/**
2300
9371
  Check appearance of new constant items in multiple equalities
2301
9372
  of a condition after reading a constant table.
2308
9379
  @param cond       condition whose multiple equalities are to be checked
2309
9380
  @param table      constant table that has been read
2310
9381
*/
2311
 
void update_const_equal_items(COND *cond, JoinTable *tab)
 
9382
 
 
9383
static void update_const_equal_items(COND *cond, JOIN_TAB *tab)
2312
9384
{
2313
9385
  if (!(cond->used_tables() & tab->table->map))
2314
9386
    return;
2335
9407
      while ((item_field= it++))
2336
9408
      {
2337
9409
        Field *field= item_field->field;
2338
 
        JoinTable *stat= field->getTable()->reginfo.join_tab;
 
9410
        JOIN_TAB *stat= field->table->reginfo.join_tab;
2339
9411
        key_map possible_keys= field->key_start;
2340
 
        possible_keys&= field->getTable()->keys_in_use_for_query;
2341
 
        stat[0].const_keys|= possible_keys;
 
9412
        possible_keys.intersect(field->table->keys_in_use_for_query);
 
9413
        stat[0].const_keys.merge(possible_keys);
2342
9414
 
2343
9415
        /*
2344
9416
          For each field in the multiple equality (for which we know that it
2345
9417
          is a constant) we have to find its corresponding key part, and set
2346
9418
          that key part in const_key_parts.
2347
9419
        */
2348
 
        if (possible_keys.any())
 
9420
        if (!possible_keys.is_clear_all())
2349
9421
        {
2350
 
          Table *field_tab= field->getTable();
2351
 
          optimizer::KeyUse *use;
2352
 
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
2353
 
            if (possible_keys.test(use->getKey()) &&
2354
 
                field_tab->key_info[use->getKey()].key_part[use->getKeypart()].field ==
 
9422
          Table *field_tab= field->table;
 
9423
          KEYUSE *use;
 
9424
          for (use= stat->keyuse; use && use->table == field_tab; use++)
 
9425
            if (possible_keys.is_set(use->key) &&
 
9426
                field_tab->key_info[use->key].key_part[use->keypart].field ==
2355
9427
                field)
2356
 
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
9428
              field_tab->const_key_parts[use->key]|= use->keypart_map;
2357
9429
        }
2358
9430
      }
2359
9431
    }
2360
9432
  }
2361
9433
}
2362
9434
 
 
9435
 
2363
9436
/*
2364
9437
  change field = field to field = const for each found field = const in the
2365
9438
  and_level
2366
9439
*/
2367
 
static void change_cond_ref_to_const(Session *session,
2368
 
                                     list<COND_CMP>& save_list,
2369
 
                                     Item *and_father,
2370
 
                                     Item *cond,
2371
 
                                     Item *field,
2372
 
                                     Item *value)
 
9440
 
 
9441
static void
 
9442
change_cond_ref_to_const(Session *session, I_List<COND_CMP> *save_list,
 
9443
                         Item *and_father, Item *cond,
 
9444
                         Item *field, Item *value)
2373
9445
{
2374
9446
  if (cond->type() == Item::COND_ITEM)
2375
9447
  {
2376
 
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
 
9448
    bool and_level= ((Item_cond*) cond)->functype() ==
 
9449
      Item_func::COND_AND_FUNC;
2377
9450
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
2378
9451
    Item *item;
2379
9452
    while ((item=li++))
2380
 
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
2381
 
 
 
9453
      change_cond_ref_to_const(session, save_list,and_level ? cond : item, item,
 
9454
                               field, value);
2382
9455
    return;
2383
9456
  }
2384
9457
  if (cond->eq_cmp_result() == Item::COND_OK)
2397
9470
       left_item->collation.collation == value->collation.collation))
2398
9471
  {
2399
9472
    Item *tmp=value->clone_item();
 
9473
    tmp->collation.set(right_item->collation);
 
9474
 
2400
9475
    if (tmp)
2401
9476
    {
2402
 
      tmp->collation.set(right_item->collation);
2403
9477
      session->change_item_tree(args + 1, tmp);
2404
9478
      func->update_used_tables();
2405
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2406
 
                and_father != cond && 
2407
 
          ! left_item->const_item())
 
9479
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
 
9480
          && and_father != cond && !left_item->const_item())
2408
9481
      {
2409
 
        cond->marker=1;
2410
 
        save_list.push_back( COND_CMP(and_father, func) );
 
9482
        cond->marker=1;
 
9483
        COND_CMP *tmp2;
 
9484
        if ((tmp2=new COND_CMP(and_father,func)))
 
9485
          save_list->push_back(tmp2);
2411
9486
      }
2412
9487
      func->set_cmp_func();
2413
9488
    }
2419
9494
            right_item->collation.collation == value->collation.collation))
2420
9495
  {
2421
9496
    Item *tmp= value->clone_item();
 
9497
    tmp->collation.set(left_item->collation);
 
9498
 
2422
9499
    if (tmp)
2423
9500
    {
2424
 
      tmp->collation.set(left_item->collation);
2425
9501
      session->change_item_tree(args, tmp);
2426
9502
      value= tmp;
2427
9503
      func->update_used_tables();
2428
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2429
 
          and_father != cond && 
2430
 
          ! right_item->const_item())
 
9504
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
 
9505
          && and_father != cond && !right_item->const_item())
2431
9506
      {
2432
9507
        args[0]= args[1];                       // For easy check
2433
9508
        session->change_item_tree(args + 1, value);
2434
 
        cond->marker=1;
2435
 
        save_list.push_back( COND_CMP(and_father, func) );
 
9509
        cond->marker=1;
 
9510
        COND_CMP *tmp2;
 
9511
        if ((tmp2=new COND_CMP(and_father,func)))
 
9512
          save_list->push_back(tmp2);
2436
9513
      }
2437
9514
      func->set_cmp_func();
2438
9515
    }
2447
9524
  @return
2448
9525
    new conditions
2449
9526
*/
2450
 
Item *remove_additional_cond(Item* conds)
 
9527
 
 
9528
static Item *remove_additional_cond(Item* conds)
2451
9529
{
2452
9530
  if (conds->name == in_additional_cond)
2453
9531
    return 0;
2470
9548
  return conds;
2471
9549
}
2472
9550
 
2473
 
static void propagate_cond_constants(Session *session, 
2474
 
                                     list<COND_CMP>& save_list, 
2475
 
                                     COND *and_father, 
2476
 
                                     COND *cond)
 
9551
static void
 
9552
propagate_cond_constants(Session *session, I_List<COND_CMP> *save_list,
 
9553
                         COND *and_father, COND *cond)
2477
9554
{
2478
9555
  if (cond->type() == Item::COND_ITEM)
2479
9556
  {
2480
 
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
 
9557
    bool and_level= ((Item_cond*) cond)->functype() ==
 
9558
      Item_func::COND_AND_FUNC;
2481
9559
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
2482
9560
    Item *item;
2483
 
    list<COND_CMP> save;
 
9561
    I_List<COND_CMP> save;
2484
9562
    while ((item=li++))
2485
9563
    {
2486
 
      propagate_cond_constants(session, save, and_level ? cond : item, item);
 
9564
      propagate_cond_constants(session, &save,and_level ? cond : item, item);
2487
9565
    }
2488
9566
    if (and_level)
2489
 
    {
2490
 
      // Handle other found items
2491
 
      for (list<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
 
9567
    {                                           // Handle other found items
 
9568
      I_List_iterator<COND_CMP> cond_itr(save);
 
9569
      COND_CMP *cond_cmp;
 
9570
      while ((cond_cmp=cond_itr++))
2492
9571
      {
2493
 
        Item **args= iter->second->arguments();
2494
 
        if (not args[0]->const_item())
2495
 
        {
2496
 
          change_cond_ref_to_const(session, save, iter->first,
2497
 
                                   iter->first, args[0], args[1] );
2498
 
        }
 
9572
        Item **args= cond_cmp->cmp_func->arguments();
 
9573
        if (!args[0]->const_item())
 
9574
          change_cond_ref_to_const(session, &save,cond_cmp->and_level,
 
9575
                                   cond_cmp->and_level, args[0], args[1]);
2499
9576
      }
2500
9577
    }
2501
9578
  }
2502
9579
  else if (and_father != cond && !cond->marker)         // In a AND group
2503
9580
  {
2504
9581
    if (cond->type() == Item::FUNC_ITEM &&
2505
 
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
2506
 
        ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
 
9582
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
 
9583
         ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
2507
9584
    {
2508
9585
      Item_func_eq *func=(Item_func_eq*) cond;
2509
9586
      Item **args= func->arguments();
2512
9589
      if (!(left_const && right_const) &&
2513
9590
          args[0]->result_type() == args[1]->result_type())
2514
9591
      {
2515
 
        if (right_const)
2516
 
        {
2517
 
                resolve_const_item(session, &args[1], args[0]);
2518
 
          func->update_used_tables();
2519
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2520
 
                                        args[0], args[1]);
2521
 
        }
2522
 
        else if (left_const)
2523
 
        {
2524
 
                resolve_const_item(session, &args[0], args[1]);
2525
 
          func->update_used_tables();
2526
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2527
 
                                        args[1], args[0]);
2528
 
        }
2529
 
      }
2530
 
    }
2531
 
  }
2532
 
}
 
9592
        if (right_const)
 
9593
        {
 
9594
          resolve_const_item(session, &args[1], args[0]);
 
9595
          func->update_used_tables();
 
9596
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
9597
                                   args[0], args[1]);
 
9598
        }
 
9599
        else if (left_const)
 
9600
        {
 
9601
          resolve_const_item(session, &args[0], args[1]);
 
9602
          func->update_used_tables();
 
9603
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
9604
                                   args[1], args[0]);
 
9605
        }
 
9606
      }
 
9607
    }
 
9608
  }
 
9609
}
 
9610
 
 
9611
 
 
9612
/**
 
9613
  Simplify joins replacing outer joins by inner joins whenever it's
 
9614
  possible.
 
9615
 
 
9616
    The function, during a retrieval of join_list,  eliminates those
 
9617
    outer joins that can be converted into inner join, possibly nested.
 
9618
    It also moves the on expressions for the converted outer joins
 
9619
    and from inner joins to conds.
 
9620
    The function also calculates some attributes for nested joins:
 
9621
    - used_tables
 
9622
    - not_null_tables
 
9623
    - dep_tables.
 
9624
    - on_expr_dep_tables
 
9625
    The first two attributes are used to test whether an outer join can
 
9626
    be substituted for an inner join. The third attribute represents the
 
9627
    relation 'to be dependent on' for tables. If table t2 is dependent
 
9628
    on table t1, then in any evaluated execution plan table access to
 
9629
    table t2 must precede access to table t2. This relation is used also
 
9630
    to check whether the query contains  invalid cross-references.
 
9631
    The forth attribute is an auxiliary one and is used to calculate
 
9632
    dep_tables.
 
9633
    As the attribute dep_tables qualifies possibles orders of tables in the
 
9634
    execution plan, the dependencies required by the straight join
 
9635
    modifiers are reflected in this attribute as well.
 
9636
    The function also removes all braces that can be removed from the join
 
9637
    expression without changing its meaning.
 
9638
 
 
9639
  @note
 
9640
    An outer join can be replaced by an inner join if the where condition
 
9641
    or the on expression for an embedding nested join contains a conjunctive
 
9642
    predicate rejecting null values for some attribute of the inner tables.
 
9643
 
 
9644
    E.g. in the query:
 
9645
    @code
 
9646
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
 
9647
    @endcode
 
9648
    the predicate t2.b < 5 rejects nulls.
 
9649
    The query is converted first to:
 
9650
    @code
 
9651
      SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
 
9652
    @endcode
 
9653
    then to the equivalent form:
 
9654
    @code
 
9655
      SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a
 
9656
    @endcode
 
9657
 
 
9658
 
 
9659
    Similarly the following query:
 
9660
    @code
 
9661
      SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b
 
9662
        WHERE t2.c < 5
 
9663
    @endcode
 
9664
    is converted to:
 
9665
    @code
 
9666
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b
 
9667
 
 
9668
    @endcode
 
9669
 
 
9670
    One conversion might trigger another:
 
9671
    @code
 
9672
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a
 
9673
                       LEFT JOIN t3 ON t3.b=t2.b
 
9674
        WHERE t3 IS NOT NULL =>
 
9675
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3
 
9676
        WHERE t3 IS NOT NULL AND t3.b=t2.b =>
 
9677
      SELECT * FROM t1, t2, t3
 
9678
        WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a
 
9679
  @endcode
 
9680
 
 
9681
    The function removes all unnecessary braces from the expression
 
9682
    produced by the conversions.
 
9683
    E.g.
 
9684
    @code
 
9685
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
 
9686
    @endcode
 
9687
    finally is converted to:
 
9688
    @code
 
9689
      SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
 
9690
 
 
9691
    @endcode
 
9692
 
 
9693
 
 
9694
    It also will remove braces from the following queries:
 
9695
    @code
 
9696
      SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b
 
9697
      SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b.
 
9698
    @endcode
 
9699
 
 
9700
    The benefit of this simplification procedure is that it might return
 
9701
    a query for which the optimizer can evaluate execution plan with more
 
9702
    join orders. With a left join operation the optimizer does not
 
9703
    consider any plan where one of the inner tables is before some of outer
 
9704
    tables.
 
9705
 
 
9706
  IMPLEMENTATION
 
9707
    The function is implemented by a recursive procedure.  On the recursive
 
9708
    ascent all attributes are calculated, all outer joins that can be
 
9709
    converted are replaced and then all unnecessary braces are removed.
 
9710
    As join list contains join tables in the reverse order sequential
 
9711
    elimination of outer joins does not require extra recursive calls.
 
9712
 
 
9713
  SEMI-JOIN NOTES
 
9714
    Remove all semi-joins that have are within another semi-join (i.e. have
 
9715
    an "ancestor" semi-join nest)
 
9716
 
 
9717
  EXAMPLES
 
9718
    Here is an example of a join query with invalid cross references:
 
9719
    @code
 
9720
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b
 
9721
    @endcode
 
9722
 
 
9723
  @param join        reference to the query info
 
9724
  @param join_list   list representation of the join to be converted
 
9725
  @param conds       conditions to add on expressions for converted joins
 
9726
  @param top         true <=> conds is the where condition
 
9727
 
 
9728
  @return
 
9729
    - The new condition, if success
 
9730
    - 0, otherwise
 
9731
*/
 
9732
 
 
9733
static COND *
 
9734
simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top,
 
9735
               bool in_sj)
 
9736
{
 
9737
  TableList *table;
 
9738
  nested_join_st *nested_join;
 
9739
  TableList *prev_table= 0;
 
9740
  List_iterator<TableList> li(*join_list);
 
9741
 
 
9742
  /*
 
9743
    Try to simplify join operations from join_list.
 
9744
    The most outer join operation is checked for conversion first.
 
9745
  */
 
9746
  while ((table= li++))
 
9747
  {
 
9748
    table_map used_tables;
 
9749
    table_map not_null_tables= (table_map) 0;
 
9750
 
 
9751
    if ((nested_join= table->nested_join))
 
9752
    {
 
9753
      /*
 
9754
         If the element of join_list is a nested join apply
 
9755
         the procedure to its nested join list first.
 
9756
      */
 
9757
      if (table->on_expr)
 
9758
      {
 
9759
        Item *expr= table->on_expr;
 
9760
        /*
 
9761
           If an on expression E is attached to the table,
 
9762
           check all null rejected predicates in this expression.
 
9763
           If such a predicate over an attribute belonging to
 
9764
           an inner table of an embedded outer join is found,
 
9765
           the outer join is converted to an inner join and
 
9766
           the corresponding on expression is added to E.
 
9767
        */
 
9768
        expr= simplify_joins(join, &nested_join->join_list,
 
9769
                             expr, false, in_sj || table->sj_on_expr);
 
9770
 
 
9771
        if (!table->prep_on_expr || expr != table->on_expr)
 
9772
        {
 
9773
          assert(expr);
 
9774
 
 
9775
          table->on_expr= expr;
 
9776
          table->prep_on_expr= expr->copy_andor_structure(join->session);
 
9777
        }
 
9778
      }
 
9779
      nested_join->used_tables= (table_map) 0;
 
9780
      nested_join->not_null_tables=(table_map) 0;
 
9781
      conds= simplify_joins(join, &nested_join->join_list, conds, top,
 
9782
                            in_sj || table->sj_on_expr);
 
9783
      used_tables= nested_join->used_tables;
 
9784
      not_null_tables= nested_join->not_null_tables;
 
9785
    }
 
9786
    else
 
9787
    {
 
9788
      if (!table->prep_on_expr)
 
9789
        table->prep_on_expr= table->on_expr;
 
9790
      used_tables= table->table->map;
 
9791
      if (conds)
 
9792
        not_null_tables= conds->not_null_tables();
 
9793
    }
 
9794
 
 
9795
    if (table->embedding)
 
9796
    {
 
9797
      table->embedding->nested_join->used_tables|= used_tables;
 
9798
      table->embedding->nested_join->not_null_tables|= not_null_tables;
 
9799
    }
 
9800
 
 
9801
    if (!table->outer_join || (used_tables & not_null_tables))
 
9802
    {
 
9803
      /*
 
9804
        For some of the inner tables there are conjunctive predicates
 
9805
        that reject nulls => the outer join can be replaced by an inner join.
 
9806
      */
 
9807
      table->outer_join= 0;
 
9808
      if (table->on_expr)
 
9809
      {
 
9810
        /* Add ON expression to the WHERE or upper-level ON condition. */
 
9811
        if (conds)
 
9812
        {
 
9813
          conds= and_conds(conds, table->on_expr);
 
9814
          conds->top_level_item();
 
9815
          /* conds is always a new item as both cond and on_expr existed */
 
9816
          assert(!conds->fixed);
 
9817
          conds->fix_fields(join->session, &conds);
 
9818
        }
 
9819
        else
 
9820
          conds= table->on_expr;
 
9821
        table->prep_on_expr= table->on_expr= 0;
 
9822
      }
 
9823
    }
 
9824
 
 
9825
    if (!top)
 
9826
      continue;
 
9827
 
 
9828
    /*
 
9829
      Only inner tables of non-convertible outer joins
 
9830
      remain with on_expr.
 
9831
    */
 
9832
    if (table->on_expr)
 
9833
    {
 
9834
      table->dep_tables|= table->on_expr->used_tables();
 
9835
      if (table->embedding)
 
9836
      {
 
9837
        table->dep_tables&= ~table->embedding->nested_join->used_tables;
 
9838
        /*
 
9839
           Embedding table depends on tables used
 
9840
           in embedded on expressions.
 
9841
        */
 
9842
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
 
9843
      }
 
9844
      else
 
9845
        table->dep_tables&= ~table->table->map;
 
9846
    }
 
9847
 
 
9848
    if (prev_table)
 
9849
    {
 
9850
      /* The order of tables is reverse: prev_table follows table */
 
9851
      if (prev_table->straight)
 
9852
        prev_table->dep_tables|= used_tables;
 
9853
      if (prev_table->on_expr)
 
9854
      {
 
9855
        prev_table->dep_tables|= table->on_expr_dep_tables;
 
9856
        table_map prev_used_tables= prev_table->nested_join ?
 
9857
                                    prev_table->nested_join->used_tables :
 
9858
                                    prev_table->table->map;
 
9859
        /*
 
9860
          If on expression contains only references to inner tables
 
9861
          we still make the inner tables dependent on the outer tables.
 
9862
          It would be enough to set dependency only on one outer table
 
9863
          for them. Yet this is really a rare case.
 
9864
        */
 
9865
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
 
9866
          prev_table->dep_tables|= used_tables;
 
9867
      }
 
9868
    }
 
9869
    prev_table= table;
 
9870
  }
 
9871
 
 
9872
  /*
 
9873
    Flatten nested joins that can be flattened.
 
9874
    no ON expression and not a semi-join => can be flattened.
 
9875
  */
 
9876
  li.rewind();
 
9877
  while ((table= li++))
 
9878
  {
 
9879
    nested_join= table->nested_join;
 
9880
    if (table->sj_on_expr && !in_sj)
 
9881
    {
 
9882
       /*
 
9883
         If this is a semi-join that is not contained within another semi-join,
 
9884
         leave it intact (otherwise it is flattened)
 
9885
       */
 
9886
      join->select_lex->sj_nests.push_back(table);
 
9887
    }
 
9888
    else if (nested_join && !table->on_expr)
 
9889
    {
 
9890
      TableList *tbl;
 
9891
      List_iterator<TableList> it(nested_join->join_list);
 
9892
      while ((tbl= it++))
 
9893
      {
 
9894
        tbl->embedding= table->embedding;
 
9895
        tbl->join_list= table->join_list;
 
9896
      }
 
9897
      li.replace(nested_join->join_list);
 
9898
    }
 
9899
  }
 
9900
  return(conds);
 
9901
}
 
9902
 
 
9903
 
 
9904
/**
 
9905
  Assign each nested join structure a bit in nested_join_map.
 
9906
 
 
9907
    Assign each nested join structure (except "confluent" ones - those that
 
9908
    embed only one element) a bit in nested_join_map.
 
9909
 
 
9910
  @param join          Join being processed
 
9911
  @param join_list     List of tables
 
9912
  @param first_unused  Number of first unused bit in nested_join_map before the
 
9913
                       call
 
9914
 
 
9915
  @note
 
9916
    This function is called after simplify_joins(), when there are no
 
9917
    redundant nested joins, #non_confluent_nested_joins <= #tables_in_join so
 
9918
    we will not run out of bits in nested_join_map.
 
9919
 
 
9920
  @return
 
9921
    First unused bit in nested_join_map after the call.
 
9922
*/
 
9923
 
 
9924
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
 
9925
                                          uint32_t first_unused)
 
9926
{
 
9927
  List_iterator<TableList> li(*join_list);
 
9928
  TableList *table;
 
9929
  while ((table= li++))
 
9930
  {
 
9931
    nested_join_st *nested_join;
 
9932
    if ((nested_join= table->nested_join))
 
9933
    {
 
9934
      /*
 
9935
        It is guaranteed by simplify_joins() function that a nested join
 
9936
        that has only one child is either
 
9937
         - a single-table view (the child is the underlying table), or
 
9938
         - a single-table semi-join nest
 
9939
 
 
9940
        We don't assign bits to such sj-nests because
 
9941
        1. it is redundant (a "sequence" of one table cannot be interleaved
 
9942
            with anything)
 
9943
        2. we could run out bits in nested_join_map otherwise.
 
9944
      */
 
9945
      if (nested_join->join_list.elements != 1)
 
9946
      {
 
9947
        /* Don't assign bits to sj-nests */
 
9948
        if (table->on_expr)
 
9949
          nested_join->nj_map= (nested_join_map) 1 << first_unused++;
 
9950
        first_unused= build_bitmap_for_nested_joins(&nested_join->join_list,
 
9951
                                                    first_unused);
 
9952
      }
 
9953
    }
 
9954
  }
 
9955
  return(first_unused);
 
9956
}
 
9957
 
 
9958
 
 
9959
/**
 
9960
  Set nested_join_st::counter=0 in all nested joins in passed list.
 
9961
 
 
9962
    Recursively set nested_join_st::counter=0 for all nested joins contained in
 
9963
    the passed join_list.
 
9964
 
 
9965
  @param join_list  List of nested joins to process. It may also contain base
 
9966
                    tables which will be ignored.
 
9967
*/
 
9968
 
 
9969
static void reset_nj_counters(List<TableList> *join_list)
 
9970
{
 
9971
  List_iterator<TableList> li(*join_list);
 
9972
  TableList *table;
 
9973
  while ((table= li++))
 
9974
  {
 
9975
    nested_join_st *nested_join;
 
9976
    if ((nested_join= table->nested_join))
 
9977
    {
 
9978
      nested_join->counter_= 0;
 
9979
      reset_nj_counters(&nested_join->join_list);
 
9980
    }
 
9981
  }
 
9982
  return;
 
9983
}
 
9984
 
2533
9985
 
2534
9986
/**
2535
9987
  Check interleaving with an inner tables of an outer join for
2607
10059
         position:
2608
10060
          1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested
2609
10061
             joins) we've opened but didn't close.
2610
 
          2. {each NestedJoin class not simplified away}->counter - number
 
10062
          2. {each nested_join_st structure not simplified away}->counter - number
2611
10063
             of this nested join's children that have already been added to to
2612
10064
             the partial join order.
2613
10065
  @endverbatim
2614
10066
 
2615
10067
  @param join       Join being processed
 
10068
  @param last_tab   Last table in current partial join order (this function is
 
10069
                    not called for empty partial join orders)
2616
10070
  @param next_tab   Table we're going to extend the current partial join with
2617
10071
 
2618
10072
  @retval
2621
10075
  @retval
2622
10076
    true   Requested join order extension not allowed.
2623
10077
*/
2624
 
bool check_interleaving_with_nj(JoinTable *next_tab)
 
10078
 
 
10079
static bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
2625
10080
{
2626
 
  TableList *next_emb= next_tab->table->pos_in_table_list->getEmbedding();
2627
 
  Join *join= next_tab->join;
 
10081
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
 
10082
  JOIN *join= last_tab->join;
2628
10083
 
2629
 
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
 
10084
  if (join->cur_embedding_map & ~next_tab->embedding_map)
2630
10085
  {
2631
10086
    /*
2632
10087
      next_tab is outside of the "pair of brackets" we're currently in.
2639
10094
    Do update counters for "pairs of brackets" that we've left (marked as
2640
10095
    X,Y,Z in the above picture)
2641
10096
  */
2642
 
  for (;next_emb; next_emb= next_emb->getEmbedding())
 
10097
  for (;next_emb; next_emb= next_emb->embedding)
2643
10098
  {
2644
 
    next_emb->getNestedJoin()->counter_++;
2645
 
    if (next_emb->getNestedJoin()->counter_ == 1)
 
10099
    next_emb->nested_join->counter_++;
 
10100
    if (next_emb->nested_join->counter_ == 1)
2646
10101
    {
2647
10102
      /*
2648
10103
        next_emb is the first table inside a nested join we've "entered". In
2649
10104
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
2650
10105
        X bracket might have Y pair bracket.
2651
10106
      */
2652
 
      join->cur_embedding_map |= next_emb->getNestedJoin()->nj_map;
 
10107
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
2653
10108
    }
2654
10109
 
2655
 
    if (next_emb->getNestedJoin()->join_list.elements !=
2656
 
        next_emb->getNestedJoin()->counter_)
 
10110
    if (next_emb->nested_join->join_list.elements !=
 
10111
        next_emb->nested_join->counter_)
2657
10112
      break;
2658
10113
 
2659
10114
    /*
2660
10115
      We're currently at Y or Z-bracket as depicted in the above picture.
2661
10116
      Mark that we've left it and continue walking up the brackets hierarchy.
2662
10117
    */
2663
 
    join->cur_embedding_map &= ~next_emb->getNestedJoin()->nj_map;
 
10118
    join->cur_embedding_map &= ~next_emb->nested_join->nj_map;
2664
10119
  }
2665
10120
  return false;
2666
10121
}
2667
10122
 
2668
 
COND *optimize_cond(Join *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
 
10123
 
 
10124
/**
 
10125
  Nested joins perspective: Remove the last table from the join order.
 
10126
 
 
10127
    Remove the last table from the partial join order and update the nested
 
10128
    joins counters and join->cur_embedding_map. It is ok to call this
 
10129
    function for the first table in join order (for which
 
10130
    check_interleaving_with_nj has not been called)
 
10131
 
 
10132
  @param last  join table to remove, it is assumed to be the last in current
 
10133
               partial join order.
 
10134
*/
 
10135
 
 
10136
static void restore_prev_nj_state(JOIN_TAB *last)
 
10137
{
 
10138
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
10139
  JOIN *join= last->join;
 
10140
  while (last_emb)
 
10141
  {
 
10142
    if (last_emb->on_expr)
 
10143
    {
 
10144
      if (!(--last_emb->nested_join->counter_))
 
10145
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
 
10146
      else if (last_emb->nested_join->join_list.elements-1 ==
 
10147
               last_emb->nested_join->counter_)
 
10148
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
 
10149
      else
 
10150
        break;
 
10151
    }
 
10152
    last_emb= last_emb->embedding;
 
10153
  }
 
10154
}
 
10155
 
 
10156
 
 
10157
 
 
10158
static
 
10159
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
 
10160
{
 
10161
  TableList *emb_sj_nest;
 
10162
  if ((emb_sj_nest= tab->emb_sj_nest))
 
10163
  {
 
10164
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
 
10165
    /* Remove the sj_nest if all of its SJ-inner tables are in cur_table_map */
 
10166
    if (!(remaining_tables & emb_sj_nest->sj_inner_tables))
 
10167
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
10168
  }
 
10169
}
 
10170
 
 
10171
 
 
10172
/*
 
10173
  we assume remaining_tables doesnt contain @tab.
 
10174
*/
 
10175
 
 
10176
static void restore_prev_sj_state(const table_map remaining_tables,
 
10177
                                  const JOIN_TAB *tab)
 
10178
{
 
10179
  TableList *emb_sj_nest;
 
10180
  if ((emb_sj_nest= tab->emb_sj_nest))
 
10181
  {
 
10182
    /* If we're removing the last SJ-inner table, remove the sj-nest */
 
10183
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) ==
 
10184
        (emb_sj_nest->sj_inner_tables & ~tab->table->map))
 
10185
    {
 
10186
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
10187
    }
 
10188
  }
 
10189
}
 
10190
 
 
10191
 
 
10192
static COND *
 
10193
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
 
10194
              Item::cond_result *cond_value)
2669
10195
{
2670
10196
  Session *session= join->session;
2671
10197
 
2685
10211
                             &join->cond_equal);
2686
10212
 
2687
10213
    /* change field = field to field = const for each found field = const */
2688
 
    list<COND_CMP> temp;
2689
 
    propagate_cond_constants(session, temp, conds, conds);
 
10214
    propagate_cond_constants(session, (I_List<COND_CMP> *) 0, conds, conds);
2690
10215
    /*
2691
10216
      Remove all instances of item == item
2692
10217
      Remove all and-levels where CONST item != CONST item
2696
10221
  return(conds);
2697
10222
}
2698
10223
 
 
10224
 
2699
10225
/**
2700
10226
  Remove const and eq items.
2701
10227
 
2706
10232
    - COND_TRUE   : always true ( 1 = 1 )
2707
10233
    - COND_FALSE  : always false        ( 1 = 2 )
2708
10234
*/
2709
 
COND *remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
 
10235
 
 
10236
COND *
 
10237
remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
2710
10238
{
2711
10239
  if (cond->type() == Item::COND_ITEM)
2712
10240
  {
2752
10280
          }
2753
10281
          break;
2754
10282
        case Item::COND_UNDEF:                  /* Impossible */
2755
 
          break;
 
10283
          break; /* purecov: deadcode */
2756
10284
      }
2757
10285
    }
2758
10286
 
2788
10316
    {
2789
10317
      Field *field= ((Item_field*) args[0])->field;
2790
10318
      if (field->flags & AUTO_INCREMENT_FLAG 
2791
 
          && ! field->getTable()->maybe_null 
 
10319
          && ! field->table->maybe_null 
2792
10320
          && session->options & OPTION_AUTO_IS_NULL
2793
10321
          && (
2794
10322
            session->first_successful_insert_id_in_prev_stmt > 0 
2846
10374
  /*
2847
10375
    TODO:
2848
10376
    Excluding all expensive functions is too restritive we should exclude only
2849
 
    materialized IN subquery predicates because they can't yet be evaluated
2850
 
    here (they need additional initialization that is done later on).
2851
 
 
2852
 
    The proper way to exclude the subqueries would be to walk the cond tree and
2853
 
    check for materialized subqueries there.
2854
 
 
 
10377
    materialized IN because it is created later than this phase, and cannot be
 
10378
    evaluated at this point.
 
10379
    The condition should be something as (need to fix member access):
 
10380
      !(cond->type() == Item::FUNC_ITEM &&
 
10381
        ((Item_func*)cond)->func_name() == "<in_optimizer>" &&
 
10382
        ((Item_in_optimizer*)cond)->is_expensive()))
2855
10383
  */
2856
10384
  {
2857
10385
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
2895
10423
    true    can be used
2896
10424
    false   cannot be used
2897
10425
*/
2898
 
static bool test_if_equality_guarantees_uniqueness(Item *l, Item *r)
 
10426
static bool
 
10427
test_if_equality_guarantees_uniqueness(Item *l, Item *r)
2899
10428
{
2900
10429
  return r->const_item() &&
2901
10430
    /* elements must be compared as dates */
2910
10439
/**
2911
10440
  Return true if the item is a const value in all the WHERE clause.
2912
10441
*/
2913
 
bool const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
 
10442
 
 
10443
static bool
 
10444
const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
2914
10445
{
2915
10446
  if (cond->type() == Item::COND_ITEM)
2916
10447
  {
2923
10454
      bool res=const_expression_in_where(item, comp_item, const_item);
2924
10455
      if (res)                                  // Is a const value
2925
10456
      {
2926
 
        if (and_level)
2927
 
          return 1;
 
10457
        if (and_level)
 
10458
          return 1;
2928
10459
      }
2929
10460
      else if (!and_level)
2930
 
        return 0;
 
10461
        return 0;
2931
10462
    }
2932
10463
    return and_level ? 0 : 1;
2933
10464
  }
2935
10466
  {                                             // boolan compare function
2936
10467
    Item_func* func= (Item_func*) cond;
2937
10468
    if (func->functype() != Item_func::EQUAL_FUNC &&
2938
 
              func->functype() != Item_func::EQ_FUNC)
 
10469
        func->functype() != Item_func::EQ_FUNC)
2939
10470
      return 0;
2940
10471
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
2941
10472
    Item *right_item= ((Item_func*) cond)->arguments()[1];
2943
10474
    {
2944
10475
      if (test_if_equality_guarantees_uniqueness (left_item, right_item))
2945
10476
      {
2946
 
        if (*const_item)
2947
 
          return right_item->eq(*const_item, 1);
2948
 
        *const_item=right_item;
2949
 
        return 1;
 
10477
        if (*const_item)
 
10478
          return right_item->eq(*const_item, 1);
 
10479
        *const_item=right_item;
 
10480
        return 1;
2950
10481
      }
2951
10482
    }
2952
10483
    else if (right_item->eq(comp_item,1))
2953
10484
    {
2954
10485
      if (test_if_equality_guarantees_uniqueness (right_item, left_item))
2955
10486
      {
2956
 
        if (*const_item)
2957
 
          return left_item->eq(*const_item, 1);
2958
 
        *const_item=left_item;
2959
 
        return 1;
 
10487
        if (*const_item)
 
10488
          return left_item->eq(*const_item, 1);
 
10489
        *const_item=left_item;
 
10490
        return 1;
2960
10491
      }
2961
10492
    }
2962
10493
  }
2963
10494
  return 0;
2964
10495
}
2965
10496
 
 
10497
 
2966
10498
/**
2967
10499
  @details
2968
10500
  Rows produced by a join sweep may end up in a temporary table or be sent
2974
10506
  @return
2975
10507
    end_select function to use. This function can't fail.
2976
10508
*/
2977
 
Next_select_func setup_end_select_func(Join *join)
 
10509
 
 
10510
Next_select_func setup_end_select_func(JOIN *join)
2978
10511
{
2979
10512
  Table *table= join->tmp_table;
2980
10513
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
2986
10519
    if (table->group && tmp_tbl->sum_func_count &&
2987
10520
        !tmp_tbl->precomputed_group_by)
2988
10521
    {
2989
 
      if (table->getShare()->sizeKeys())
 
10522
      if (table->s->keys)
2990
10523
      {
2991
 
        end_select= end_update;
 
10524
        end_select=end_update;
2992
10525
      }
2993
10526
      else
2994
10527
      {
2995
 
        end_select= end_unique_update;
 
10528
        end_select=end_unique_update;
2996
10529
      }
2997
10530
    }
2998
10531
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
2999
10532
    {
3000
 
      end_select= end_write_group;
 
10533
      end_select=end_write_group;
3001
10534
    }
3002
10535
    else
3003
10536
    {
3004
 
      end_select= end_write;
 
10537
      end_select=end_write;
3005
10538
      if (tmp_tbl->precomputed_group_by)
3006
10539
      {
3007
10540
        /*
3029
10562
  return end_select;
3030
10563
}
3031
10564
 
 
10565
 
3032
10566
/**
3033
10567
  Make a join of all tables and write it on socket or to table.
3034
10568
 
3039
10573
  @retval
3040
10574
    -1  if error should be sent
3041
10575
*/
3042
 
int do_select(Join *join, List<Item> *fields, Table *table)
 
10576
 
 
10577
static int
 
10578
do_select(JOIN *join,List<Item> *fields,Table *table)
3043
10579
{
3044
10580
  int rc= 0;
3045
10581
  enum_nested_loop_state error= NESTED_LOOP_OK;
3046
 
  JoinTable *join_tab= NULL;
 
10582
  JOIN_TAB *join_tab= NULL;
3047
10583
 
3048
10584
  join->tmp_table= table;                       /* Save for easy recursion */
3049
10585
  join->fields= fields;
3050
10586
 
3051
10587
  if (table)
3052
10588
  {
3053
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
3054
 
    table->emptyRecord();
 
10589
    table->file->extra(HA_EXTRA_WRITE_CACHE);
 
10590
    empty_record(table);
3055
10591
    if (table->group && join->tmp_table_param.sum_func_count &&
3056
 
        table->getShare()->sizeKeys() && !table->cursor->inited)
3057
 
    {
3058
 
      int tmp_error;
3059
 
      tmp_error= table->cursor->startIndexScan(0, 0);
3060
 
      if (tmp_error != 0)
3061
 
      {
3062
 
        table->print_error(tmp_error, MYF(0));
3063
 
        return -1;
3064
 
      }
3065
 
    }
 
10592
        table->s->keys && !table->file->inited)
 
10593
      table->file->ha_index_init(0, 0);
3066
10594
  }
3067
10595
  /* Set up select_end */
3068
10596
  Next_select_func end_select= setup_end_select_func(join);
3083
10611
    {
3084
10612
      error= (*end_select)(join, 0, 0);
3085
10613
      if (error == NESTED_LOOP_OK || error == NESTED_LOOP_QUERY_LIMIT)
3086
 
              error= (*end_select)(join, 0, 1);
 
10614
        error= (*end_select)(join, 0, 1);
3087
10615
 
3088
10616
      /*
3089
10617
        If we don't go through evaluate_join_record(), do the counting
3121
10649
    if (!table)                                 // If sending data to client
3122
10650
    {
3123
10651
      /*
3124
 
        The following will unlock all cursors if the command wasn't an
3125
 
        update command
 
10652
        The following will unlock all cursors if the command wasn't an
 
10653
        update command
3126
10654
      */
3127
10655
      join->join_free();                        // Unlock all cursors
3128
10656
      if (join->result->send_eof())
3129
 
        rc= 1;                                  // Don't send error
 
10657
        rc= 1;                                  // Don't send error
3130
10658
    }
3131
10659
  }
3132
10660
  else
3134
10662
  if (table)
3135
10663
  {
3136
10664
    int tmp, new_errno= 0;
3137
 
    if ((tmp=table->cursor->extra(HA_EXTRA_NO_CACHE)))
 
10665
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
3138
10666
    {
3139
10667
      new_errno= tmp;
3140
10668
    }
3141
 
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
 
10669
    if ((tmp=table->file->ha_index_or_rnd_end()))
3142
10670
    {
3143
10671
      new_errno= tmp;
3144
10672
    }
3145
10673
    if (new_errno)
3146
 
      table->print_error(new_errno,MYF(0));
 
10674
      table->file->print_error(new_errno,MYF(0));
3147
10675
  }
3148
10676
  return(join->session->is_error() ? -1 : rc);
3149
10677
}
3150
10678
 
3151
 
enum_nested_loop_state sub_select_cache(Join *join, JoinTable *join_tab, bool end_of_records)
 
10679
 
 
10680
enum_nested_loop_state
 
10681
sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
3152
10682
{
3153
10683
  enum_nested_loop_state rc;
3154
10684
 
3159
10689
      rc= sub_select(join,join_tab,end_of_records);
3160
10690
    return rc;
3161
10691
  }
3162
 
  if (join->session->getKilled())               // If aborted by user
 
10692
  if (join->session->killed)            // If aborted by user
3163
10693
  {
3164
10694
    join->session->send_kill_message();
3165
 
    return NESTED_LOOP_KILLED;
 
10695
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
3166
10696
  }
3167
10697
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3168
10698
  {
3169
 
    if (! join_tab->cache.store_record_in_cache())
 
10699
    if (!store_record_in_cache(&join_tab->cache))
3170
10700
      return NESTED_LOOP_OK;                     // There is more room in cache
3171
10701
    return flush_cached_records(join,join_tab,false);
3172
10702
  }
3295
10825
  @return
3296
10826
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
3297
10827
*/
3298
 
enum_nested_loop_state sub_select(Join *join, JoinTable *join_tab, bool end_of_records)
 
10828
int do_sj_reset(SJ_TMP_TABLE *sj_tbl);
 
10829
 
 
10830
enum_nested_loop_state
 
10831
sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
3299
10832
{
3300
10833
  join_tab->table->null_row=0;
3301
10834
  if (end_of_records)
3303
10836
 
3304
10837
  int error;
3305
10838
  enum_nested_loop_state rc;
3306
 
  ReadRecord *info= &join_tab->read_record;
 
10839
  READ_RECORD *info= &join_tab->read_record;
 
10840
 
 
10841
  if (join_tab->flush_weedout_table)
 
10842
  {
 
10843
    do_sj_reset(join_tab->flush_weedout_table);
 
10844
  }
3307
10845
 
3308
10846
  if (join->resume_nested_loop)
3309
10847
  {
3356
10894
  return rc;
3357
10895
}
3358
10896
 
3359
 
int safe_index_read(JoinTable *tab)
 
10897
 
 
10898
 
 
10899
 
 
10900
/*
 
10901
  SemiJoinDuplicateElimination: Weed out duplicate row combinations
 
10902
 
 
10903
  SYNPOSIS
 
10904
    do_sj_dups_weedout()
 
10905
 
 
10906
  RETURN
 
10907
    -1  Error
 
10908
    1   The row combination is a duplicate (discard it)
 
10909
    0   The row combination is not a duplicate (continue)
 
10910
*/
 
10911
 
 
10912
int do_sj_dups_weedout(Session *session, SJ_TMP_TABLE *sjtbl)
 
10913
{
 
10914
  int error;
 
10915
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
 
10916
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
 
10917
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
 
10918
  unsigned char *nulls_ptr= ptr;
 
10919
 
 
10920
  /* Put the the rowids tuple into table->record[0]: */
 
10921
 
 
10922
  // 1. Store the length
 
10923
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
 
10924
  {
 
10925
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
 
10926
    ptr++;
 
10927
  }
 
10928
  else
 
10929
  {
 
10930
    int2store(ptr, sjtbl->rowid_len + sjtbl->null_bytes);
 
10931
    ptr += 2;
 
10932
  }
 
10933
 
 
10934
  // 2. Zero the null bytes
 
10935
  if (sjtbl->null_bytes)
 
10936
  {
 
10937
    memset(ptr, 0, sjtbl->null_bytes);
 
10938
    ptr += sjtbl->null_bytes;
 
10939
  }
 
10940
 
 
10941
  // 3. Put the rowids
 
10942
  for (uint32_t i=0; tab != tab_end; tab++, i++)
 
10943
  {
 
10944
    handler *h= tab->join_tab->table->file;
 
10945
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
 
10946
    {
 
10947
      /* It's a NULL-complemented row */
 
10948
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
 
10949
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
 
10950
    }
 
10951
    else
 
10952
    {
 
10953
      /* Copy the rowid value */
 
10954
      if (tab->join_tab->rowid_keep_flags & JOIN_TAB::CALL_POSITION)
 
10955
        h->position(tab->join_tab->table->record[0]);
 
10956
      memcpy(ptr + tab->rowid_offset, h->ref, h->ref_length);
 
10957
    }
 
10958
  }
 
10959
 
 
10960
  error= sjtbl->tmp_table->file->ha_write_row(sjtbl->tmp_table->record[0]);
 
10961
  if (error)
 
10962
  {
 
10963
    /* create_myisam_from_heap will generate error if needed */
 
10964
    if (sjtbl->tmp_table->file->is_fatal_error(error, HA_CHECK_DUP) &&
 
10965
        create_myisam_from_heap(session, sjtbl->tmp_table, sjtbl->start_recinfo,
 
10966
                                &sjtbl->recinfo, error, 1))
 
10967
      return -1;
 
10968
    //return (error == HA_ERR_FOUND_DUPP_KEY || error== HA_ERR_FOUND_DUPP_UNIQUE) ? 1: -1;
 
10969
    return 1;
 
10970
  }
 
10971
  return 0;
 
10972
}
 
10973
 
 
10974
 
 
10975
/*
 
10976
  SemiJoinDuplicateElimination: Reset the temporary table
 
10977
*/
 
10978
 
 
10979
int do_sj_reset(SJ_TMP_TABLE *sj_tbl)
 
10980
{
 
10981
  if (sj_tbl->tmp_table)
 
10982
    return sj_tbl->tmp_table->file->ha_delete_all_rows();
 
10983
  return 0;
 
10984
}
 
10985
 
 
10986
/*
 
10987
  Process one record of the nested loop join.
 
10988
 
 
10989
    This function will evaluate parts of WHERE/ON clauses that are
 
10990
    applicable to the partial record on hand and in case of success
 
10991
    submit this record to the next level of the nested loop.
 
10992
*/
 
10993
 
 
10994
static enum_nested_loop_state
 
10995
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
 
10996
                     int error)
 
10997
{
 
10998
  bool not_used_in_distinct=join_tab->not_used_in_distinct;
 
10999
  ha_rows found_records=join->found_records;
 
11000
  COND *select_cond= join_tab->select_cond;
 
11001
 
 
11002
  if (error > 0 || (join->session->is_error()))     // Fatal error
 
11003
    return NESTED_LOOP_ERROR;
 
11004
  if (error < 0)
 
11005
    return NESTED_LOOP_NO_MORE_ROWS;
 
11006
  if (join->session->killed)                    // Aborted by user
 
11007
  {
 
11008
    join->session->send_kill_message();
 
11009
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
 
11010
  }
 
11011
  if (!select_cond || select_cond->val_int())
 
11012
  {
 
11013
    /*
 
11014
      There is no select condition or the attached pushed down
 
11015
      condition is true => a match is found.
 
11016
    */
 
11017
    bool found= 1;
 
11018
    while (join_tab->first_unmatched && found)
 
11019
    {
 
11020
      /*
 
11021
        The while condition is always false if join_tab is not
 
11022
        the last inner join table of an outer join operation.
 
11023
      */
 
11024
      JOIN_TAB *first_unmatched= join_tab->first_unmatched;
 
11025
      /*
 
11026
        Mark that a match for current outer table is found.
 
11027
        This activates push down conditional predicates attached
 
11028
        to the all inner tables of the outer join.
 
11029
      */
 
11030
      first_unmatched->found= 1;
 
11031
      for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
 
11032
      {
 
11033
        if (tab->table->reginfo.not_exists_optimize)
 
11034
          return NESTED_LOOP_NO_MORE_ROWS;
 
11035
        /* Check all predicates that has just been activated. */
 
11036
        /*
 
11037
          Actually all predicates non-guarded by first_unmatched->found
 
11038
          will be re-evaluated again. It could be fixed, but, probably,
 
11039
          it's not worth doing now.
 
11040
        */
 
11041
        if (tab->select_cond && !tab->select_cond->val_int())
 
11042
        {
 
11043
          /* The condition attached to table tab is false */
 
11044
          if (tab == join_tab)
 
11045
            found= 0;
 
11046
          else
 
11047
          {
 
11048
            /*
 
11049
              Set a return point if rejected predicate is attached
 
11050
              not to the last table of the current nest level.
 
11051
            */
 
11052
            join->return_tab= tab;
 
11053
            return NESTED_LOOP_OK;
 
11054
          }
 
11055
        }
 
11056
      }
 
11057
      /*
 
11058
        Check whether join_tab is not the last inner table
 
11059
        for another embedding outer join.
 
11060
      */
 
11061
      if ((first_unmatched= first_unmatched->first_upper) &&
 
11062
          first_unmatched->last_inner != join_tab)
 
11063
        first_unmatched= 0;
 
11064
      join_tab->first_unmatched= first_unmatched;
 
11065
    }
 
11066
 
 
11067
    JOIN_TAB *return_tab= join->return_tab;
 
11068
    join_tab->found_match= true;
 
11069
    if (join_tab->check_weed_out_table)
 
11070
    {
 
11071
      int res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table);
 
11072
      if (res == -1)
 
11073
        return NESTED_LOOP_ERROR;
 
11074
      if (res == 1)
 
11075
        return NESTED_LOOP_OK;
 
11076
    }
 
11077
    else if (join_tab->do_firstmatch)
 
11078
    {
 
11079
      /*
 
11080
        We should return to the join_tab->do_firstmatch after we have
 
11081
        enumerated all the suffixes for current prefix row combination
 
11082
      */
 
11083
      return_tab= join_tab->do_firstmatch;
 
11084
    }
 
11085
 
 
11086
    /*
 
11087
      It was not just a return to lower loop level when one
 
11088
      of the newly activated predicates is evaluated as false
 
11089
      (See above join->return_tab= tab).
 
11090
    */
 
11091
    join->examined_rows++;
 
11092
    join->session->row_count++;
 
11093
 
 
11094
    if (found)
 
11095
    {
 
11096
      enum enum_nested_loop_state rc;
 
11097
      /* A match from join_tab is found for the current partial join. */
 
11098
      rc= (*join_tab->next_select)(join, join_tab+1, 0);
 
11099
      if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
11100
        return rc;
 
11101
      if (return_tab < join->return_tab)
 
11102
        join->return_tab= return_tab;
 
11103
 
 
11104
      if (join->return_tab < join_tab)
 
11105
        return NESTED_LOOP_OK;
 
11106
      /*
 
11107
        Test if this was a SELECT DISTINCT query on a table that
 
11108
        was not in the field list;  In this case we can abort if
 
11109
        we found a row, as no new rows can be added to the result.
 
11110
      */
 
11111
      if (not_used_in_distinct && found_records != join->found_records)
 
11112
        return NESTED_LOOP_NO_MORE_ROWS;
 
11113
    }
 
11114
    else
 
11115
      join_tab->read_record.file->unlock_row();
 
11116
  }
 
11117
  else
 
11118
  {
 
11119
    /*
 
11120
      The condition pushed down to the table join_tab rejects all rows
 
11121
      with the beginning coinciding with the current partial join.
 
11122
    */
 
11123
    join->examined_rows++;
 
11124
    join->session->row_count++;
 
11125
    join_tab->read_record.file->unlock_row();
 
11126
  }
 
11127
  return NESTED_LOOP_OK;
 
11128
}
 
11129
 
 
11130
 
 
11131
/**
 
11132
 
 
11133
  @details
 
11134
    Construct a NULL complimented partial join record and feed it to the next
 
11135
    level of the nested loop. This function is used in case we have
 
11136
    an OUTER join and no matching record was found.
 
11137
*/
 
11138
 
 
11139
static enum_nested_loop_state
 
11140
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab)
 
11141
{
 
11142
  /*
 
11143
    The table join_tab is the first inner table of a outer join operation
 
11144
    and no matches has been found for the current outer row.
 
11145
  */
 
11146
  JOIN_TAB *last_inner_tab= join_tab->last_inner;
 
11147
  /* Cache variables for faster loop */
 
11148
  COND *select_cond;
 
11149
  for ( ; join_tab <= last_inner_tab ; join_tab++)
 
11150
  {
 
11151
    /* Change the the values of guard predicate variables. */
 
11152
    join_tab->found= 1;
 
11153
    join_tab->not_null_compl= 0;
 
11154
    /* The outer row is complemented by nulls for each inner tables */
 
11155
    restore_record(join_tab->table,s->default_values);  // Make empty record
 
11156
    mark_as_null_row(join_tab->table);       // For group by without error
 
11157
    select_cond= join_tab->select_cond;
 
11158
    /* Check all attached conditions for inner table rows. */
 
11159
    if (select_cond && !select_cond->val_int())
 
11160
      return NESTED_LOOP_OK;
 
11161
  }
 
11162
  join_tab--;
 
11163
  /*
 
11164
    The row complemented by nulls might be the first row
 
11165
    of embedding outer joins.
 
11166
    If so, perform the same actions as in the code
 
11167
    for the first regular outer join row above.
 
11168
  */
 
11169
  for ( ; ; )
 
11170
  {
 
11171
    JOIN_TAB *first_unmatched= join_tab->first_unmatched;
 
11172
    if ((first_unmatched= first_unmatched->first_upper) &&
 
11173
        first_unmatched->last_inner != join_tab)
 
11174
      first_unmatched= 0;
 
11175
    join_tab->first_unmatched= first_unmatched;
 
11176
    if (!first_unmatched)
 
11177
      break;
 
11178
    first_unmatched->found= 1;
 
11179
    for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
 
11180
    {
 
11181
      if (tab->select_cond && !tab->select_cond->val_int())
 
11182
      {
 
11183
        join->return_tab= tab;
 
11184
        return NESTED_LOOP_OK;
 
11185
      }
 
11186
    }
 
11187
  }
 
11188
  /*
 
11189
    The row complemented by nulls satisfies all conditions
 
11190
    attached to inner tables.
 
11191
    Send the row complemented by nulls to be joined with the
 
11192
    remaining tables.
 
11193
  */
 
11194
  return (*join_tab->next_select)(join, join_tab+1, 0);
 
11195
}
 
11196
 
 
11197
 
 
11198
static enum_nested_loop_state
 
11199
flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last)
 
11200
{
 
11201
  enum_nested_loop_state rc= NESTED_LOOP_OK;
 
11202
  int error;
 
11203
  READ_RECORD *info;
 
11204
 
 
11205
  join_tab->table->null_row= 0;
 
11206
  if (!join_tab->cache.records)
 
11207
    return NESTED_LOOP_OK;                      /* Nothing to do */
 
11208
  if (skip_last)
 
11209
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
 
11210
  if (join_tab->use_quick == 2)
 
11211
  {
 
11212
    if (join_tab->select->quick)
 
11213
    {                                   /* Used quick select last. reset it */
 
11214
      delete join_tab->select->quick;
 
11215
      join_tab->select->quick=0;
 
11216
    }
 
11217
  }
 
11218
 /* read through all records */
 
11219
  if ((error=join_init_read_record(join_tab)))
 
11220
  {
 
11221
    reset_cache_write(&join_tab->cache);
 
11222
    return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR;
 
11223
  }
 
11224
 
 
11225
  for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++)
 
11226
  {
 
11227
    tmp->status=tmp->table->status;
 
11228
    tmp->table->status=0;
 
11229
  }
 
11230
 
 
11231
  info= &join_tab->read_record;
 
11232
  do
 
11233
  {
 
11234
    if (join->session->killed)
 
11235
    {
 
11236
      join->session->send_kill_message();
 
11237
      return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */
 
11238
    }
 
11239
    SQL_SELECT *select=join_tab->select;
 
11240
    if (rc == NESTED_LOOP_OK &&
 
11241
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
 
11242
    {
 
11243
      uint32_t i;
 
11244
      reset_cache_read(&join_tab->cache);
 
11245
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
 
11246
      {
 
11247
        read_cached_record(join_tab);
 
11248
        if (!select || !select->skip_record())
 
11249
        {
 
11250
          int res= 0;
 
11251
          if (!join_tab->check_weed_out_table ||
 
11252
              !(res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table)))
 
11253
          {
 
11254
            rc= (join_tab->next_select)(join,join_tab+1,0);
 
11255
            if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
 
11256
            {
 
11257
              reset_cache_write(&join_tab->cache);
 
11258
              return rc;
 
11259
            }
 
11260
          }
 
11261
          if (res == -1)
 
11262
            return NESTED_LOOP_ERROR;
 
11263
        }
 
11264
      }
 
11265
    }
 
11266
  } while (!(error=info->read_record(info)));
 
11267
 
 
11268
  if (skip_last)
 
11269
    read_cached_record(join_tab);               // Restore current record
 
11270
  reset_cache_write(&join_tab->cache);
 
11271
  if (error > 0)                                // Fatal error
 
11272
    return NESTED_LOOP_ERROR;                   /* purecov: inspected */
 
11273
  for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
 
11274
    tmp2->table->status=tmp2->status;
 
11275
  return NESTED_LOOP_OK;
 
11276
}
 
11277
 
 
11278
int safe_index_read(JOIN_TAB *tab)
3360
11279
{
3361
11280
  int error;
3362
11281
  Table *table= tab->table;
3363
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
11282
  if ((error=table->file->index_read_map(table->record[0],
3364
11283
                                         tab->ref.key_buff,
3365
11284
                                         make_prev_keypart_map(tab->ref.key_parts),
3366
11285
                                         HA_READ_KEY_EXACT)))
3368
11287
  return 0;
3369
11288
}
3370
11289
 
 
11290
 
 
11291
static int
 
11292
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
 
11293
{
 
11294
  int error;
 
11295
  Table *table=tab->table;
 
11296
  table->const_table=1;
 
11297
  table->null_row=0;
 
11298
  table->status=STATUS_NO_RECORD;
 
11299
 
 
11300
  if (tab->type == JT_SYSTEM)
 
11301
  {
 
11302
    if ((error=join_read_system(tab)))
 
11303
    {                                           // Info for DESCRIBE
 
11304
      tab->info="const row not found";
 
11305
      /* Mark for EXPLAIN that the row was not found */
 
11306
      pos->records_read=0.0;
 
11307
      pos->ref_depend_map= 0;
 
11308
      if (!table->maybe_null || error > 0)
 
11309
        return(error);
 
11310
    }
 
11311
  }
 
11312
  else
 
11313
  {
 
11314
    if (!table->key_read && table->covering_keys.is_set(tab->ref.key) &&
 
11315
        !table->no_keyread &&
 
11316
        (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY)
 
11317
    {
 
11318
      table->key_read=1;
 
11319
      table->file->extra(HA_EXTRA_KEYREAD);
 
11320
      tab->index= tab->ref.key;
 
11321
    }
 
11322
    error=join_read_const(tab);
 
11323
    if (table->key_read)
 
11324
    {
 
11325
      table->key_read=0;
 
11326
      table->file->extra(HA_EXTRA_NO_KEYREAD);
 
11327
    }
 
11328
    if (error)
 
11329
    {
 
11330
      tab->info="unique row not found";
 
11331
      /* Mark for EXPLAIN that the row was not found */
 
11332
      pos->records_read=0.0;
 
11333
      pos->ref_depend_map= 0;
 
11334
      if (!table->maybe_null || error > 0)
 
11335
        return(error);
 
11336
    }
 
11337
  }
 
11338
  if (*tab->on_expr_ref && !table->null_row)
 
11339
  {
 
11340
    if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0)))
 
11341
      mark_as_null_row(table);
 
11342
  }
 
11343
  if (!table->null_row)
 
11344
    table->maybe_null=0;
 
11345
 
 
11346
  /* Check appearance of new constant items in Item_equal objects */
 
11347
  JOIN *join= tab->join;
 
11348
  if (join->conds)
 
11349
    update_const_equal_items(join->conds, tab);
 
11350
  TableList *tbl;
 
11351
  for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
 
11352
  {
 
11353
    TableList *embedded;
 
11354
    TableList *embedding= tbl;
 
11355
    do
 
11356
    {
 
11357
      embedded= embedding;
 
11358
      if (embedded->on_expr)
 
11359
         update_const_equal_items(embedded->on_expr, tab);
 
11360
      embedding= embedded->embedding;
 
11361
    }
 
11362
    while (embedding &&
 
11363
           embedding->nested_join->join_list.head() == embedded);
 
11364
  }
 
11365
 
 
11366
  return(0);
 
11367
}
 
11368
 
 
11369
 
 
11370
static int
 
11371
join_read_system(JOIN_TAB *tab)
 
11372
{
 
11373
  Table *table= tab->table;
 
11374
  int error;
 
11375
  if (table->status & STATUS_GARBAGE)           // If first read
 
11376
  {
 
11377
    if ((error=table->file->read_first_row(table->record[0],
 
11378
                                           table->s->primary_key)))
 
11379
    {
 
11380
      if (error != HA_ERR_END_OF_FILE)
 
11381
        return table->report_error(error);
 
11382
      mark_as_null_row(tab->table);
 
11383
      empty_record(table);                      // Make empty record
 
11384
      return -1;
 
11385
    }
 
11386
    update_virtual_fields_marked_for_write(table);
 
11387
    store_record(table,record[1]);
 
11388
  }
 
11389
  else if (!table->status)                      // Only happens with left join
 
11390
    restore_record(table,record[1]);                    // restore old record
 
11391
  table->null_row=0;
 
11392
  return table->status ? -1 : 0;
 
11393
}
 
11394
 
 
11395
 
3371
11396
/**
3372
11397
  Read a (constant) table when there is at most one matching row.
3373
11398
 
3380
11405
  @retval
3381
11406
    1   Got an error (other than row not found) during read
3382
11407
*/
3383
 
int join_read_const(JoinTable *tab)
 
11408
 
 
11409
static int
 
11410
join_read_const(JOIN_TAB *tab)
3384
11411
{
3385
11412
  int error;
3386
11413
  Table *table= tab->table;
3388
11415
  {
3389
11416
    table->status= 0;
3390
11417
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3391
 
      error= HA_ERR_KEY_NOT_FOUND;
 
11418
      error=HA_ERR_KEY_NOT_FOUND;
3392
11419
    else
3393
11420
    {
3394
 
      error=table->cursor->index_read_idx_map(table->getInsertRecord(),tab->ref.key,
 
11421
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
3395
11422
                                            (unsigned char*) tab->ref.key_buff,
3396
11423
                                            make_prev_keypart_map(tab->ref.key_parts),
3397
11424
                                            HA_READ_KEY_EXACT);
3399
11426
    if (error)
3400
11427
    {
3401
11428
      table->status= STATUS_NOT_FOUND;
3402
 
      tab->table->mark_as_null_row();
3403
 
      table->emptyRecord();
 
11429
      mark_as_null_row(tab->table);
 
11430
      empty_record(table);
3404
11431
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3405
 
        return table->report_error(error);
 
11432
        return table->report_error(error);
3406
11433
      return -1;
3407
11434
    }
3408
 
    table->storeRecord();
 
11435
    update_virtual_fields_marked_for_write(table);
 
11436
    store_record(table,record[1]);
3409
11437
  }
3410
11438
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
3411
11439
  {
3412
11440
    table->status=0;
3413
 
    table->restoreRecord();                     // restore old record
 
11441
    restore_record(table,record[1]);                    // restore old record
3414
11442
  }
3415
11443
  table->null_row=0;
3416
11444
  return table->status ? -1 : 0;
3417
11445
}
3418
11446
 
 
11447
 
3419
11448
/*
3420
11449
  eq_ref access method implementation: "read_first" function
3421
11450
 
3422
11451
  SYNOPSIS
3423
11452
    join_read_key()
3424
 
      tab  JoinTable of the accessed table
 
11453
      tab  JOIN_TAB of the accessed table
3425
11454
 
3426
11455
  DESCRIPTION
3427
11456
    This is "read_fist" function for the "ref" access method. The difference
3432
11461
   -1  - Row not found
3433
11462
    1  - Error
3434
11463
*/
3435
 
int join_read_key(JoinTable *tab)
 
11464
 
 
11465
static int
 
11466
join_read_key(JOIN_TAB *tab)
3436
11467
{
3437
11468
  int error;
3438
11469
  Table *table= tab->table;
3439
11470
 
3440
 
  if (!table->cursor->inited)
 
11471
  if (!table->file->inited)
3441
11472
  {
3442
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3443
 
    if (error != 0)
3444
 
    {
3445
 
      table->print_error(error, MYF(0));
3446
 
    }
 
11473
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3447
11474
  }
3448
11475
 
3449
11476
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3455
11482
      table->status=STATUS_NOT_FOUND;
3456
11483
      return -1;
3457
11484
    }
3458
 
    error=table->cursor->index_read_map(table->getInsertRecord(),
 
11485
    error=table->file->index_read_map(table->record[0],
3459
11486
                                      tab->ref.key_buff,
3460
11487
                                      make_prev_keypart_map(tab->ref.key_parts),
3461
11488
                                      HA_READ_KEY_EXACT);
3466
11493
  return table->status ? -1 : 0;
3467
11494
}
3468
11495
 
 
11496
 
3469
11497
/*
3470
11498
  ref access method implementation: "read_first" function
3471
11499
 
3472
11500
  SYNOPSIS
3473
11501
    join_read_always_key()
3474
 
      tab  JoinTable of the accessed table
 
11502
      tab  JOIN_TAB of the accessed table
3475
11503
 
3476
11504
  DESCRIPTION
3477
 
    This is "read_first" function for the "ref" access method.
 
11505
    This is "read_fist" function for the "ref" access method.
3478
11506
 
3479
11507
    The functon must leave the index initialized when it returns.
3480
11508
    ref_or_null access implementation depends on that.
3484
11512
   -1  - Row not found
3485
11513
    1  - Error
3486
11514
*/
3487
 
int join_read_always_key(JoinTable *tab)
 
11515
 
 
11516
static int
 
11517
join_read_always_key(JOIN_TAB *tab)
3488
11518
{
3489
11519
  int error;
3490
11520
  Table *table= tab->table;
3491
11521
 
3492
11522
  /* Initialize the index first */
3493
 
  if (!table->cursor->inited)
3494
 
  {
3495
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3496
 
    if (error != 0)
3497
 
      return table->report_error(error);
3498
 
  }
 
11523
  if (!table->file->inited)
 
11524
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3499
11525
 
3500
11526
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3501
11527
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3506
11532
 
3507
11533
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3508
11534
    return -1;
3509
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
11535
  if ((error=table->file->index_read_map(table->record[0],
3510
11536
                                         tab->ref.key_buff,
3511
11537
                                         make_prev_keypart_map(tab->ref.key_parts),
3512
11538
                                         HA_READ_KEY_EXACT)))
3513
11539
  {
3514
11540
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3515
11541
      return table->report_error(error);
3516
 
    return -1;
 
11542
    return -1; /* purecov: inspected */
3517
11543
  }
3518
 
 
 
11544
  update_virtual_fields_marked_for_write(table);
3519
11545
  return 0;
3520
11546
}
3521
11547
 
 
11548
 
3522
11549
/**
3523
 
  This function is used when optimizing away ORDER BY in
3524
 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
 
11550
  This function is used when optimizing away order_st BY in
 
11551
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
3525
11552
*/
3526
 
int join_read_last_key(JoinTable *tab)
 
11553
 
 
11554
static int
 
11555
join_read_last_key(JOIN_TAB *tab)
3527
11556
{
3528
11557
  int error;
3529
11558
  Table *table= tab->table;
3530
11559
 
3531
 
  if (!table->cursor->inited)
3532
 
  {
3533
 
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3534
 
    if (error != 0)
3535
 
      return table->report_error(error);
3536
 
  }
 
11560
  if (!table->file->inited)
 
11561
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3537
11562
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3538
11563
    return -1;
3539
 
  if ((error=table->cursor->index_read_last_map(table->getInsertRecord(),
 
11564
  if ((error=table->file->index_read_last_map(table->record[0],
3540
11565
                                              tab->ref.key_buff,
3541
11566
                                              make_prev_keypart_map(tab->ref.key_parts))))
3542
11567
  {
3543
11568
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3544
11569
      return table->report_error(error);
3545
 
    return -1;
 
11570
    return -1; /* purecov: inspected */
3546
11571
  }
3547
11572
  return 0;
3548
11573
}
3549
11574
 
3550
 
int join_no_more_records(ReadRecord *)
 
11575
 
 
11576
        /* ARGSUSED */
 
11577
static int
 
11578
join_no_more_records(READ_RECORD *)
3551
11579
{
3552
11580
  return -1;
3553
11581
}
3554
11582
 
3555
 
int join_read_next_same_diff(ReadRecord *info)
 
11583
static int
 
11584
join_read_next_same_diff(READ_RECORD *info)
3556
11585
{
3557
11586
  Table *table= info->table;
3558
 
  JoinTable *tab=table->reginfo.join_tab;
 
11587
  JOIN_TAB *tab=table->reginfo.join_tab;
3559
11588
  if (tab->insideout_match_tab->found_match)
3560
11589
  {
3561
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
11590
    KEY *key= tab->table->key_info + tab->index;
3562
11591
    do
3563
11592
    {
3564
11593
      int error;
3565
11594
      /* Save index tuple from record to the buffer */
3566
11595
      key_copy(tab->insideout_buf, info->record, key, 0);
3567
11596
 
3568
 
      if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
11597
      if ((error=table->file->index_next_same(table->record[0],
3569
11598
                                              tab->ref.key_buff,
3570
11599
                                              tab->ref.key_length)))
3571
11600
      {
3583
11612
    return join_read_next_same(info);
3584
11613
}
3585
11614
 
3586
 
int join_read_next_same(ReadRecord *info)
 
11615
static int
 
11616
join_read_next_same(READ_RECORD *info)
3587
11617
{
3588
11618
  int error;
3589
11619
  Table *table= info->table;
3590
 
  JoinTable *tab=table->reginfo.join_tab;
 
11620
  JOIN_TAB *tab=table->reginfo.join_tab;
3591
11621
 
3592
 
  if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
11622
  if ((error=table->file->index_next_same(table->record[0],
3593
11623
                                          tab->ref.key_buff,
3594
11624
                                          tab->ref.key_length)))
3595
11625
  {
3598
11628
    table->status= STATUS_GARBAGE;
3599
11629
    return -1;
3600
11630
  }
3601
 
 
 
11631
  update_virtual_fields_marked_for_write(table);
3602
11632
  return 0;
3603
11633
}
3604
11634
 
3605
 
int join_read_prev_same(ReadRecord *info)
 
11635
 
 
11636
static int
 
11637
join_read_prev_same(READ_RECORD *info)
3606
11638
{
3607
11639
  int error;
3608
11640
  Table *table= info->table;
3609
 
  JoinTable *tab=table->reginfo.join_tab;
 
11641
  JOIN_TAB *tab=table->reginfo.join_tab;
3610
11642
 
3611
 
  if ((error=table->cursor->index_prev(table->getInsertRecord())))
 
11643
  if ((error=table->file->index_prev(table->record[0])))
3612
11644
    return table->report_error(error);
3613
11645
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3614
11646
                      tab->ref.key_length))
3616
11648
    table->status=STATUS_NOT_FOUND;
3617
11649
    error= -1;
3618
11650
  }
 
11651
  update_virtual_fields_marked_for_write(table);
3619
11652
  return error;
3620
11653
}
3621
11654
 
3622
 
int join_init_quick_read_record(JoinTable *tab)
 
11655
 
 
11656
static int
 
11657
join_init_quick_read_record(JOIN_TAB *tab)
3623
11658
{
3624
11659
  if (test_if_quick_select(tab) == -1)
3625
11660
    return -1;                                  /* No possible records */
3626
11661
  return join_init_read_record(tab);
3627
11662
}
3628
11663
 
3629
 
int init_read_record_seq(JoinTable *tab)
 
11664
 
 
11665
int rr_sequential(READ_RECORD *info);
 
11666
int init_read_record_seq(JOIN_TAB *tab)
3630
11667
{
3631
 
  tab->read_record.init_reard_record_sequential();
3632
 
 
3633
 
  if (tab->read_record.cursor->startTableScan(1))
 
11668
  tab->read_record.read_record= rr_sequential;
 
11669
  if (tab->read_record.file->ha_rnd_init(1))
3634
11670
    return 1;
3635
11671
  return (*tab->read_record.read_record)(&tab->read_record);
3636
11672
}
3637
11673
 
3638
 
int test_if_quick_select(JoinTable *tab)
 
11674
static int
 
11675
test_if_quick_select(JOIN_TAB *tab)
3639
11676
{
3640
11677
  delete tab->select->quick;
3641
 
  tab->select->quick= 0;
 
11678
  tab->select->quick=0;
3642
11679
  return tab->select->test_quick_select(tab->join->session, tab->keys,
3643
 
                                        (table_map) 0, HA_POS_ERROR, 0, false);
 
11680
                                        (table_map) 0, HA_POS_ERROR, 0,
 
11681
                                        false);
3644
11682
}
3645
11683
 
3646
 
int join_init_read_record(JoinTable *tab)
 
11684
 
 
11685
static int
 
11686
join_init_read_record(JOIN_TAB *tab)
3647
11687
{
3648
11688
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3649
11689
    return 1;
3650
 
 
3651
 
  if (tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true))
3652
 
    return 1;
3653
 
 
 
11690
  init_read_record(&tab->read_record, tab->join->session, tab->table,
 
11691
                   tab->select,1,1);
3654
11692
  return (*tab->read_record.read_record)(&tab->read_record);
3655
11693
}
3656
11694
 
3657
 
int join_read_first(JoinTable *tab)
 
11695
 
 
11696
static int
 
11697
join_read_first(JOIN_TAB *tab)
3658
11698
{
3659
11699
  int error;
3660
11700
  Table *table=tab->table;
3661
 
  if (!table->key_read && table->covering_keys.test(tab->index) &&
 
11701
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
3662
11702
      !table->no_keyread)
3663
11703
  {
3664
 
    table->key_read= 1;
3665
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
11704
    table->key_read=1;
 
11705
    table->file->extra(HA_EXTRA_KEYREAD);
3666
11706
  }
3667
 
  tab->table->status= 0;
 
11707
  tab->table->status=0;
3668
11708
  tab->read_record.table=table;
3669
 
  tab->read_record.cursor=table->cursor;
 
11709
  tab->read_record.file=table->file;
3670
11710
  tab->read_record.index=tab->index;
3671
 
  tab->read_record.record=table->getInsertRecord();
 
11711
  tab->read_record.record=table->record[0];
3672
11712
  if (tab->insideout_match_tab)
3673
11713
  {
3674
11714
    tab->read_record.do_insideout_scan= tab;
3681
11721
    tab->read_record.do_insideout_scan= 0;
3682
11722
  }
3683
11723
 
3684
 
  if (!table->cursor->inited)
3685
 
  {
3686
 
    error= table->cursor->startIndexScan(tab->index, tab->sorted);
3687
 
    if (error != 0)
3688
 
    {
3689
 
      table->report_error(error);
3690
 
      return -1;
3691
 
    }
3692
 
  }
3693
 
  if ((error=tab->table->cursor->index_first(tab->table->getInsertRecord())))
 
11724
  if (!table->file->inited)
 
11725
    table->file->ha_index_init(tab->index, tab->sorted);
 
11726
  if ((error=tab->table->file->index_first(tab->table->record[0])))
3694
11727
  {
3695
11728
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3696
11729
      table->report_error(error);
3697
11730
    return -1;
3698
11731
  }
3699
 
 
 
11732
  if (not error)
 
11733
    update_virtual_fields_marked_for_write(tab->table);
3700
11734
  return 0;
3701
11735
}
3702
11736
 
3703
 
int join_read_next_different(ReadRecord *info)
 
11737
 
 
11738
static int
 
11739
join_read_next_different(READ_RECORD *info)
3704
11740
{
3705
 
  JoinTable *tab= info->do_insideout_scan;
 
11741
  JOIN_TAB *tab= info->do_insideout_scan;
3706
11742
  if (tab->insideout_match_tab->found_match)
3707
11743
  {
3708
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
11744
    KEY *key= tab->table->key_info + tab->index;
3709
11745
    do
3710
11746
    {
3711
11747
      int error;
3712
11748
      /* Save index tuple from record to the buffer */
3713
11749
      key_copy(tab->insideout_buf, info->record, key, 0);
3714
11750
 
3715
 
      if ((error=info->cursor->index_next(info->record)))
 
11751
      if ((error=info->file->index_next(info->record)))
3716
11752
        return info->table->report_error(error);
 
11753
      if (not error)
 
11754
        update_virtual_fields_marked_for_write(tab->table);
3717
11755
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
3718
11756
                      tab->insideout_buf, key->key_length));
3719
11757
    tab->insideout_match_tab->found_match= 0;
3723
11761
    return join_read_next(info);
3724
11762
}
3725
11763
 
3726
 
int join_read_next(ReadRecord *info)
 
11764
 
 
11765
static int
 
11766
join_read_next(READ_RECORD *info)
3727
11767
{
3728
11768
  int error;
3729
 
  if ((error=info->cursor->index_next(info->record)))
 
11769
  if ((error=info->file->index_next(info->record)))
3730
11770
    return info->table->report_error(error);
 
11771
  if (not error)
 
11772
    update_virtual_fields_marked_for_write(info->table);
3731
11773
  return 0;
3732
11774
}
3733
11775
 
3734
 
int join_read_last(JoinTable *tab)
 
11776
 
 
11777
static int
 
11778
join_read_last(JOIN_TAB *tab)
3735
11779
{
3736
11780
  Table *table=tab->table;
3737
11781
  int error;
3738
 
  if (!table->key_read && table->covering_keys.test(tab->index) &&
 
11782
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
3739
11783
      !table->no_keyread)
3740
11784
  {
3741
11785
    table->key_read=1;
3742
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
11786
    table->file->extra(HA_EXTRA_KEYREAD);
3743
11787
  }
3744
11788
  tab->table->status=0;
3745
11789
  tab->read_record.read_record=join_read_prev;
3746
11790
  tab->read_record.table=table;
3747
 
  tab->read_record.cursor=table->cursor;
 
11791
  tab->read_record.file=table->file;
3748
11792
  tab->read_record.index=tab->index;
3749
 
  tab->read_record.record=table->getInsertRecord();
3750
 
  if (!table->cursor->inited)
3751
 
  {
3752
 
    error= table->cursor->startIndexScan(tab->index, 1);
3753
 
    if (error != 0)
3754
 
      return table->report_error(error);
3755
 
  }
3756
 
  if ((error= tab->table->cursor->index_last(tab->table->getInsertRecord())))
 
11793
  tab->read_record.record=table->record[0];
 
11794
  if (!table->file->inited)
 
11795
    table->file->ha_index_init(tab->index, 1);
 
11796
  if ((error= tab->table->file->index_last(tab->table->record[0])))
3757
11797
    return table->report_error(error);
3758
 
 
 
11798
  if (not error)
 
11799
    update_virtual_fields_marked_for_write(tab->table);
3759
11800
  return 0;
3760
11801
}
3761
11802
 
3762
 
int join_read_prev(ReadRecord *info)
 
11803
 
 
11804
static int
 
11805
join_read_prev(READ_RECORD *info)
3763
11806
{
3764
11807
  int error;
3765
 
  if ((error= info->cursor->index_prev(info->record)))
 
11808
  if ((error= info->file->index_prev(info->record)))
3766
11809
    return info->table->report_error(error);
3767
 
 
 
11810
  if (not error)
 
11811
    update_virtual_fields_marked_for_write(info->table);
3768
11812
  return 0;
3769
11813
}
3770
11814
 
3771
11815
/**
3772
11816
  Reading of key with key reference and one part that may be NULL.
3773
11817
*/
3774
 
int join_read_always_key_or_null(JoinTable *tab)
 
11818
 
 
11819
int
 
11820
join_read_always_key_or_null(JOIN_TAB *tab)
3775
11821
{
3776
11822
  int res;
3777
11823
 
3785
11831
  return safe_index_read(tab);
3786
11832
}
3787
11833
 
3788
 
int join_read_next_same_or_null(ReadRecord *info)
 
11834
 
 
11835
int
 
11836
join_read_next_same_or_null(READ_RECORD *info)
3789
11837
{
3790
11838
  int error;
3791
11839
  if ((error= join_read_next_same(info)) >= 0)
3792
11840
    return error;
3793
 
  JoinTable *tab= info->table->reginfo.join_tab;
 
11841
  JOIN_TAB *tab= info->table->reginfo.join_tab;
3794
11842
 
3795
11843
  /* Test if we have already done a read after null key */
3796
11844
  if (*tab->ref.null_ref_key)
3799
11847
  return safe_index_read(tab);                  // then read null keys
3800
11848
}
3801
11849
 
3802
 
enum_nested_loop_state end_send_group(Join *join, JoinTable *, bool end_of_records)
 
11850
 
 
11851
/*****************************************************************************
 
11852
  DESCRIPTION
 
11853
    Functions that end one nested loop iteration. Different functions
 
11854
    are used to support GROUP BY clause and to redirect records
 
11855
    to a table (e.g. in case of SELECT into a temporary table) or to the
 
11856
    network client.
 
11857
 
 
11858
  RETURN VALUES
 
11859
    NESTED_LOOP_OK           - the record has been successfully handled
 
11860
    NESTED_LOOP_ERROR        - a fatal error (like table corruption)
 
11861
                               was detected
 
11862
    NESTED_LOOP_KILLED       - thread shutdown was requested while processing
 
11863
                               the record
 
11864
    NESTED_LOOP_QUERY_LIMIT  - the record has been successfully handled;
 
11865
                               additionally, the nested loop produced the
 
11866
                               number of rows specified in the LIMIT clause
 
11867
                               for the query
 
11868
    NESTED_LOOP_CURSOR_LIMIT - the record has been successfully handled;
 
11869
                               additionally, there is a cursor and the nested
 
11870
                               loop algorithm produced the number of rows
 
11871
                               that is specified for current cursor fetch
 
11872
                               operation.
 
11873
   All return values except NESTED_LOOP_OK abort the nested loop.
 
11874
*****************************************************************************/
 
11875
 
 
11876
/* ARGSUSED */
 
11877
static enum_nested_loop_state
 
11878
end_send(JOIN *join, JOIN_TAB *,
 
11879
         bool end_of_records)
 
11880
{
 
11881
  if (!end_of_records)
 
11882
  {
 
11883
    int error;
 
11884
    if (join->having && join->having->val_int() == 0)
 
11885
      return(NESTED_LOOP_OK);               // Didn't match having
 
11886
    error=0;
 
11887
    if (join->do_send_rows)
 
11888
      error=join->result->send_data(*join->fields);
 
11889
    if (error)
 
11890
      return(NESTED_LOOP_ERROR); /* purecov: inspected */
 
11891
    if (++join->send_records >= join->unit->select_limit_cnt &&
 
11892
        join->do_send_rows)
 
11893
    {
 
11894
      if (join->select_options & OPTION_FOUND_ROWS)
 
11895
      {
 
11896
        JOIN_TAB *jt=join->join_tab;
 
11897
        if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group
 
11898
            && !join->send_group_parts && !join->having && !jt->select_cond &&
 
11899
            !(jt->select && jt->select->quick) &&
 
11900
            (jt->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
11901
            (jt->ref.key < 0))
 
11902
        {
 
11903
          /* Join over all rows in table;  Return number of found rows */
 
11904
          Table *table=jt->table;
 
11905
 
 
11906
          join->select_options ^= OPTION_FOUND_ROWS;
 
11907
          if (table->sort.record_pointers ||
 
11908
              (table->sort.io_cache && my_b_inited(table->sort.io_cache)))
 
11909
          {
 
11910
            /* Using filesort */
 
11911
            join->send_records= table->sort.found_records;
 
11912
          }
 
11913
          else
 
11914
          {
 
11915
            table->file->info(HA_STATUS_VARIABLE);
 
11916
            join->send_records= table->file->stats.records;
 
11917
          }
 
11918
        }
 
11919
        else
 
11920
        {
 
11921
          join->do_send_rows= 0;
 
11922
          if (join->unit->fake_select_lex)
 
11923
            join->unit->fake_select_lex->select_limit= 0;
 
11924
          return(NESTED_LOOP_OK);
 
11925
        }
 
11926
      }
 
11927
      return(NESTED_LOOP_QUERY_LIMIT);      // Abort nicely
 
11928
    }
 
11929
    else if (join->send_records >= join->fetch_limit)
 
11930
    {
 
11931
      /*
 
11932
        There is a server side cursor and all rows for
 
11933
        this fetch request are sent.
 
11934
      */
 
11935
      return(NESTED_LOOP_CURSOR_LIMIT);
 
11936
    }
 
11937
  }
 
11938
 
 
11939
  return(NESTED_LOOP_OK);
 
11940
}
 
11941
 
 
11942
 
 
11943
/* ARGSUSED */
 
11944
enum_nested_loop_state
 
11945
end_send_group(JOIN *join, JOIN_TAB *, bool end_of_records)
3803
11946
{
3804
11947
  int idx= -1;
3805
11948
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
3812
11955
    {
3813
11956
      if (idx < (int) join->send_group_parts)
3814
11957
      {
3815
 
        int error=0;
3816
 
        {
3817
 
          if (!join->first_record)
3818
 
          {
3819
 
                  List_iterator_fast<Item> it(*join->fields);
3820
 
                  Item *item;
3821
 
            /* No matching rows for group function */
3822
 
            join->clear();
 
11958
        int error=0;
 
11959
        {
 
11960
          if (!join->first_record)
 
11961
          {
 
11962
            List_iterator_fast<Item> it(*join->fields);
 
11963
            Item *item;
 
11964
            /* No matching rows for group function */
 
11965
            join->clear();
3823
11966
 
3824
11967
            while ((item= it++))
3825
11968
              item->no_rows_in_result();
3826
 
          }
3827
 
          if (join->having && join->having->val_int() == 0)
3828
 
            error= -1;                          // Didn't satisfy having
3829
 
          else
3830
 
          {
3831
 
            if (join->do_send_rows)
3832
 
              error=join->result->send_data(*join->fields) ? 1 : 0;
3833
 
            join->send_records++;
3834
 
          }
3835
 
          if (join->rollup.getState() != Rollup::STATE_NONE && error <= 0)
3836
 
          {
3837
 
            if (join->rollup_send_data((uint32_t) (idx+1)))
3838
 
              error= 1;
3839
 
          }
3840
 
        }
3841
 
        if (error > 0)
3842
 
          return(NESTED_LOOP_ERROR);
3843
 
        if (end_of_records)
3844
 
          return(NESTED_LOOP_OK);
3845
 
        if (join->send_records >= join->unit->select_limit_cnt &&
3846
 
            join->do_send_rows)
3847
 
        {
3848
 
          if (!(join->select_options & OPTION_FOUND_ROWS))
3849
 
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
3850
 
          join->do_send_rows=0;
3851
 
          join->unit->select_limit_cnt = HA_POS_ERROR;
 
11969
          }
 
11970
          if (join->having && join->having->val_int() == 0)
 
11971
            error= -1;                          // Didn't satisfy having
 
11972
          else
 
11973
          {
 
11974
            if (join->do_send_rows)
 
11975
              error=join->result->send_data(*join->fields) ? 1 : 0;
 
11976
            join->send_records++;
 
11977
          }
 
11978
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
 
11979
          {
 
11980
            if (join->rollup_send_data((uint32_t) (idx+1)))
 
11981
              error= 1;
 
11982
          }
 
11983
        }
 
11984
        if (error > 0)
 
11985
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
 
11986
        if (end_of_records)
 
11987
          return(NESTED_LOOP_OK);
 
11988
        if (join->send_records >= join->unit->select_limit_cnt &&
 
11989
            join->do_send_rows)
 
11990
        {
 
11991
          if (!(join->select_options & OPTION_FOUND_ROWS))
 
11992
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
 
11993
          join->do_send_rows=0;
 
11994
          join->unit->select_limit_cnt = HA_POS_ERROR;
3852
11995
        }
3853
11996
        else if (join->send_records >= join->fetch_limit)
3854
11997
        {
3867
12010
    else
3868
12011
    {
3869
12012
      if (end_of_records)
3870
 
        return(NESTED_LOOP_OK);
 
12013
        return(NESTED_LOOP_OK);
3871
12014
      join->first_record=1;
3872
12015
      test_if_item_cache_changed(join->group_fields);
3873
12016
    }
3879
12022
      */
3880
12023
      copy_fields(&join->tmp_table_param);
3881
12024
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
3882
 
        return(NESTED_LOOP_ERROR);
 
12025
        return(NESTED_LOOP_ERROR);
3883
12026
      return(ok_code);
3884
12027
    }
3885
12028
  }
3888
12031
  return(NESTED_LOOP_OK);
3889
12032
}
3890
12033
 
3891
 
enum_nested_loop_state end_write_group(Join *join, JoinTable *, bool end_of_records)
 
12034
 
 
12035
/* ARGSUSED */
 
12036
enum_nested_loop_state
 
12037
end_write(JOIN *join, JOIN_TAB *,
 
12038
          bool end_of_records)
 
12039
{
 
12040
  Table *table=join->tmp_table;
 
12041
 
 
12042
  if (join->session->killed)                    // Aborted by user
 
12043
  {
 
12044
    join->session->send_kill_message();
 
12045
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12046
  }
 
12047
  if (!end_of_records)
 
12048
  {
 
12049
    copy_fields(&join->tmp_table_param);
 
12050
    copy_funcs(join->tmp_table_param.items_to_copy);
 
12051
    if (!join->having || join->having->val_int())
 
12052
    {
 
12053
      int error;
 
12054
      join->found_records++;
 
12055
      if ((error=table->file->ha_write_row(table->record[0])))
 
12056
      {
 
12057
        if (!table->file->is_fatal_error(error, HA_CHECK_DUP))
 
12058
          goto end;
 
12059
        if (create_myisam_from_heap(join->session, table,
 
12060
                                    join->tmp_table_param.start_recinfo,
 
12061
                                    &join->tmp_table_param.recinfo,
 
12062
                                    error, 1))
 
12063
          return(NESTED_LOOP_ERROR);        // Not a table_is_full error
 
12064
        table->s->uniques=0;                    // To ensure rows are the same
 
12065
      }
 
12066
      if (++join->send_records >= join->tmp_table_param.end_write_records &&
 
12067
          join->do_send_rows)
 
12068
      {
 
12069
        if (!(join->select_options & OPTION_FOUND_ROWS))
 
12070
          return(NESTED_LOOP_QUERY_LIMIT);
 
12071
        join->do_send_rows=0;
 
12072
        join->unit->select_limit_cnt = HA_POS_ERROR;
 
12073
        return(NESTED_LOOP_OK);
 
12074
      }
 
12075
    }
 
12076
  }
 
12077
end:
 
12078
  return(NESTED_LOOP_OK);
 
12079
}
 
12080
 
 
12081
/* ARGSUSED */
 
12082
/** Group by searching after group record and updating it if possible. */
 
12083
 
 
12084
static enum_nested_loop_state
 
12085
end_update(JOIN *join, JOIN_TAB *,
 
12086
           bool end_of_records)
 
12087
{
 
12088
  Table *table=join->tmp_table;
 
12089
  order_st   *group;
 
12090
  int     error;
 
12091
 
 
12092
  if (end_of_records)
 
12093
    return(NESTED_LOOP_OK);
 
12094
  if (join->session->killed)                    // Aborted by user
 
12095
  {
 
12096
    join->session->send_kill_message();
 
12097
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12098
  }
 
12099
 
 
12100
  join->found_records++;
 
12101
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
 
12102
  /* Make a key of group index */
 
12103
  for (group=table->group ; group ; group=group->next)
 
12104
  {
 
12105
    Item *item= *group->item;
 
12106
    item->save_org_in_field(group->field);
 
12107
    /* Store in the used key if the field was 0 */
 
12108
    if (item->maybe_null)
 
12109
      group->buff[-1]= (char) group->field->is_null();
 
12110
  }
 
12111
  if (!table->file->index_read_map(table->record[1],
 
12112
                                   join->tmp_table_param.group_buff,
 
12113
                                   HA_WHOLE_KEY,
 
12114
                                   HA_READ_KEY_EXACT))
 
12115
  {                                             /* Update old record */
 
12116
    restore_record(table,record[1]);
 
12117
    update_tmptable_sum_func(join->sum_funcs,table);
 
12118
    if ((error=table->file->ha_update_row(table->record[1],
 
12119
                                          table->record[0])))
 
12120
    {
 
12121
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12122
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12123
    }
 
12124
    return(NESTED_LOOP_OK);
 
12125
  }
 
12126
 
 
12127
  /*
 
12128
    Copy null bits from group key to table
 
12129
    We can't copy all data as the key may have different format
 
12130
    as the row data (for example as with VARCHAR keys)
 
12131
  */
 
12132
  KEY_PART_INFO *key_part;
 
12133
  for (group=table->group,key_part=table->key_info[0].key_part;
 
12134
       group ;
 
12135
       group=group->next,key_part++)
 
12136
  {
 
12137
    if (key_part->null_bit)
 
12138
      memcpy(table->record[0]+key_part->offset, group->buff, 1);
 
12139
  }
 
12140
  init_tmptable_sum_functions(join->sum_funcs);
 
12141
  copy_funcs(join->tmp_table_param.items_to_copy);
 
12142
  if ((error=table->file->ha_write_row(table->record[0])))
 
12143
  {
 
12144
    if (create_myisam_from_heap(join->session, table,
 
12145
                                join->tmp_table_param.start_recinfo,
 
12146
                                &join->tmp_table_param.recinfo,
 
12147
                                error, 0))
 
12148
      return(NESTED_LOOP_ERROR);            // Not a table_is_full error
 
12149
    /* Change method to update rows */
 
12150
    table->file->ha_index_init(0, 0);
 
12151
    join->join_tab[join->tables-1].next_select=end_unique_update;
 
12152
  }
 
12153
  join->send_records++;
 
12154
  return(NESTED_LOOP_OK);
 
12155
}
 
12156
 
 
12157
 
 
12158
/** Like end_update, but this is done with unique constraints instead of keys.  */
 
12159
 
 
12160
static enum_nested_loop_state
 
12161
end_unique_update(JOIN *join, JOIN_TAB *,
 
12162
                  bool end_of_records)
 
12163
{
 
12164
  Table *table=join->tmp_table;
 
12165
  int     error;
 
12166
 
 
12167
  if (end_of_records)
 
12168
    return(NESTED_LOOP_OK);
 
12169
  if (join->session->killed)                    // Aborted by user
 
12170
  {
 
12171
    join->session->send_kill_message();
 
12172
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
12173
  }
 
12174
 
 
12175
  init_tmptable_sum_functions(join->sum_funcs);
 
12176
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
 
12177
  copy_funcs(join->tmp_table_param.items_to_copy);
 
12178
 
 
12179
  if (!(error=table->file->ha_write_row(table->record[0])))
 
12180
    join->send_records++;                       // New group
 
12181
  else
 
12182
  {
 
12183
    if ((int) table->file->get_dup_key(error) < 0)
 
12184
    {
 
12185
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12186
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12187
    }
 
12188
    if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
 
12189
    {
 
12190
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12191
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12192
    }
 
12193
    restore_record(table,record[1]);
 
12194
    update_tmptable_sum_func(join->sum_funcs,table);
 
12195
    if ((error=table->file->ha_update_row(table->record[1],
 
12196
                                          table->record[0])))
 
12197
    {
 
12198
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
 
12199
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
12200
    }
 
12201
  }
 
12202
  return(NESTED_LOOP_OK);
 
12203
}
 
12204
 
 
12205
 
 
12206
/* ARGSUSED */
 
12207
enum_nested_loop_state
 
12208
end_write_group(JOIN *join, JOIN_TAB *,
 
12209
                bool end_of_records)
3892
12210
{
3893
12211
  Table *table=join->tmp_table;
3894
12212
  int     idx= -1;
3895
12213
 
3896
 
  if (join->session->getKilled())
 
12214
  if (join->session->killed)
3897
12215
  {                                             // Aborted by user
3898
12216
    join->session->send_kill_message();
3899
 
    return NESTED_LOOP_KILLED;
 
12217
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
3900
12218
  }
3901
12219
  if (!join->first_record || end_of_records ||
3902
12220
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
3906
12224
      int send_group_parts= join->send_group_parts;
3907
12225
      if (idx < send_group_parts)
3908
12226
      {
3909
 
        if (!join->first_record)
3910
 
        {
3911
 
          /* No matching rows for group function */
3912
 
          join->clear();
3913
 
        }
3914
 
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
3915
 
        if (!join->having || join->having->val_int())
3916
 
        {
3917
 
          int error= table->cursor->insertRecord(table->getInsertRecord());
3918
 
 
3919
 
          if (error)
3920
 
          {
3921
 
            my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
3922
 
            return NESTED_LOOP_ERROR;
3923
 
          }
3924
 
        }
3925
 
        if (join->rollup.getState() != Rollup::STATE_NONE)
3926
 
        {
3927
 
          if (join->rollup_write_data((uint32_t) (idx+1), table))
3928
 
            return NESTED_LOOP_ERROR;
3929
 
        }
3930
 
        if (end_of_records)
3931
 
          return NESTED_LOOP_OK;
 
12227
        if (!join->first_record)
 
12228
        {
 
12229
          /* No matching rows for group function */
 
12230
          join->clear();
 
12231
        }
 
12232
        copy_sum_funcs(join->sum_funcs,
 
12233
                       join->sum_funcs_end[send_group_parts]);
 
12234
        if (!join->having || join->having->val_int())
 
12235
        {
 
12236
          int error= table->file->ha_write_row(table->record[0]);
 
12237
          if (error && create_myisam_from_heap(join->session, table,
 
12238
                                               join->tmp_table_param.start_recinfo,
 
12239
                                                &join->tmp_table_param.recinfo,
 
12240
                                               error, 0))
 
12241
            return(NESTED_LOOP_ERROR);
 
12242
        }
 
12243
        if (join->rollup.state != ROLLUP::STATE_NONE)
 
12244
        {
 
12245
          if (join->rollup_write_data((uint32_t) (idx+1), table))
 
12246
            return(NESTED_LOOP_ERROR);
 
12247
        }
 
12248
        if (end_of_records)
 
12249
          return(NESTED_LOOP_OK);
3932
12250
      }
3933
12251
    }
3934
12252
    else
3935
12253
    {
3936
12254
      if (end_of_records)
3937
 
        return NESTED_LOOP_OK;
 
12255
        return(NESTED_LOOP_OK);
3938
12256
      join->first_record=1;
3939
12257
      test_if_item_cache_changed(join->group_fields);
3940
12258
    }
3941
12259
    if (idx < (int) join->send_group_parts)
3942
12260
    {
3943
12261
      copy_fields(&join->tmp_table_param);
3944
 
      if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
3945
 
        return NESTED_LOOP_ERROR;
 
12262
      copy_funcs(join->tmp_table_param.items_to_copy);
3946
12263
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
3947
 
        return NESTED_LOOP_ERROR;
3948
 
      return NESTED_LOOP_OK;
 
12264
        return(NESTED_LOOP_ERROR);
 
12265
      return(NESTED_LOOP_OK);
3949
12266
    }
3950
12267
  }
3951
12268
  if (update_sum_func(join->sum_funcs))
3952
 
    return NESTED_LOOP_ERROR;
3953
 
  return NESTED_LOOP_OK;
 
12269
    return(NESTED_LOOP_ERROR);
 
12270
  return(NESTED_LOOP_OK);
3954
12271
}
3955
12272
 
 
12273
 
3956
12274
/*****************************************************************************
3957
12275
  Remove calculation with tables that aren't yet read. Remove also tests
3958
12276
  against fields that are read through key where the table is not a
3959
12277
  outer join table.
3960
12278
  We can't remove tests that are made against columns which are stored
3961
12279
  in sorted order.
 
12280
*****************************************************************************/
 
12281
 
 
12282
/**
3962
12283
  @return
3963
 
    1 if right_item used is a removable reference key on left_item
3964
 
    0 otherwise.
3965
 
****************************************************************************/
3966
 
bool test_if_ref(Item_field *left_item,Item *right_item)
 
12284
    1 if right_item is used removable reference key on left_item
 
12285
*/
 
12286
 
 
12287
static bool test_if_ref(Item_field *left_item,Item *right_item)
3967
12288
{
3968
12289
  Field *field=left_item->field;
3969
12290
  // No need to change const test. We also have to keep tests on LEFT JOIN
3970
 
  if (not field->getTable()->const_table && !field->getTable()->maybe_null)
 
12291
  if (!field->table->const_table && !field->table->maybe_null)
3971
12292
  {
3972
 
    Item *ref_item=part_of_refkey(field->getTable(),field);
 
12293
    Item *ref_item=part_of_refkey(field->table,field);
3973
12294
    if (ref_item && ref_item->eq(right_item,1))
3974
12295
    {
3975
12296
      right_item= right_item->real_item();
3976
12297
      if (right_item->type() == Item::FIELD_ITEM)
3977
 
        return (field->eq_def(((Item_field *) right_item)->field));
 
12298
        return (field->eq_def(((Item_field *) right_item)->field));
3978
12299
      /* remove equalities injected by IN->EXISTS transformation */
3979
12300
      else if (right_item->type() == Item::CACHE_ITEM)
3980
12301
        return ((Item_cache *)right_item)->eq_def (field);
3981
12302
      if (right_item->const_item() && !(right_item->is_null()))
3982
12303
      {
3983
 
        /*
3984
 
          We can remove binary fields and numerical fields except float,
3985
 
          as float comparison isn't 100 % secure
3986
 
          We have to keep normal strings to be able to check for end spaces
 
12304
        /*
 
12305
          We can remove binary fields and numerical fields except float,
 
12306
          as float comparison isn't 100 % secure
 
12307
          We have to keep normal strings to be able to check for end spaces
3987
12308
 
3988
 
                sergefp: the above seems to be too restrictive. Counterexample:
3989
 
                  create table t100 (v varchar(10), key(v)) default charset=latin1;
3990
 
                  insert into t100 values ('a'),('a ');
3991
 
                  explain select * from t100 where v='a';
3992
 
                The EXPLAIN shows 'using Where'. Running the query returns both
3993
 
                rows, so it seems there are no problems with endspace in the most
3994
 
                frequent case?
3995
 
        */
3996
 
        if (field->binary() &&
3997
 
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
3998
 
            field->decimals() == 0)
3999
 
        {
4000
 
          return ! store_val_in_field(field, right_item, CHECK_FIELD_WARN);
4001
 
        }
 
12309
          sergefp: the above seems to be too restrictive. Counterexample:
 
12310
            create table t100 (v varchar(10), key(v)) default charset=latin1;
 
12311
            insert into t100 values ('a'),('a ');
 
12312
            explain select * from t100 where v='a';
 
12313
          The EXPLAIN shows 'using Where'. Running the query returns both
 
12314
          rows, so it seems there are no problems with endspace in the most
 
12315
          frequent case?
 
12316
        */
 
12317
        if (field->binary() &&
 
12318
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
 
12319
            field->decimals() == 0)
 
12320
        {
 
12321
          return !store_val_in_field(field, right_item, CHECK_FIELD_WARN);
 
12322
        }
4002
12323
      }
4003
12324
    }
4004
12325
  }
4005
 
  return 0;
 
12326
  return 0;                                     // keep test
 
12327
}
 
12328
 
 
12329
/**
 
12330
   @brief Replaces an expression destructively inside the expression tree of
 
12331
   the WHERE clase.
 
12332
 
 
12333
   @note Because of current requirements for semijoin flattening, we do not
 
12334
   need to recurse here, hence this function will only examine the top-level
 
12335
   AND conditions. (see JOIN::prepare, comment above the line
 
12336
   'if (do_materialize)'
 
12337
 
 
12338
   @param join The top-level query.
 
12339
   @param old_cond The expression to be replaced.
 
12340
   @param new_cond The expression to be substituted.
 
12341
   @param do_fix_fields If true, Item::fix_fields(Session*, Item**) is called for
 
12342
   the new expression.
 
12343
   @return <code>true</code> if there was an error, <code>false</code> if
 
12344
   successful.
 
12345
*/
 
12346
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
 
12347
                                       Item *new_cond, bool do_fix_fields)
 
12348
{
 
12349
  if (join->conds == old_cond) {
 
12350
    join->conds= new_cond;
 
12351
    if (do_fix_fields)
 
12352
      new_cond->fix_fields(join->session, &join->conds);
 
12353
    return false;
 
12354
  }
 
12355
 
 
12356
  if (join->conds->type() == Item::COND_ITEM) {
 
12357
    List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
 
12358
    Item *item;
 
12359
    while ((item= li++))
 
12360
      if (item == old_cond)
 
12361
      {
 
12362
        li.replace(new_cond);
 
12363
        if (do_fix_fields)
 
12364
          new_cond->fix_fields(join->session, li.ref());
 
12365
        return false;
 
12366
      }
 
12367
  }
 
12368
 
 
12369
  return true;
4006
12370
}
4007
12371
 
4008
12372
/*
4036
12400
  RETURN
4037
12401
    Extracted condition
4038
12402
*/
4039
 
COND *make_cond_for_table(COND *cond, table_map tables, table_map used_table, bool exclude_expensive_cond)
 
12403
 
 
12404
static COND *
 
12405
make_cond_for_table(COND *cond, table_map tables, table_map used_table,
 
12406
                    bool exclude_expensive_cond)
4040
12407
{
4041
12408
  if (used_table && !(cond->used_tables() & used_table) &&
4042
 
    /*
4043
 
      Exclude constant conditions not checked at optimization time if
4044
 
      the table we are pushing conditions to is the first one.
4045
 
      As a result, such conditions are not considered as already checked
4046
 
      and will be checked at execution time, attached to the first table.
4047
 
    */
4048
 
    !((used_table & 1) && cond->is_expensive()))
 
12409
      /*
 
12410
        Exclude constant conditions not checked at optimization time if
 
12411
        the table we are pushing conditions to is the first one.
 
12412
        As a result, such conditions are not considered as already checked
 
12413
        and will be checked at execution time, attached to the first table.
 
12414
      */
 
12415
      !((used_table & 1) && cond->is_expensive()))
4049
12416
    return (COND*) 0;                           // Already checked
4050
12417
  if (cond->type() == Item::COND_ITEM)
4051
12418
  {
4054
12421
      /* Create new top level AND item */
4055
12422
      Item_cond_and *new_cond=new Item_cond_and;
4056
12423
      if (!new_cond)
4057
 
        return (COND*) 0;
 
12424
        return (COND*) 0;                       // OOM /* purecov: inspected */
4058
12425
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4059
12426
      Item *item;
4060
12427
      while ((item=li++))
4061
12428
      {
4062
 
        Item *fix= make_cond_for_table(item,tables,used_table,
4063
 
                                            exclude_expensive_cond);
4064
 
        if (fix)
4065
 
          new_cond->argument_list()->push_back(fix);
 
12429
        Item *fix=make_cond_for_table(item,tables,used_table,
 
12430
                                      exclude_expensive_cond);
 
12431
        if (fix)
 
12432
          new_cond->argument_list()->push_back(fix);
4066
12433
      }
4067
 
      switch (new_cond->argument_list()->elements) 
4068
 
      {
4069
 
        case 0:
4070
 
          return (COND*) 0;                     // Always true
4071
 
        case 1:
4072
 
          return new_cond->argument_list()->head();
4073
 
        default:
4074
 
          /*
4075
 
            Item_cond_and do not need fix_fields for execution, its parameters
4076
 
            are fixed or do not need fix_fields, too
4077
 
          */
4078
 
          new_cond->quick_fix_field();
4079
 
          new_cond->used_tables_cache= ((Item_cond_and*) cond)->used_tables_cache & tables;
4080
 
          return new_cond;
 
12434
      switch (new_cond->argument_list()->elements) {
 
12435
      case 0:
 
12436
        return (COND*) 0;                       // Always true
 
12437
      case 1:
 
12438
        return new_cond->argument_list()->head();
 
12439
      default:
 
12440
        /*
 
12441
          Item_cond_and do not need fix_fields for execution, its parameters
 
12442
          are fixed or do not need fix_fields, too
 
12443
        */
 
12444
        new_cond->quick_fix_field();
 
12445
        new_cond->used_tables_cache=
 
12446
          ((Item_cond_and*) cond)->used_tables_cache &
 
12447
          tables;
 
12448
        return new_cond;
4081
12449
      }
4082
12450
    }
4083
12451
    else
4084
12452
    {                                           // Or list
4085
12453
      Item_cond_or *new_cond=new Item_cond_or;
4086
12454
      if (!new_cond)
4087
 
        return (COND*) 0;
 
12455
        return (COND*) 0;                       // OOM /* purecov: inspected */
4088
12456
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4089
12457
      Item *item;
4090
12458
      while ((item=li++))
4091
12459
      {
4092
 
        Item *fix= make_cond_for_table(item,tables,0L, exclude_expensive_cond);
4093
 
        if (!fix)
4094
 
          return (COND*) 0;                     // Always true
4095
 
        new_cond->argument_list()->push_back(fix);
 
12460
        Item *fix=make_cond_for_table(item,tables,0L, exclude_expensive_cond);
 
12461
        if (!fix)
 
12462
          return (COND*) 0;                     // Always true
 
12463
        new_cond->argument_list()->push_back(fix);
4096
12464
      }
4097
12465
      /*
4098
 
        Item_cond_and do not need fix_fields for execution, its parameters
4099
 
        are fixed or do not need fix_fields, too
 
12466
        Item_cond_and do not need fix_fields for execution, its parameters
 
12467
        are fixed or do not need fix_fields, too
4100
12468
      */
4101
12469
      new_cond->quick_fix_field();
4102
12470
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
4129
12497
  {
4130
12498
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
4131
12499
    Item *right_item= ((Item_func*) cond)->arguments()[1];
4132
 
    if (left_item->type() == Item::FIELD_ITEM && test_if_ref((Item_field*) left_item,right_item))
 
12500
    if (left_item->type() == Item::FIELD_ITEM &&
 
12501
        test_if_ref((Item_field*) left_item,right_item))
4133
12502
    {
4134
12503
      cond->marker=3;                   // Checked when read
4135
12504
      return (COND*) 0;
4136
12505
    }
4137
 
    if (right_item->type() == Item::FIELD_ITEM &&       test_if_ref((Item_field*) right_item,left_item))
 
12506
    if (right_item->type() == Item::FIELD_ITEM &&
 
12507
        test_if_ref((Item_field*) right_item,left_item))
4138
12508
    {
4139
12509
      cond->marker=3;                   // Checked when read
4140
12510
      return (COND*) 0;
4144
12514
  return cond;
4145
12515
}
4146
12516
 
4147
 
static Item *part_of_refkey(Table *table,Field *field)
 
12517
 
 
12518
static Item *
 
12519
part_of_refkey(Table *table,Field *field)
4148
12520
{
4149
12521
  if (!table->reginfo.join_tab)
4150
12522
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
4152
12524
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
4153
12525
  if (ref_parts)
4154
12526
  {
4155
 
    KeyPartInfo *key_part=
 
12527
    KEY_PART_INFO *key_part=
4156
12528
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
4157
12529
    uint32_t part;
4158
12530
 
4163
12535
    }
4164
12536
 
4165
12537
    for (part=0 ; part < ref_parts ; part++,key_part++)
4166
 
    {
4167
12538
      if (field->eq(key_part->field) &&
4168
 
          !(key_part->key_part_flag & HA_PART_KEY_SEG) &&
4169
 
          //If field can be NULL, we should not remove this predicate, as
4170
 
          //it may lead to non-rejection of NULL values. 
4171
 
          !(field->real_maybe_null()))
4172
 
      {
 
12539
          !(key_part->key_part_flag & HA_PART_KEY_SEG))
4173
12540
        return table->reginfo.join_tab->ref.items[part];
4174
 
      }
4175
 
    }
4176
12541
  }
4177
12542
  return (Item*) 0;
4178
12543
}
4179
12544
 
 
12545
 
4180
12546
/**
4181
12547
  Test if one can use the key to resolve order_st BY.
4182
12548
 
4197
12563
  @retval
4198
12564
    -1   Reverse key can be used
4199
12565
*/
4200
 
static int test_if_order_by_key(Order *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
 
12566
 
 
12567
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx,
 
12568
                                uint32_t *used_key_parts)
4201
12569
{
4202
 
  KeyPartInfo *key_part= NULL;
4203
 
  KeyPartInfo *key_part_end= NULL;
4204
 
  key_part= table->key_info[idx].key_part;
4205
 
  key_part_end= key_part + table->key_info[idx].key_parts;
 
12570
  KEY_PART_INFO *key_part,*key_part_end;
 
12571
  key_part=table->key_info[idx].key_part;
 
12572
  key_part_end=key_part+table->key_info[idx].key_parts;
4206
12573
  key_part_map const_key_parts=table->const_key_parts[idx];
4207
 
  int reverse= 0;
 
12574
  int reverse=0;
4208
12575
  bool on_primary_key= false;
4209
12576
 
4210
12577
  for (; order ; order=order->next, const_key_parts>>=1)
4214
12581
 
4215
12582
    /*
4216
12583
      Skip key parts that are constants in the WHERE clause.
4217
 
      These are already skipped in the ORDER BY by const_expression_in_where()
 
12584
      These are already skipped in the order_st BY by const_expression_in_where()
4218
12585
    */
4219
12586
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4220
12587
      key_part++;
4227
12594
        the primary key as a suffix.
4228
12595
      */
4229
12596
      if (!on_primary_key &&
4230
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
4231
 
          table->getShare()->hasPrimaryKey())
 
12597
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
12598
          table->s->primary_key != MAX_KEY)
4232
12599
      {
4233
12600
        on_primary_key= true;
4234
 
        key_part= table->key_info[table->getShare()->getPrimaryKey()].key_part;
4235
 
        key_part_end=key_part+table->key_info[table->getShare()->getPrimaryKey()].key_parts;
4236
 
        const_key_parts=table->const_key_parts[table->getShare()->getPrimaryKey()];
 
12601
        key_part= table->key_info[table->s->primary_key].key_part;
 
12602
        key_part_end=key_part+table->key_info[table->s->primary_key].key_parts;
 
12603
        const_key_parts=table->const_key_parts[table->s->primary_key];
4237
12604
 
4238
12605
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
4239
12606
          key_part++;
4261
12628
  }
4262
12629
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4263
12630
    (uint32_t) (key_part - table->key_info[idx].key_part);
4264
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
12631
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
4265
12632
                         HA_READ_PREV))
4266
12633
    reverse= 0;                                 // Index can't be used
4267
12634
  return(reverse);
4268
12635
}
4269
12636
 
 
12637
 
4270
12638
/**
4271
12639
  Test if a second key is the subkey of the first one.
4272
12640
 
4282
12650
  @retval
4283
12651
    0   no sub key
4284
12652
*/
4285
 
inline bool is_subkey(KeyPartInfo *key_part,
4286
 
                      KeyPartInfo *ref_key_part,
4287
 
                      KeyPartInfo *ref_key_part_end)
 
12653
 
 
12654
inline bool
 
12655
is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
 
12656
          KEY_PART_INFO *ref_key_part_end)
4288
12657
{
4289
12658
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4290
 
    if (! key_part->field->eq(ref_key_part->field))
 
12659
    if (!key_part->field->eq(ref_key_part->field))
4291
12660
      return 0;
4292
12661
  return 1;
4293
12662
}
4303
12672
    - MAX_KEY                   If we can't use other key
4304
12673
    - the number of found key   Otherwise
4305
12674
*/
4306
 
static uint32_t test_if_subkey(Order *order,
4307
 
                               Table *table,
4308
 
                               uint32_t ref,
4309
 
                               uint32_t ref_key_parts,
4310
 
                               const key_map *usable_keys)
 
12675
 
 
12676
static uint
 
12677
test_if_subkey(order_st *order, Table *table, uint32_t ref, uint32_t ref_key_parts,
 
12678
               const key_map *usable_keys)
4311
12679
{
4312
12680
  uint32_t nr;
4313
12681
  uint32_t min_length= UINT32_MAX;
4314
12682
  uint32_t best= MAX_KEY;
4315
12683
  uint32_t not_used;
4316
 
  KeyPartInfo *ref_key_part= table->key_info[ref].key_part;
4317
 
  KeyPartInfo *ref_key_part_end= ref_key_part + ref_key_parts;
 
12684
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
 
12685
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
4318
12686
 
4319
 
  for (nr= 0 ; nr < table->getShare()->sizeKeys() ; nr++)
 
12687
  for (nr= 0 ; nr < table->s->keys ; nr++)
4320
12688
  {
4321
 
    if (usable_keys->test(nr) &&
 
12689
    if (usable_keys->is_set(nr) &&
4322
12690
        table->key_info[nr].key_length < min_length &&
4323
12691
        table->key_info[nr].key_parts >= ref_key_parts &&
4324
12692
        is_subkey(table->key_info[nr].key_part, ref_key_part,
4332
12700
  return best;
4333
12701
}
4334
12702
 
 
12703
 
4335
12704
/**
4336
12705
  Check if GROUP BY/DISTINCT can be optimized away because the set is
4337
12706
  already known to be distinct.
4363
12732
  @retval
4364
12733
    0                    not found.
4365
12734
*/
4366
 
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
 
12735
 
 
12736
static bool
 
12737
list_contains_unique_index(Table *table,
 
12738
                          bool (*find_func) (Field *, void *), void *data)
4367
12739
{
4368
 
  for (uint32_t keynr= 0; keynr < table->getShare()->sizeKeys(); keynr++)
 
12740
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
4369
12741
  {
4370
 
    if (keynr == table->getShare()->getPrimaryKey() ||
 
12742
    if (keynr == table->s->primary_key ||
4371
12743
         (table->key_info[keynr].flags & HA_NOSAME))
4372
12744
    {
4373
 
      KeyInfo *keyinfo= table->key_info + keynr;
4374
 
      KeyPartInfo *key_part= NULL;
4375
 
      KeyPartInfo *key_part_end= NULL;
 
12745
      KEY *keyinfo= table->key_info + keynr;
 
12746
      KEY_PART_INFO *key_part, *key_part_end;
4376
12747
 
4377
12748
      for (key_part=keyinfo->key_part,
4378
12749
           key_part_end=key_part+ keyinfo->key_parts;
4380
12751
           key_part++)
4381
12752
      {
4382
12753
        if (key_part->field->maybe_null() ||
4383
 
            ! find_func(key_part->field, data))
 
12754
            !find_func(key_part->field, data))
4384
12755
          break;
4385
12756
      }
4386
12757
      if (key_part == key_part_end)
4390
12761
  return 0;
4391
12762
}
4392
12763
 
 
12764
 
4393
12765
/**
4394
12766
  Helper function for list_contains_unique_index.
4395
12767
  Find a field reference in a list of order_st structures.
4403
12775
  @retval
4404
12776
    0                    not found.
4405
12777
*/
4406
 
bool find_field_in_order_list (Field *field, void *data)
 
12778
 
 
12779
static bool
 
12780
find_field_in_order_list (Field *field, void *data)
4407
12781
{
4408
 
  Order *group= (Order *) data;
 
12782
  order_st *group= (order_st *) data;
4409
12783
  bool part_found= 0;
4410
 
  for (Order *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
12784
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
4411
12785
  {
4412
12786
    Item *item= (*tmp_group->item)->real_item();
4413
12787
    if (item->type() == Item::FIELD_ITEM &&
4420
12794
  return part_found;
4421
12795
}
4422
12796
 
 
12797
 
4423
12798
/**
4424
12799
  Helper function for list_contains_unique_index.
4425
12800
  Find a field reference in a dynamic list of Items.
4433
12808
  @retval
4434
12809
    0                    not found.
4435
12810
*/
4436
 
bool find_field_in_item_list (Field *field, void *data)
 
12811
 
 
12812
static bool
 
12813
find_field_in_item_list (Field *field, void *data)
4437
12814
{
4438
12815
  List<Item> *fields= (List<Item> *) data;
4439
12816
  bool part_found= 0;
4452
12829
  return part_found;
4453
12830
}
4454
12831
 
 
12832
 
4455
12833
/**
4456
 
  Test if we can skip the ORDER BY by using an index.
 
12834
  Test if we can skip the order_st BY by using an index.
4457
12835
 
4458
12836
  SYNOPSIS
4459
12837
    test_if_skip_sort_order()
4463
12841
      no_changes
4464
12842
      map
4465
12843
 
4466
 
  If we can use an index, the JoinTable / tab->select struct
 
12844
  If we can use an index, the JOIN_TAB / tab->select struct
4467
12845
  is changed to use the index.
4468
12846
 
4469
12847
  The index must cover all fields in <order>, or it will not be considered.
4477
12855
  @retval
4478
12856
    1    We can use an index.
4479
12857
*/
4480
 
bool test_if_skip_sort_order(JoinTable *tab, Order *order, ha_rows select_limit, bool no_changes, const key_map *map)
 
12858
 
 
12859
static bool
 
12860
test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,ha_rows select_limit,
 
12861
                        bool no_changes, const key_map *map)
4481
12862
{
4482
12863
  int32_t ref_key;
4483
12864
  uint32_t ref_key_parts;
4484
12865
  int order_direction;
4485
12866
  uint32_t used_key_parts;
4486
12867
  Table *table=tab->table;
4487
 
  optimizer::SqlSelect *select= tab->select;
 
12868
  SQL_SELECT *select=tab->select;
4488
12869
  key_map usable_keys;
4489
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
12870
  QUICK_SELECT_I *save_quick= 0;
4490
12871
 
4491
12872
  /*
4492
12873
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4494
12875
  */
4495
12876
  usable_keys= *map;
4496
12877
 
4497
 
  for (Order *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
12878
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
4498
12879
  {
4499
12880
    Item *item= (*tmp_order->item)->real_item();
4500
12881
    if (item->type() != Item::FIELD_ITEM)
4501
12882
    {
4502
 
      usable_keys.reset();
 
12883
      usable_keys.clear_all();
4503
12884
      return(0);
4504
12885
    }
4505
 
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
4506
 
    if (usable_keys.none())
 
12886
    usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey);
 
12887
    if (usable_keys.is_clear_all())
4507
12888
      return(0);                                        // No usable keys
4508
12889
  }
4509
12890
 
4513
12894
  {
4514
12895
    ref_key=       tab->ref.key;
4515
12896
    ref_key_parts= tab->ref.key_parts;
4516
 
    if (tab->type == AM_REF_OR_NULL)
 
12897
    if (tab->type == JT_REF_OR_NULL)
4517
12898
      return(0);
4518
12899
  }
4519
 
  else if (select && select->quick)             // Range found by optimizer/range
 
12900
  else if (select && select->quick)             // Range found by opt_range
4520
12901
  {
4521
12902
    int quick_type= select->quick->get_type();
4522
12903
    save_quick= select->quick;
4526
12907
      by clustered PK values.
4527
12908
    */
4528
12909
 
4529
 
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4530
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4531
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT)
 
12910
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
12911
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
12912
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
4532
12913
      return(0);
4533
12914
    ref_key=       select->quick->index;
4534
12915
    ref_key_parts= select->quick->used_key_parts;
4539
12920
    /*
4540
12921
      We come here when there is a REF key.
4541
12922
    */
4542
 
    if (! usable_keys.test(ref_key))
 
12923
    if (!usable_keys.is_set(ref_key))
4543
12924
    {
4544
12925
      /*
4545
 
        We come here when ref_key is not among usable_keys
 
12926
        We come here when ref_key is not among usable_keys
4546
12927
      */
4547
12928
      uint32_t new_ref_key;
4548
12929
      /*
4549
 
        If using index only read, only consider other possible index only
4550
 
        keys
 
12930
        If using index only read, only consider other possible index only
 
12931
        keys
4551
12932
      */
4552
 
      if (table->covering_keys.test(ref_key))
4553
 
        usable_keys&= table->covering_keys;
 
12933
      if (table->covering_keys.is_set(ref_key))
 
12934
        usable_keys.intersect(table->covering_keys);
4554
12935
      if (tab->pre_idx_push_select_cond)
4555
12936
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
4556
12937
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
4557
12938
                                       &usable_keys)) < MAX_KEY)
4558
12939
      {
4559
 
        /* Found key that can be used to retrieve data in sorted order */
4560
 
        if (tab->ref.key >= 0)
4561
 
        {
 
12940
        /* Found key that can be used to retrieve data in sorted order */
 
12941
        if (tab->ref.key >= 0)
 
12942
        {
4562
12943
          /*
4563
12944
            We'll use ref access method on key new_ref_key. In general case
4564
12945
            the index search tuple for new_ref_key will be different (e.g.
4567
12948
            "part1 = const1 AND part2=const2".
4568
12949
            So we build tab->ref from scratch here.
4569
12950
          */
4570
 
          optimizer::KeyUse *keyuse= tab->keyuse;
4571
 
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
 
12951
          KEYUSE *keyuse= tab->keyuse;
 
12952
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
4572
12953
            keyuse++;
4573
12954
 
4574
12955
          if (create_ref_for_key(tab->join, tab, keyuse,
4575
12956
                                 tab->join->const_table_map))
4576
12957
            return(0);
4577
 
        }
4578
 
        else
4579
 
        {
 
12958
        }
 
12959
        else
 
12960
        {
4580
12961
          /*
4581
 
            The range optimizer constructed QuickRange for ref_key, and
 
12962
            The range optimizer constructed QUICK_RANGE for ref_key, and
4582
12963
            we want to use instead new_ref_key as the index. We can't
4583
12964
            just change the index of the quick select, because this may
4584
12965
            result in an incosistent QUICK_SELECT object. Below we
4586
12967
            parameres are set correctly by the range optimizer.
4587
12968
           */
4588
12969
          key_map new_ref_key_map;
4589
 
          new_ref_key_map.reset();  // Force the creation of quick select
4590
 
          new_ref_key_map.set(new_ref_key); // only for new_ref_key.
 
12970
          new_ref_key_map.clear_all();  // Force the creation of quick select
 
12971
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
4591
12972
 
4592
12973
          if (select->test_quick_select(tab->join->session, new_ref_key_map, 0,
4593
12974
                                        (tab->join->select_options &
4597
12978
                                        true) <=
4598
12979
              0)
4599
12980
            return(0);
4600
 
        }
 
12981
        }
4601
12982
        ref_key= new_ref_key;
4602
12983
      }
4603
12984
    }
4604
12985
    /* Check if we get the rows in requested sorted order by using the key */
4605
 
    if (usable_keys.test(ref_key) &&
 
12986
    if (usable_keys.is_set(ref_key) &&
4606
12987
        (order_direction= test_if_order_by_key(order,table,ref_key,
4607
12988
                                               &used_key_parts)))
4608
12989
      goto check_reverse_order;
4623
13004
    int best_key= -1;
4624
13005
    bool is_best_covering= false;
4625
13006
    double fanout= 1;
4626
 
    Join *join= tab->join;
 
13007
    JOIN *join= tab->join;
4627
13008
    uint32_t tablenr= tab - join->join_tab;
4628
 
    ha_rows table_records= table->cursor->stats.records;
 
13009
    ha_rows table_records= table->file->stats.records;
4629
13010
    bool group= join->group && order == join->group_list;
4630
 
    optimizer::Position cur_pos;
4631
13011
 
4632
13012
    /*
4633
13013
      If not used with LIMIT, only use keys if the whole query can be
4640
13020
        filesort() and join cache are usually faster than reading in
4641
13021
        index order and not using join cache
4642
13022
        */
4643
 
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
 
13023
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
4644
13024
        return(0);
4645
 
      keys= *table->cursor->keys_to_use_for_scanning();
4646
 
      keys|= table->covering_keys;
 
13025
      keys= *table->file->keys_to_use_for_scanning();
 
13026
      keys.merge(table->covering_keys);
4647
13027
 
4648
13028
      /*
4649
 
        We are adding here also the index specified in FORCE INDEX clause,
4650
 
        if any.
 
13029
        We are adding here also the index specified in FORCE INDEX clause,
 
13030
        if any.
4651
13031
        This is to allow users to use index in order_st BY.
4652
13032
      */
4653
13033
      if (table->force_index)
4654
 
        keys|= (group ? table->keys_in_use_for_group_by :
4655
 
                                table->keys_in_use_for_order_by);
4656
 
      keys&= usable_keys;
 
13034
        keys.merge(group ? table->keys_in_use_for_group_by :
 
13035
                           table->keys_in_use_for_order_by);
 
13036
      keys.intersect(usable_keys);
4657
13037
    }
4658
13038
    else
4659
13039
      keys= usable_keys;
4660
13040
 
4661
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4662
 
    read_time= cur_pos.getCost();
 
13041
    read_time= join->best_positions[tablenr].read_time;
4663
13042
    for (uint32_t i= tablenr+1; i < join->tables; i++)
4664
 
    {
4665
 
      cur_pos= join->getPosFromOptimalPlan(i);
4666
 
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
4667
 
    }
 
13043
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
4668
13044
 
4669
 
    for (nr=0; nr < table->getShare()->sizeKeys() ; nr++)
 
13045
    for (nr=0; nr < table->s->keys ; nr++)
4670
13046
    {
4671
13047
      int direction;
4672
 
      if (keys.test(nr) &&
 
13048
      if (keys.is_set(nr) &&
4673
13049
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4674
13050
      {
4675
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->getShare()->getPrimaryKey() && table->cursor->primary_key_is_clustered());
 
13051
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
4676
13052
 
4677
13053
        /*
4678
 
          Don't use an index scan with ORDER BY without limit.
 
13054
          Don't use an index scan with order_st BY without limit.
4679
13055
          For GROUP BY without limit always use index scan
4680
13056
          if there is a suitable index.
4681
13057
          Why we hold to this asymmetry hardly can be explained
4682
13058
          rationally. It's easy to demonstrate that using
4683
13059
          temporary table + filesort could be cheaper for grouping
4684
13060
          queries too.
4685
 
        */
 
13061
        */
4686
13062
        if (is_covering ||
4687
13063
            select_limit != HA_POS_ERROR ||
4688
13064
            (ref_key < 0 && (group || table->force_index)))
4689
13065
        {
4690
13066
          double rec_per_key;
4691
13067
          double index_scan_time;
4692
 
          KeyInfo *keyinfo= tab->table->key_info+nr;
 
13068
          KEY *keyinfo= tab->table->key_info+nr;
4693
13069
          if (select_limit == HA_POS_ERROR)
4694
13070
            select_limit= table_records;
4695
13071
          if (group)
4696
13072
          {
4697
13073
            rec_per_key= keyinfo->rec_per_key[used_key_parts-1];
4698
 
            set_if_bigger(rec_per_key, 1.0);
 
13074
            set_if_bigger(rec_per_key, 1);
4699
13075
            /*
4700
13076
              With a grouping query each group containing on average
4701
13077
              rec_per_key records produces only one row that will
4702
13078
              be included into the result set.
4703
 
            */
 
13079
            */
4704
13080
            if (select_limit > table_records/rec_per_key)
4705
13081
                select_limit= table_records;
4706
13082
            else
4715
13091
            So the estimate for L/fanout(tk,tn) will be too optimistic
4716
13092
            and as result we'll choose an index scan when using ref/range
4717
13093
            access + filesort will be cheaper.
4718
 
          */
 
13094
          */
4719
13095
          select_limit= (ha_rows) (select_limit < fanout ?
4720
13096
                                   1 : select_limit/fanout);
4721
13097
          /*
4735
13111
                                     (double) table_records /
4736
13112
                                      table->quick_condition_rows);
4737
13113
          rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1];
4738
 
          set_if_bigger(rec_per_key, 1.0);
 
13114
          set_if_bigger(rec_per_key, 1);
4739
13115
          /*
4740
13116
            Here we take into account the fact that rows are
4741
13117
            accessed in sequences rec_per_key records in each.
4742
13118
            Rows in such a sequence are supposed to be ordered
4743
13119
            by rowid/primary key. When reading the data
4744
13120
            in a sequence we'll touch not more pages than the
4745
 
            table cursor contains.
 
13121
            table file contains.
4746
13122
            TODO. Use the formula for a disk sweep sequential access
4747
13123
            to calculate the cost of accessing data rows for one
4748
13124
            index entry.
4749
 
          */
 
13125
          */
4750
13126
          index_scan_time= select_limit/rec_per_key *
4751
 
                           min(rec_per_key, table->cursor->scan_time());
 
13127
                           cmin(rec_per_key, table->file->scan_time());
4752
13128
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
4753
13129
              index_scan_time < read_time)
4754
13130
          {
4755
13131
            ha_rows quick_records= table_records;
4756
13132
            if (is_best_covering && !is_covering)
4757
13133
              continue;
4758
 
            if (table->quick_keys.test(nr))
 
13134
            if (table->quick_keys.is_set(nr))
4759
13135
              quick_records= table->quick_rows[nr];
4760
13136
            if (best_key < 0 ||
4761
 
                (select_limit <= min(quick_records,best_records) ?
 
13137
                (select_limit <= cmin(quick_records,best_records) ?
4762
13138
                 keyinfo->key_parts < best_key_parts :
4763
13139
                 quick_records < best_records))
4764
13140
            {
4769
13145
              best_key_direction= direction;
4770
13146
            }
4771
13147
          }
4772
 
        }
 
13148
        }
4773
13149
      }
4774
13150
    }
4775
13151
    if (best_key >= 0)
4776
13152
    {
4777
13153
      bool quick_created= false;
4778
 
      if (table->quick_keys.test(best_key) && best_key != ref_key)
 
13154
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
4779
13155
      {
4780
13156
        key_map test_map;
4781
 
        test_map.reset();       // Force the creation of quick select
4782
 
        test_map.set(best_key); // only best_key.
 
13157
        test_map.clear_all();       // Force the creation of quick select
 
13158
        test_map.set_bit(best_key); // only best_key.
4783
13159
        quick_created=
4784
13160
          select->test_quick_select(join->session, test_map, 0,
4785
13161
                                    join->select_options & OPTION_FOUND_ROWS ?
4790
13166
      if (!no_changes)
4791
13167
      {
4792
13168
        if (!quick_created)
4793
 
        {
 
13169
        {
4794
13170
          tab->index= best_key;
4795
13171
          tab->read_first_record= best_key_direction > 0 ?
4796
13172
                                  join_read_first:join_read_last;
4797
 
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
 
13173
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
4798
13174
          if (select && select->quick)
4799
13175
          {
4800
13176
            delete select->quick;
4801
13177
            select->quick= 0;
4802
13178
          }
4803
 
          if (table->covering_keys.test(best_key))
 
13179
          if (table->covering_keys.is_set(best_key))
4804
13180
          {
4805
13181
            table->key_read=1;
4806
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
13182
            table->file->extra(HA_EXTRA_KEYREAD);
4807
13183
          }
4808
 
          table->cursor->ha_index_or_rnd_end();
 
13184
          table->file->ha_index_or_rnd_end();
4809
13185
          if (join->select_options & SELECT_DESCRIBE)
4810
13186
          {
4811
13187
            tab->ref.key= -1;
4814
13190
              tab->limit= select_limit;
4815
13191
          }
4816
13192
        }
4817
 
        else if (tab->type != AM_ALL)
 
13193
        else if (tab->type != JT_ALL)
4818
13194
        {
4819
13195
          /*
4820
13196
            We're about to use a quick access to the table.
4822
13198
            method is actually used.
4823
13199
          */
4824
13200
          assert(tab->select->quick);
4825
 
          tab->type= AM_ALL;
 
13201
          tab->type=JT_ALL;
4826
13202
          tab->use_quick=1;
4827
13203
          tab->ref.key= -1;
4828
13204
          tab->ref.key_parts=0;         // Don't use ref key.
4829
13205
          tab->read_first_record= join_init_read_record;
 
13206
          /*
 
13207
            TODO: update the number of records in join->best_positions[tablenr]
 
13208
          */
4830
13209
        }
4831
13210
      }
4832
13211
      used_key_parts= best_key_parts;
4837
13216
  }
4838
13217
 
4839
13218
check_reverse_order:
4840
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
13219
  if (order_direction == -1)            // If order_st BY ... DESC
4841
13220
  {
4842
13221
    if (select && select->quick)
4843
13222
    {
4844
13223
      /*
4845
 
        Don't reverse the sort order, if it's already done.
 
13224
        Don't reverse the sort order, if it's already done.
4846
13225
        (In some cases test_if_order_by_key() can be called multiple times
4847
13226
      */
4848
 
      if (! select->quick->reverse_sorted())
 
13227
      if (!select->quick->reverse_sorted())
4849
13228
      {
4850
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
13229
        QUICK_SELECT_DESC *tmp;
4851
13230
        bool error= false;
4852
13231
        int quick_type= select->quick->get_type();
4853
 
        if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4854
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT ||
4855
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4856
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX)
 
13232
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
13233
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
13234
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
13235
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
4857
13236
        {
4858
13237
          tab->limit= 0;
4859
13238
          select->quick= save_quick;
4860
 
          return 0; // Use filesort
 
13239
          return(0);                   // Use filesort
4861
13240
        }
4862
13241
 
4863
 
        /* ORDER BY range_key DESC */
4864
 
        tmp= new optimizer::QuickSelectDescending((optimizer::QuickRangeSelect*)(select->quick),
4865
 
                                                  used_key_parts, 
4866
 
                                                  &error);
4867
 
        if (! tmp || error)
4868
 
        {
4869
 
          delete tmp;
 
13242
        /* order_st BY range_key DESC */
 
13243
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
13244
                                    used_key_parts, &error);
 
13245
        if (!tmp || error)
 
13246
        {
 
13247
          delete tmp;
4870
13248
          select->quick= save_quick;
4871
13249
          tab->limit= 0;
4872
 
          return 0; // Reverse sort not supported
4873
 
        }
4874
 
        select->quick=tmp;
 
13250
          return(0);            // Reverse sort not supported
 
13251
        }
 
13252
        select->quick=tmp;
4875
13253
      }
4876
13254
    }
4877
 
    else if (tab->type != AM_NEXT &&
 
13255
    else if (tab->type != JT_NEXT &&
4878
13256
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
4879
13257
    {
4880
13258
      /*
4881
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
13259
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
4882
13260
 
4883
 
        Use a traversal function that starts by reading the last row
4884
 
        with key part (A) and then traverse the index backwards.
 
13261
        Use a traversal function that starts by reading the last row
 
13262
        with key part (A) and then traverse the index backwards.
4885
13263
      */
4886
13264
      tab->read_first_record= join_read_last_key;
4887
13265
      tab->read_record.read_record= join_read_prev_same;
4889
13267
  }
4890
13268
  else if (select && select->quick)
4891
13269
    select->quick->sorted= 1;
4892
 
  return 1;
 
13270
  return(1);
4893
13271
}
4894
13272
 
 
13273
 
4895
13274
/*
4896
13275
  If not selecting by given key, create an index how records should be read
4897
13276
 
4898
13277
  SYNOPSIS
4899
13278
   create_sort_index()
4900
 
     session            Thread Cursor
 
13279
     session            Thread handler
4901
13280
     tab                Table to sort (in join structure)
4902
13281
     order              How table should be sorted
4903
13282
     filesort_limit     Max number of rows that needs to be sorted
4910
13289
  IMPLEMENTATION
4911
13290
   - If there is an index that can be used, 'tab' is modified to use
4912
13291
     this index.
4913
 
   - If no index, create with filesort() an index cursor that can be used to
 
13292
   - If no index, create with filesort() an index file that can be used to
4914
13293
     retrieve rows in order (should be done with 'read_record').
4915
13294
     The sorted data is stored in tab->table and will be freed when calling
4916
 
     tab->table->free_io_cache().
 
13295
     free_io_cache(tab->table).
4917
13296
 
4918
13297
  RETURN VALUES
4919
13298
    0           ok
4920
13299
    -1          Some fatal error
4921
13300
    1           No records
4922
13301
*/
4923
 
int create_sort_index(Session *session, Join *join, Order *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
 
13302
 
 
13303
static int
 
13304
create_sort_index(Session *session, JOIN *join, order_st *order,
 
13305
                  ha_rows filesort_limit, ha_rows select_limit,
 
13306
                  bool is_order_by)
4924
13307
{
4925
13308
  uint32_t length= 0;
4926
13309
  ha_rows examined_rows;
4927
13310
  Table *table;
4928
 
  optimizer::SqlSelect *select= NULL;
4929
 
  JoinTable *tab;
 
13311
  SQL_SELECT *select;
 
13312
  JOIN_TAB *tab;
4930
13313
 
4931
13314
  if (join->tables == join->const_tables)
4932
13315
    return(0);                          // One row, no need to sort
4942
13325
  */
4943
13326
  if ((order != join->group_list ||
4944
13327
       !(join->select_options & SELECT_BIG_RESULT) ||
4945
 
       (select && select->quick && (select->quick->get_type() == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))) &&
 
13328
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
4946
13329
      test_if_skip_sort_order(tab,order,select_limit,0,
4947
13330
                              is_order_by ?  &table->keys_in_use_for_order_by :
4948
13331
                              &table->keys_in_use_for_group_by))
4949
13332
    return(0);
4950
 
  for (Order *ord= join->order; ord; ord= ord->next)
 
13333
  for (order_st *ord= join->order; ord; ord= ord->next)
4951
13334
    length++;
4952
 
  if (!(join->sortorder= make_unireg_sortorder(order, &length, join->sortorder)))
4953
 
  {
4954
 
    return(-1);
4955
 
  }
 
13335
  if (!(join->sortorder=
 
13336
        make_unireg_sortorder(order, &length, join->sortorder)))
 
13337
    goto err;                           /* purecov: inspected */
4956
13338
 
4957
 
  table->sort.io_cache= new internal::IO_CACHE;
 
13339
  table->sort.io_cache= new IO_CACHE;
 
13340
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
4958
13341
  table->status=0;                              // May be wrong if quick_select
4959
13342
 
4960
13343
  // If table has a range, move it to select
4970
13353
      */
4971
13354
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
4972
13355
      {
4973
 
        table->key_read=0;
4974
 
        table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
13356
        table->key_read=0;
 
13357
        table->file->extra(HA_EXTRA_NO_KEYREAD);
4975
13358
      }
4976
13359
    }
4977
13360
    else
4978
13361
    {
4979
13362
      /*
4980
 
        We have a ref on a const;  Change this to a range that filesort
4981
 
        can use.
4982
 
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
4983
 
        field, quick will contain an empty record set.
 
13363
        We have a ref on a const;  Change this to a range that filesort
 
13364
        can use.
 
13365
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
 
13366
        field, quick will contain an empty record set.
4984
13367
      */
4985
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
4986
 
                                                                 table, 
4987
 
                                                                 &tab->ref,
4988
 
                                                                 tab->found_records))))
4989
 
      {
4990
 
        return(-1);
4991
 
      }
 
13368
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
13369
                                                     tab->found_records))))
 
13370
        goto err;
4992
13371
    }
4993
13372
  }
4994
13373
 
4995
 
  if (table->getShare()->getType())
4996
 
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
 
13374
  /* Fill schema tables with data before filesort if it's necessary */
 
13375
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
 
13376
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
 
13377
    goto err;
4997
13378
 
4998
 
  FileSort filesort(*session);
4999
 
  table->sort.found_records=filesort.run(table,join->sortorder, length,
5000
 
                                         select, filesort_limit, 0,
5001
 
                                         examined_rows);
 
13379
  if (table->s->tmp_table)
 
13380
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
 
13381
  table->sort.found_records=filesort(session, table,join->sortorder, length,
 
13382
                                     select, filesort_limit, 0,
 
13383
                                     &examined_rows);
5002
13384
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
5003
13385
  if (select)
5004
13386
  {
5008
13390
  tab->select_cond=0;
5009
13391
  tab->last_inner= 0;
5010
13392
  tab->first_unmatched= 0;
5011
 
  tab->type= AM_ALL;                            // Read with normal read_record
 
13393
  tab->type=JT_ALL;                             // Read with normal read_record
5012
13394
  tab->read_first_record= join_init_read_record;
5013
13395
  tab->join->examined_rows+=examined_rows;
5014
13396
  if (table->key_read)                          // Restore if we used indexes
5015
13397
  {
5016
13398
    table->key_read=0;
5017
 
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
13399
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5018
13400
  }
5019
 
 
5020
13401
  return(table->sort.found_records == HA_POS_ERROR);
5021
 
}
5022
 
 
5023
 
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5024
 
{
5025
 
  Cursor *cursor=table->cursor;
 
13402
err:
 
13403
  return(-1);
 
13404
}
 
13405
 
 
13406
static bool copy_blobs(Field **ptr)
 
13407
{
 
13408
  for (; *ptr ; ptr++)
 
13409
  {
 
13410
    if ((*ptr)->flags & BLOB_FLAG)
 
13411
      if (((Field_blob *) (*ptr))->copy())
 
13412
        return 1;                               // Error
 
13413
  }
 
13414
  return 0;
 
13415
}
 
13416
 
 
13417
static void free_blobs(Field **ptr)
 
13418
{
 
13419
  for (; *ptr ; ptr++)
 
13420
  {
 
13421
    if ((*ptr)->flags & BLOB_FLAG)
 
13422
      ((Field_blob *) (*ptr))->free();
 
13423
  }
 
13424
}
 
13425
 
 
13426
 
 
13427
static int
 
13428
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
 
13429
{
 
13430
  int error;
 
13431
  uint32_t reclength,offset;
 
13432
  uint32_t field_count;
 
13433
  Session *session= join->session;
 
13434
 
 
13435
  entry->reginfo.lock_type=TL_WRITE;
 
13436
 
 
13437
  /* Calculate how many saved fields there is in list */
 
13438
  field_count=0;
 
13439
  List_iterator<Item> it(fields);
 
13440
  Item *item;
 
13441
  while ((item=it++))
 
13442
  {
 
13443
    if (item->get_tmp_table_field() && ! item->const_item())
 
13444
      field_count++;
 
13445
  }
 
13446
 
 
13447
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having)
 
13448
  {                    // only const items with no OPTION_FOUND_ROWS
 
13449
    join->unit->select_limit_cnt= 1;            // Only send first row
 
13450
    return(0);
 
13451
  }
 
13452
  Field **first_field=entry->field+entry->s->fields - field_count;
 
13453
  offset= (field_count ?
 
13454
           entry->field[entry->s->fields - field_count]->
 
13455
           offset(entry->record[0]) : 0);
 
13456
  reclength= entry->s->reclength-offset;
 
13457
 
 
13458
  free_io_cache(entry);                         // Safety
 
13459
  entry->file->info(HA_STATUS_VARIABLE);
 
13460
  if (entry->s->db_type() == heap_hton ||
 
13461
      (!entry->s->blob_fields &&
 
13462
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
 
13463
        session->variables.sortbuff_size)))
 
13464
    error= remove_dup_with_hash_index(join->session, entry,
 
13465
                                     field_count, first_field,
 
13466
                                     reclength, having);
 
13467
  else
 
13468
    error= remove_dup_with_compare(join->session, entry, first_field, offset,
 
13469
                                  having);
 
13470
 
 
13471
  free_blobs(first_field);
 
13472
  return(error);
 
13473
}
 
13474
 
 
13475
 
 
13476
static int remove_dup_with_compare(Session *session, Table *table, Field **first_field,
 
13477
                                   uint32_t offset, Item *having)
 
13478
{
 
13479
  handler *file=table->file;
5026
13480
  char *org_record,*new_record;
5027
13481
  unsigned char *record;
5028
13482
  int error;
5029
 
  uint32_t reclength= table->getShare()->getRecordLength() - offset;
5030
 
 
5031
 
  org_record=(char*) (record=table->getInsertRecord())+offset;
5032
 
  new_record=(char*) table->getUpdateRecord()+offset;
5033
 
 
5034
 
  if ((error= cursor->startTableScan(1)))
5035
 
    goto err;
5036
 
 
5037
 
  error=cursor->rnd_next(record);
 
13483
  uint32_t reclength= table->s->reclength-offset;
 
13484
 
 
13485
  org_record=(char*) (record=table->record[0])+offset;
 
13486
  new_record=(char*) table->record[1]+offset;
 
13487
 
 
13488
  file->ha_rnd_init(1);
 
13489
  error=file->rnd_next(record);
5038
13490
  for (;;)
5039
13491
  {
5040
 
    if (session->getKilled())
 
13492
    if (session->killed)
5041
13493
    {
5042
13494
      session->send_kill_message();
5043
13495
      error=0;
5046
13498
    if (error)
5047
13499
    {
5048
13500
      if (error == HA_ERR_RECORD_DELETED)
5049
 
        continue;
 
13501
        continue;
5050
13502
      if (error == HA_ERR_END_OF_FILE)
5051
 
        break;
 
13503
        break;
5052
13504
      goto err;
5053
13505
    }
5054
13506
    if (having && !having->val_int())
5055
13507
    {
5056
 
      if ((error=cursor->deleteRecord(record)))
5057
 
        goto err;
5058
 
      error=cursor->rnd_next(record);
 
13508
      if ((error=file->ha_delete_row(record)))
 
13509
        goto err;
 
13510
      error=file->rnd_next(record);
5059
13511
      continue;
5060
13512
    }
5061
13513
    if (copy_blobs(first_field))
5066
13518
    }
5067
13519
    memcpy(new_record,org_record,reclength);
5068
13520
 
5069
 
    /* Read through rest of cursor and mark duplicated rows deleted */
 
13521
    /* Read through rest of file and mark duplicated rows deleted */
5070
13522
    bool found=0;
5071
13523
    for (;;)
5072
13524
    {
5073
 
      if ((error=cursor->rnd_next(record)))
 
13525
      if ((error=file->rnd_next(record)))
5074
13526
      {
5075
 
        if (error == HA_ERR_RECORD_DELETED)
5076
 
          continue;
5077
 
        if (error == HA_ERR_END_OF_FILE)
5078
 
          break;
5079
 
        goto err;
 
13527
        if (error == HA_ERR_RECORD_DELETED)
 
13528
          continue;
 
13529
        if (error == HA_ERR_END_OF_FILE)
 
13530
          break;
 
13531
        goto err;
5080
13532
      }
5081
13533
      if (table->compare_record(first_field) == 0)
5082
13534
      {
5083
 
        if ((error=cursor->deleteRecord(record)))
5084
 
          goto err;
 
13535
        if ((error=file->ha_delete_row(record)))
 
13536
          goto err;
5085
13537
      }
5086
13538
      else if (!found)
5087
13539
      {
5088
 
        found= 1;
5089
 
        cursor->position(record);       // Remember position
 
13540
        found=1;
 
13541
        file->position(record); // Remember position
5090
13542
      }
5091
13543
    }
5092
13544
    if (!found)
5093
 
      break;                                    // End of cursor
5094
 
    /* Move current position to the next row */
5095
 
    error= cursor->rnd_pos(record, cursor->ref);
 
13545
      break;                                    // End of file
 
13546
    /* Restart search on next row */
 
13547
    error=file->restart_rnd_next(record,file->ref);
5096
13548
  }
5097
13549
 
5098
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
13550
  file->extra(HA_EXTRA_NO_CACHE);
5099
13551
  return(0);
5100
13552
err:
5101
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
13553
  file->extra(HA_EXTRA_NO_CACHE);
5102
13554
  if (error)
5103
 
    table->print_error(error,MYF(0));
 
13555
    file->print_error(error,MYF(0));
5104
13556
  return(1);
5105
13557
}
5106
13558
 
 
13559
 
5107
13560
/**
5108
13561
  Generate a hash index for each row to quickly find duplicate rows.
5109
13562
 
5110
13563
  @note
5111
13564
    Note that this will not work on tables with blobs!
5112
13565
*/
5113
 
int remove_dup_with_hash_index(Session *session, 
5114
 
                               Table *table,
5115
 
                               uint32_t field_count,
5116
 
                               Field **first_field,
5117
 
                               uint32_t key_length,
5118
 
                               Item *having)
 
13566
 
 
13567
static int remove_dup_with_hash_index(Session *session, Table *table,
 
13568
                                      uint32_t field_count,
 
13569
                                      Field **first_field,
 
13570
                                      uint32_t key_length,
 
13571
                                      Item *having)
5119
13572
{
5120
 
  unsigned char *key_pos, *record=table->getInsertRecord();
 
13573
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5121
13574
  int error;
5122
 
  Cursor *cursor= table->cursor;
 
13575
  handler *file= table->file;
5123
13576
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5124
 
  uint32_t *field_length;
 
13577
  uint32_t *field_lengths,*field_length;
5125
13578
  HASH hash;
5126
 
  std::vector<unsigned char> key_buffer;
5127
 
  std::vector<uint32_t> field_lengths;
5128
13579
 
5129
 
  key_buffer.resize((key_length + extra_length) * (long) cursor->stats.records);
5130
 
  field_lengths.resize(field_count);
 
13580
  if (!my_multi_malloc(MYF(MY_WME),
 
13581
                       &key_buffer,
 
13582
                       (uint32_t) ((key_length + extra_length) *
 
13583
                               (long) file->stats.records),
 
13584
                       &field_lengths,
 
13585
                       (uint32_t) (field_count*sizeof(*field_lengths)),
 
13586
                       NULL))
 
13587
    return(1);
5131
13588
 
5132
13589
  {
5133
13590
    Field **ptr;
5134
13591
    uint32_t total_length= 0;
5135
 
 
5136
 
    for (ptr= first_field, field_length= &field_lengths[0] ; *ptr ; ptr++)
 
13592
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
5137
13593
    {
5138
13594
      uint32_t length= (*ptr)->sort_length();
5139
13595
      (*field_length++)= length;
5144
13600
    extra_length= ALIGN_SIZE(key_length)-key_length;
5145
13601
  }
5146
13602
 
5147
 
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor->stats.records, 0,
 
13603
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
5148
13604
                key_length, (hash_get_key) 0, 0, 0))
5149
13605
  {
 
13606
    free((char*) key_buffer);
5150
13607
    return(1);
5151
13608
  }
5152
13609
 
5153
 
  if ((error= cursor->startTableScan(1)))
5154
 
    goto err;
5155
 
 
5156
 
  key_pos= &key_buffer[0];
 
13610
  file->ha_rnd_init(1);
 
13611
  key_pos=key_buffer;
5157
13612
  for (;;)
5158
13613
  {
5159
13614
    unsigned char *org_key_pos;
5160
 
    if (session->getKilled())
 
13615
    if (session->killed)
5161
13616
    {
5162
13617
      session->send_kill_message();
5163
13618
      error=0;
5164
13619
      goto err;
5165
13620
    }
5166
 
    if ((error=cursor->rnd_next(record)))
 
13621
    if ((error=file->rnd_next(record)))
5167
13622
    {
5168
13623
      if (error == HA_ERR_RECORD_DELETED)
5169
 
        continue;
 
13624
        continue;
5170
13625
      if (error == HA_ERR_END_OF_FILE)
5171
 
        break;
 
13626
        break;
5172
13627
      goto err;
5173
13628
    }
5174
13629
    if (having && !having->val_int())
5175
13630
    {
5176
 
      if ((error=cursor->deleteRecord(record)))
5177
 
        goto err;
 
13631
      if ((error=file->ha_delete_row(record)))
 
13632
        goto err;
5178
13633
      continue;
5179
13634
    }
5180
13635
 
5181
13636
    /* copy fields to key buffer */
5182
13637
    org_key_pos= key_pos;
5183
 
    field_length= &field_lengths[0];
 
13638
    field_length=field_lengths;
5184
13639
    for (Field **ptr= first_field ; *ptr ; ptr++)
5185
13640
    {
5186
13641
      (*ptr)->sort_string(key_pos,*field_length);
5190
13645
    if (hash_search(&hash, org_key_pos, key_length))
5191
13646
    {
5192
13647
      /* Duplicated found ; Remove the row */
5193
 
      if ((error=cursor->deleteRecord(record)))
5194
 
        goto err;
 
13648
      if ((error=file->ha_delete_row(record)))
 
13649
        goto err;
5195
13650
    }
5196
13651
    else
5197
13652
      (void) my_hash_insert(&hash, org_key_pos);
5198
13653
    key_pos+=extra_length;
5199
13654
  }
 
13655
  free((char*) key_buffer);
5200
13656
  hash_free(&hash);
5201
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5202
 
  (void) cursor->endTableScan();
 
13657
  file->extra(HA_EXTRA_NO_CACHE);
 
13658
  (void) file->ha_rnd_end();
5203
13659
  return(0);
5204
13660
 
5205
13661
err:
 
13662
  free((char*) key_buffer);
5206
13663
  hash_free(&hash);
5207
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5208
 
  (void) cursor->endTableScan();
 
13664
  file->extra(HA_EXTRA_NO_CACHE);
 
13665
  (void) file->ha_rnd_end();
5209
13666
  if (error)
5210
 
    table->print_error(error,MYF(0));
 
13667
    file->print_error(error,MYF(0));
5211
13668
  return(1);
5212
13669
}
5213
13670
 
5214
 
SortField *make_unireg_sortorder(Order *order, uint32_t *length, SortField *sortorder)
 
13671
 
 
13672
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length,
 
13673
                                  SORT_FIELD *sortorder)
5215
13674
{
5216
13675
  uint32_t count;
5217
 
  SortField *sort,*pos;
 
13676
  SORT_FIELD *sort,*pos;
5218
13677
 
5219
13678
  count=0;
5220
 
  for (Order *tmp = order; tmp; tmp=tmp->next)
 
13679
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5221
13680
    count++;
5222
13681
  if (!sortorder)
5223
 
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) *
5224
 
                                       (max(count, *length) + 1));
 
13682
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
 
13683
                                       (cmax(count, *length) + 1));
5225
13684
  pos= sort= sortorder;
5226
13685
 
5227
13686
  if (!pos)
5247
13706
  return(sort);
5248
13707
}
5249
13708
 
 
13709
 
 
13710
/*****************************************************************************
 
13711
  Fill join cache with packed records
 
13712
  Records are stored in tab->cache.buffer and last record in
 
13713
  last record is stored with pointers to blobs to support very big
 
13714
  records
 
13715
******************************************************************************/
 
13716
 
 
13717
static int
 
13718
join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count)
 
13719
{
 
13720
  register unsigned int i;
 
13721
  unsigned int length, blobs;
 
13722
  size_t size;
 
13723
  CACHE_FIELD *copy,**blob_ptr;
 
13724
  JOIN_CACHE  *cache;
 
13725
  JOIN_TAB *join_tab;
 
13726
 
 
13727
  cache= &tables[table_count].cache;
 
13728
  cache->fields=blobs=0;
 
13729
 
 
13730
  join_tab=tables;
 
13731
  for (i=0 ; i < table_count ; i++,join_tab++)
 
13732
  {
 
13733
    if (!join_tab->used_fieldlength)            /* Not calced yet */
 
13734
      calc_used_field_length(session, join_tab);
 
13735
    cache->fields+=join_tab->used_fields;
 
13736
    blobs+=join_tab->used_blobs;
 
13737
 
 
13738
    /* SemiJoinDuplicateElimination: reserve space for rowid */
 
13739
    if (join_tab->rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
 
13740
    {
 
13741
      cache->fields++;
 
13742
      join_tab->used_fieldlength += join_tab->table->file->ref_length;
 
13743
    }
 
13744
  }
 
13745
  if (!(cache->field=(CACHE_FIELD*)
 
13746
        sql_alloc(sizeof(CACHE_FIELD)*(cache->fields+table_count*2)+(blobs+1)*
 
13747
 
 
13748
                  sizeof(CACHE_FIELD*))))
 
13749
  {
 
13750
    free((unsigned char*) cache->buff);         /* purecov: inspected */
 
13751
    cache->buff=0;                              /* purecov: inspected */
 
13752
    return(1);                          /* purecov: inspected */
 
13753
  }
 
13754
  copy=cache->field;
 
13755
  blob_ptr=cache->blob_ptr=(CACHE_FIELD**)
 
13756
    (cache->field+cache->fields+table_count*2);
 
13757
 
 
13758
  length=0;
 
13759
  for (i=0 ; i < table_count ; i++)
 
13760
  {
 
13761
    uint32_t null_fields=0, used_fields;
 
13762
    Field **f_ptr,*field;
 
13763
    MY_BITMAP *read_set= tables[i].table->read_set;
 
13764
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
 
13765
         used_fields ;
 
13766
         f_ptr++)
 
13767
    {
 
13768
      field= *f_ptr;
 
13769
      if (bitmap_is_set(read_set, field->field_index))
 
13770
      {
 
13771
        used_fields--;
 
13772
        length+=field->fill_cache_field(copy);
 
13773
        if (copy->blob_field)
 
13774
          (*blob_ptr++)=copy;
 
13775
        if (field->maybe_null())
 
13776
          null_fields++;
 
13777
        copy->get_rowid= NULL;
 
13778
        copy++;
 
13779
      }
 
13780
    }
 
13781
    /* Copy null bits from table */
 
13782
    if (null_fields && tables[i].table->getNullFields())
 
13783
    {                                           /* must copy null bits */
 
13784
      copy->str= tables[i].table->null_flags;
 
13785
      copy->length= tables[i].table->s->null_bytes;
 
13786
      copy->strip=0;
 
13787
      copy->blob_field=0;
 
13788
      copy->get_rowid= NULL;
 
13789
      length+=copy->length;
 
13790
      copy++;
 
13791
      cache->fields++;
 
13792
    }
 
13793
    /* If outer join table, copy null_row flag */
 
13794
    if (tables[i].table->maybe_null)
 
13795
    {
 
13796
      copy->str= (unsigned char*) &tables[i].table->null_row;
 
13797
      copy->length=sizeof(tables[i].table->null_row);
 
13798
      copy->strip=0;
 
13799
      copy->blob_field=0;
 
13800
      copy->get_rowid= NULL;
 
13801
      length+=copy->length;
 
13802
      copy++;
 
13803
      cache->fields++;
 
13804
    }
 
13805
    /* SemiJoinDuplicateElimination: Allocate space for rowid if needed */
 
13806
    if (tables[i].rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
 
13807
    {
 
13808
      copy->str= tables[i].table->file->ref;
 
13809
      copy->length= tables[i].table->file->ref_length;
 
13810
      copy->strip=0;
 
13811
      copy->blob_field=0;
 
13812
      copy->get_rowid= NULL;
 
13813
      if (tables[i].rowid_keep_flags & JOIN_TAB::CALL_POSITION)
 
13814
      {
 
13815
        /* We will need to call h->position(): */
 
13816
        copy->get_rowid= tables[i].table;
 
13817
        /* And those after us won't have to: */
 
13818
        tables[i].rowid_keep_flags &=  ~((int)JOIN_TAB::CALL_POSITION);
 
13819
      }
 
13820
      copy++;
 
13821
    }
 
13822
  }
 
13823
 
 
13824
  cache->length=length+blobs*sizeof(char*);
 
13825
  cache->blobs=blobs;
 
13826
  *blob_ptr= NULL;                                      /* End sequentel */
 
13827
  size= max((size_t)session->variables.join_buff_size,
 
13828
            (size_t)cache->length);
 
13829
  if (!(cache->buff=(unsigned char*) malloc(size)))
 
13830
    return 1;                           /* Don't use cache */ /* purecov: inspected */
 
13831
  cache->end=cache->buff+size;
 
13832
  reset_cache_write(cache);
 
13833
  return 0;
 
13834
}
 
13835
 
 
13836
 
 
13837
static uint32_t used_blob_length(CACHE_FIELD **ptr)
 
13838
{
 
13839
  uint32_t length,blob_length;
 
13840
  for (length=0 ; *ptr ; ptr++)
 
13841
  {
 
13842
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
 
13843
    length+=blob_length;
 
13844
    (*ptr)->blob_field->get_ptr(&(*ptr)->str);
 
13845
  }
 
13846
  return length;
 
13847
}
 
13848
 
 
13849
 
 
13850
static bool
 
13851
store_record_in_cache(JOIN_CACHE *cache)
 
13852
{
 
13853
  uint32_t length;
 
13854
  unsigned char *pos;
 
13855
  CACHE_FIELD *copy,*end_field;
 
13856
  bool last_record;
 
13857
 
 
13858
  pos=cache->pos;
 
13859
  end_field=cache->field+cache->fields;
 
13860
 
 
13861
  length=cache->length;
 
13862
  if (cache->blobs)
 
13863
    length+= used_blob_length(cache->blob_ptr);
 
13864
  if ((last_record= (length + cache->length > (size_t) (cache->end - pos))))
 
13865
    cache->ptr_record=cache->records;
 
13866
  /*
 
13867
    There is room in cache. Put record there
 
13868
  */
 
13869
  cache->records++;
 
13870
  for (copy=cache->field ; copy < end_field; copy++)
 
13871
  {
 
13872
    if (copy->blob_field)
 
13873
    {
 
13874
      if (last_record)
 
13875
      {
 
13876
        copy->blob_field->get_image(pos, copy->length+sizeof(char*),
 
13877
                                    copy->blob_field->charset());
 
13878
        pos+=copy->length+sizeof(char*);
 
13879
      }
 
13880
      else
 
13881
      {
 
13882
        copy->blob_field->get_image(pos, copy->length, // blob length
 
13883
                                    copy->blob_field->charset());
 
13884
        memcpy(pos+copy->length,copy->str,copy->blob_length);  // Blob data
 
13885
        pos+=copy->length+copy->blob_length;
 
13886
      }
 
13887
    }
 
13888
    else
 
13889
    {
 
13890
      // SemiJoinDuplicateElimination: Get the rowid into table->ref:
 
13891
      if (copy->get_rowid)
 
13892
        copy->get_rowid->file->position(copy->get_rowid->record[0]);
 
13893
 
 
13894
      if (copy->strip)
 
13895
      {
 
13896
        unsigned char *str,*end;
 
13897
        for (str=copy->str,end= str+copy->length;
 
13898
             end > str && end[-1] == ' ' ;
 
13899
             end--) ;
 
13900
        length=(uint32_t) (end-str);
 
13901
        memcpy(pos+2, str, length);
 
13902
        int2store(pos, length);
 
13903
        pos+= length+2;
 
13904
      }
 
13905
      else
 
13906
      {
 
13907
        memcpy(pos,copy->str,copy->length);
 
13908
        pos+=copy->length;
 
13909
      }
 
13910
    }
 
13911
  }
 
13912
  cache->pos=pos;
 
13913
  return last_record || (size_t) (cache->end - pos) < cache->length;
 
13914
}
 
13915
 
 
13916
 
 
13917
static void
 
13918
reset_cache_read(JOIN_CACHE *cache)
 
13919
{
 
13920
  cache->record_nr=0;
 
13921
  cache->pos=cache->buff;
 
13922
}
 
13923
 
 
13924
 
 
13925
static void reset_cache_write(JOIN_CACHE *cache)
 
13926
{
 
13927
  reset_cache_read(cache);
 
13928
  cache->records= 0;
 
13929
  cache->ptr_record= UINT32_MAX;
 
13930
}
 
13931
 
 
13932
 
 
13933
static void
 
13934
read_cached_record(JOIN_TAB *tab)
 
13935
{
 
13936
  unsigned char *pos;
 
13937
  uint32_t length;
 
13938
  bool last_record;
 
13939
  CACHE_FIELD *copy,*end_field;
 
13940
 
 
13941
  last_record=tab->cache.record_nr++ == tab->cache.ptr_record;
 
13942
  pos=tab->cache.pos;
 
13943
  for (copy=tab->cache.field,end_field=copy+tab->cache.fields ;
 
13944
       copy < end_field;
 
13945
       copy++)
 
13946
  {
 
13947
    if (copy->blob_field)
 
13948
    {
 
13949
      if (last_record)
 
13950
      {
 
13951
        copy->blob_field->set_image(pos, copy->length+sizeof(char*),
 
13952
                                    copy->blob_field->charset());
 
13953
        pos+=copy->length+sizeof(char*);
 
13954
      }
 
13955
      else
 
13956
      {
 
13957
        copy->blob_field->set_ptr(pos, pos+copy->length);
 
13958
        pos+=copy->length+copy->blob_field->get_length();
 
13959
      }
 
13960
    }
 
13961
    else
 
13962
    {
 
13963
      if (copy->strip)
 
13964
      {
 
13965
        length= uint2korr(pos);
 
13966
        memcpy(copy->str, pos+2, length);
 
13967
        memset(copy->str+length, ' ', copy->length-length);
 
13968
        pos+= 2 + length;
 
13969
      }
 
13970
      else
 
13971
      {
 
13972
        memcpy(copy->str,pos,copy->length);
 
13973
        pos+=copy->length;
 
13974
      }
 
13975
    }
 
13976
  }
 
13977
  tab->cache.pos=pos;
 
13978
  return;
 
13979
}
 
13980
 
 
13981
 
5250
13982
/*
5251
13983
  eq_ref: Create the lookup key and check if it is the same as saved key
5252
13984
 
5265
13997
    false  The created key is the same as the previous one (and the record
5266
13998
           is already in table->record)
5267
13999
*/
5268
 
static bool cmp_buffer_with_ref(JoinTable *tab)
 
14000
 
 
14001
static bool
 
14002
cmp_buffer_with_ref(JOIN_TAB *tab)
5269
14003
{
5270
14004
  bool no_prev_key;
5271
14005
  if (!tab->ref.disable_cache)
5285
14019
    != 0;
5286
14020
}
5287
14021
 
5288
 
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
 
14022
 
 
14023
bool
 
14024
cp_buffer_from_ref(Session *session, TABLE_REF *ref)
5289
14025
{
5290
14026
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
5291
14027
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
5292
14028
  bool result= 0;
5293
14029
 
5294
 
  for (StoredKey **copy=ref->key_copy ; *copy ; copy++)
 
14030
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
5295
14031
  {
5296
14032
    if ((*copy)->copy() & 1)
5297
14033
    {
5303
14039
  return result;
5304
14040
}
5305
14041
 
 
14042
 
5306
14043
/*****************************************************************************
5307
14044
  Group and order functions
5308
14045
*****************************************************************************/
5309
14046
 
5310
14047
/**
5311
 
  Resolve an ORDER BY or GROUP BY column reference.
 
14048
  Resolve an order_st BY or GROUP BY column reference.
5312
14049
 
5313
14050
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5314
14051
  BY clause, find the actual column it represents. If the column being
5315
14052
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5316
14053
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
5317
 
  the ORDER BY clause, only the SELECT list is being searched.
 
14054
  the order_st BY clause, only the SELECT list is being searched.
5318
14055
 
5319
14056
  If 'order' is resolved to an Item, then order->item is set to the found
5320
14057
  Item. If there is no item for the found column (that is, it was resolved
5339
14076
  @retval
5340
14077
    true  if error occurred
5341
14078
*/
5342
 
static bool find_order_in_list(Session *session, 
5343
 
                               Item **ref_pointer_array, 
5344
 
                               TableList *tables,
5345
 
                               Order *order,
5346
 
                               List<Item> &fields,
5347
 
                               List<Item> &all_fields,
5348
 
                               bool is_group_field)
 
14079
 
 
14080
static bool
 
14081
find_order_in_list(Session *session, Item **ref_pointer_array, TableList *tables,
 
14082
                   order_st *order, List<Item> &fields, List<Item> &all_fields,
 
14083
                   bool is_group_field)
5349
14084
{
5350
14085
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
5351
14086
  Item::Type order_item_type;
5364
14099
    if (!count || count > fields.elements)
5365
14100
    {
5366
14101
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
5367
 
               order_item->full_name(), session->where());
 
14102
               order_item->full_name(), session->where);
5368
14103
      return true;
5369
14104
    }
5370
14105
    order->item= ref_pointer_array + count - 1;
5374
14109
    return false;
5375
14110
  }
5376
14111
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
5377
 
  select_item= find_item_in_list(session, order_item, fields, &counter,
 
14112
  select_item= find_item_in_list(order_item, fields, &counter,
5378
14113
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
5379
14114
  if (!select_item)
5380
14115
    return true; /* The item is not unique, or some other error occured. */
5400
14135
        order_item_type == Item::REF_ITEM)
5401
14136
    {
5402
14137
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5403
 
                                       NULL, &view_ref, IGNORE_ERRORS, false);
 
14138
                                       NULL, &view_ref, IGNORE_ERRORS, true,
 
14139
                                       false);
5404
14140
      if (!from_field)
5405
14141
        from_field= (Field*) not_found_field;
5406
14142
    }
5441
14177
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
5442
14178
                          ER(ER_NON_UNIQ_ERROR),
5443
14179
                          ((Item_ident*) order_item)->field_name,
5444
 
                          session->where());
 
14180
                          current_session->where);
5445
14181
    }
5446
14182
  }
5447
14183
 
5470
14206
  return false;
5471
14207
}
5472
14208
 
 
14209
 
5473
14210
/**
5474
14211
  Change order to point at item in select list.
5475
14212
 
5476
14213
  If item isn't a number and doesn't exits in the select list, add it the
5477
14214
  the field list.
5478
14215
*/
5479
 
int setup_order(Session *session,
5480
 
                Item **ref_pointer_array,
5481
 
                TableList *tables,
5482
 
                            List<Item> &fields,
5483
 
                List<Item> &all_fields,
5484
 
                Order *order)
 
14216
 
 
14217
int setup_order(Session *session, Item **ref_pointer_array, TableList *tables,
 
14218
                List<Item> &fields, List<Item> &all_fields, order_st *order)
5485
14219
{
5486
 
  session->setWhere("order clause");
 
14220
  session->where="order clause";
5487
14221
  for (; order; order=order->next)
5488
14222
  {
5489
14223
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
5493
14227
  return 0;
5494
14228
}
5495
14229
 
 
14230
 
5496
14231
/**
5497
14232
  Intitialize the GROUP BY list.
5498
14233
 
5499
 
  @param session                        Thread Cursor
 
14234
  @param session                        Thread handler
5500
14235
  @param ref_pointer_array      We store references to all fields that was
5501
14236
                               not in 'fields' here.
5502
14237
  @param fields         All fields in the select part. Any item in
5518
14253
  @retval
5519
14254
    1  error (probably out of memory)
5520
14255
*/
5521
 
int setup_group(Session *session,
5522
 
                Item **ref_pointer_array,
5523
 
                TableList *tables,
5524
 
                      List<Item> &fields,
5525
 
                List<Item> &all_fields,
5526
 
                Order *order,
5527
 
                      bool *hidden_group_fields)
 
14256
 
 
14257
int
 
14258
setup_group(Session *session, Item **ref_pointer_array, TableList *tables,
 
14259
            List<Item> &fields, List<Item> &all_fields, order_st *order,
 
14260
            bool *hidden_group_fields)
5528
14261
{
5529
14262
  *hidden_group_fields=0;
5530
 
  Order *ord;
 
14263
  order_st *ord;
5531
14264
 
5532
14265
  if (!order)
5533
14266
    return 0;                           /* Everything is ok */
5534
14267
 
5535
14268
  uint32_t org_fields=all_fields.elements;
5536
14269
 
5537
 
  session->setWhere("group statement");
 
14270
  session->where="group statement";
5538
14271
  for (ord= order; ord; ord= ord->next)
5539
14272
  {
5540
14273
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
5617
14350
  Try to use the fields in the order given by 'order' to allow one to
5618
14351
  optimize away 'order by'.
5619
14352
*/
5620
 
Order *create_distinct_group(Session *session,
5621
 
                                Item **ref_pointer_array,
5622
 
                                Order *order_list,
5623
 
                                List<Item> &fields,
5624
 
                                List<Item> &,
5625
 
                                bool *all_order_by_fields_used)
 
14353
 
 
14354
static order_st *
 
14355
create_distinct_group(Session *session, Item **ref_pointer_array,
 
14356
                      order_st *order_list, List<Item> &fields,
 
14357
                      List<Item> &, bool *all_order_by_fields_used)
5626
14358
{
5627
14359
  List_iterator<Item> li(fields);
5628
14360
  Item *item;
5629
 
  Order *order,*group,**prev;
 
14361
  order_st *order,*group,**prev;
5630
14362
 
5631
14363
  *all_order_by_fields_used= 1;
5632
14364
  while ((item=li++))
5637
14369
  {
5638
14370
    if (order->in_field_list)
5639
14371
    {
5640
 
      Order *ord=(Order*) session->getMemRoot()->duplicate((char*) order,sizeof(Order));
 
14372
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
5641
14373
      if (!ord)
5642
 
        return 0;
 
14374
        return 0;
5643
14375
      *prev=ord;
5644
14376
      prev= &ord->next;
5645
14377
      (*ord->item)->marker=1;
5657
14389
        Don't put duplicate columns from the SELECT list into the
5658
14390
        GROUP BY list.
5659
14391
      */
5660
 
      Order *ord_iter;
 
14392
      order_st *ord_iter;
5661
14393
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
5662
14394
        if ((*ord_iter->item)->eq(item, 1))
5663
14395
          goto next_item;
5664
14396
 
5665
 
      Order *ord=(Order*) session->calloc(sizeof(Order));
 
14397
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
5666
14398
      if (!ord)
5667
 
        return 0;
 
14399
        return 0;
5668
14400
 
5669
14401
      /*
5670
14402
        We have here only field_list (not all_field_list), so we can use
5683
14415
  return group;
5684
14416
}
5685
14417
 
 
14418
 
5686
14419
/**
5687
14420
  Update join with count of the different type of fields.
5688
14421
*/
5689
 
void count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param, List<Item> &fields, bool reset_with_sum_func)
 
14422
 
 
14423
void
 
14424
count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param,
 
14425
                  List<Item> &fields, bool reset_with_sum_func)
5690
14426
{
5691
14427
  List_iterator<Item> li(fields);
5692
14428
  Item *field;
5703
14439
    {
5704
14440
      if (! field->const_item())
5705
14441
      {
5706
 
        Item_sum *sum_item=(Item_sum*) field->real_item();
 
14442
        Item_sum *sum_item=(Item_sum*) field->real_item();
5707
14443
        if (!sum_item->depended_from() ||
5708
14444
            sum_item->depended_from() == select_lex)
5709
14445
        {
5726
14462
    {
5727
14463
      param->func_count++;
5728
14464
      if (reset_with_sum_func)
5729
 
        field->with_sum_func=0;
5730
 
    }
5731
 
  }
5732
 
}
 
14465
        field->with_sum_func=0;
 
14466
    }
 
14467
  }
 
14468
}
 
14469
 
 
14470
 
 
14471
/**
 
14472
  Return 1 if second is a subpart of first argument.
 
14473
 
 
14474
  If first parts has different direction, change it to second part
 
14475
  (group is sorted like order)
 
14476
*/
 
14477
 
 
14478
static bool
 
14479
test_if_subpart(order_st *a,order_st *b)
 
14480
{
 
14481
  for (; a && b; a=a->next,b=b->next)
 
14482
  {
 
14483
    if ((*a->item)->eq(*b->item,1))
 
14484
      a->asc=b->asc;
 
14485
    else
 
14486
      return 0;
 
14487
  }
 
14488
  return test(!b);
 
14489
}
 
14490
 
 
14491
/**
 
14492
  Return table number if there is only one table in sort order
 
14493
  and group and order is compatible, else return 0.
 
14494
*/
 
14495
 
 
14496
static Table *
 
14497
get_sort_by_table(order_st *a,order_st *b,TableList *tables)
 
14498
{
 
14499
  table_map map= (table_map) 0;
 
14500
 
 
14501
  if (!a)
 
14502
    a=b;                                        // Only one need to be given
 
14503
  else if (!b)
 
14504
    b=a;
 
14505
 
 
14506
  for (; a && b; a=a->next,b=b->next)
 
14507
  {
 
14508
    if (!(*a->item)->eq(*b->item,1))
 
14509
      return(0);
 
14510
    map|=a->item[0]->used_tables();
 
14511
  }
 
14512
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
 
14513
    return(0);
 
14514
 
 
14515
  for (; !(map & tables->table->map); tables= tables->next_leaf) {};
 
14516
  if (map != tables->table->map)
 
14517
    return(0);                          // More than one table
 
14518
  return(tables->table);
 
14519
}
 
14520
 
 
14521
 
 
14522
/**
 
14523
  calc how big buffer we need for comparing group entries.
 
14524
*/
 
14525
 
 
14526
static void
 
14527
calc_group_buffer(JOIN *join,order_st *group)
 
14528
{
 
14529
  uint32_t key_length=0, parts=0, null_parts=0;
 
14530
 
 
14531
  if (group)
 
14532
    join->group= 1;
 
14533
  for (; group ; group=group->next)
 
14534
  {
 
14535
    Item *group_item= *group->item;
 
14536
    Field *field= group_item->get_tmp_table_field();
 
14537
    if (field)
 
14538
    {
 
14539
      enum_field_types type;
 
14540
      if ((type= field->type()) == DRIZZLE_TYPE_BLOB)
 
14541
        key_length+=MAX_BLOB_WIDTH;             // Can't be used as a key
 
14542
      else if (type == DRIZZLE_TYPE_VARCHAR)
 
14543
        key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
 
14544
      else
 
14545
        key_length+= field->pack_length();
 
14546
    }
 
14547
    else
 
14548
    {
 
14549
      switch (group_item->result_type()) {
 
14550
      case REAL_RESULT:
 
14551
        key_length+= sizeof(double);
 
14552
        break;
 
14553
      case INT_RESULT:
 
14554
        key_length+= sizeof(int64_t);
 
14555
        break;
 
14556
      case DECIMAL_RESULT:
 
14557
        key_length+= my_decimal_get_binary_size(group_item->max_length -
 
14558
                                                (group_item->decimals ? 1 : 0),
 
14559
                                                group_item->decimals);
 
14560
        break;
 
14561
      case STRING_RESULT:
 
14562
      {
 
14563
        enum enum_field_types type= group_item->field_type();
 
14564
        /*
 
14565
          As items represented as DATE/TIME fields in the group buffer
 
14566
          have STRING_RESULT result type, we increase the length
 
14567
          by 8 as maximum pack length of such fields.
 
14568
        */
 
14569
        if (type == DRIZZLE_TYPE_DATE ||
 
14570
            type == DRIZZLE_TYPE_DATETIME ||
 
14571
            type == DRIZZLE_TYPE_TIMESTAMP)
 
14572
        {
 
14573
          key_length+= 8;
 
14574
        }
 
14575
        else
 
14576
        {
 
14577
          /*
 
14578
            Group strings are taken as varstrings and require an length field.
 
14579
            A field is not yet created by create_tmp_field()
 
14580
            and the sizes should match up.
 
14581
          */
 
14582
          key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
 
14583
        }
 
14584
        break;
 
14585
      }
 
14586
      default:
 
14587
        /* This case should never be choosen */
 
14588
        assert(0);
 
14589
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
14590
      }
 
14591
    }
 
14592
    parts++;
 
14593
    if (group_item->maybe_null)
 
14594
      null_parts++;
 
14595
  }
 
14596
  join->tmp_table_param.group_length=key_length+null_parts;
 
14597
  join->tmp_table_param.group_parts=parts;
 
14598
  join->tmp_table_param.group_null_parts=null_parts;
 
14599
}
 
14600
 
 
14601
 
 
14602
/**
 
14603
  allocate group fields or take prepared (cached).
 
14604
 
 
14605
  @param main_join   join of current select
 
14606
  @param curr_join   current join (join of current select or temporary copy
 
14607
                     of it)
 
14608
 
 
14609
  @retval
 
14610
    0   ok
 
14611
  @retval
 
14612
    1   failed
 
14613
*/
 
14614
 
 
14615
static bool
 
14616
make_group_fields(JOIN *main_join, JOIN *curr_join)
 
14617
{
 
14618
  if (main_join->group_fields_cache.elements)
 
14619
  {
 
14620
    curr_join->group_fields= main_join->group_fields_cache;
 
14621
    curr_join->sort_and_group= 1;
 
14622
  }
 
14623
  else
 
14624
  {
 
14625
    if (alloc_group_fields(curr_join, curr_join->group_list))
 
14626
      return (1);
 
14627
    main_join->group_fields_cache= curr_join->group_fields;
 
14628
  }
 
14629
  return (0);
 
14630
}
 
14631
 
 
14632
 
 
14633
/**
 
14634
  Get a list of buffers for saveing last group.
 
14635
 
 
14636
  Groups are saved in reverse order for easyer check loop.
 
14637
*/
 
14638
 
 
14639
static bool
 
14640
alloc_group_fields(JOIN *join,order_st *group)
 
14641
{
 
14642
  if (group)
 
14643
  {
 
14644
    for (; group ; group=group->next)
 
14645
    {
 
14646
      Cached_item *tmp=new_Cached_item(join->session, *group->item, false);
 
14647
      if (!tmp || join->group_fields.push_front(tmp))
 
14648
        return true;
 
14649
    }
 
14650
  }
 
14651
  join->sort_and_group=1;                       /* Mark for do_select */
 
14652
  return false;
 
14653
}
 
14654
 
5733
14655
 
5734
14656
/*
5735
14657
  Test if a single-row cache of items changed, and update the cache.
5743
14665
  @return -1 if no item changed
5744
14666
  @return index of the first item that changed
5745
14667
*/
 
14668
 
5746
14669
int test_if_item_cache_changed(List<Cached_item> &list)
5747
14670
{
5748
14671
  List_iterator<Cached_item> li(list);
5757
14680
  return(idx);
5758
14681
}
5759
14682
 
 
14683
 
5760
14684
/**
5761
14685
  Setup copy_fields to save fields at start of new group.
5762
14686
 
5785
14709
  @retval
5786
14710
    !=0   error
5787
14711
*/
5788
 
bool setup_copy_fields(Session *session,
5789
 
                       Tmp_Table_Param *param,
5790
 
                       Item **ref_pointer_array,
5791
 
                       List<Item> &res_selected_fields,
5792
 
                       List<Item> &res_all_fields,
5793
 
                       uint32_t elements,
5794
 
                       List<Item> &all_fields)
 
14712
 
 
14713
bool
 
14714
setup_copy_fields(Session *session, Tmp_Table_Param *param,
 
14715
                  Item **ref_pointer_array,
 
14716
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
 
14717
                  uint32_t elements, List<Item> &all_fields)
5795
14718
{
5796
14719
  Item *pos;
5797
14720
  List_iterator_fast<Item> li(all_fields);
5798
 
  CopyField *copy= NULL;
 
14721
  Copy_field *copy= NULL;
5799
14722
  res_selected_fields.empty();
5800
14723
  res_all_fields.empty();
5801
14724
  List_iterator_fast<Item> itr(res_all_fields);
5803
14726
  uint32_t i, border= all_fields.elements - elements;
5804
14727
 
5805
14728
  if (param->field_count &&
5806
 
      !(copy=param->copy_field= new CopyField[param->field_count]))
 
14729
      !(copy=param->copy_field= new Copy_field[param->field_count]))
5807
14730
    goto err2;
5808
14731
 
5809
14732
  param->copy_funcs.empty();
5816
14739
    {
5817
14740
      Item_field *item;
5818
14741
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
5819
 
        goto err;
 
14742
        goto err;
5820
14743
      if (pos->type() == Item::REF_ITEM)
5821
14744
      {
5822
14745
        /* preserve the names of the ref when dereferncing */
5828
14751
      pos= item;
5829
14752
      if (item->field->flags & BLOB_FLAG)
5830
14753
      {
5831
 
        if (!(pos= new Item_copy_string(pos)))
5832
 
          goto err;
5833
 
            /*
5834
 
              Item_copy_string::copy for function can call
5835
 
              Item_copy_string::val_int for blob via Item_ref.
5836
 
              But if Item_copy_string::copy for blob isn't called before,
5837
 
              it's value will be wrong
5838
 
              so let's insert Item_copy_string for blobs in the beginning of
5839
 
              copy_funcs
5840
 
              (to see full test case look at having.test, BUG #4358)
5841
 
            */
5842
 
        if (param->copy_funcs.push_front(pos))
5843
 
          goto err;
 
14754
        if (!(pos= new Item_copy_string(pos)))
 
14755
          goto err;
 
14756
       /*
 
14757
         Item_copy_string::copy for function can call
 
14758
         Item_copy_string::val_int for blob via Item_ref.
 
14759
         But if Item_copy_string::copy for blob isn't called before,
 
14760
         it's value will be wrong
 
14761
         so let's insert Item_copy_string for blobs in the beginning of
 
14762
         copy_funcs
 
14763
         (to see full test case look at having.test, BUG #4358)
 
14764
       */
 
14765
        if (param->copy_funcs.push_front(pos))
 
14766
          goto err;
5844
14767
      }
5845
14768
      else
5846
14769
      {
 
14770
        /*
 
14771
           set up save buffer and change result_field to point at
 
14772
           saved value
 
14773
        */
 
14774
        field= item->field;
 
14775
        item->result_field=field->new_field(session->mem_root,field->table, 1);
5847
14776
        /*
5848
 
          set up save buffer and change result_field to point at
5849
 
          saved value
 
14777
          We need to allocate one extra byte for null handling and
 
14778
          another extra byte to not get warnings from purify in
 
14779
          Field_varstring::val_int
5850
14780
        */
5851
 
        field= item->field;
5852
 
        item->result_field=field->new_field(session->mem_root,field->getTable(), 1);
5853
 
              /*
5854
 
                We need to allocate one extra byte for null handling and
5855
 
                another extra byte to not get warnings from purify in
5856
 
                Field_varstring::val_int
5857
 
              */
5858
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
5859
 
          goto err;
 
14781
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
 
14782
          goto err;
5860
14783
        if (copy)
5861
14784
        {
5862
14785
          copy->set(tmp, item->result_field);
5863
14786
          item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1);
5864
 
#ifdef HAVE_VALGRIND
 
14787
#ifdef HAVE_purify
5865
14788
          copy->to_ptr[copy->from_length]= 0;
5866
14789
#endif
5867
14790
          copy++;
5876
14799
    {                                           // Save for send fields
5877
14800
      pos= real_pos;
5878
14801
      /* TODO:
5879
 
        In most cases this result will be sent to the user.
5880
 
        This should be changed to use copy_int or copy_real depending
5881
 
        on how the value is to be used: In some cases this may be an
5882
 
        argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
 
14802
         In most cases this result will be sent to the user.
 
14803
         This should be changed to use copy_int or copy_real depending
 
14804
         on how the value is to be used: In some cases this may be an
 
14805
         argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
5883
14806
      */
5884
14807
      if (!(pos=new Item_copy_string(pos)))
5885
 
        goto err;
 
14808
        goto err;
5886
14809
      if (i < border)                           // HAVING, order_st and GROUP BY
5887
14810
      {
5888
14811
        if (extra_funcs.push_back(pos))
5889
14812
          goto err;
5890
14813
      }
5891
14814
      else if (param->copy_funcs.push_back(pos))
5892
 
        goto err;
 
14815
        goto err;
5893
14816
    }
5894
14817
    res_all_fields.push_back(pos);
5895
14818
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
5901
14824
    itr++;
5902
14825
  itr.sublist(res_selected_fields, elements);
5903
14826
  /*
5904
 
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
 
14827
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
5905
14828
    reference used in these will resolve to a item that is already calculated
5906
14829
  */
5907
14830
  param->copy_funcs.concat(&extra_funcs);
5908
14831
 
5909
14832
  return(0);
5910
14833
 
5911
 
err:
 
14834
 err:
5912
14835
  if (copy)
5913
14836
    delete [] param->copy_field;                        // This is never 0
5914
14837
  param->copy_field=0;
5916
14839
  return(true);
5917
14840
}
5918
14841
 
 
14842
 
5919
14843
/**
5920
14844
  Make a copy of all simple SELECT'ed items.
5921
14845
 
5922
14846
  This is done at the start of a new group so that we can retrieve
5923
14847
  these later when the group changes.
5924
14848
*/
5925
 
void copy_fields(Tmp_Table_Param *param)
 
14849
 
 
14850
void
 
14851
copy_fields(Tmp_Table_Param *param)
5926
14852
{
5927
 
  CopyField *ptr= param->copy_field;
5928
 
  CopyField *end= param->copy_field_end;
 
14853
  Copy_field *ptr=param->copy_field;
 
14854
  Copy_field *end=param->copy_field_end;
5929
14855
 
5930
14856
  for (; ptr != end; ptr++)
5931
14857
    (*ptr->do_copy)(ptr);
5936
14862
    item->copy();
5937
14863
}
5938
14864
 
 
14865
 
 
14866
/**
 
14867
  Make an array of pointers to sum_functions to speed up
 
14868
  sum_func calculation.
 
14869
 
 
14870
  @retval
 
14871
    0   ok
 
14872
  @retval
 
14873
    1   Error
 
14874
*/
 
14875
 
 
14876
bool JOIN::alloc_func_list()
 
14877
{
 
14878
  uint32_t func_count, group_parts;
 
14879
 
 
14880
  func_count= tmp_table_param.sum_func_count;
 
14881
  /*
 
14882
    If we are using rollup, we need a copy of the summary functions for
 
14883
    each level
 
14884
  */
 
14885
  if (rollup.state != ROLLUP::STATE_NONE)
 
14886
    func_count*= (send_group_parts+1);
 
14887
 
 
14888
  group_parts= send_group_parts;
 
14889
  /*
 
14890
    If distinct, reserve memory for possible
 
14891
    disctinct->group_by optimization
 
14892
  */
 
14893
  if (select_distinct)
 
14894
  {
 
14895
    group_parts+= fields_list.elements;
 
14896
    /*
 
14897
      If the order_st clause is specified then it's possible that
 
14898
      it also will be optimized, so reserve space for it too
 
14899
    */
 
14900
    if (order)
 
14901
    {
 
14902
      order_st *ord;
 
14903
      for (ord= order; ord; ord= ord->next)
 
14904
        group_parts++;
 
14905
    }
 
14906
  }
 
14907
 
 
14908
  /* This must use calloc() as rollup_make_fields depends on this */
 
14909
  sum_funcs= (Item_sum**) session->calloc(sizeof(Item_sum**) * (func_count+1) +
 
14910
                                      sizeof(Item_sum***) * (group_parts+1));
 
14911
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
 
14912
  return(sum_funcs == 0);
 
14913
}
 
14914
 
 
14915
 
 
14916
/**
 
14917
  Initialize 'sum_funcs' array with all Item_sum objects.
 
14918
 
 
14919
  @param field_list        All items
 
14920
  @param send_fields       Items in select list
 
14921
  @param before_group_by   Set to 1 if this is called before GROUP BY handling
 
14922
  @param recompute         Set to true if sum_funcs must be recomputed
 
14923
 
 
14924
  @retval
 
14925
    0  ok
 
14926
  @retval
 
14927
    1  error
 
14928
*/
 
14929
 
 
14930
bool JOIN::make_sum_func_list(List<Item> &field_list, List<Item> &send_fields,
 
14931
                              bool before_group_by, bool recompute)
 
14932
{
 
14933
  List_iterator_fast<Item> it(field_list);
 
14934
  Item_sum **func;
 
14935
  Item *item;
 
14936
 
 
14937
  if (*sum_funcs && !recompute)
 
14938
    return(false); /* We have already initialized sum_funcs. */
 
14939
 
 
14940
  func= sum_funcs;
 
14941
  while ((item=it++))
 
14942
  {
 
14943
    if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
 
14944
        (!((Item_sum*) item)->depended_from() ||
 
14945
         ((Item_sum *)item)->depended_from() == select_lex))
 
14946
      *func++= (Item_sum*) item;
 
14947
  }
 
14948
  if (before_group_by && rollup.state == ROLLUP::STATE_INITED)
 
14949
  {
 
14950
    rollup.state= ROLLUP::STATE_READY;
 
14951
    if (rollup_make_fields(field_list, send_fields, &func))
 
14952
      return(true);                     // Should never happen
 
14953
  }
 
14954
  else if (rollup.state == ROLLUP::STATE_NONE)
 
14955
  {
 
14956
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
 
14957
      sum_funcs_end[i]= func;
 
14958
  }
 
14959
  else if (rollup.state == ROLLUP::STATE_READY)
 
14960
    return(false);                         // Don't put end marker
 
14961
  *func=0;                                      // End marker
 
14962
  return(false);
 
14963
}
 
14964
 
 
14965
 
5939
14966
/**
5940
14967
  Change all funcs and sum_funcs to fields in tmp table, and create
5941
14968
  new list of all items.
5952
14979
  @retval
5953
14980
    !=0   error
5954
14981
*/
5955
 
bool change_to_use_tmp_fields(Session *session,
5956
 
                              Item **ref_pointer_array,
5957
 
                                                List<Item> &res_selected_fields,
5958
 
                                                List<Item> &res_all_fields,
5959
 
                                                uint32_t elements,
5960
 
                              List<Item> &all_fields)
 
14982
 
 
14983
static bool
 
14984
change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
 
14985
                         List<Item> &res_selected_fields,
 
14986
                         List<Item> &res_all_fields,
 
14987
                         uint32_t elements, List<Item> &all_fields)
5961
14988
{
5962
14989
  List_iterator_fast<Item> it(all_fields);
5963
14990
  Item *item_field,*item;
5978
15005
    {
5979
15006
      if (item->type() == Item::FIELD_ITEM)
5980
15007
      {
5981
 
        item_field= item->get_tmp_table_item(session);
 
15008
        item_field= item->get_tmp_table_item(session);
5982
15009
      }
5983
15010
      else if ((field= item->get_tmp_table_field()))
5984
15011
      {
5985
 
        if (item->type() == Item::SUM_FUNC_ITEM && field->getTable()->group)
5986
 
          item_field= ((Item_sum*) item)->result_item(field);
5987
 
        else
5988
 
          item_field= (Item*) new Item_field(field);
5989
 
        if (!item_field)
5990
 
          return(true);                    // Fatal error
 
15012
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
 
15013
          item_field= ((Item_sum*) item)->result_item(field);
 
15014
        else
 
15015
          item_field= (Item*) new Item_field(field);
 
15016
        if (!item_field)
 
15017
          return(true);                    // Fatal error
5991
15018
 
5992
15019
        if (item->real_item()->type() != Item::FIELD_ITEM)
5993
15020
          field->orig_table= 0;
5994
 
        item_field->name= item->name;
 
15021
        item_field->name= item->name;
5995
15022
        if (item->type() == Item::REF_ITEM)
5996
15023
        {
5997
15024
          Item_field *ifield= (Item_field *) item_field;
6001
15028
        }
6002
15029
      }
6003
15030
      else
6004
 
        item_field= item;
 
15031
        item_field= item;
6005
15032
    }
6006
15033
    res_all_fields.push_back(item_field);
6007
15034
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
6015
15042
  return(false);
6016
15043
}
6017
15044
 
 
15045
 
6018
15046
/**
6019
15047
  Change all sum_func refs to fields to point at fields in tmp table.
6020
15048
  Change all funcs to be fields in tmp table.
6031
15059
  @retval
6032
15060
    1   error
6033
15061
*/
6034
 
bool change_refs_to_tmp_fields(Session *session,
6035
 
                               Item **ref_pointer_array,
6036
 
                               List<Item> &res_selected_fields,
6037
 
                               List<Item> &res_all_fields,
6038
 
                               uint32_t elements,
6039
 
                                                 List<Item> &all_fields)
 
15062
 
 
15063
static bool
 
15064
change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
 
15065
                          List<Item> &res_selected_fields,
 
15066
                          List<Item> &res_all_fields, uint32_t elements,
 
15067
                          List<Item> &all_fields)
6040
15068
{
6041
15069
  List_iterator_fast<Item> it(all_fields);
6042
15070
  Item *item, *new_item;
6059
15087
  return session->is_fatal_error;
6060
15088
}
6061
15089
 
 
15090
 
 
15091
 
6062
15092
/******************************************************************************
6063
15093
  Code for calculating functions
6064
15094
******************************************************************************/
6065
15095
 
 
15096
 
6066
15097
/**
6067
15098
  Call ::setup for all sum functions.
6068
15099
 
6069
 
  @param session           thread Cursor
 
15100
  @param session           thread handler
6070
15101
  @param func_ptr      sum function list
6071
15102
 
6072
15103
  @retval
6074
15105
  @retval
6075
15106
    true   error
6076
15107
*/
6077
 
bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
 
15108
 
 
15109
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
6078
15110
{
6079
15111
  Item_sum *func;
6080
15112
  while ((func= *(func_ptr++)))
6085
15117
  return(false);
6086
15118
}
6087
15119
 
6088
 
void init_tmptable_sum_functions(Item_sum **func_ptr)
 
15120
 
 
15121
static void
 
15122
init_tmptable_sum_functions(Item_sum **func_ptr)
6089
15123
{
6090
15124
  Item_sum *func;
6091
15125
  while ((func= *(func_ptr++)))
6092
15126
    func->reset_field();
6093
15127
}
6094
15128
 
 
15129
 
6095
15130
/** Update record 0 in tmp_table from record 1. */
6096
 
void update_tmptable_sum_func(Item_sum **func_ptr, Table *)
 
15131
 
 
15132
static void
 
15133
update_tmptable_sum_func(Item_sum **func_ptr, Table *)
6097
15134
{
6098
15135
  Item_sum *func;
6099
15136
  while ((func= *(func_ptr++)))
6100
15137
    func->update_field();
6101
15138
}
6102
15139
 
 
15140
 
6103
15141
/** Copy result of sum functions to record in tmp_table. */
6104
 
void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
 
15142
 
 
15143
static void
 
15144
copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
6105
15145
{
6106
15146
  for (; func_ptr != end_ptr ; func_ptr++)
6107
15147
    (void) (*func_ptr)->save_in_result_field(1);
6108
15148
  return;
6109
15149
}
6110
15150
 
6111
 
bool init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
 
15151
 
 
15152
static bool
 
15153
init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
6112
15154
{
6113
15155
  for (; func_ptr != end_ptr ;func_ptr++)
6114
15156
  {
6124
15166
  return 0;
6125
15167
}
6126
15168
 
6127
 
bool update_sum_func(Item_sum **func_ptr)
 
15169
 
 
15170
static bool
 
15171
update_sum_func(Item_sum **func_ptr)
6128
15172
{
6129
15173
  Item_sum *func;
6130
15174
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
6134
15178
}
6135
15179
 
6136
15180
/** Copy result of functions to record in tmp_table. */
6137
 
bool copy_funcs(Item **func_ptr, const Session *session)
 
15181
 
 
15182
void
 
15183
copy_funcs(Item **func_ptr)
6138
15184
{
6139
15185
  Item *func;
6140
15186
  for (; (func = *func_ptr) ; func_ptr++)
6141
 
  {
6142
15187
    func->save_in_result_field(1);
6143
 
    /*
6144
 
      Need to check the THD error state because Item::val_xxx() don't
6145
 
      return error code, but can generate errors
6146
 
      TODO: change it for a real status check when Item::val_xxx()
6147
 
      are extended to return status code.
6148
 
    */
6149
 
    if (session->is_error())
6150
 
      return true;
6151
 
  }
6152
 
  return false;
6153
 
}
 
15188
}
 
15189
 
 
15190
 
 
15191
/**
 
15192
  Create a condition for a const reference and add this to the
 
15193
  currenct select for the table.
 
15194
*/
 
15195
 
 
15196
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab)
 
15197
{
 
15198
  if (!join_tab->ref.key_parts)
 
15199
    return(false);
 
15200
 
 
15201
  Item_cond_and *cond=new Item_cond_and();
 
15202
  Table *table=join_tab->table;
 
15203
  int error;
 
15204
  if (!cond)
 
15205
    return(true);
 
15206
 
 
15207
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
 
15208
  {
 
15209
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
 
15210
                              fieldnr-1];
 
15211
    Item *value=join_tab->ref.items[i];
 
15212
    cond->add(new Item_func_equal(new Item_field(field), value));
 
15213
  }
 
15214
  if (session->is_fatal_error)
 
15215
    return(true);
 
15216
 
 
15217
  if (!cond->fixed)
 
15218
    cond->fix_fields(session, (Item**)&cond);
 
15219
  if (join_tab->select)
 
15220
  {
 
15221
    error=(int) cond->add(join_tab->select->cond);
 
15222
    join_tab->select_cond=join_tab->select->cond=cond;
 
15223
  }
 
15224
  else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0,
 
15225
                                          &error)))
 
15226
    join_tab->select_cond=cond;
 
15227
 
 
15228
  return(error ? true : false);
 
15229
}
 
15230
 
6154
15231
 
6155
15232
/**
6156
15233
  Free joins of subselect of this select.
6158
15235
  @param session      Session pointer
6159
15236
  @param select   pointer to Select_Lex which subselects joins we will free
6160
15237
*/
 
15238
 
6161
15239
void free_underlaid_joins(Session *, Select_Lex *select)
6162
15240
{
6163
15241
  for (Select_Lex_Unit *unit= select->first_inner_unit();
6209
15287
  @retval
6210
15288
    1   on error
6211
15289
*/
6212
 
bool change_group_ref(Session *session, Item_func *expr, Order *group_list, bool *changed)
 
15290
 
 
15291
static bool change_group_ref(Session *session, Item_func *expr, order_st *group_list,
 
15292
                             bool *changed)
6213
15293
{
6214
15294
  if (expr->arg_count)
6215
15295
  {
6223
15303
      Item *item= *arg;
6224
15304
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
6225
15305
      {
6226
 
        Order *group_tmp;
 
15306
        order_st *group_tmp;
6227
15307
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
6228
15308
        {
6229
15309
          if (item->eq(*group_tmp->item,0))
6253
15333
}
6254
15334
 
6255
15335
 
 
15336
/** Allocate memory needed for other rollup functions. */
 
15337
 
 
15338
bool JOIN::rollup_init()
 
15339
{
 
15340
  uint32_t i,j;
 
15341
  Item **ref_array;
 
15342
 
 
15343
  tmp_table_param.quick_group= 0;       // Can't create groups in tmp table
 
15344
  rollup.state= ROLLUP::STATE_INITED;
 
15345
 
 
15346
  /*
 
15347
    Create pointers to the different sum function groups
 
15348
    These are updated by rollup_make_fields()
 
15349
  */
 
15350
  tmp_table_param.group_parts= send_group_parts;
 
15351
 
 
15352
  if (!(rollup.null_items= (Item_null_result**) session->alloc((sizeof(Item*) +
 
15353
                                                sizeof(Item**) +
 
15354
                                                sizeof(List<Item>) +
 
15355
                                                ref_pointer_array_size)
 
15356
                                                * send_group_parts )))
 
15357
    return 1;
 
15358
 
 
15359
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
 
15360
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
 
15361
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
 
15362
 
 
15363
  /*
 
15364
    Prepare space for field list for the different levels
 
15365
    These will be filled up in rollup_make_fields()
 
15366
  */
 
15367
  for (i= 0 ; i < send_group_parts ; i++)
 
15368
  {
 
15369
    rollup.null_items[i]= new (session->mem_root) Item_null_result();
 
15370
    List<Item> *rollup_fields= &rollup.fields[i];
 
15371
    rollup_fields->empty();
 
15372
    rollup.ref_pointer_arrays[i]= ref_array;
 
15373
    ref_array+= all_fields.elements;
 
15374
  }
 
15375
  for (i= 0 ; i < send_group_parts; i++)
 
15376
  {
 
15377
    for (j=0 ; j < fields_list.elements ; j++)
 
15378
      rollup.fields[i].push_back(rollup.null_items[i]);
 
15379
  }
 
15380
  List_iterator<Item> it(all_fields);
 
15381
  Item *item;
 
15382
  while ((item= it++))
 
15383
  {
 
15384
    order_st *group_tmp;
 
15385
    bool found_in_group= 0;
 
15386
 
 
15387
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
 
15388
    {
 
15389
      if (*group_tmp->item == item)
 
15390
      {
 
15391
        item->maybe_null= 1;
 
15392
        found_in_group= 1;
 
15393
        if (item->const_item())
 
15394
        {
 
15395
          /*
 
15396
            For ROLLUP queries each constant item referenced in GROUP BY list
 
15397
            is wrapped up into an Item_func object yielding the same value
 
15398
            as the constant item. The objects of the wrapper class are never
 
15399
            considered as constant items and besides they inherit all
 
15400
            properties of the Item_result_field class.
 
15401
            This wrapping allows us to ensure writing constant items
 
15402
            into temporary tables whenever the result of the ROLLUP
 
15403
            operation has to be written into a temporary table, e.g. when
 
15404
            ROLLUP is used together with DISTINCT in the SELECT list.
 
15405
            Usually when creating temporary tables for a intermidiate
 
15406
            result we do not include fields for constant expressions.
 
15407
          */
 
15408
          Item* new_item= new Item_func_rollup_const(item);
 
15409
          if (!new_item)
 
15410
            return 1;
 
15411
          new_item->fix_fields(session, (Item **) 0);
 
15412
          session->change_item_tree(it.ref(), new_item);
 
15413
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
 
15414
          {
 
15415
            if (*tmp->item == item)
 
15416
              session->change_item_tree(tmp->item, new_item);
 
15417
          }
 
15418
        }
 
15419
      }
 
15420
    }
 
15421
    if (item->type() == Item::FUNC_ITEM && !found_in_group)
 
15422
    {
 
15423
      bool changed= false;
 
15424
      if (change_group_ref(session, (Item_func *) item, group_list, &changed))
 
15425
        return 1;
 
15426
      /*
 
15427
        We have to prevent creation of a field in a temporary table for
 
15428
        an expression that contains GROUP BY attributes.
 
15429
        Marking the expression item as 'with_sum_func' will ensure this.
 
15430
      */
 
15431
      if (changed)
 
15432
        item->with_sum_func= 1;
 
15433
    }
 
15434
  }
 
15435
  return 0;
 
15436
}
 
15437
 
 
15438
 
 
15439
/**
 
15440
  Fill up rollup structures with pointers to fields to use.
 
15441
 
 
15442
  Creates copies of item_sum items for each sum level.
 
15443
 
 
15444
  @param fields_arg             List of all fields (hidden and real ones)
 
15445
  @param sel_fields             Pointer to selected fields
 
15446
  @param func                   Store here a pointer to all fields
 
15447
 
 
15448
  @retval
 
15449
    0   if ok;
 
15450
    In this case func is pointing to next not used element.
 
15451
  @retval
 
15452
    1    on error
 
15453
*/
 
15454
 
 
15455
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields,
 
15456
                              Item_sum ***func)
 
15457
{
 
15458
  List_iterator_fast<Item> it(fields_arg);
 
15459
  Item *first_field= sel_fields.head();
 
15460
  uint32_t level;
 
15461
 
 
15462
  /*
 
15463
    Create field lists for the different levels
 
15464
 
 
15465
    The idea here is to have a separate field list for each rollup level to
 
15466
    avoid all runtime checks of which columns should be NULL.
 
15467
 
 
15468
    The list is stored in reverse order to get sum function in such an order
 
15469
    in func that it makes it easy to reset them with init_sum_functions()
 
15470
 
 
15471
    Assuming:  SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
 
15472
 
 
15473
    rollup.fields[0] will contain list where a,b,c is NULL
 
15474
    rollup.fields[1] will contain list where b,c is NULL
 
15475
    ...
 
15476
    rollup.ref_pointer_array[#] points to fields for rollup.fields[#]
 
15477
    ...
 
15478
    sum_funcs_end[0] points to all sum functions
 
15479
    sum_funcs_end[1] points to all sum functions, except grand totals
 
15480
    ...
 
15481
  */
 
15482
 
 
15483
  for (level=0 ; level < send_group_parts ; level++)
 
15484
  {
 
15485
    uint32_t i;
 
15486
    uint32_t pos= send_group_parts - level -1;
 
15487
    bool real_fields= 0;
 
15488
    Item *item;
 
15489
    List_iterator<Item> new_it(rollup.fields[pos]);
 
15490
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
 
15491
    order_st *start_group;
 
15492
 
 
15493
    /* Point to first hidden field */
 
15494
    Item **ref_array= ref_array_start + fields_arg.elements-1;
 
15495
 
 
15496
    /* Remember where the sum functions ends for the previous level */
 
15497
    sum_funcs_end[pos+1]= *func;
 
15498
 
 
15499
    /* Find the start of the group for this level */
 
15500
    for (i= 0, start_group= group_list ;
 
15501
         i++ < pos ;
 
15502
         start_group= start_group->next)
 
15503
      ;
 
15504
 
 
15505
    it.rewind();
 
15506
    while ((item= it++))
 
15507
    {
 
15508
      if (item == first_field)
 
15509
      {
 
15510
        real_fields= 1;                         // End of hidden fields
 
15511
        ref_array= ref_array_start;
 
15512
      }
 
15513
 
 
15514
      if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
 
15515
          (!((Item_sum*) item)->depended_from() ||
 
15516
           ((Item_sum *)item)->depended_from() == select_lex))
 
15517
 
 
15518
      {
 
15519
        /*
 
15520
          This is a top level summary function that must be replaced with
 
15521
          a sum function that is reset for this level.
 
15522
 
 
15523
          NOTE: This code creates an object which is not that nice in a
 
15524
          sub select.  Fortunately it's not common to have rollup in
 
15525
          sub selects.
 
15526
        */
 
15527
        item= item->copy_or_same(session);
 
15528
        ((Item_sum*) item)->make_unique();
 
15529
        *(*func)= (Item_sum*) item;
 
15530
        (*func)++;
 
15531
      }
 
15532
      else
 
15533
      {
 
15534
        /* Check if this is something that is part of this group by */
 
15535
        order_st *group_tmp;
 
15536
        for (group_tmp= start_group, i= pos ;
 
15537
             group_tmp ; group_tmp= group_tmp->next, i++)
 
15538
        {
 
15539
          if (*group_tmp->item == item)
 
15540
          {
 
15541
            /*
 
15542
              This is an element that is used by the GROUP BY and should be
 
15543
              set to NULL in this level
 
15544
            */
 
15545
            Item_null_result *null_item= new (session->mem_root) Item_null_result();
 
15546
            if (!null_item)
 
15547
              return 1;
 
15548
            item->maybe_null= 1;                // Value will be null sometimes
 
15549
            null_item->result_field= item->get_tmp_table_field();
 
15550
            item= null_item;
 
15551
            break;
 
15552
          }
 
15553
        }
 
15554
      }
 
15555
      *ref_array= item;
 
15556
      if (real_fields)
 
15557
      {
 
15558
        (void) new_it++;                        // Point to next item
 
15559
        new_it.replace(item);                   // Replace previous
 
15560
        ref_array++;
 
15561
      }
 
15562
      else
 
15563
        ref_array--;
 
15564
    }
 
15565
  }
 
15566
  sum_funcs_end[0]= *func;                      // Point to last function
 
15567
  return 0;
 
15568
}
 
15569
 
 
15570
/**
 
15571
  Send all rollup levels higher than the current one to the client.
 
15572
 
 
15573
  @b SAMPLE
 
15574
    @code
 
15575
      SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
 
15576
  @endcode
 
15577
 
 
15578
  @param idx            Level we are on:
 
15579
                        - 0 = Total sum level
 
15580
                        - 1 = First group changed  (a)
 
15581
                        - 2 = Second group changed (a,b)
 
15582
 
 
15583
  @retval
 
15584
    0   ok
 
15585
  @retval
 
15586
    1   If send_data_failed()
 
15587
*/
 
15588
 
 
15589
int JOIN::rollup_send_data(uint32_t idx)
 
15590
{
 
15591
  uint32_t i;
 
15592
  for (i= send_group_parts ; i-- > idx ; )
 
15593
  {
 
15594
    /* Get reference pointers to sum functions in place */
 
15595
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
15596
           ref_pointer_array_size);
 
15597
    if ((!having || having->val_int()))
 
15598
    {
 
15599
      if (send_records < unit->select_limit_cnt && do_send_rows &&
 
15600
          result->send_data(rollup.fields[i]))
 
15601
        return 1;
 
15602
      send_records++;
 
15603
    }
 
15604
  }
 
15605
  /* Restore ref_pointer_array */
 
15606
  set_items_ref_array(current_ref_pointer_array);
 
15607
  return 0;
 
15608
}
 
15609
 
 
15610
/**
 
15611
  Write all rollup levels higher than the current one to a temp table.
 
15612
 
 
15613
  @b SAMPLE
 
15614
    @code
 
15615
      SELECT a, b, SUM(c) FROM t1 GROUP BY a,b WITH ROLLUP
 
15616
  @endcode
 
15617
 
 
15618
  @param idx                 Level we are on:
 
15619
                               - 0 = Total sum level
 
15620
                               - 1 = First group changed  (a)
 
15621
                               - 2 = Second group changed (a,b)
 
15622
  @param table               reference to temp table
 
15623
 
 
15624
  @retval
 
15625
    0   ok
 
15626
  @retval
 
15627
    1   if write_data_failed()
 
15628
*/
 
15629
 
 
15630
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
 
15631
{
 
15632
  uint32_t i;
 
15633
  for (i= send_group_parts ; i-- > idx ; )
 
15634
  {
 
15635
    /* Get reference pointers to sum functions in place */
 
15636
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
15637
           ref_pointer_array_size);
 
15638
    if ((!having || having->val_int()))
 
15639
    {
 
15640
      int write_error;
 
15641
      Item *item;
 
15642
      List_iterator_fast<Item> it(rollup.fields[i]);
 
15643
      while ((item= it++))
 
15644
      {
 
15645
        if (item->type() == Item::NULL_ITEM && item->is_result_field())
 
15646
          item->save_in_result_field(1);
 
15647
      }
 
15648
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
 
15649
      if ((write_error= table_arg->file->ha_write_row(table_arg->record[0])))
 
15650
      {
 
15651
        if (create_myisam_from_heap(session, table_arg,
 
15652
                                    tmp_table_param.start_recinfo,
 
15653
                                    &tmp_table_param.recinfo,
 
15654
                                    write_error, 0))
 
15655
          return 1;
 
15656
      }
 
15657
    }
 
15658
  }
 
15659
  /* Restore ref_pointer_array */
 
15660
  set_items_ref_array(current_ref_pointer_array);
 
15661
  return 0;
 
15662
}
 
15663
 
 
15664
/**
 
15665
  clear results if there are not rows found for group
 
15666
  (end_send_group/end_write_group)
 
15667
*/
 
15668
 
 
15669
void JOIN::clear()
 
15670
{
 
15671
  clear_tables(this);
 
15672
  copy_fields(&tmp_table_param);
 
15673
 
 
15674
  if (sum_funcs)
 
15675
  {
 
15676
    Item_sum *func, **func_ptr= sum_funcs;
 
15677
    while ((func= *(func_ptr++)))
 
15678
      func->clear();
 
15679
  }
 
15680
}
 
15681
 
 
15682
/**
 
15683
  EXPLAIN handling.
 
15684
 
 
15685
  Send a description about what how the select will be done to stdout.
 
15686
*/
 
15687
 
 
15688
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
 
15689
                     bool distinct,const char *message)
 
15690
{
 
15691
  List<Item> field_list;
 
15692
  List<Item> item_list;
 
15693
  Session *session=join->session;
 
15694
  select_result *result=join->result;
 
15695
  Item *item_null= new Item_null();
 
15696
  const CHARSET_INFO * const cs= system_charset_info;
 
15697
  int quick_type;
 
15698
  /* Don't log this into the slow query log */
 
15699
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
15700
  join->unit->offset_limit_cnt= 0;
 
15701
 
 
15702
  /*
 
15703
    NOTE: the number/types of items pushed into item_list must be in sync with
 
15704
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
 
15705
  */
 
15706
  if (message)
 
15707
  {
 
15708
    item_list.push_back(new Item_int((int32_t)
 
15709
                                     join->select_lex->select_number));
 
15710
    item_list.push_back(new Item_string(join->select_lex->type,
 
15711
                                        strlen(join->select_lex->type), cs));
 
15712
    for (uint32_t i=0 ; i < 7; i++)
 
15713
      item_list.push_back(item_null);
 
15714
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15715
      item_list.push_back(item_null);
 
15716
 
 
15717
    item_list.push_back(new Item_string(message,strlen(message),cs));
 
15718
    if (result->send_data(item_list))
 
15719
      join->error= 1;
 
15720
  }
 
15721
  else if (join->select_lex == join->unit->fake_select_lex)
 
15722
  {
 
15723
    /*
 
15724
      here we assume that the query will return at least two rows, so we
 
15725
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
 
15726
      and no filesort will be actually done, but executing all selects in
 
15727
      the UNION to provide precise EXPLAIN information will hardly be
 
15728
      appreciated :)
 
15729
    */
 
15730
    char table_name_buffer[NAME_LEN];
 
15731
    item_list.empty();
 
15732
    /* id */
 
15733
    item_list.push_back(new Item_null);
 
15734
    /* select_type */
 
15735
    item_list.push_back(new Item_string(join->select_lex->type,
 
15736
                                        strlen(join->select_lex->type),
 
15737
                                        cs));
 
15738
    /* table */
 
15739
    {
 
15740
      Select_Lex *sl= join->unit->first_select();
 
15741
      uint32_t len= 6, lastop= 0;
 
15742
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
 
15743
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
 
15744
      {
 
15745
        len+= lastop;
 
15746
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
 
15747
                         "%u,", sl->select_number);
 
15748
      }
 
15749
      if (sl || len + lastop >= NAME_LEN)
 
15750
      {
 
15751
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
 
15752
        len+= 4;
 
15753
      }
 
15754
      else
 
15755
      {
 
15756
        len+= lastop;
 
15757
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
 
15758
      }
 
15759
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
15760
    }
 
15761
    /* type */
 
15762
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
 
15763
                                          strlen(join_type_str[JT_ALL]),
 
15764
                                          cs));
 
15765
    /* possible_keys */
 
15766
    item_list.push_back(item_null);
 
15767
    /* key*/
 
15768
    item_list.push_back(item_null);
 
15769
    /* key_len */
 
15770
    item_list.push_back(item_null);
 
15771
    /* ref */
 
15772
    item_list.push_back(item_null);
 
15773
    /* in_rows */
 
15774
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15775
      item_list.push_back(item_null);
 
15776
    /* rows */
 
15777
    item_list.push_back(item_null);
 
15778
    /* extra */
 
15779
    if (join->unit->global_parameters->order_list.first)
 
15780
      item_list.push_back(new Item_string("Using filesort",
 
15781
                                          14, cs));
 
15782
    else
 
15783
      item_list.push_back(new Item_string("", 0, cs));
 
15784
 
 
15785
    if (result->send_data(item_list))
 
15786
      join->error= 1;
 
15787
  }
 
15788
  else
 
15789
  {
 
15790
    table_map used_tables=0;
 
15791
    for (uint32_t i=0 ; i < join->tables ; i++)
 
15792
    {
 
15793
      JOIN_TAB *tab=join->join_tab+i;
 
15794
      Table *table=tab->table;
 
15795
      TableList *table_list= tab->table->pos_in_table_list;
 
15796
      char buff[512];
 
15797
      char buff1[512], buff2[512], buff3[512];
 
15798
      char keylen_str_buf[64];
 
15799
      String extra(buff, sizeof(buff),cs);
 
15800
      char table_name_buffer[NAME_LEN];
 
15801
      String tmp1(buff1,sizeof(buff1),cs);
 
15802
      String tmp2(buff2,sizeof(buff2),cs);
 
15803
      String tmp3(buff3,sizeof(buff3),cs);
 
15804
      extra.length(0);
 
15805
      tmp1.length(0);
 
15806
      tmp2.length(0);
 
15807
      tmp3.length(0);
 
15808
 
 
15809
      quick_type= -1;
 
15810
      item_list.empty();
 
15811
      /* id */
 
15812
      item_list.push_back(new Item_uint((uint32_t)
 
15813
                                       join->select_lex->select_number));
 
15814
      /* select_type */
 
15815
      item_list.push_back(new Item_string(join->select_lex->type,
 
15816
                                          strlen(join->select_lex->type),
 
15817
                                          cs));
 
15818
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
 
15819
      {
 
15820
        quick_type= tab->select->quick->get_type();
 
15821
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
 
15822
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
 
15823
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
 
15824
          tab->type = JT_INDEX_MERGE;
 
15825
        else
 
15826
          tab->type = JT_RANGE;
 
15827
      }
 
15828
      /* table */
 
15829
      if (table->derived_select_number)
 
15830
      {
 
15831
        /* Derived table name generation */
 
15832
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
15833
                          "<derived%u>",
 
15834
                          table->derived_select_number);
 
15835
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
15836
      }
 
15837
      else
 
15838
      {
 
15839
        TableList *real_table= table->pos_in_table_list;
 
15840
        item_list.push_back(new Item_string(real_table->alias,
 
15841
                                            strlen(real_table->alias),
 
15842
                                            cs));
 
15843
      }
 
15844
      /* "type" column */
 
15845
      item_list.push_back(new Item_string(join_type_str[tab->type],
 
15846
                                          strlen(join_type_str[tab->type]),
 
15847
                                          cs));
 
15848
      /* Build "possible_keys" value and add it to item_list */
 
15849
      if (!tab->keys.is_clear_all())
 
15850
      {
 
15851
        uint32_t j;
 
15852
        for (j=0 ; j < table->s->keys ; j++)
 
15853
        {
 
15854
          if (tab->keys.is_set(j))
 
15855
          {
 
15856
            if (tmp1.length())
 
15857
              tmp1.append(',');
 
15858
            tmp1.append(table->key_info[j].name,
 
15859
                        strlen(table->key_info[j].name),
 
15860
                        system_charset_info);
 
15861
          }
 
15862
        }
 
15863
      }
 
15864
      if (tmp1.length())
 
15865
        item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
 
15866
      else
 
15867
        item_list.push_back(item_null);
 
15868
 
 
15869
      /* Build "key", "key_len", and "ref" values and add them to item_list */
 
15870
      if (tab->ref.key_parts)
 
15871
      {
 
15872
        KEY *key_info=table->key_info+ tab->ref.key;
 
15873
        register uint32_t length;
 
15874
        item_list.push_back(new Item_string(key_info->name,
 
15875
                                            strlen(key_info->name),
 
15876
                                            system_charset_info));
 
15877
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
 
15878
                keylen_str_buf;
 
15879
        item_list.push_back(new Item_string(keylen_str_buf, length,
 
15880
                                            system_charset_info));
 
15881
        for (store_key **ref=tab->ref.key_copy ; *ref ; ref++)
 
15882
        {
 
15883
          if (tmp2.length())
 
15884
            tmp2.append(',');
 
15885
          tmp2.append((*ref)->name(), strlen((*ref)->name()),
 
15886
                      system_charset_info);
 
15887
        }
 
15888
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15889
      }
 
15890
      else if (tab->type == JT_NEXT)
 
15891
      {
 
15892
        KEY *key_info=table->key_info+ tab->index;
 
15893
        register uint32_t length;
 
15894
        item_list.push_back(new Item_string(key_info->name,
 
15895
                                            strlen(key_info->name),cs));
 
15896
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
 
15897
                keylen_str_buf;
 
15898
        item_list.push_back(new Item_string(keylen_str_buf,
 
15899
                                            length,
 
15900
                                            system_charset_info));
 
15901
        item_list.push_back(item_null);
 
15902
      }
 
15903
      else if (tab->select && tab->select->quick)
 
15904
      {
 
15905
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
 
15906
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15907
        item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
 
15908
        item_list.push_back(item_null);
 
15909
      }
 
15910
      else
 
15911
      {
 
15912
        if (table_list->schema_table && table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
15913
        {
 
15914
          const char *tmp_buff;
 
15915
          int f_idx;
 
15916
          if (table_list->has_db_lookup_value)
 
15917
          {
 
15918
            f_idx= table_list->schema_table->idx_field1;
 
15919
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
 
15920
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
 
15921
          }
 
15922
          if (table_list->has_table_lookup_value)
 
15923
          {
 
15924
            if (table_list->has_db_lookup_value)
 
15925
              tmp2.append(',');
 
15926
            f_idx= table_list->schema_table->idx_field2;
 
15927
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
 
15928
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
 
15929
          }
 
15930
          if (tmp2.length())
 
15931
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
15932
          else
 
15933
            item_list.push_back(item_null);
 
15934
        }
 
15935
        else
 
15936
          item_list.push_back(item_null);
 
15937
        item_list.push_back(item_null);
 
15938
        item_list.push_back(item_null);
 
15939
      }
 
15940
 
 
15941
      /* Add "rows" field to item_list. */
 
15942
      if (table_list->schema_table)
 
15943
      {
 
15944
        /* in_rows */
 
15945
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15946
          item_list.push_back(item_null);
 
15947
        /* rows */
 
15948
        item_list.push_back(item_null);
 
15949
      }
 
15950
      else
 
15951
      {
 
15952
        double examined_rows;
 
15953
        if (tab->select && tab->select->quick)
 
15954
          examined_rows= rows2double(tab->select->quick->records);
 
15955
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
 
15956
          examined_rows= rows2double(tab->limit ? tab->limit :
 
15957
                                     tab->table->file->records());
 
15958
        else
 
15959
          examined_rows= join->best_positions[i].records_read;
 
15960
 
 
15961
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
 
15962
                                         MY_INT64_NUM_DECIMAL_DIGITS));
 
15963
 
 
15964
        /* Add "filtered" field to item_list. */
 
15965
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
15966
        {
 
15967
          float f= 0.0;
 
15968
          if (examined_rows)
 
15969
            f= (float) (100.0 * join->best_positions[i].records_read /
 
15970
                        examined_rows);
 
15971
          item_list.push_back(new Item_float(f, 2));
 
15972
        }
 
15973
      }
 
15974
 
 
15975
      /* Build "Extra" field and add it to item_list. */
 
15976
      bool key_read=table->key_read;
 
15977
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
 
15978
          table->covering_keys.is_set(tab->index))
 
15979
        key_read=1;
 
15980
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
 
15981
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
 
15982
        key_read=1;
 
15983
 
 
15984
      if (tab->info)
 
15985
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
 
15986
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
 
15987
      {
 
15988
        if (tab->packed_info & TAB_INFO_USING_INDEX)
 
15989
          extra.append(STRING_WITH_LEN("; Using index"));
 
15990
        if (tab->packed_info & TAB_INFO_USING_WHERE)
 
15991
          extra.append(STRING_WITH_LEN("; Using where"));
 
15992
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
 
15993
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
15994
        /* Skip initial "; "*/
 
15995
        const char *str= extra.ptr();
 
15996
        uint32_t len= extra.length();
 
15997
        if (len)
 
15998
        {
 
15999
          str += 2;
 
16000
          len -= 2;
 
16001
        }
 
16002
        item_list.push_back(new Item_string(str, len, cs));
 
16003
      }
 
16004
      else
 
16005
      {
 
16006
        uint32_t keyno= MAX_KEY;
 
16007
        if (tab->ref.key_parts)
 
16008
          keyno= tab->ref.key;
 
16009
        else if (tab->select && tab->select->quick)
 
16010
          keyno = tab->select->quick->index;
 
16011
 
 
16012
        if (keyno != MAX_KEY && keyno == table->file->pushed_idx_cond_keyno &&
 
16013
            table->file->pushed_idx_cond)
 
16014
          extra.append(STRING_WITH_LEN("; Using index condition"));
 
16015
 
 
16016
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
16017
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
16018
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
 
16019
        {
 
16020
          extra.append(STRING_WITH_LEN("; Using "));
 
16021
          tab->select->quick->add_info_string(&extra);
 
16022
        }
 
16023
          if (tab->select)
 
16024
        {
 
16025
          if (tab->use_quick == 2)
 
16026
          {
 
16027
            /* 4 bits per 1 hex digit + terminating '\0' */
 
16028
            char buf[MAX_KEY / 4 + 1];
 
16029
            extra.append(STRING_WITH_LEN("; Range checked for each "
 
16030
                                         "record (index map: 0x"));
 
16031
            extra.append(tab->keys.print(buf));
 
16032
            extra.append(')');
 
16033
          }
 
16034
          else if (tab->select->cond)
 
16035
          {
 
16036
            const COND *pushed_cond= tab->table->file->pushed_cond;
 
16037
 
 
16038
            if (session->variables.engine_condition_pushdown && pushed_cond)
 
16039
            {
 
16040
              extra.append(STRING_WITH_LEN("; Using where with pushed "
 
16041
                                           "condition"));
 
16042
              if (session->lex->describe & DESCRIBE_EXTENDED)
 
16043
              {
 
16044
                extra.append(STRING_WITH_LEN(": "));
 
16045
                ((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
 
16046
              }
 
16047
            }
 
16048
            else
 
16049
              extra.append(STRING_WITH_LEN("; Using where"));
 
16050
          }
 
16051
        }
 
16052
        if (key_read)
 
16053
        {
 
16054
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
 
16055
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
 
16056
          else
 
16057
            extra.append(STRING_WITH_LEN("; Using index"));
 
16058
        }
 
16059
        if (table->reginfo.not_exists_optimize)
 
16060
          extra.append(STRING_WITH_LEN("; Not exists"));
 
16061
 
 
16062
        if (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE &&
 
16063
            !(((QUICK_RANGE_SELECT*)(tab->select->quick))->mrr_flags &
 
16064
             HA_MRR_USE_DEFAULT_IMPL))
 
16065
        {
 
16066
          extra.append(STRING_WITH_LEN("; Using MRR"));
 
16067
        }
 
16068
 
 
16069
        if (table_list->schema_table &&
 
16070
            table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
16071
        {
 
16072
          if (!table_list->table_open_method)
 
16073
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
 
16074
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
 
16075
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
 
16076
          else
 
16077
            extra.append(STRING_WITH_LEN("; Open_full_table"));
 
16078
          if (table_list->has_db_lookup_value &&
 
16079
              table_list->has_table_lookup_value)
 
16080
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
 
16081
          else if (table_list->has_db_lookup_value ||
 
16082
                   table_list->has_table_lookup_value)
 
16083
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
 
16084
          else
 
16085
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
 
16086
        }
 
16087
        if (need_tmp_table)
 
16088
        {
 
16089
          need_tmp_table=0;
 
16090
          extra.append(STRING_WITH_LEN("; Using temporary"));
 
16091
        }
 
16092
        if (need_order)
 
16093
        {
 
16094
          need_order=0;
 
16095
          extra.append(STRING_WITH_LEN("; Using filesort"));
 
16096
        }
 
16097
        if (distinct & test_all_bits(used_tables,session->used_tables))
 
16098
          extra.append(STRING_WITH_LEN("; Distinct"));
 
16099
 
 
16100
        if (tab->insideout_match_tab)
 
16101
        {
 
16102
          extra.append(STRING_WITH_LEN("; LooseScan"));
 
16103
        }
 
16104
 
 
16105
        if (tab->flush_weedout_table)
 
16106
          extra.append(STRING_WITH_LEN("; Start temporary"));
 
16107
        else if (tab->check_weed_out_table)
 
16108
          extra.append(STRING_WITH_LEN("; End temporary"));
 
16109
        else if (tab->do_firstmatch)
 
16110
        {
 
16111
          extra.append(STRING_WITH_LEN("; FirstMatch("));
 
16112
          Table *prev_table=tab->do_firstmatch->table;
 
16113
          if (prev_table->derived_select_number)
 
16114
          {
 
16115
            char namebuf[NAME_LEN];
 
16116
            /* Derived table name generation */
 
16117
            int len= snprintf(namebuf, sizeof(namebuf)-1,
 
16118
                              "<derived%u>",
 
16119
                              prev_table->derived_select_number);
 
16120
            extra.append(namebuf, len);
 
16121
          }
 
16122
          else
 
16123
            extra.append(prev_table->pos_in_table_list->alias);
 
16124
          extra.append(STRING_WITH_LEN(")"));
 
16125
        }
 
16126
 
 
16127
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
16128
        {
 
16129
          if (tab->ref.cond_guards[part])
 
16130
          {
 
16131
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
16132
            break;
 
16133
          }
 
16134
        }
 
16135
 
 
16136
        if (i > 0 && tab[-1].next_select == sub_select_cache)
 
16137
          extra.append(STRING_WITH_LEN("; Using join buffer"));
 
16138
 
 
16139
        /* Skip initial "; "*/
 
16140
        const char *str= extra.ptr();
 
16141
        uint32_t len= extra.length();
 
16142
        if (len)
 
16143
        {
 
16144
          str += 2;
 
16145
          len -= 2;
 
16146
        }
 
16147
        item_list.push_back(new Item_string(str, len, cs));
 
16148
      }
 
16149
      // For next iteration
 
16150
      used_tables|=table->map;
 
16151
      if (result->send_data(item_list))
 
16152
        join->error= 1;
 
16153
    }
 
16154
  }
 
16155
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
 
16156
       unit;
 
16157
       unit= unit->next_unit())
 
16158
  {
 
16159
    if (mysql_explain_union(session, unit, result))
 
16160
      return;
 
16161
  }
 
16162
  return;
 
16163
}
 
16164
 
 
16165
 
 
16166
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
 
16167
{
 
16168
  bool res= false;
 
16169
  Select_Lex *first= unit->first_select();
 
16170
 
 
16171
  for (Select_Lex *sl= first;
 
16172
       sl;
 
16173
       sl= sl->next_select())
 
16174
  {
 
16175
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
 
16176
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
16177
    sl->type= (((&session->lex->select_lex)==sl)?
 
16178
               (sl->first_inner_unit() || sl->next_select() ?
 
16179
                "PRIMARY" : "SIMPLE"):
 
16180
               ((sl == first)?
 
16181
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
 
16182
                 "DERIVED":
 
16183
                 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
16184
                  "DEPENDENT SUBQUERY":
 
16185
                  (uncacheable?"UNCACHEABLE SUBQUERY":
 
16186
                   "SUBQUERY"))):
 
16187
                ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
16188
                 "DEPENDENT UNION":
 
16189
                 uncacheable?"UNCACHEABLE UNION":
 
16190
                 "UNION")));
 
16191
    sl->options|= SELECT_DESCRIBE;
 
16192
  }
 
16193
  if (unit->is_union())
 
16194
  {
 
16195
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
 
16196
    unit->fake_select_lex->type= "UNION RESULT";
 
16197
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
 
16198
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
16199
      res= unit->exec();
 
16200
    res|= unit->cleanup();
 
16201
  }
 
16202
  else
 
16203
  {
 
16204
    session->lex->current_select= first;
 
16205
    unit->set_limit(unit->global_parameters);
 
16206
    res= mysql_select(session, &first->ref_pointer_array,
 
16207
                        (TableList*) first->table_list.first,
 
16208
                        first->with_wild, first->item_list,
 
16209
                        first->where,
 
16210
                        first->order_list.elements +
 
16211
                        first->group_list.elements,
 
16212
                        (order_st*) first->order_list.first,
 
16213
                        (order_st*) first->group_list.first,
 
16214
                        first->having,
 
16215
                        first->options | session->options | SELECT_DESCRIBE,
 
16216
                        result, unit, first);
 
16217
  }
 
16218
  return(res || session->is_error());
 
16219
}
 
16220
 
 
16221
 
6256
16222
static void print_table_array(Session *session, String *str, TableList **table,
6257
16223
                              TableList **end)
6258
16224
{
6268
16234
    }
6269
16235
    else if (curr->straight)
6270
16236
      str->append(STRING_WITH_LEN(" straight_join "));
 
16237
    else if (curr->sj_inner_tables)
 
16238
      str->append(STRING_WITH_LEN(" semi join "));
6271
16239
    else
6272
16240
      str->append(STRING_WITH_LEN(" join "));
6273
16241
    curr->print(session, str, QT_ORDINARY);
6280
16248
  }
6281
16249
}
6282
16250
 
 
16251
 
6283
16252
/**
6284
16253
  Print joins from the FROM clause.
6285
 
  @param session     thread Cursor
 
16254
  @param session     thread handler
6286
16255
  @param str     string where table should be printed
6287
16256
  @param tables  list of tables in join
6288
16257
  @query_type    type of the query is being generated
6289
16258
*/
6290
 
void print_join(Session *session, String *str,
6291
 
                List<TableList> *tables, enum_query_type)
 
16259
 
 
16260
static void print_join(Session *session, String *str,
 
16261
                       List<TableList> *tables, enum_query_type)
6292
16262
{
6293
16263
  /* List is reversed => we should reverse it before using */
6294
16264
  List_iterator_fast<TableList> ti(*tables);
6295
 
  TableList **table= (TableList **)session->getMemRoot()->allocate(sizeof(TableList*) *
 
16265
  TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
6296
16266
                                                tables->elements);
6297
16267
  if (table == 0)
6298
16268
    return;  // out of memory
6299
16269
 
6300
16270
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
6301
16271
    *t= ti++;
 
16272
 
 
16273
  /*
 
16274
    If the first table is a semi-join nest, swap it with something that is
 
16275
    not a semi-join nest.
 
16276
  */
 
16277
  if ((*table)->sj_inner_tables)
 
16278
  {
 
16279
    TableList **end= table + tables->elements;
 
16280
    for (TableList **t2= table; t2!=end; t2++)
 
16281
    {
 
16282
      if (!(*t2)->sj_inner_tables)
 
16283
      {
 
16284
        TableList *tmp= *t2;
 
16285
        *t2= *table;
 
16286
        *table= tmp;
 
16287
        break;
 
16288
      }
 
16289
    }
 
16290
  }
6302
16291
  assert(tables->elements >= 1);
6303
16292
  print_table_array(session, str, table, table + tables->elements);
6304
16293
}
6305
16294
 
 
16295
 
 
16296
/**
 
16297
  @brief Print an index hint
 
16298
 
 
16299
  @details Prints out the USE|FORCE|IGNORE index hint.
 
16300
 
 
16301
  @param      session         the current thread
 
16302
  @param[out] str         appends the index hint here
 
16303
  @param      hint        what the hint is (as string : "USE INDEX"|
 
16304
                          "FORCE INDEX"|"IGNORE INDEX")
 
16305
  @param      hint_length the length of the string in 'hint'
 
16306
  @param      indexes     a list of index names for the hint
 
16307
*/
 
16308
 
 
16309
void
 
16310
Index_hint::print(Session *session, String *str)
 
16311
{
 
16312
  switch (type)
 
16313
  {
 
16314
    case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
 
16315
    case INDEX_HINT_USE:    str->append(STRING_WITH_LEN("USE INDEX")); break;
 
16316
    case INDEX_HINT_FORCE:  str->append(STRING_WITH_LEN("FORCE INDEX")); break;
 
16317
  }
 
16318
  str->append (STRING_WITH_LEN(" ("));
 
16319
  if (key_name.length)
 
16320
  {
 
16321
    if (session && is_primary_key_name(key_name.str))
 
16322
      str->append(is_primary_key_name(key_name.str));
 
16323
    else
 
16324
      str->append_identifier(key_name.str, key_name.length);
 
16325
  }
 
16326
  str->append(')');
 
16327
}
 
16328
 
 
16329
 
 
16330
/**
 
16331
  Print table as it should be in join list.
 
16332
 
 
16333
  @param str   string where table should be printed
 
16334
*/
 
16335
 
 
16336
void TableList::print(Session *session, String *str, enum_query_type query_type)
 
16337
{
 
16338
  if (nested_join)
 
16339
  {
 
16340
    str->append('(');
 
16341
    print_join(session, str, &nested_join->join_list, query_type);
 
16342
    str->append(')');
 
16343
  }
 
16344
  else
 
16345
  {
 
16346
    const char *cmp_name;                         // Name to compare with alias
 
16347
    if (derived)
 
16348
    {
 
16349
      // A derived table
 
16350
      str->append('(');
 
16351
      derived->print(str, query_type);
 
16352
      str->append(')');
 
16353
      cmp_name= "";                               // Force printing of alias
 
16354
    }
 
16355
    else
 
16356
    {
 
16357
      // A normal table
 
16358
      {
 
16359
        str->append_identifier(db, db_length);
 
16360
        str->append('.');
 
16361
      }
 
16362
      if (schema_table)
 
16363
      {
 
16364
        str->append_identifier(schema_table_name, strlen(schema_table_name));
 
16365
        cmp_name= schema_table_name;
 
16366
      }
 
16367
      else
 
16368
      {
 
16369
        str->append_identifier(table_name, table_name_length);
 
16370
        cmp_name= table_name;
 
16371
      }
 
16372
    }
 
16373
    if (my_strcasecmp(table_alias_charset, cmp_name, alias))
 
16374
    {
 
16375
 
 
16376
      if (alias && alias[0])
 
16377
      {
 
16378
        str->append(' ');
 
16379
 
 
16380
        string t_alias(alias);
 
16381
        if (lower_case_table_names== 1)
 
16382
          transform(t_alias.begin(), t_alias.end(),
 
16383
                    t_alias.begin(), ::tolower);
 
16384
 
 
16385
        str->append_identifier(t_alias.c_str(), t_alias.length());
 
16386
      }
 
16387
 
 
16388
    }
 
16389
 
 
16390
    if (index_hints)
 
16391
    {
 
16392
      List_iterator<Index_hint> it(*index_hints);
 
16393
      Index_hint *hint;
 
16394
 
 
16395
      while ((hint= it++))
 
16396
      {
 
16397
        str->append (STRING_WITH_LEN(" "));
 
16398
        hint->print (session, str);
 
16399
      }
 
16400
    }
 
16401
  }
 
16402
}
 
16403
 
 
16404
 
6306
16405
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
6307
16406
{
6308
16407
  /* QQ: session may not be set for sub queries, but this should be fixed */
6309
 
  if(not session)
 
16408
  if (!session)
6310
16409
    session= current_session;
6311
16410
 
6312
 
 
6313
16411
  str->append(STRING_WITH_LEN("select "));
6314
16412
 
6315
16413
  /* First add options */
6316
16414
  if (options & SELECT_STRAIGHT_JOIN)
6317
16415
    str->append(STRING_WITH_LEN("straight_join "));
 
16416
  if ((session->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
 
16417
      (this == &session->lex->select_lex))
 
16418
    str->append(STRING_WITH_LEN("high_priority "));
6318
16419
  if (options & SELECT_DISTINCT)
6319
16420
    str->append(STRING_WITH_LEN("distinct "));
6320
16421
  if (options & SELECT_SMALL_RESULT)
6375
16476
  if (group_list.elements)
6376
16477
  {
6377
16478
    str->append(STRING_WITH_LEN(" group by "));
6378
 
    print_order(str, (Order *) group_list.first, query_type);
 
16479
    print_order(str, (order_st *) group_list.first, query_type);
6379
16480
    switch (olap)
6380
16481
    {
6381
16482
      case CUBE_TYPE:
6406
16507
  if (order_list.elements)
6407
16508
  {
6408
16509
    str->append(STRING_WITH_LEN(" order by "));
6409
 
    print_order(str, (Order *) order_list.first, query_type);
 
16510
    print_order(str, (order_st *) order_list.first, query_type);
6410
16511
  }
6411
16512
 
6412
16513
  // limit
6415
16516
  // PROCEDURE unsupported here
6416
16517
}
6417
16518
 
 
16519
 
 
16520
/**
 
16521
  change select_result object of JOIN.
 
16522
 
 
16523
  @param res            new select_result object
 
16524
 
 
16525
  @retval
 
16526
    false   OK
 
16527
  @retval
 
16528
    true    error
 
16529
*/
 
16530
 
 
16531
bool JOIN::change_result(select_result *res)
 
16532
{
 
16533
  result= res;
 
16534
  if (result->prepare(fields_list, select_lex->master_unit()))
 
16535
  {
 
16536
    return(true);
 
16537
  }
 
16538
  return(false);
 
16539
}
 
16540
 
6418
16541
/**
6419
16542
  @} (end of group Query_Optimizer)
6420
16543
*/
6421
 
 
6422
 
} /* namespace drizzled */