~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

Merged in latest plugin-slot-reorg.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
  @brief
20
20
  mysql_select and join optimization
21
21
 
22
 
 
23
22
  @defgroup Query_Optimizer  Query Optimizer
24
23
  @{
25
24
*/
26
 
#include <drizzled/server_includes.h>
27
 
#include <drizzled/sql_select.h>
28
 
#include "sj_tmp_table.h"
29
 
 
30
 
#include <mysys/my_bit.h>
31
 
#include <drizzled/drizzled_error_messages.h>
32
 
#include <libdrizzle/gettext.h>
33
 
 
34
 
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
35
 
                              "MAYBE_REF","ALL","range","index",
36
 
                              "ref_or_null","unique_subquery","index_subquery",
37
 
                              "index_merge"
 
25
#include "drizzled/server_includes.h"
 
26
#include "drizzled/sql_select.h" /* include join.h */
 
27
#include "drizzled/table_map_iterator.h"
 
28
 
 
29
#include "drizzled/error.h"
 
30
#include "drizzled/gettext.h"
 
31
#include "drizzled/util/test.h"
 
32
#include "drizzled/name_resolution_context_state.h"
 
33
#include "drizzled/nested_join.h"
 
34
#include "drizzled/probes.h"
 
35
#include "drizzled/show.h"
 
36
#include "drizzled/plugin/info_schema_table.h"
 
37
#include "drizzled/item/cache.h"
 
38
#include "drizzled/item/cmpfunc.h"
 
39
#include "drizzled/item/copy_string.h"
 
40
#include "drizzled/item/uint.h"
 
41
#include "drizzled/cached_item.h"
 
42
#include "drizzled/sql_base.h"
 
43
#include "drizzled/field/blob.h"
 
44
#include "drizzled/check_stack_overrun.h"
 
45
#include "drizzled/lock.h"
 
46
#include "drizzled/item/outer_ref.h"
 
47
#include "drizzled/index_hint.h"
 
48
 
 
49
#include "drizzled/sql_union.h"
 
50
#include "drizzled/optimizer/key_field.h"
 
51
#include "drizzled/optimizer/position.h"
 
52
#include "drizzled/optimizer/sargable_param.h"
 
53
#include "drizzled/optimizer/key_use.h"
 
54
 
 
55
#include <string>
 
56
#include <iostream>
 
57
#include <algorithm>
 
58
#include <vector>
 
59
 
 
60
using namespace std;
 
61
using namespace drizzled;
 
62
 
 
63
static const string access_method_str[]=
 
64
{
 
65
  "UNKNOWN",
 
66
  "system",
 
67
  "const",
 
68
  "eq_ref",
 
69
  "ref",
 
70
  "MAYBE_REF",
 
71
  "ALL",
 
72
  "range",
 
73
  "index",
 
74
  "ref_or_null",
 
75
  "unique_subquery",
 
76
  "index_subquery",
 
77
  "index_merge"
38
78
};
39
79
 
40
 
struct st_sargable_param;
41
 
 
42
 
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
43
 
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
44
 
                                 DYNAMIC_ARRAY *keyuse);
45
 
static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
46
 
                                JOIN_TAB *join_tab,
47
 
                                uint32_t tables, COND *conds,
48
 
                                COND_EQUAL *cond_equal,
49
 
                                table_map table_map, SELECT_LEX *select_lex,
50
 
                                st_sargable_param **sargables);
51
 
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
52
 
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
53
 
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
54
 
                               table_map used_tables);
55
 
static bool choose_plan(JOIN *join,table_map join_tables);
56
 
 
57
 
static void best_access_path(JOIN *join, JOIN_TAB *s, THD *thd,
58
 
                             table_map remaining_tables, uint32_t idx,
59
 
                             double record_count, double read_time);
60
 
static void optimize_straight_join(JOIN *join, table_map join_tables);
61
 
static bool greedy_search(JOIN *join, table_map remaining_tables,
62
 
                             uint32_t depth, uint32_t prune_level);
63
 
static bool best_extension_by_limited_search(JOIN *join,
64
 
                                             table_map remaining_tables,
65
 
                                             uint32_t idx, double record_count,
66
 
                                             double read_time, uint32_t depth,
67
 
                                             uint32_t prune_level);
68
 
static uint32_t determine_search_depth(JOIN* join);
69
 
static int join_tab_cmp(const void* ptr1, const void* ptr2);
70
 
static int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
71
 
/*
72
 
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
73
 
  tested and approved.
74
 
*/
75
 
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index,
76
 
                      double record_count,double read_time);
77
 
static uint32_t cache_record_length(JOIN *join,uint32_t index);
78
 
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
79
 
static bool get_best_combination(JOIN *join);
80
 
static store_key *get_store_key(THD *thd,
81
 
                                KEYUSE *keyuse, table_map used_tables,
82
 
                                KEY_PART_INFO *key_part, unsigned char *key_buff,
83
 
                                uint32_t maybe_null);
84
 
static bool make_simple_join(JOIN *join,Table *tmp_table);
85
 
static void make_outerjoin_info(JOIN *join);
86
 
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
87
 
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
88
 
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
89
 
static void update_depend_map(JOIN *join);
90
 
static void update_depend_map(JOIN *join, order_st *order);
91
 
static order_st *remove_const(JOIN *join,order_st *first_order,COND *cond,
92
 
                           bool change_list, bool *simple_order);
93
 
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
94
 
                            List<Item> &fields, bool send_row,
95
 
                            uint64_t select_options, const char *info,
96
 
                            Item *having);
97
 
static COND *build_equal_items(THD *thd, COND *cond,
 
80
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
 
81
static COND *build_equal_items(Session *session, COND *cond,
98
82
                               COND_EQUAL *inherited,
99
83
                               List<TableList> *join_list,
100
84
                               COND_EQUAL **cond_equal_ref);
101
 
static COND* substitute_for_best_equal_field(COND *cond,
102
 
                                             COND_EQUAL *cond_equal,
103
 
                                             void *table_join_idx);
104
 
static COND *simplify_joins(JOIN *join, List<TableList> *join_list,
105
 
                            COND *conds, bool top, bool in_sj);
106
 
static bool check_interleaving_with_nj(JOIN_TAB *last, JOIN_TAB *next);
107
 
static void restore_prev_nj_state(JOIN_TAB *last);
108
 
static void reset_nj_counters(List<TableList> *join_list);
109
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
110
 
                                          uint32_t first_unused);
111
 
 
112
 
static 
113
 
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab);
114
 
static void restore_prev_sj_state(const table_map remaining_tables, 
115
 
                                  const JOIN_TAB *tab);
116
 
 
117
 
static COND *optimize_cond(JOIN *join, COND *conds,
118
 
                           List<TableList> *join_list,
119
 
                           Item::cond_result *cond_value);
120
 
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
121
 
static int do_select(JOIN *join,List<Item> *fields,Table *tmp_table);
122
 
 
123
 
static enum_nested_loop_state
124
 
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
125
 
                     int error);
126
 
static enum_nested_loop_state
127
 
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab);
128
 
static enum_nested_loop_state
129
 
flush_cached_records(JOIN *join, JOIN_TAB *join_tab, bool skip_last);
130
 
static enum_nested_loop_state
131
 
end_send(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
132
 
static enum_nested_loop_state
133
 
end_write(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
134
 
static enum_nested_loop_state
135
 
end_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
136
 
static enum_nested_loop_state
137
 
end_unique_update(JOIN *join, JOIN_TAB *join_tab, bool end_of_records);
138
 
 
139
 
static int join_read_const_table(JOIN_TAB *tab, POSITION *pos);
140
 
static int join_read_system(JOIN_TAB *tab);
141
 
static int join_read_const(JOIN_TAB *tab);
142
 
static int join_read_key(JOIN_TAB *tab);
143
 
static int join_read_always_key(JOIN_TAB *tab);
144
 
static int join_read_last_key(JOIN_TAB *tab);
145
 
static int join_no_more_records(READ_RECORD *info);
146
 
static int join_read_next(READ_RECORD *info);
147
 
static int join_read_next_different(READ_RECORD *info);
148
 
static int join_init_quick_read_record(JOIN_TAB *tab);
149
 
static int test_if_quick_select(JOIN_TAB *tab);
150
 
static int join_init_read_record(JOIN_TAB *tab);
151
 
static int join_read_first(JOIN_TAB *tab);
152
 
static int join_read_next_same(READ_RECORD *info);
153
 
static int join_read_next_same_diff(READ_RECORD *info);
154
 
static int join_read_last(JOIN_TAB *tab);
155
 
static int join_read_prev_same(READ_RECORD *info);
156
 
static int join_read_prev(READ_RECORD *info);
157
 
int join_read_always_key_or_null(JOIN_TAB *tab);
158
 
int join_read_next_same_or_null(READ_RECORD *info);
159
 
static COND *make_cond_for_table(COND *cond,table_map table,
160
 
                                 table_map used_table,
161
 
                                 bool exclude_expensive_cond);
 
85
 
162
86
static Item* part_of_refkey(Table *form,Field *field);
163
 
static bool test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,
164
 
                                    ha_rows select_limit, bool no_changes,
165
 
                                    const key_map *map);
166
 
static bool list_contains_unique_index(Table *table,
167
 
                          bool (*find_func) (Field *, void *), void *data);
168
 
static bool find_field_in_item_list (Field *field, void *data);
169
 
static bool find_field_in_order_list (Field *field, void *data);
170
 
static int create_sort_index(THD *thd, JOIN *join, order_st *order,
171
 
                             ha_rows filesort_limit, ha_rows select_limit,
172
 
                             bool is_order_by);
173
 
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
174
 
                             Item *having);
175
 
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
176
 
                                   ulong offset,Item *having);
177
 
static int remove_dup_with_hash_index(THD *thd,Table *table,
178
 
                                      uint32_t field_count, Field **first_field,
 
87
static bool cmp_buffer_with_ref(JoinTable *tab);
 
88
static void change_cond_ref_to_const(Session *session,
 
89
                                     vector<COND_CMP>& save_list,
 
90
                                     Item *and_father,
 
91
                                     Item *cond,
 
92
                                     Item *field,
 
93
                                     Item *value);
 
94
static bool copy_blobs(Field **ptr);
179
95
 
180
 
                                      ulong key_length,Item *having);
181
 
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count);
182
 
static ulong used_blob_length(CACHE_FIELD **ptr);
183
 
static bool store_record_in_cache(JOIN_CACHE *cache);
184
 
static void reset_cache_read(JOIN_CACHE *cache);
185
 
static void reset_cache_write(JOIN_CACHE *cache);
186
 
static void read_cached_record(JOIN_TAB *tab);
187
 
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
188
 
static order_st *create_distinct_group(THD *thd, Item **ref_pointer_array,
189
 
                                    order_st *order, List<Item> &fields,
190
 
                                    List<Item> &all_fields,
191
 
                                    bool *all_order_by_fields_used);
192
 
static bool test_if_subpart(order_st *a,order_st *b);
193
 
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
194
 
static void calc_group_buffer(JOIN *join,order_st *group);
195
 
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
196
 
static bool alloc_group_fields(JOIN *join,order_st *group);
197
 
// Create list for using with tempory table
198
 
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
199
 
                                     List<Item> &new_list1,
200
 
                                     List<Item> &new_list2,
201
 
                                     uint32_t elements, List<Item> &items);
202
 
// Create list for using with tempory table
203
 
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
204
 
                                      List<Item> &new_list1,
205
 
                                      List<Item> &new_list2,
206
 
                                      uint32_t elements, List<Item> &items);
207
 
static void init_tmptable_sum_functions(Item_sum **func);
208
 
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
209
 
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
210
 
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
211
 
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
212
 
static bool init_sum_functions(Item_sum **func, Item_sum **end);
213
 
static bool update_sum_func(Item_sum **func);
214
 
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
215
 
                            bool distinct, const char *message=NULL);
216
 
static Item *remove_additional_cond(Item* conds);
217
 
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
218
 
static bool test_if_ref(Item_field *left_item,Item *right_item);
219
 
static bool replace_where_subcondition(JOIN *join, Item *old_cond, 
220
 
                                       Item *new_cond, bool fix_fields);
 
96
static bool eval_const_cond(COND *cond)
 
97
{
 
98
    return ((Item_func*) cond)->val_int() ? true : false;
 
99
}
221
100
 
222
101
/*
223
102
  This is used to mark equalities that were made from i-th IN-equality.
227
106
const char *subq_sj_cond_name=
228
107
  "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
229
108
 
230
 
static bool bitmap_covers(const table_map x, const table_map y)
 
109
static bool copy_blobs(Field **ptr)
231
110
{
232
 
  return !test(y & ~x);
 
111
  for (; *ptr ; ptr++)
 
112
  {
 
113
    if ((*ptr)->flags & BLOB_FLAG)
 
114
      if (((Field_blob *) (*ptr))->copy())
 
115
        return 1;                               // Error
 
116
  }
 
117
  return 0;
233
118
}
234
119
 
235
120
/**
236
121
  This handles SELECT with and without UNION.
237
122
*/
238
 
 
239
 
bool handle_select(THD *thd, LEX *lex, select_result *result,
240
 
                   ulong setup_tables_done_option)
 
123
bool handle_select(Session *session, LEX *lex, select_result *result,
 
124
                   uint64_t setup_tables_done_option)
241
125
{
242
126
  bool res;
243
 
  register SELECT_LEX *select_lex = &lex->select_lex;
244
 
  DRIZZLE_SELECT_START();
 
127
  register Select_Lex *select_lex= &lex->select_lex;
 
128
  DRIZZLE_SELECT_START(session->query);
245
129
 
246
 
  if (select_lex->master_unit()->is_union() || 
 
130
  if (select_lex->master_unit()->is_union() ||
247
131
      select_lex->master_unit()->fake_select_lex)
248
 
    res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option);
 
132
    res= drizzle_union(session, lex, result, &lex->unit,
 
133
                       setup_tables_done_option);
249
134
  else
250
135
  {
251
 
    SELECT_LEX_UNIT *unit= &lex->unit;
 
136
    Select_Lex_Unit *unit= &lex->unit;
252
137
    unit->set_limit(unit->global_parameters);
253
 
    thd->thd_marker= 0;
 
138
    session->session_marker= 0;
254
139
    /*
255
140
      'options' of mysql_select will be set in JOIN, as far as JOIN for
256
 
      every PS/SP execution new, we will not need reset this flag if 
 
141
      every PS/SP execution new, we will not need reset this flag if
257
142
      setup_tables_done_option changed for next rexecution
258
143
    */
259
 
    res= mysql_select(thd, &select_lex->ref_pointer_array,
 
144
    res= mysql_select(session, &select_lex->ref_pointer_array,
260
145
                      (TableList*) select_lex->table_list.first,
261
146
                      select_lex->with_wild, select_lex->item_list,
262
147
                      select_lex->where,
265
150
                      (order_st*) select_lex->order_list.first,
266
151
                      (order_st*) select_lex->group_list.first,
267
152
                      select_lex->having,
268
 
                      (order_st*) lex->proc_list.first,
269
 
                      select_lex->options | thd->options |
 
153
                      select_lex->options | session->options |
270
154
                      setup_tables_done_option,
271
155
                      result, unit, select_lex);
272
156
  }
273
 
  res|= thd->is_error();
 
157
  res|= session->is_error();
274
158
  if (unlikely(res))
275
159
    result->abort();
276
160
 
277
 
  DRIZZLE_SELECT_END();
278
 
  return(res);
 
161
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
 
162
  return res;
279
163
}
280
164
 
281
 
 
282
165
/*
283
166
  Fix fields referenced from inner selects.
284
167
 
285
168
  SYNOPSIS
286
169
    fix_inner_refs()
287
 
    thd               Thread handle
 
170
    session               Thread handle
288
171
    all_fields        List of all fields used in select
289
172
    select            Current select
290
173
    ref_pointer_array Array of references to Items used in current select
319
202
    true  an error occured
320
203
    false ok
321
204
*/
322
 
 
323
 
bool
324
 
fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
325
 
                 Item **ref_pointer_array)
 
205
bool fix_inner_refs(Session *session, 
 
206
                    List<Item> &all_fields, 
 
207
                    Select_Lex *select, 
 
208
                    Item **ref_pointer_array)
326
209
{
327
210
  Item_outer_ref *ref;
328
211
  bool res= false;
382
265
    ref->outer_ref= new_ref;
383
266
    ref->ref= &ref->outer_ref;
384
267
 
385
 
    if (!ref->fixed && ref->fix_fields(thd, 0))
 
268
    if (!ref->fixed && ref->fix_fields(session, 0))
386
269
      return true;
387
 
    thd->used_tables|= item->used_tables();
 
270
    session->used_tables|= item->used_tables();
388
271
  }
389
272
  return res;
390
273
}
391
274
 
392
 
#define MAGIC_IN_WHERE_TOP_LEVEL 10
393
 
/**
394
 
  Function to setup clauses without sum functions.
395
 
*/
396
 
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
397
 
                               TableList *tables,
398
 
                               TableList *leaves,
399
 
                               List<Item> &fields,
400
 
                               List<Item> &all_fields,
401
 
                               COND **conds,
402
 
                               order_st *order,
403
 
                               order_st *group, bool *hidden_group_fields)
404
 
{
405
 
  int res;
406
 
  nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
407
 
 
408
 
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
409
 
  res= setup_conds(thd, tables, leaves, conds);
410
 
 
411
 
  thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
412
 
  res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
413
 
                          order);
414
 
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
415
 
  res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
416
 
                          group, hidden_group_fields);
417
 
  thd->lex->allow_sum_func= save_allow_sum_func;
418
 
  return(res);
419
 
}
420
 
 
421
275
/*****************************************************************************
422
276
  Check fields, find best join, do the select and output fields.
423
277
  mysql_select assumes that all tables are already opened
424
278
*****************************************************************************/
425
279
 
426
 
/**
427
 
  Prepare of whole select (including sub queries in future).
428
 
 
429
 
  @todo
430
 
    Add check of calculation of GROUP functions and fields:
431
 
    SELECT COUNT(*)+table.col1 from table1;
432
 
 
433
 
  @retval
434
 
    -1   on error
435
 
  @retval
436
 
    0   on success
437
 
*/
438
 
int
439
 
JOIN::prepare(Item ***rref_pointer_array,
440
 
              TableList *tables_init,
441
 
              uint32_t wild_num, COND *conds_init, uint32_t og_num,
442
 
              order_st *order_init, order_st *group_init,
443
 
              Item *having_init,
444
 
              order_st *proc_param_init, SELECT_LEX *select_lex_arg,
445
 
              SELECT_LEX_UNIT *unit_arg)
446
 
{
447
 
  // to prevent double initialization on EXPLAIN
448
 
  if (optimized)
449
 
    return(0);
450
 
 
451
 
  conds= conds_init;
452
 
  order= order_init;
453
 
  group_list= group_init;
454
 
  having= having_init;
455
 
  proc_param= proc_param_init;
456
 
  tables_list= tables_init;
457
 
  select_lex= select_lex_arg;
458
 
  select_lex->join= this;
459
 
  join_list= &select_lex->top_join_list;
460
 
  union_part= unit_arg->is_union();
461
 
 
462
 
  thd->lex->current_select->is_item_list_lookup= 1;
463
 
  /*
464
 
    If we have already executed SELECT, then it have not sense to prevent
465
 
    its table from update (see unique_table())
466
 
  */
467
 
  if (thd->derived_tables_processing)
468
 
    select_lex->exclude_from_table_unique_test= true;
469
 
 
470
 
  /* Check that all tables, fields, conds and order are ok */
471
 
 
472
 
  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
473
 
      setup_tables_and_check_access(thd, &select_lex->context, join_list,
474
 
                                    tables_list, &select_lex->leaf_tables,
475
 
                                    false))
476
 
      return(-1);
477
 
 
478
 
  TableList *table_ptr;
479
 
  for (table_ptr= select_lex->leaf_tables;
480
 
       table_ptr;
481
 
       table_ptr= table_ptr->next_leaf)
482
 
    tables++;
483
 
 
484
 
  if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
485
 
      select_lex->setup_ref_array(thd, og_num) ||
486
 
      setup_fields(thd, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
487
 
                   &all_fields, 1) ||
488
 
      setup_without_group(thd, (*rref_pointer_array), tables_list,
489
 
                          select_lex->leaf_tables, fields_list,
490
 
                          all_fields, &conds, order, group_list,
491
 
                          &hidden_group_fields))
492
 
    return(-1);                         /* purecov: inspected */
493
 
 
494
 
  ref_pointer_array= *rref_pointer_array;
495
 
  
496
 
  if (having)
497
 
  {
498
 
    nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
499
 
    thd->where="having clause";
500
 
    thd->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
501
 
    select_lex->having_fix_field= 1;
502
 
    bool having_fix_rc= (!having->fixed &&
503
 
                         (having->fix_fields(thd, &having) ||
504
 
                          having->check_cols(1)));
505
 
    select_lex->having_fix_field= 0;
506
 
    if (having_fix_rc || thd->is_error())
507
 
      return(-1);                               /* purecov: inspected */
508
 
    thd->lex->allow_sum_func= save_allow_sum_func;
509
 
  }
510
 
 
511
 
  {
512
 
    Item_subselect *subselect;
513
 
    Item_in_subselect *in_subs= NULL;
514
 
    /*
515
 
      Are we in a subquery predicate?
516
 
      TODO: the block below will be executed for every PS execution without need.
517
 
    */
518
 
    if ((subselect= select_lex->master_unit()->item))
519
 
    {
520
 
      bool do_semijoin= !test(thd->variables.optimizer_switch &
521
 
                              OPTIMIZER_SWITCH_NO_SEMIJOIN);
522
 
      if (subselect->substype() == Item_subselect::IN_SUBS)
523
 
        in_subs= (Item_in_subselect*)subselect;
524
 
 
525
 
      /*
526
 
        Check if we're in subquery that is a candidate for flattening into a
527
 
        semi-join (which is done done in flatten_subqueries()). The
528
 
        requirements are:
529
 
          1. Subquery predicate is an IN/=ANY subq predicate
530
 
          2. Subquery is a single SELECT (not a UNION)
531
 
          3. Subquery does not have GROUP BY or order_st BY
532
 
          4. Subquery does not use aggregate functions or HAVING
533
 
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
534
 
          6. No execution method was already chosen (by a prepared statement).
535
 
 
536
 
          (*). We are not in a subquery of a single table UPDATE/DELETE that 
537
 
               doesn't have a JOIN (TODO: We should handle this at some
538
 
               point by switching to multi-table UPDATE/DELETE)
539
 
 
540
 
          (**). We're not in a confluent table-less subquery, like
541
 
                "SELECT 1". 
542
 
      */
543
 
      if (in_subs &&                                                    // 1
544
 
          !select_lex->master_unit()->first_select()->next_select() &&  // 2
545
 
          !select_lex->group_list.elements && !order &&                 // 3
546
 
          !having && !select_lex->with_sum_func &&                      // 4
547
 
          thd->thd_marker &&                                            // 5
548
 
          select_lex->outer_select()->join &&                           // (*)
549
 
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**) 
550
 
          do_semijoin &&
551
 
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
552
 
      {
553
 
        {
554
 
          if (!in_subs->left_expr->fixed &&
555
 
               in_subs->left_expr->fix_fields(thd, &in_subs->left_expr))
556
 
          {
557
 
            return(-1);
558
 
          }
559
 
          /*
560
 
            Check that the right part of the subselect contains no more than one
561
 
            column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
562
 
          */
563
 
          if (subselect->substype() == Item_subselect::IN_SUBS &&
564
 
             (select_lex->item_list.elements != 
565
 
              ((Item_in_subselect*)subselect)->left_expr->cols()))
566
 
          {
567
 
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
568
 
            return(-1);
569
 
          }
570
 
        }
571
 
 
572
 
        /* Register the subquery for further processing */
573
 
        select_lex->outer_select()->join->sj_subselects.append(thd->mem_root, in_subs);
574
 
        in_subs->expr_join_nest= (TableList*)thd->thd_marker;
575
 
      }
576
 
      else
577
 
      {
578
 
        bool do_materialize= !test(thd->variables.optimizer_switch &
579
 
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
580
 
        /*
581
 
          Check if the subquery predicate can be executed via materialization.
582
 
          The required conditions are:
583
 
          1. Subquery predicate is an IN/=ANY subq predicate
584
 
          2. Subquery is a single SELECT (not a UNION)
585
 
          3. Subquery is not a table-less query. In this case there is no
586
 
             point in materializing.
587
 
          4. Subquery predicate is a top-level predicate
588
 
             (this implies it is not negated)
589
 
             TODO: this is a limitation that should be lifeted once we
590
 
             implement correct NULL semantics (WL#3830)
591
 
          5. Subquery is non-correlated
592
 
             TODO:
593
 
             This is an overly restrictive condition. It can be extended to:
594
 
             (Subquery is non-correlated ||
595
 
              Subquery is correlated to any query outer to IN predicate ||
596
 
              (Subquery is correlated to the immediate outer query &&
597
 
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
598
 
               aggregate functions) && subquery predicate is not under "NOT IN"))
599
 
          6. No execution method was already chosen (by a prepared statement).
600
 
 
601
 
          (*) The subquery must be part of a SELECT statement. The current
602
 
               condition also excludes multi-table update statements.
603
 
 
604
 
          We have to determine whether we will perform subquery materialization
605
 
          before calling the IN=>EXISTS transformation, so that we know whether to
606
 
          perform the whole transformation or only that part of it which wraps
607
 
          Item_in_subselect in an Item_in_optimizer.
608
 
        */
609
 
        if (do_materialize && 
610
 
            in_subs  &&                                                   // 1
611
 
            !select_lex->master_unit()->first_select()->next_select() &&  // 2
612
 
            select_lex->master_unit()->first_select()->leaf_tables &&     // 3
613
 
            thd->lex->sql_command == SQLCOM_SELECT)                       // *
614
 
        {
615
 
          if (in_subs->is_top_level_item() &&                             // 4
616
 
              !in_subs->is_correlated &&                                  // 5
617
 
              in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED) // 6
618
 
            in_subs->exec_method= Item_in_subselect::MATERIALIZATION;
619
 
        }
620
 
 
621
 
        Item_subselect::trans_res trans_res;
622
 
        if ((trans_res= subselect->select_transformer(this)) !=
623
 
            Item_subselect::RES_OK)
624
 
        {
625
 
          return((trans_res == Item_subselect::RES_ERROR));
626
 
        }
627
 
      }
628
 
    }
629
 
  }
630
 
 
631
 
  if (order)
632
 
  {
633
 
    order_st *ord;
634
 
    for (ord= order; ord; ord= ord->next)
635
 
    {
636
 
      Item *item= *ord->item;
637
 
      if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
638
 
        item->split_sum_func(thd, ref_pointer_array, all_fields);
639
 
    }
640
 
  }
641
 
 
642
 
  if (having && having->with_sum_func)
643
 
    having->split_sum_func2(thd, ref_pointer_array, all_fields,
644
 
                            &having, true);
645
 
  if (select_lex->inner_sum_func_list)
646
 
  {
647
 
    Item_sum *end=select_lex->inner_sum_func_list;
648
 
    Item_sum *item_sum= end;  
649
 
    do
650
 
    { 
651
 
      item_sum= item_sum->next;
652
 
      item_sum->split_sum_func2(thd, ref_pointer_array,
653
 
                                all_fields, item_sum->ref_by, false);
654
 
    } while (item_sum != end);
655
 
  }
656
 
 
657
 
  if (select_lex->inner_refs_list.elements &&
658
 
      fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array))
659
 
    return(-1);
660
 
 
661
 
  /*
662
 
    Check if there are references to un-aggregated columns when computing 
663
 
    aggregate functions with implicit grouping (there is no GROUP BY).
664
 
 
665
 
    MODE_ONLY_FULL_GROUP_BY is enabled here by default
666
 
  */
667
 
  if (!group_list && select_lex->full_group_by_flag == (NON_AGG_FIELD_USED | SUM_FUNC_USED))
668
 
  {
669
 
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
670
 
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
671
 
    return(-1);
672
 
  }
673
 
  {
674
 
    /* Caclulate the number of groups */
675
 
    send_group_parts= 0;
676
 
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
677
 
      send_group_parts++;
678
 
  }
679
 
  
680
 
  if (error)
681
 
    goto err;                                   /* purecov: inspected */
682
 
 
683
 
  if (result && result->prepare(fields_list, unit_arg))
684
 
    goto err;                                   /* purecov: inspected */
685
 
 
686
 
  /* Init join struct */
687
 
  count_field_types(select_lex, &tmp_table_param, all_fields, 0);
688
 
  ref_pointer_array_size= all_fields.elements*sizeof(Item*);
689
 
  this->group= group_list != 0;
690
 
  unit= unit_arg;
691
 
 
692
 
#ifdef RESTRICTED_GROUP
693
 
  if (sum_func_count && !group_list && (func_count || field_count))
694
 
  {
695
 
    my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
696
 
    goto err;
697
 
  }
698
 
#endif
699
 
  if (select_lex->olap == ROLLUP_TYPE && rollup_init())
700
 
    goto err;
701
 
  if (alloc_func_list())
702
 
    goto err;
703
 
 
704
 
  return(0); // All OK
705
 
 
706
 
err:
707
 
  return(-1);                           /* purecov: inspected */
708
 
}
709
 
 
710
 
 
711
 
/*
712
 
  Remove the predicates pushed down into the subquery
713
 
 
714
 
  SYNOPSIS
715
 
    JOIN::remove_subq_pushed_predicates()
716
 
      where   IN  Must be NULL
717
 
              OUT The remaining WHERE condition, or NULL
718
 
 
719
 
  DESCRIPTION
720
 
    Given that this join will be executed using (unique|index)_subquery,
721
 
    without "checking NULL", remove the predicates that were pushed down
722
 
    into the subquery.
723
 
 
724
 
    If the subquery compares scalar values, we can remove the condition that
725
 
    was wrapped into trig_cond (it will be checked when needed by the subquery
726
 
    engine)
727
 
 
728
 
    If the subquery compares row values, we need to keep the wrapped
729
 
    equalities in the WHERE clause: when the left (outer) tuple has both NULL
730
 
    and non-NULL values, we'll do a full table scan and will rely on the
731
 
    equalities corresponding to non-NULL parts of left tuple to filter out
732
 
    non-matching records.
733
 
 
734
 
    TODO: We can remove the equalities that will be guaranteed to be true by the
735
 
    fact that subquery engine will be using index lookup. This must be done only
736
 
    for cases where there are no conversion errors of significance, e.g. 257
737
 
    that is searched in a byte. But this requires homogenization of the return 
738
 
    codes of all Field*::store() methods.
739
 
*/
740
 
 
741
 
void JOIN::remove_subq_pushed_predicates(Item **where)
742
 
{
743
 
  if (conds->type() == Item::FUNC_ITEM &&
744
 
      ((Item_func *)this->conds)->functype() == Item_func::EQ_FUNC &&
745
 
      ((Item_func *)conds)->arguments()[0]->type() == Item::REF_ITEM &&
746
 
      ((Item_func *)conds)->arguments()[1]->type() == Item::FIELD_ITEM &&
747
 
      test_if_ref ((Item_field *)((Item_func *)conds)->arguments()[1],
748
 
                   ((Item_func *)conds)->arguments()[0]))
749
 
  {
750
 
    *where= 0;
751
 
    return;
752
 
  }
753
 
}
754
 
 
755
 
 
756
280
/*
757
281
  Index lookup-based subquery: save some flags for EXPLAIN output
758
282
 
765
289
  DESCRIPTION
766
290
    For index lookup-based subquery (i.e. one executed with
767
291
    subselect_uniquesubquery_engine or subselect_indexsubquery_engine),
768
 
    check its EXPLAIN output row should contain 
769
 
      "Using index" (TAB_INFO_FULL_SCAN_ON_NULL) 
 
292
    check its EXPLAIN output row should contain
 
293
      "Using index" (TAB_INFO_FULL_SCAN_ON_NULL)
770
294
      "Using Where" (TAB_INFO_USING_WHERE)
771
295
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
772
296
    and set appropriate flags in join_tab->packed_info.
773
297
*/
774
 
 
775
 
static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
 
298
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
776
299
{
777
300
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
778
 
  if (join_tab->table->covering_keys.is_set(join_tab->ref.key))
 
301
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
779
302
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
780
303
  if (where)
781
304
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
789
312
  }
790
313
}
791
314
 
792
 
 
793
 
 
794
 
 
795
 
/*
796
 
  Check if the table's rowid is included in the temptable
797
 
 
798
 
  SYNOPSIS
799
 
    sj_table_is_included()
800
 
      join      The join
801
 
      join_tab  The table to be checked
802
 
 
803
 
  DESCRIPTION
804
 
    SemiJoinDuplicateElimination: check the table's rowid should be included
805
 
    in the temptable. This is so if
806
 
 
807
 
    1. The table is not embedded within some semi-join nest
808
 
    2. The has been pulled out of a semi-join nest, or
809
 
 
810
 
    3. The table is functionally dependent on some previous table
811
 
 
812
 
    [4. This is also true for constant tables that can't be
813
 
        NULL-complemented but this function is not called for such tables]
814
 
 
815
 
  RETURN
816
 
    true  - Include table's rowid
817
 
    false - Don't
818
 
*/
819
 
 
820
 
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab)
821
 
{
822
 
  if (join_tab->emb_sj_nest)
823
 
    return false;
824
 
  
825
 
  /* Check if this table is functionally dependent on the tables that
826
 
     are within the same outer join nest
827
 
  */
828
 
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
829
 
  if (join_tab->type == JT_EQ_REF)
830
 
  {
831
 
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
832
 
    uint32_t idx;
833
 
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
834
 
    {
835
 
      JOIN_TAB *ref_tab= join->join_tab + idx;
836
 
      if (embedding == ref_tab->table->pos_in_table_list->embedding)
837
 
        return true;
838
 
    }
839
 
    /* Ok, functionally dependent */
840
 
    return false;
841
 
  }
842
 
  /* Not functionally dependent => need to include*/
843
 
  return true;
844
 
}
845
 
 
846
 
 
847
 
/*
848
 
  Setup the strategies to eliminate semi-join duplicates.
849
 
  
850
 
  SYNOPSIS
851
 
    setup_semijoin_dups_elimination()
852
 
      join           Join to process
853
 
      options        Join options (needed to see if join buffering will be 
854
 
                     used or not)
855
 
      no_jbuf_after  Another bit of information re where join buffering will
856
 
                     be used.
857
 
 
858
 
  DESCRIPTION
859
 
    Setup the strategies to eliminate semi-join duplicates. ATM there are 3
860
 
    strategies:
861
 
 
862
 
    1. DuplicateWeedout (use of temptable to remove duplicates based on rowids
863
 
                         of row combinations)
864
 
    2. FirstMatch (pick only the 1st matching row combination of inner tables)
865
 
    3. InsideOut (scanning the sj-inner table in a way that groups duplicates
866
 
                  together and picking the 1st one)
867
 
    
868
 
    The join order has "duplicate-generating ranges", and every range is
869
 
    served by one strategy or a combination of FirstMatch with with some
870
 
    other strategy.
871
 
    
872
 
    "Duplicate-generating range" is defined as a range within the join order
873
 
    that contains all of the inner tables of a semi-join. All ranges must be
874
 
    disjoint, if tables of several semi-joins are interleaved, then the ranges
875
 
    are joined together, which is equivalent to converting
876
 
      SELECT ... WHERE oe1 IN (SELECT ie1 ...) AND oe2 IN (SELECT ie2 )
877
 
    to
878
 
      SELECT ... WHERE (oe1, oe2) IN (SELECT ie1, ie2 ... ...)
879
 
    .
880
 
 
881
 
    Applicability conditions are as follows:
882
 
 
883
 
    DuplicateWeedout strategy
884
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~
885
 
 
886
 
      (ot|nt)*  [ it ((it|ot|nt)* (it|ot))]  (nt)*
887
 
      +------+  +=========================+  +---+
888
 
        (1)                 (2)               (3)
889
 
 
890
 
       (1) - Prefix of OuterTables (those that participate in 
891
 
             IN-equality and/or are correlated with subquery) and outer 
892
 
             Noncorrelated Tables.
893
 
       (2) - The handled range. The range starts with the first sj-inner
894
 
             table, and covers all sj-inner and outer tables 
895
 
             Within the range,  Inner, Outer, outer Noncorrelated tables
896
 
             may follow in any order.
897
 
       (3) - The suffix of outer Noncorrelated tables.
898
 
    
899
 
    FirstMatch strategy
900
 
    ~~~~~~~~~~~~~~~~~~~
901
 
 
902
 
      (ot|nt)*  [ it ((it|nt)* it) ]  (nt)*
903
 
      +------+  +==================+  +---+
904
 
        (1)             (2)          (3)
905
 
 
906
 
      (1) - Prefix of outer and non-correlated tables
907
 
      (2) - The handled range, which may contain only inner and
908
 
            non-correlated tables.
909
 
      (3) - The suffix of outer Noncorrelated tables.
910
 
 
911
 
    InsideOut strategy 
912
 
    ~~~~~~~~~~~~~~~~~~
913
 
 
914
 
     (ot|ct|nt) [ insideout_tbl (ot|nt|it)* it ]  (ot|nt)*
915
 
     +--------+   +===========+ +=============+   +------+
916
 
        (1)           (2)          (3)              (4)
917
 
     
918
 
      (1) - Prefix that may contain any outer tables. The prefix must contain
919
 
            all the non-trivially correlated outer tables. (non-trivially means
920
 
            that the correlation is not just through the IN-equality).
921
 
      
922
 
      (2) - Inner table for which the InsideOut scan is performed.
923
 
 
924
 
      (3) - The remainder of the duplicate-generating range. It is served by 
925
 
            application of FirstMatch strategy, with the exception that
926
 
            outer IN-correlated tables are considered to be non-correlated.
927
 
 
928
 
      (4) - THe suffix of outer and outer non-correlated tables.
929
 
 
930
 
    If several strategies are applicable, their relative priorities are:
931
 
      1. InsideOut
932
 
      2. FirstMatch 
933
 
      3. DuplicateWeedout
934
 
 
935
 
    This function walks over the join order and sets up the strategies by
936
 
    setting appropriate members in join_tab structures.
937
 
 
938
 
  RETURN
939
 
    false  OK 
940
 
    true   Out of memory error
941
 
*/
942
 
 
943
 
static
944
 
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
945
 
{
946
 
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
947
 
  struct {
948
 
    /* 
949
 
      0 - invalid (EOF marker), 
950
 
      1 - InsideOut, 
951
 
      2 - Temptable (maybe confluent),
952
 
      3 - Temptable with join buffering
953
 
    */
954
 
    uint32_t strategy;
955
 
    uint32_t start_idx; /* Left range bound */
956
 
    uint32_t end_idx;   /* Right range bound */
957
 
    /* 
958
 
      For Temptable strategy: Bitmap of all outer and correlated tables from 
959
 
      all involved join nests.
960
 
    */
961
 
    table_map outer_tables;
962
 
  } dups_ranges [MAX_TABLES];
963
 
 
964
 
  TableList *emb_insideout_nest= NULL;
965
 
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
966
 
                               tables) whose ranges we're in */
967
 
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
968
 
  table_map range_start_map= 0; /* table_map at current range start */
969
 
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
970
 
  int cur_range= 0;
971
 
  uint32_t i;
972
 
 
973
 
  /*
974
 
    First pass: locate the duplicate-generating ranges and pick the strategies.
975
 
  */
976
 
  for (i=join->const_tables ; i < join->tables ; i++)
977
 
  {
978
 
    JOIN_TAB *tab=join->join_tab+i;
979
 
    Table *table=tab->table;
980
 
    cur_map |= table->map;
981
 
 
982
 
    if (tab->emb_sj_nest) // Encountered an sj-inner table
983
 
    {
984
 
      if (!emb_sj_map)
985
 
      {
986
 
        dups_ranges[cur_range].start_idx= i;
987
 
        range_start_map= cur_map & ~table->map;
988
 
        /*
989
 
          Remember if this is a possible start of range that is covered by
990
 
          the InsideOut strategy (the reason that it is not covered could
991
 
          be that it overlaps with anther semi-join's range. we don't
992
 
          support InsideOut for joined ranges)
993
 
        */
994
 
        if (join->best_positions[i].use_insideout_scan)
995
 
          emb_insideout_nest= tab->emb_sj_nest;
996
 
      }
997
 
 
998
 
      emb_sj_map |= tab->emb_sj_nest->sj_inner_tables;
999
 
      emb_outer_tables |= tab->emb_sj_nest->nested_join->sj_depends_on;
1000
 
 
1001
 
      if (tab->emb_sj_nest != emb_insideout_nest)
1002
 
      {
1003
 
        /*
1004
 
          Two different semi-joins interleave. This cannot be handled by
1005
 
          InsideOut strategy.
1006
 
        */
1007
 
        emb_insideout_nest= NULL;
1008
 
      }
1009
 
    }
1010
 
 
1011
 
    if (emb_sj_map) /* We're in duplicate-generating range */
1012
 
    {
1013
 
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
1014
 
          tab->type == JT_ALL && tab->use_quick != 2 && !tab->first_inner &&
1015
 
          i <= no_jbuf_after && !dealing_with_jbuf)
1016
 
      {
1017
 
        /*
1018
 
          This table uses join buffering, which makes use of FirstMatch or 
1019
 
          InsideOut strategies impossible for the current and (we assume) 
1020
 
          preceding duplicate-producing ranges.
1021
 
          That is, for the join order:
1022
 
 
1023
 
              x x [ x  x]  x  [x x x]  x  [x x X*  x] x
1024
 
                  |     |     |     |          | \
1025
 
                  +-----+     +-----+          |  join buffering use
1026
 
                     r1          r2         we're here
1027
 
 
1028
 
          we'll have to remove r1 and r2 and use duplicate-elimination
1029
 
          strategy that spans all the tables, starting from the very 1st
1030
 
          one.
1031
 
        */
1032
 
        dealing_with_jbuf= true;
1033
 
        emb_insideout_nest= false;
1034
 
 
1035
 
        /* 
1036
 
          Absorb all preceding duplicate-eliminating ranges. Their strategies
1037
 
          do not matter: 
1038
 
        */
1039
 
        for (int prev_range= 0; prev_range < cur_range; prev_range++)
1040
 
        {
1041
 
          dups_ranges[cur_range].outer_tables |= 
1042
 
            dups_ranges[prev_range].outer_tables;
1043
 
        }
1044
 
        dups_ranges[0].start_idx= 0; /* Will need to start from the 1st table */
1045
 
        dups_ranges[0].outer_tables= dups_ranges[cur_range].outer_tables;
1046
 
        cur_range=  0;
1047
 
      }
1048
 
 
1049
 
      /*
1050
 
        Check if we are at the end of duplicate-producing range. We are if
1051
 
 
1052
 
        1. It's an InsideOut range (which presumes all correlated tables are
1053
 
           in the prefix), and all inner tables are in the join order prefix,
1054
 
           or
1055
 
        2. It's a DuplicateElimination range (possibly covering several
1056
 
           SJ-nests), and all inner, outer, and correlated tables of all 
1057
 
           sj-nests are in the join order prefix.
1058
 
      */
1059
 
      bool end_of_range= false;
1060
 
      if (emb_insideout_nest && 
1061
 
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
1062
 
      {
1063
 
        /* Save that this range is handled with InsideOut: */
1064
 
        dups_ranges[cur_range].strategy= 1;
1065
 
        end_of_range= true;
1066
 
      }
1067
 
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
1068
 
      {
1069
 
        /*
1070
 
          This is a complete range to be handled with either DuplicateWeedout 
1071
 
          or FirstMatch
1072
 
        */
1073
 
        dups_ranges[cur_range].strategy= dealing_with_jbuf? 3 : 2;
1074
 
        /* 
1075
 
          This will hold tables from within the range that need to be put 
1076
 
          into the join buffer before we can use the FirstMatch on its tail.
1077
 
        */
1078
 
        dups_ranges[cur_range].outer_tables= emb_outer_tables & 
1079
 
                                             ~range_start_map;
1080
 
        end_of_range= true;
1081
 
      }
1082
 
 
1083
 
      if (end_of_range)
1084
 
      {
1085
 
        dups_ranges[cur_range].end_idx= i+1;
1086
 
        emb_sj_map= emb_outer_tables= 0;
1087
 
        emb_insideout_nest= NULL;
1088
 
        dealing_with_jbuf= false;
1089
 
        dups_ranges[++cur_range].strategy= 0;
1090
 
      }
1091
 
    }
1092
 
  }
1093
 
 
1094
 
  THD *thd= join->thd;
1095
 
  SJ_TMP_TABLE **next_sjtbl_ptr= &join->sj_tmp_tables;
1096
 
  /*
1097
 
    Second pass: setup the chosen strategies    
1098
 
  */
1099
 
  for (int j= 0; j < cur_range; j++)
1100
 
  {
1101
 
    JOIN_TAB *tab=join->join_tab + dups_ranges[j].start_idx;
1102
 
    JOIN_TAB *jump_to;
1103
 
    if (dups_ranges[j].strategy == 1)  // InsideOut strategy
1104
 
    {
1105
 
      tab->insideout_match_tab= join->join_tab + dups_ranges[j].end_idx - 1;
1106
 
      jump_to= tab++;
1107
 
    }
1108
 
    else // DuplicateWeedout strategy
1109
 
    {
1110
 
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
1111
 
      table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
1112
 
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
1113
 
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
1114
 
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
1115
 
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
1116
 
      JOIN_TAB *last_outer_tab= tab - 1;
1117
 
      /*
1118
 
        Walk through the range and remember
1119
 
         - tables that need their rowids to be put into temptable
1120
 
         - the last outer table
1121
 
      */
1122
 
      for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
1123
 
      {
1124
 
        if (sj_table_is_included(join, tab))
1125
 
        {
1126
 
          last_tab->join_tab= tab;
1127
 
          last_tab->rowid_offset= jt_rowid_offset;
1128
 
          jt_rowid_offset += tab->table->file->ref_length;
1129
 
          if (tab->table->maybe_null)
1130
 
          {
1131
 
            last_tab->null_byte= jt_null_bits / 8;
1132
 
            last_tab->null_bit= jt_null_bits++;
1133
 
          }
1134
 
          last_tab++;
1135
 
          tab->table->prepare_for_position();
1136
 
          tab->rowid_keep_flags= rowid_keep_flags;
1137
 
        }
1138
 
        cur_map |= tab->table->map;
1139
 
        if (!tab->emb_sj_nest && bitmap_covers(cur_map, 
1140
 
                                               dups_ranges[j].outer_tables))
1141
 
          last_outer_tab= tab;
1142
 
      }
1143
 
 
1144
 
      if (jt_rowid_offset) /* Temptable has at least one rowid */
1145
 
      {
1146
 
        SJ_TMP_TABLE *sjtbl;
1147
 
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
1148
 
        if (!(sjtbl= (SJ_TMP_TABLE*)thd->alloc(sizeof(SJ_TMP_TABLE))) ||
1149
 
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) thd->alloc(tabs_size)))
1150
 
          return(true);
1151
 
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
1152
 
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
1153
 
        sjtbl->rowid_len= jt_rowid_offset;
1154
 
        sjtbl->null_bits= jt_null_bits;
1155
 
        sjtbl->null_bytes= (jt_null_bits + 7)/8;
1156
 
 
1157
 
        *next_sjtbl_ptr= sjtbl;
1158
 
        next_sjtbl_ptr= &(sjtbl->next);
1159
 
        sjtbl->next= NULL;
1160
 
 
1161
 
        sjtbl->tmp_table= 
1162
 
          create_duplicate_weedout_tmp_table(thd, 
1163
 
                                             sjtbl->rowid_len + 
1164
 
                                             sjtbl->null_bytes,
1165
 
                                             sjtbl);
1166
 
 
1167
 
        join->join_tab[dups_ranges[j].start_idx].flush_weedout_table= sjtbl;
1168
 
        join->join_tab[dups_ranges[j].end_idx - 1].check_weed_out_table= sjtbl;
1169
 
      }
1170
 
      tab= last_outer_tab + 1;
1171
 
      jump_to= last_outer_tab;
1172
 
    }
1173
 
 
1174
 
    /* Create the FirstMatch tail */
1175
 
    for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
1176
 
    {
1177
 
      if (tab->emb_sj_nest)
1178
 
        tab->do_firstmatch= jump_to; 
1179
 
      else
1180
 
        jump_to= tab;
1181
 
    }
1182
 
  }
1183
 
  return(false);
1184
 
}
1185
 
 
1186
 
 
1187
 
static void cleanup_sj_tmp_tables(JOIN *join)
1188
 
{
1189
 
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl; 
1190
 
       sj_tbl= sj_tbl->next)
1191
 
  {
1192
 
    if (sj_tbl->tmp_table)
1193
 
    {
1194
 
      sj_tbl->tmp_table->free_tmp_table(join->thd);
1195
 
    }
1196
 
  }
1197
 
  join->sj_tmp_tables= NULL;
1198
 
}
1199
 
 
1200
 
uint32_t make_join_orderinfo(JOIN *join);
1201
 
 
1202
 
/**
1203
 
  global select optimisation.
1204
 
 
1205
 
  @note
1206
 
    error code saved in field 'error'
1207
 
 
1208
 
  @retval
1209
 
    0   success
1210
 
  @retval
1211
 
    1   error
1212
 
*/
1213
 
 
1214
 
int
1215
 
JOIN::optimize()
1216
 
{
1217
 
  // to prevent double initialization on EXPLAIN
1218
 
  if (optimized)
1219
 
    return(0);
1220
 
  optimized= 1;
1221
 
 
1222
 
  thd_proc_info(thd, "optimizing");
1223
 
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
1224
 
              unit->select_limit_cnt);
1225
 
  /* select_limit is used to decide if we are likely to scan the whole table */
1226
 
  select_limit= unit->select_limit_cnt;
1227
 
  if (having || (select_options & OPTION_FOUND_ROWS))
1228
 
    select_limit= HA_POS_ERROR;
1229
 
  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
1230
 
  // Ignore errors of execution if option IGNORE present
1231
 
  if (thd->lex->ignore)
1232
 
    thd->lex->current_select->no_error= 1;
1233
 
 
1234
 
#ifdef HAVE_REF_TO_FIELDS                       // Not done yet
1235
 
  /* Add HAVING to WHERE if possible */
1236
 
  if (having && !group_list && !sum_func_count)
1237
 
  {
1238
 
    if (!conds)
1239
 
    {
1240
 
      conds= having;
1241
 
      having= 0;
1242
 
    }
1243
 
    else if ((conds=new Item_cond_and(conds,having)))
1244
 
    {
1245
 
      /*
1246
 
        Item_cond_and can't be fixed after creation, so we do not check
1247
 
        conds->fixed
1248
 
      */
1249
 
      conds->fix_fields(thd, &conds);
1250
 
      conds->change_ref_to_fields(thd, tables_list);
1251
 
      conds->top_level_item();
1252
 
      having= 0;
1253
 
    }
1254
 
  }
1255
 
#endif
1256
 
 
1257
 
  /* Convert all outer joins to inner joins if possible */
1258
 
  conds= simplify_joins(this, join_list, conds, true, false);
1259
 
  build_bitmap_for_nested_joins(join_list, 0);
1260
 
 
1261
 
  conds= optimize_cond(this, conds, join_list, &cond_value);   
1262
 
  if (thd->is_error())
1263
 
  {
1264
 
    error= 1;
1265
 
    return(1);
1266
 
  }
1267
 
 
1268
 
  {
1269
 
    having= optimize_cond(this, having, join_list, &having_value);
1270
 
    if (thd->is_error())
1271
 
    {
1272
 
      error= 1;
1273
 
      return(1);
1274
 
    }
1275
 
    if (select_lex->where)
1276
 
      select_lex->cond_value= cond_value;
1277
 
    if (select_lex->having)
1278
 
      select_lex->having_value= having_value;
1279
 
 
1280
 
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE || 
1281
 
        (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
1282
 
    {                                           /* Impossible cond */
1283
 
      zero_result_cause=  having_value == Item::COND_FALSE ?
1284
 
                           "Impossible HAVING" : "Impossible WHERE";
1285
 
      error= 0;
1286
 
      return(0);
1287
 
    }
1288
 
  }
1289
 
 
1290
 
  /* Optimize count(*), cmin() and cmax() */
1291
 
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
1292
 
  {
1293
 
    int res;
1294
 
    /*
1295
 
      opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
1296
 
      to the WHERE conditions,
1297
 
      or 1 if all items were resolved,
1298
 
      or 0, or an error number HA_ERR_...
1299
 
    */
1300
 
    if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
1301
 
    {
1302
 
      if (res == HA_ERR_KEY_NOT_FOUND)
1303
 
      {
1304
 
        zero_result_cause= "No matching min/max row";
1305
 
        error=0;
1306
 
        return(0);
1307
 
      }
1308
 
      if (res > 1)
1309
 
      {
1310
 
        error= res;
1311
 
        return(1);
1312
 
      }
1313
 
      if (res < 0)
1314
 
      {
1315
 
        zero_result_cause= "No matching min/max row";
1316
 
        error=0;
1317
 
        return(0);
1318
 
      }
1319
 
      zero_result_cause= "Select tables optimized away";
1320
 
      tables_list= 0;                           // All tables resolved
1321
 
      /*
1322
 
        Extract all table-independent conditions and replace the WHERE
1323
 
        clause with them. All other conditions were computed by opt_sum_query
1324
 
        and the MIN/MAX/COUNT function(s) have been replaced by constants,
1325
 
        so there is no need to compute the whole WHERE clause again.
1326
 
        Notice that make_cond_for_table() will always succeed to remove all
1327
 
        computed conditions, because opt_sum_query() is applicable only to
1328
 
        conjunctions.
1329
 
        Preserve conditions for EXPLAIN.
1330
 
      */
1331
 
      if (conds && !(thd->lex->describe & DESCRIBE_EXTENDED))
1332
 
      {
1333
 
        COND *table_independent_conds=
1334
 
          make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
1335
 
        conds= table_independent_conds;
1336
 
      }
1337
 
    }
1338
 
  }
1339
 
  if (!tables_list)
1340
 
  {
1341
 
    error= 0;
1342
 
    return(0);
1343
 
  }
1344
 
  error= -1;                                    // Error is sent to client
1345
 
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
1346
 
 
1347
 
  /* Calculate how to do the join */
1348
 
  thd_proc_info(thd, "statistics");
1349
 
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
1350
 
      thd->is_fatal_error)
1351
 
  {
1352
 
    return(1);
1353
 
  }
1354
 
 
1355
 
  /* Remove distinct if only const tables */
1356
 
  select_distinct= select_distinct && (const_tables != tables);
1357
 
  thd_proc_info(thd, "preparing");
1358
 
  if (result->initialize_tables(this))
1359
 
  {
1360
 
    return(1);                          // error == -1
1361
 
  }
1362
 
  if (const_table_map != found_const_table_map &&
1363
 
      !(select_options & SELECT_DESCRIBE) &&
1364
 
      (!conds ||
1365
 
       !(conds->used_tables() & RAND_TABLE_BIT) ||
1366
 
       select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
1367
 
  {
1368
 
    zero_result_cause= "no matching row in const table";
1369
 
    error= 0;
1370
 
    return(0);
1371
 
  }
1372
 
  if (!(thd->options & OPTION_BIG_SELECTS) &&
1373
 
      best_read > (double) thd->variables.max_join_size &&
1374
 
      !(select_options & SELECT_DESCRIBE))
1375
 
  {                                             /* purecov: inspected */
1376
 
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
1377
 
    error= -1;
1378
 
    return(1);
1379
 
  }
1380
 
  if (const_tables && !thd->locked_tables &&
1381
 
      !(select_options & SELECT_NO_UNLOCK))
1382
 
    mysql_unlock_some_tables(thd, table, const_tables);
1383
 
  if (!conds && outer_join)
1384
 
  {
1385
 
    /* Handle the case where we have an OUTER JOIN without a WHERE */
1386
 
    conds=new Item_int((int64_t) 1,1);  // Always true
1387
 
  }
1388
 
  select= make_select(*table, const_table_map,
1389
 
                      const_table_map, conds, 1, &error);
1390
 
  if (error)
1391
 
  {                                             /* purecov: inspected */
1392
 
    error= -1;                                  /* purecov: inspected */
1393
 
    return(1);
1394
 
  }
1395
 
  
1396
 
  reset_nj_counters(join_list);
1397
 
  make_outerjoin_info(this);
1398
 
 
1399
 
  /*
1400
 
    Among the equal fields belonging to the same multiple equality
1401
 
    choose the one that is to be retrieved first and substitute
1402
 
    all references to these in where condition for a reference for
1403
 
    the selected field.
1404
 
  */
1405
 
  if (conds)
1406
 
  {
1407
 
    conds= substitute_for_best_equal_field(conds, cond_equal, map2table);
1408
 
    conds->update_used_tables();
1409
 
  }
1410
 
 
1411
 
  /*
1412
 
    Permorm the the optimization on fields evaluation mentioned above
1413
 
    for all on expressions.
1414
 
  */ 
1415
 
  for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
1416
 
  {
1417
 
    if (*tab->on_expr_ref)
1418
 
    {
1419
 
      *tab->on_expr_ref= substitute_for_best_equal_field(*tab->on_expr_ref,
1420
 
                                                         tab->cond_equal,
1421
 
                                                         map2table);
1422
 
      (*tab->on_expr_ref)->update_used_tables();
1423
 
    }
1424
 
  }
1425
 
 
1426
 
  if (conds &&!outer_join && const_table_map != found_const_table_map && 
1427
 
      (select_options & SELECT_DESCRIBE) &&
1428
 
      select_lex->master_unit() == &thd->lex->unit) // upper level SELECT
1429
 
  {
1430
 
    conds=new Item_int((int64_t) 0,1);  // Always false
1431
 
  }
1432
 
  if (make_join_select(this, select, conds))
1433
 
  {
1434
 
    zero_result_cause=
1435
 
      "Impossible WHERE noticed after reading const tables";
1436
 
    return(0);                          // error == 0
1437
 
  }
1438
 
 
1439
 
  error= -1;                                    /* if goto err */
1440
 
 
1441
 
  /* Optimize distinct away if possible */
1442
 
  {
1443
 
    order_st *org_order= order;
1444
 
    order=remove_const(this, order,conds,1, &simple_order);
1445
 
    if (thd->is_error())
1446
 
    {
1447
 
      error= 1;
1448
 
      return(1);
1449
 
    }
1450
 
 
1451
 
    /*
1452
 
      If we are using order_st BY NULL or order_st BY const_expression,
1453
 
      return result in any order (even if we are using a GROUP BY)
1454
 
    */
1455
 
    if (!order && org_order)
1456
 
      skip_sort_order= 1;
1457
 
  }
1458
 
  /*
1459
 
     Check if we can optimize away GROUP BY/DISTINCT.
1460
 
     We can do that if there are no aggregate functions, the
1461
 
     fields in DISTINCT clause (if present) and/or columns in GROUP BY
1462
 
     (if present) contain direct references to all key parts of
1463
 
     an unique index (in whatever order) and if the key parts of the
1464
 
     unique index cannot contain NULLs.
1465
 
     Note that the unique keys for DISTINCT and GROUP BY should not
1466
 
     be the same (as long as they are unique).
1467
 
 
1468
 
     The FROM clause must contain a single non-constant table.
1469
 
  */
1470
 
  if (tables - const_tables == 1 && (group_list || select_distinct) &&
1471
 
      !tmp_table_param.sum_func_count &&
1472
 
      (!join_tab[const_tables].select ||
1473
 
       !join_tab[const_tables].select->quick ||
1474
 
       join_tab[const_tables].select->quick->get_type() != 
1475
 
       QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
1476
 
  {
1477
 
    if (group_list &&
1478
 
       list_contains_unique_index(join_tab[const_tables].table,
1479
 
                                 find_field_in_order_list,
1480
 
                                 (void *) group_list))
1481
 
    {
1482
 
      /*
1483
 
        We have found that grouping can be removed since groups correspond to
1484
 
        only one row anyway, but we still have to guarantee correct result
1485
 
        order. The line below effectively rewrites the query from GROUP BY
1486
 
        <fields> to order_st BY <fields>. There are two exceptions:
1487
 
        - if skip_sort_order is set (see above), then we can simply skip
1488
 
          GROUP BY;
1489
 
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
1490
 
          with the GROUP BY ones, i.e. either one is a prefix of another.
1491
 
          We only check if the order_st BY is a prefix of GROUP BY. In this case
1492
 
          test_if_subpart() copies the ASC/DESC attributes from the original
1493
 
          order_st BY fields.
1494
 
          If GROUP BY is a prefix of order_st BY, then it is safe to leave
1495
 
          'order' as is.
1496
 
       */
1497
 
      if (!order || test_if_subpart(group_list, order))
1498
 
          order= skip_sort_order ? 0 : group_list;
1499
 
      /*
1500
 
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be 
1501
 
        rewritten to IGNORE INDEX FOR order_st BY(fields).
1502
 
      */
1503
 
      join_tab->table->keys_in_use_for_order_by=
1504
 
        join_tab->table->keys_in_use_for_group_by;
1505
 
      group_list= 0;
1506
 
      group= 0;
1507
 
    }
1508
 
    if (select_distinct &&
1509
 
       list_contains_unique_index(join_tab[const_tables].table,
1510
 
                                 find_field_in_item_list,
1511
 
                                 (void *) &fields_list))
1512
 
    {
1513
 
      select_distinct= 0;
1514
 
    }
1515
 
  }
1516
 
  if (group_list || tmp_table_param.sum_func_count)
1517
 
  {
1518
 
    if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
1519
 
      select_distinct=0;
1520
 
  }
1521
 
  else if (select_distinct && tables - const_tables == 1)
1522
 
  {
1523
 
    /*
1524
 
      We are only using one table. In this case we change DISTINCT to a
1525
 
      GROUP BY query if:
1526
 
      - The GROUP BY can be done through indexes (no sort) and the order_st
1527
 
        BY only uses selected fields.
1528
 
        (In this case we can later optimize away GROUP BY and order_st BY)
1529
 
      - We are scanning the whole table without LIMIT
1530
 
        This can happen if:
1531
 
        - We are using CALC_FOUND_ROWS
1532
 
        - We are using an order_st BY that can't be optimized away.
1533
 
 
1534
 
      We don't want to use this optimization when we are using LIMIT
1535
 
      because in this case we can just create a temporary table that
1536
 
      holds LIMIT rows and stop when this table is full.
1537
 
    */
1538
 
    JOIN_TAB *tab= &join_tab[const_tables];
1539
 
    bool all_order_fields_used;
1540
 
    if (order)
1541
 
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1, 
1542
 
        &tab->table->keys_in_use_for_order_by);
1543
 
    if ((group_list=create_distinct_group(thd, select_lex->ref_pointer_array,
1544
 
                                          order, fields_list, all_fields,
1545
 
                                          &all_order_fields_used)))
1546
 
    {
1547
 
      bool skip_group= (skip_sort_order &&
1548
 
        test_if_skip_sort_order(tab, group_list, select_limit, 1, 
1549
 
                                &tab->table->keys_in_use_for_group_by) != 0);
1550
 
      count_field_types(select_lex, &tmp_table_param, all_fields, 0);
1551
 
      if ((skip_group && all_order_fields_used) ||
1552
 
          select_limit == HA_POS_ERROR ||
1553
 
          (order && !skip_sort_order))
1554
 
      {
1555
 
        /*  Change DISTINCT to GROUP BY */
1556
 
        select_distinct= 0;
1557
 
        no_order= !order;
1558
 
        if (all_order_fields_used)
1559
 
        {
1560
 
          if (order && skip_sort_order)
1561
 
          {
1562
 
            /*
1563
 
              Force MySQL to read the table in sorted order to get result in
1564
 
              order_st BY order.
1565
 
            */
1566
 
            tmp_table_param.quick_group=0;
1567
 
          }
1568
 
          order=0;
1569
 
        }
1570
 
        group=1;                                // For end_write_group
1571
 
      }
1572
 
      else
1573
 
        group_list= 0;
1574
 
    }
1575
 
    else if (thd->is_fatal_error)                       // End of memory
1576
 
      return(1);
1577
 
  }
1578
 
  simple_group= 0;
1579
 
  {
1580
 
    order_st *old_group_list;
1581
 
    group_list= remove_const(this, (old_group_list= group_list), conds,
1582
 
                             rollup.state == ROLLUP::STATE_NONE,
1583
 
                             &simple_group);
1584
 
    if (thd->is_error())
1585
 
    {
1586
 
      error= 1;
1587
 
      return(1);
1588
 
    }
1589
 
    if (old_group_list && !group_list)
1590
 
      select_distinct= 0;
1591
 
  }
1592
 
  if (!group_list && group)
1593
 
  {
1594
 
    order=0;                                    // The output has only one row
1595
 
    simple_order=1;
1596
 
    select_distinct= 0;                       // No need in distinct for 1 row
1597
 
    group_optimized_away= 1;
1598
 
  }
1599
 
 
1600
 
  calc_group_buffer(this, group_list);
1601
 
  send_group_parts= tmp_table_param.group_parts; /* Save org parts */
1602
 
 
1603
 
  if (test_if_subpart(group_list, order) ||
1604
 
      (!group_list && tmp_table_param.sum_func_count))
1605
 
    order=0;
1606
 
 
1607
 
  // Can't use sort on head table if using row cache
1608
 
  if (full_join)
1609
 
  {
1610
 
    if (group_list)
1611
 
      simple_group=0;
1612
 
    if (order)
1613
 
      simple_order=0;
1614
 
  }
1615
 
 
1616
 
  /*
1617
 
    Check if we need to create a temporary table.
1618
 
    This has to be done if all tables are not already read (const tables)
1619
 
    and one of the following conditions holds:
1620
 
    - We are using DISTINCT (simple distinct's are already optimized away)
1621
 
    - We are using an order_st BY or GROUP BY on fields not in the first table
1622
 
    - We are using different order_st BY and GROUP BY orders
1623
 
    - The user wants us to buffer the result.
1624
 
  */
1625
 
  need_tmp= (const_tables != tables &&
1626
 
             ((select_distinct || !simple_order || !simple_group) ||
1627
 
              (group_list && order) ||
1628
 
              test(select_options & OPTION_BUFFER_RESULT)));
1629
 
 
1630
 
  uint32_t no_jbuf_after= make_join_orderinfo(this);
1631
 
  uint64_t select_opts_for_readinfo= 
1632
 
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
1633
 
 
1634
 
  sj_tmp_tables= NULL;
1635
 
  if (!select_lex->sj_nests.is_empty())
1636
 
    setup_semijoin_dups_elimination(this, select_opts_for_readinfo,
1637
 
                                    no_jbuf_after);
1638
 
 
1639
 
  // No cache for MATCH == 'Don't use join buffering when we use MATCH'.
1640
 
  if (make_join_readinfo(this, select_opts_for_readinfo, no_jbuf_after))
1641
 
    return(1);
1642
 
 
1643
 
  /* Create all structures needed for materialized subquery execution. */
1644
 
  if (setup_subquery_materialization())
1645
 
    return(1);
1646
 
 
1647
 
  /*
1648
 
    is this simple IN subquery?
1649
 
  */
1650
 
  if (!group_list && !order &&
1651
 
      unit->item && unit->item->substype() == Item_subselect::IN_SUBS &&
1652
 
      tables == 1 && conds &&
1653
 
      !unit->is_union())
1654
 
  {
1655
 
    if (!having)
1656
 
    {
1657
 
      Item *where= conds;
1658
 
      if (join_tab[0].type == JT_EQ_REF &&
1659
 
          join_tab[0].ref.items[0]->name == in_left_expr_name)
1660
 
      {
1661
 
        remove_subq_pushed_predicates(&where);
1662
 
        save_index_subquery_explain_info(join_tab, where);
1663
 
        join_tab[0].type= JT_UNIQUE_SUBQUERY;
1664
 
        error= 0;
1665
 
        return(unit->item->
1666
 
                    change_engine(new
1667
 
                                  subselect_uniquesubquery_engine(thd,
1668
 
                                                                  join_tab,
1669
 
                                                                  unit->item,
1670
 
                                                                  where)));
1671
 
      }
1672
 
      else if (join_tab[0].type == JT_REF &&
1673
 
               join_tab[0].ref.items[0]->name == in_left_expr_name)
1674
 
      {
1675
 
        remove_subq_pushed_predicates(&where);
1676
 
        save_index_subquery_explain_info(join_tab, where);
1677
 
        join_tab[0].type= JT_INDEX_SUBQUERY;
1678
 
        error= 0;
1679
 
        return(unit->item->
1680
 
                    change_engine(new
1681
 
                                  subselect_indexsubquery_engine(thd,
1682
 
                                                                 join_tab,
1683
 
                                                                 unit->item,
1684
 
                                                                 where,
1685
 
                                                                 NULL,
1686
 
                                                                 0)));
1687
 
      }
1688
 
    } else if (join_tab[0].type == JT_REF_OR_NULL &&
1689
 
               join_tab[0].ref.items[0]->name == in_left_expr_name &&
1690
 
               having->name == in_having_cond)
1691
 
    {
1692
 
      join_tab[0].type= JT_INDEX_SUBQUERY;
1693
 
      error= 0;
1694
 
      conds= remove_additional_cond(conds);
1695
 
      save_index_subquery_explain_info(join_tab, conds);
1696
 
      return(unit->item->
1697
 
                  change_engine(new subselect_indexsubquery_engine(thd,
1698
 
                                                                   join_tab,
1699
 
                                                                   unit->item,
1700
 
                                                                   conds,
1701
 
                                                                   having,
1702
 
                                                                   1)));
1703
 
    }
1704
 
 
1705
 
  }
1706
 
  /*
1707
 
    Need to tell handlers that to play it safe, it should fetch all
1708
 
    columns of the primary key of the tables: this is because MySQL may
1709
 
    build row pointers for the rows, and for all columns of the primary key
1710
 
    the read set has not necessarily been set by the server code.
1711
 
  */
1712
 
  if (need_tmp || select_distinct || group_list || order)
1713
 
  {
1714
 
    for (uint32_t i = const_tables; i < tables; i++)
1715
 
      join_tab[i].table->prepare_for_position();
1716
 
  }
1717
 
 
1718
 
  if (const_tables != tables)
1719
 
  {
1720
 
    /*
1721
 
      Because filesort always does a full table scan or a quick range scan
1722
 
      we must add the removed reference to the select for the table.
1723
 
      We only need to do this when we have a simple_order or simple_group
1724
 
      as in other cases the join is done before the sort.
1725
 
    */
1726
 
    if ((order || group_list) &&
1727
 
        (join_tab[const_tables].type != JT_ALL) &&
1728
 
        (join_tab[const_tables].type != JT_REF_OR_NULL) &&
1729
 
        ((order && simple_order) || (group_list && simple_group)))
1730
 
    {
1731
 
      if (add_ref_to_table_cond(thd,&join_tab[const_tables])) {
1732
 
        return(1);
1733
 
      }
1734
 
    }
1735
 
    
1736
 
    if (!(select_options & SELECT_BIG_RESULT) &&
1737
 
        ((group_list &&
1738
 
          (!simple_group ||
1739
 
           !test_if_skip_sort_order(&join_tab[const_tables], group_list,
1740
 
                                    unit->select_limit_cnt, 0, 
1741
 
                                    &join_tab[const_tables].table->
1742
 
                                    keys_in_use_for_group_by))) ||
1743
 
         select_distinct) &&
1744
 
        tmp_table_param.quick_group)
1745
 
    {
1746
 
      need_tmp=1; simple_order=simple_group=0;  // Force tmp table without sort
1747
 
    }
1748
 
    if (order)
1749
 
    {
1750
 
      /*
1751
 
        Force using of tmp table if sorting by a SP or UDF function due to
1752
 
        their expensive and probably non-deterministic nature.
1753
 
      */
1754
 
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
1755
 
      {
1756
 
        Item *item= *tmp_order->item;
1757
 
        if (item->is_expensive())
1758
 
        {
1759
 
          /* Force tmp table without sort */
1760
 
          need_tmp=1; simple_order=simple_group=0;
1761
 
          break;
1762
 
        }
1763
 
      }
1764
 
    }
1765
 
  }
1766
 
 
1767
 
  tmp_having= having;
1768
 
  if (select_options & SELECT_DESCRIBE)
1769
 
  {
1770
 
    error= 0;
1771
 
    return(0);
1772
 
  }
1773
 
  having= 0;
1774
 
 
1775
 
  /*
1776
 
    The loose index scan access method guarantees that all grouping or
1777
 
    duplicate row elimination (for distinct) is already performed
1778
 
    during data retrieval, and that all MIN/MAX functions are already
1779
 
    computed for each group. Thus all MIN/MAX functions should be
1780
 
    treated as regular functions, and there is no need to perform
1781
 
    grouping in the main execution loop.
1782
 
    Notice that currently loose index scan is applicable only for
1783
 
    single table queries, thus it is sufficient to test only the first
1784
 
    join_tab element of the plan for its access method.
1785
 
  */
1786
 
  if (join_tab->is_using_loose_index_scan())
1787
 
    tmp_table_param.precomputed_group_by= true;
1788
 
 
1789
 
  /* Create a tmp table if distinct or if the sort is too complicated */
1790
 
  if (need_tmp)
1791
 
  {
1792
 
    thd_proc_info(thd, "Creating tmp table");
1793
 
 
1794
 
    init_items_ref_array();
1795
 
 
1796
 
    tmp_table_param.hidden_field_count= (all_fields.elements -
1797
 
                                         fields_list.elements);
1798
 
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
1799
 
                                                             (order_st*) 0);
1800
 
    /*
1801
 
      Pushing LIMIT to the temporary table creation is not applicable
1802
 
      when there is order_st BY or GROUP BY or there is no GROUP BY, but
1803
 
      there are aggregate functions, because in all these cases we need
1804
 
      all result rows.
1805
 
    */
1806
 
    ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
1807
 
                             !tmp_group &&
1808
 
                             !thd->lex->current_select->with_sum_func) ?
1809
 
                            select_limit : HA_POS_ERROR;
1810
 
 
1811
 
    if (!(exec_tmp_table1=
1812
 
          create_tmp_table(thd, &tmp_table_param, all_fields,
1813
 
                           tmp_group,
1814
 
                           group_list ? 0 : select_distinct,
1815
 
                           group_list && simple_group,
1816
 
                           select_options,
1817
 
                           tmp_rows_limit,
1818
 
                           (char *) "")))
1819
 
                {
1820
 
      return(1);
1821
 
    }
1822
 
 
1823
 
    /*
1824
 
      We don't have to store rows in temp table that doesn't match HAVING if:
1825
 
      - we are sorting the table and writing complete group rows to the
1826
 
        temp table.
1827
 
      - We are using DISTINCT without resolving the distinct as a GROUP BY
1828
 
        on all columns.
1829
 
      
1830
 
      If having is not handled here, it will be checked before the row
1831
 
      is sent to the client.
1832
 
    */    
1833
 
    if (tmp_having && 
1834
 
        (sort_and_group || (exec_tmp_table1->distinct && !group_list)))
1835
 
      having= tmp_having;
1836
 
 
1837
 
    /* if group or order on first table, sort first */
1838
 
    if (group_list && simple_group)
1839
 
    {
1840
 
      thd_proc_info(thd, "Sorting for group");
1841
 
      if (create_sort_index(thd, this, group_list,
1842
 
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
1843
 
          alloc_group_fields(this, group_list) ||
1844
 
          make_sum_func_list(all_fields, fields_list, 1) ||
1845
 
          setup_sum_funcs(thd, sum_funcs))
1846
 
      {
1847
 
        return(1);
1848
 
      }
1849
 
      group_list=0;
1850
 
    }
1851
 
    else
1852
 
    {
1853
 
      if (make_sum_func_list(all_fields, fields_list, 0) ||
1854
 
          setup_sum_funcs(thd, sum_funcs))
1855
 
      {
1856
 
        return(1);
1857
 
      }
1858
 
 
1859
 
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1860
 
      {
1861
 
        thd_proc_info(thd, "Sorting for order");
1862
 
        if (create_sort_index(thd, this, order,
1863
 
                              HA_POS_ERROR, HA_POS_ERROR, true))
1864
 
        {
1865
 
          return(1);
1866
 
        }
1867
 
        order=0;
1868
 
      }
1869
 
    }
1870
 
    
1871
 
    /*
1872
 
      Optimize distinct when used on some of the tables
1873
 
      SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
1874
 
      In this case we can stop scanning t2 when we have found one t1.a
1875
 
    */
1876
 
 
1877
 
    if (exec_tmp_table1->distinct)
1878
 
    {
1879
 
      table_map used_tables= thd->used_tables;
1880
 
      JOIN_TAB *last_join_tab= join_tab+tables-1;
1881
 
      do
1882
 
      {
1883
 
        if (used_tables & last_join_tab->table->map)
1884
 
          break;
1885
 
        last_join_tab->not_used_in_distinct=1;
1886
 
      } while (last_join_tab-- != join_tab);
1887
 
      /* Optimize "select distinct b from t1 order by key_part_1 limit #" */
1888
 
      if (order && skip_sort_order)
1889
 
      {
1890
 
        /* Should always succeed */
1891
 
        if (test_if_skip_sort_order(&join_tab[const_tables],
1892
 
                                    order, unit->select_limit_cnt, 0, 
1893
 
                                    &join_tab[const_tables].table->
1894
 
                                      keys_in_use_for_order_by))
1895
 
          order=0;
1896
 
      }
1897
 
    }
1898
 
 
1899
 
    /* 
1900
 
      If this join belongs to an uncacheable subquery save 
1901
 
      the original join 
1902
 
    */
1903
 
    if (select_lex->uncacheable && !is_top_level_join() &&
1904
 
        init_save_join_tab())
1905
 
      return(-1);                         /* purecov: inspected */
1906
 
  }
1907
 
 
1908
 
  error= 0;
1909
 
  return(0);
1910
 
}
1911
 
 
1912
 
 
1913
 
/**
1914
 
  Restore values in temporary join.
1915
 
*/
1916
 
void JOIN::restore_tmp()
1917
 
{
1918
 
  memcpy(tmp_join, this, (size_t) sizeof(JOIN));
1919
 
}
1920
 
 
1921
 
 
1922
 
int
1923
 
JOIN::reinit()
1924
 
{
1925
 
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1926
 
                                    select_lex->offset_limit->val_uint() :
1927
 
                                    0UL);
1928
 
 
1929
 
  first_record= 0;
1930
 
 
1931
 
  if (exec_tmp_table1)
1932
 
  {
1933
 
    exec_tmp_table1->file->extra(HA_EXTRA_RESET_STATE);
1934
 
    exec_tmp_table1->file->ha_delete_all_rows();
1935
 
    free_io_cache(exec_tmp_table1);
1936
 
    filesort_free_buffers(exec_tmp_table1,0);
1937
 
  }
1938
 
  if (exec_tmp_table2)
1939
 
  {
1940
 
    exec_tmp_table2->file->extra(HA_EXTRA_RESET_STATE);
1941
 
    exec_tmp_table2->file->ha_delete_all_rows();
1942
 
    free_io_cache(exec_tmp_table2);
1943
 
    filesort_free_buffers(exec_tmp_table2,0);
1944
 
  }
1945
 
  if (items0)
1946
 
    set_items_ref_array(items0);
1947
 
 
1948
 
  if (join_tab_save)
1949
 
    memcpy(join_tab, join_tab_save, sizeof(JOIN_TAB) * tables);
1950
 
 
1951
 
  if (tmp_join)
1952
 
    restore_tmp();
1953
 
 
1954
 
  /* Reset of sum functions */
1955
 
  if (sum_funcs)
1956
 
  {
1957
 
    Item_sum *func, **func_ptr= sum_funcs;
1958
 
    while ((func= *(func_ptr++)))
1959
 
      func->clear();
1960
 
  }
1961
 
 
1962
 
  return(0);
1963
 
}
1964
 
 
1965
 
/**
1966
 
   @brief Save the original join layout
1967
 
      
1968
 
   @details Saves the original join layout so it can be reused in 
1969
 
   re-execution and for EXPLAIN.
1970
 
             
1971
 
   @return Operation status
1972
 
   @retval 0      success.
1973
 
   @retval 1      error occurred.
1974
 
*/
1975
 
 
1976
 
bool
1977
 
JOIN::init_save_join_tab()
1978
 
{
1979
 
  if (!(tmp_join= (JOIN*)thd->alloc(sizeof(JOIN))))
1980
 
    return 1;                                  /* purecov: inspected */
1981
 
  error= 0;                                    // Ensure that tmp_join.error= 0
1982
 
  restore_tmp();
1983
 
  return 0;
1984
 
}
1985
 
 
1986
 
 
1987
 
bool
1988
 
JOIN::save_join_tab()
1989
 
{
1990
 
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1991
 
  {
1992
 
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((unsigned char*) join_tab,
1993
 
                                                sizeof(JOIN_TAB) * tables)))
1994
 
      return 1;
1995
 
  }
1996
 
  return 0;
1997
 
}
1998
 
 
1999
 
 
2000
 
/**
2001
 
  Exec select.
2002
 
 
2003
 
  @todo
2004
 
    Note, that create_sort_index calls test_if_skip_sort_order and may
2005
 
    finally replace sorting with index scan if there is a LIMIT clause in
2006
 
    the query.  It's never shown in EXPLAIN!
2007
 
 
2008
 
  @todo
2009
 
    When can we have here thd->net.report_error not zero?
2010
 
*/
2011
 
void
2012
 
JOIN::exec()
2013
 
{
2014
 
  List<Item> *columns_list= &fields_list;
2015
 
  int      tmp_error;
2016
 
 
2017
 
  thd_proc_info(thd, "executing");
2018
 
  error= 0;
2019
 
  (void) result->prepare2(); // Currently, this cannot fail.
2020
 
 
2021
 
  if (!tables_list && (tables || !select_lex->with_sum_func))
2022
 
  {                                           // Only test of functions
2023
 
    if (select_options & SELECT_DESCRIBE)
2024
 
      select_describe(this, false, false, false,
2025
 
                      (zero_result_cause?zero_result_cause:"No tables used"));
2026
 
    else
2027
 
    {
2028
 
      result->send_fields(*columns_list,
2029
 
                          Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2030
 
      /*
2031
 
        We have to test for 'conds' here as the WHERE may not be constant
2032
 
        even if we don't have any tables for prepared statements or if
2033
 
        conds uses something like 'rand()'.
2034
 
      */
2035
 
      if (cond_value != Item::COND_FALSE &&
2036
 
          (!conds || conds->val_int()) &&
2037
 
          (!having || having->val_int()))
2038
 
      {
2039
 
        if (do_send_rows && result->send_data(fields_list))
2040
 
          error= 1;
2041
 
        else
2042
 
        {
2043
 
          error= (int) result->send_eof();
2044
 
          send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 :
2045
 
                         thd->sent_row_count);
2046
 
        }
2047
 
      }
2048
 
      else
2049
 
      {
2050
 
        error=(int) result->send_eof();
2051
 
        send_records= 0;
2052
 
      }
2053
 
    }
2054
 
    /* Single select (without union) always returns 0 or 1 row */
2055
 
    thd->limit_found_rows= send_records;
2056
 
    thd->examined_row_count= 0;
2057
 
    return;
2058
 
  }
2059
 
  /*
2060
 
    Don't reset the found rows count if there're no tables as
2061
 
    FOUND_ROWS() may be called. Never reset the examined row count here.
2062
 
    It must be accumulated from all join iterations of all join parts.
2063
 
  */
2064
 
  if (tables)
2065
 
    thd->limit_found_rows= 0;
2066
 
 
2067
 
  if (zero_result_cause)
2068
 
  {
2069
 
    (void) return_zero_rows(this, result, select_lex->leaf_tables,
2070
 
                            *columns_list,
2071
 
                            send_row_on_empty_set(),
2072
 
                            select_options,
2073
 
                            zero_result_cause,
2074
 
                            having);
2075
 
    return;
2076
 
  }
2077
 
 
2078
 
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) &&
2079
 
      get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
2080
 
    return;
2081
 
 
2082
 
  if (select_options & SELECT_DESCRIBE)
2083
 
  {
2084
 
    /*
2085
 
      Check if we managed to optimize order_st BY away and don't use temporary
2086
 
      table to resolve order_st BY: in that case, we only may need to do
2087
 
      filesort for GROUP BY.
2088
 
    */
2089
 
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
2090
 
    {
2091
 
      /*
2092
 
        Reset 'order' to 'group_list' and reinit variables describing
2093
 
        'order'
2094
 
      */
2095
 
      order= group_list;
2096
 
      simple_order= simple_group;
2097
 
      skip_sort_order= 0;
2098
 
    }
2099
 
    if (order && 
2100
 
        (order != group_list || !(select_options & SELECT_BIG_RESULT)) &&
2101
 
        (const_tables == tables ||
2102
 
         ((simple_order || skip_sort_order) &&
2103
 
          test_if_skip_sort_order(&join_tab[const_tables], order,
2104
 
                                  select_limit, 0, 
2105
 
                                  &join_tab[const_tables].table->
2106
 
                                    keys_in_use_for_query))))
2107
 
      order=0;
2108
 
    having= tmp_having;
2109
 
    select_describe(this, need_tmp,
2110
 
                    order != 0 && !skip_sort_order,
2111
 
                    select_distinct,
2112
 
                    !tables ? "No tables used" : NULL);
2113
 
    return;
2114
 
  }
2115
 
 
2116
 
  JOIN *curr_join= this;
2117
 
  List<Item> *curr_all_fields= &all_fields;
2118
 
  List<Item> *curr_fields_list= &fields_list;
2119
 
  Table *curr_tmp_table= 0;
2120
 
  /*
2121
 
    Initialize examined rows here because the values from all join parts
2122
 
    must be accumulated in examined_row_count. Hence every join
2123
 
    iteration must count from zero.
2124
 
  */
2125
 
  curr_join->examined_rows= 0;
2126
 
 
2127
 
  /* Create a tmp table if distinct or if the sort is too complicated */
2128
 
  if (need_tmp)
2129
 
  {
2130
 
    if (tmp_join)
2131
 
    {
2132
 
      /*
2133
 
        We are in a non cacheable sub query. Get the saved join structure
2134
 
        after optimization.
2135
 
        (curr_join may have been modified during last exection and we need
2136
 
        to reset it)
2137
 
      */
2138
 
      curr_join= tmp_join;
2139
 
    }
2140
 
    curr_tmp_table= exec_tmp_table1;
2141
 
 
2142
 
    /* Copy data to the temporary table */
2143
 
    thd_proc_info(thd, "Copying to tmp table");
2144
 
    if (!curr_join->sort_and_group &&
2145
 
        curr_join->const_tables != curr_join->tables)
2146
 
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
2147
 
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2148
 
    {
2149
 
      error= tmp_error;
2150
 
      return;
2151
 
    }
2152
 
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
2153
 
    
2154
 
    if (curr_join->having)
2155
 
      curr_join->having= curr_join->tmp_having= 0; // Allready done
2156
 
    
2157
 
    /* Change sum_fields reference to calculated fields in tmp_table */
2158
 
    curr_join->all_fields= *curr_all_fields;
2159
 
    if (!items1)
2160
 
    {
2161
 
      items1= items0 + all_fields.elements;
2162
 
      if (sort_and_group || curr_tmp_table->group)
2163
 
      {
2164
 
        if (change_to_use_tmp_fields(thd, items1,
2165
 
                                     tmp_fields_list1, tmp_all_fields1,
2166
 
                                     fields_list.elements, all_fields))
2167
 
          return;
2168
 
      }
2169
 
      else
2170
 
      {
2171
 
        if (change_refs_to_tmp_fields(thd, items1,
2172
 
                                      tmp_fields_list1, tmp_all_fields1,
2173
 
                                      fields_list.elements, all_fields))
2174
 
          return;
2175
 
      }
2176
 
      curr_join->tmp_all_fields1= tmp_all_fields1;
2177
 
      curr_join->tmp_fields_list1= tmp_fields_list1;
2178
 
      curr_join->items1= items1;
2179
 
    }
2180
 
    curr_all_fields= &tmp_all_fields1;
2181
 
    curr_fields_list= &tmp_fields_list1;
2182
 
    curr_join->set_items_ref_array(items1);
2183
 
    
2184
 
    if (sort_and_group || curr_tmp_table->group)
2185
 
    {
2186
 
      curr_join->tmp_table_param.field_count+= 
2187
 
        curr_join->tmp_table_param.sum_func_count+
2188
 
        curr_join->tmp_table_param.func_count;
2189
 
      curr_join->tmp_table_param.sum_func_count= 
2190
 
        curr_join->tmp_table_param.func_count= 0;
2191
 
    }
2192
 
    else
2193
 
    {
2194
 
      curr_join->tmp_table_param.field_count+= 
2195
 
        curr_join->tmp_table_param.func_count;
2196
 
      curr_join->tmp_table_param.func_count= 0;
2197
 
    }
2198
 
    
2199
 
    if (curr_tmp_table->group)
2200
 
    {                                           // Already grouped
2201
 
      if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
2202
 
        curr_join->order= curr_join->group_list;  /* order by group */
2203
 
      curr_join->group_list= 0;
2204
 
    }
2205
 
    
2206
 
    /*
2207
 
      If we have different sort & group then we must sort the data by group
2208
 
      and copy it to another tmp table
2209
 
      This code is also used if we are using distinct something
2210
 
      we haven't been able to store in the temporary table yet
2211
 
      like SEC_TO_TIME(SUM(...)).
2212
 
    */
2213
 
 
2214
 
    if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
2215
 
    {                                   /* Must copy to another table */
2216
 
      /* Free first data from old join */
2217
 
      curr_join->join_free();
2218
 
      if (make_simple_join(curr_join, curr_tmp_table))
2219
 
        return;
2220
 
      calc_group_buffer(curr_join, group_list);
2221
 
      count_field_types(select_lex, &curr_join->tmp_table_param,
2222
 
                        curr_join->tmp_all_fields1,
2223
 
                        curr_join->select_distinct && !curr_join->group_list);
2224
 
      curr_join->tmp_table_param.hidden_field_count= 
2225
 
        (curr_join->tmp_all_fields1.elements-
2226
 
         curr_join->tmp_fields_list1.elements);
2227
 
      
2228
 
      
2229
 
      if (exec_tmp_table2)
2230
 
        curr_tmp_table= exec_tmp_table2;
2231
 
      else
2232
 
      {
2233
 
        /* group data to new table */
2234
 
 
2235
 
        /*
2236
 
          If the access method is loose index scan then all MIN/MAX
2237
 
          functions are precomputed, and should be treated as regular
2238
 
          functions. See extended comment in JOIN::exec.
2239
 
        */
2240
 
        if (curr_join->join_tab->is_using_loose_index_scan())
2241
 
          curr_join->tmp_table_param.precomputed_group_by= true;
2242
 
 
2243
 
        if (!(curr_tmp_table=
2244
 
              exec_tmp_table2= create_tmp_table(thd,
2245
 
                                                &curr_join->tmp_table_param,
2246
 
                                                *curr_all_fields,
2247
 
                                                (order_st*) 0,
2248
 
                                                curr_join->select_distinct && 
2249
 
                                                !curr_join->group_list,
2250
 
                                                1, curr_join->select_options,
2251
 
                                                HA_POS_ERROR,
2252
 
                                                (char *) "")))
2253
 
          return;
2254
 
        curr_join->exec_tmp_table2= exec_tmp_table2;
2255
 
      }
2256
 
      if (curr_join->group_list)
2257
 
      {
2258
 
        thd_proc_info(thd, "Creating sort index");
2259
 
        if (curr_join->join_tab == join_tab && save_join_tab())
2260
 
        {
2261
 
          return;
2262
 
        }
2263
 
        if (create_sort_index(thd, curr_join, curr_join->group_list,
2264
 
                              HA_POS_ERROR, HA_POS_ERROR, false) ||
2265
 
            make_group_fields(this, curr_join))
2266
 
        {
2267
 
          return;
2268
 
        }
2269
 
        sortorder= curr_join->sortorder;
2270
 
      }
2271
 
      
2272
 
      thd_proc_info(thd, "Copying to group table");
2273
 
      tmp_error= -1;
2274
 
      if (curr_join != this)
2275
 
      {
2276
 
        if (sum_funcs2)
2277
 
        {
2278
 
          curr_join->sum_funcs= sum_funcs2;
2279
 
          curr_join->sum_funcs_end= sum_funcs_end2; 
2280
 
        }
2281
 
        else
2282
 
        {
2283
 
          curr_join->alloc_func_list();
2284
 
          sum_funcs2= curr_join->sum_funcs;
2285
 
          sum_funcs_end2= curr_join->sum_funcs_end;
2286
 
        }
2287
 
      }
2288
 
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2289
 
                                        1, true))
2290
 
        return;
2291
 
      curr_join->group_list= 0;
2292
 
      if (!curr_join->sort_and_group &&
2293
 
          curr_join->const_tables != curr_join->tables)
2294
 
        curr_join->join_tab[curr_join->const_tables].sorted= 0;
2295
 
      if (setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2296
 
          (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2297
 
      {
2298
 
        error= tmp_error;
2299
 
        return;
2300
 
      }
2301
 
      end_read_record(&curr_join->join_tab->read_record);
2302
 
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
2303
 
      curr_join->join_tab[0].table= 0;           // Table is freed
2304
 
      
2305
 
      // No sum funcs anymore
2306
 
      if (!items2)
2307
 
      {
2308
 
        items2= items1 + all_fields.elements;
2309
 
        if (change_to_use_tmp_fields(thd, items2,
2310
 
                                     tmp_fields_list2, tmp_all_fields2, 
2311
 
                                     fields_list.elements, tmp_all_fields1))
2312
 
          return;
2313
 
        curr_join->tmp_fields_list2= tmp_fields_list2;
2314
 
        curr_join->tmp_all_fields2= tmp_all_fields2;
2315
 
      }
2316
 
      curr_fields_list= &curr_join->tmp_fields_list2;
2317
 
      curr_all_fields= &curr_join->tmp_all_fields2;
2318
 
      curr_join->set_items_ref_array(items2);
2319
 
      curr_join->tmp_table_param.field_count+= 
2320
 
        curr_join->tmp_table_param.sum_func_count;
2321
 
      curr_join->tmp_table_param.sum_func_count= 0;
2322
 
    }
2323
 
    if (curr_tmp_table->distinct)
2324
 
      curr_join->select_distinct=0;             /* Each row is unique */
2325
 
    
2326
 
    curr_join->join_free();                     /* Free quick selects */
2327
 
    if (curr_join->select_distinct && ! curr_join->group_list)
2328
 
    {
2329
 
      thd_proc_info(thd, "Removing duplicates");
2330
 
      if (curr_join->tmp_having)
2331
 
        curr_join->tmp_having->update_used_tables();
2332
 
      if (remove_duplicates(curr_join, curr_tmp_table,
2333
 
                            *curr_fields_list, curr_join->tmp_having))
2334
 
        return;
2335
 
      curr_join->tmp_having=0;
2336
 
      curr_join->select_distinct=0;
2337
 
    }
2338
 
    curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
2339
 
    if (make_simple_join(curr_join, curr_tmp_table))
2340
 
      return;
2341
 
    calc_group_buffer(curr_join, curr_join->group_list);
2342
 
    count_field_types(select_lex, &curr_join->tmp_table_param, 
2343
 
                      *curr_all_fields, 0);
2344
 
    
2345
 
  }
2346
 
  
2347
 
  if (curr_join->group || curr_join->tmp_table_param.sum_func_count)
2348
 
  {
2349
 
    if (make_group_fields(this, curr_join))
2350
 
    {
2351
 
      return;
2352
 
    }
2353
 
    if (!items3)
2354
 
    {
2355
 
      if (!items0)
2356
 
        init_items_ref_array();
2357
 
      items3= ref_pointer_array + (all_fields.elements*4);
2358
 
      setup_copy_fields(thd, &curr_join->tmp_table_param,
2359
 
                        items3, tmp_fields_list3, tmp_all_fields3,
2360
 
                        curr_fields_list->elements, *curr_all_fields);
2361
 
      tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
2362
 
      tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
2363
 
      tmp_table_param.save_copy_field_end=
2364
 
        curr_join->tmp_table_param.copy_field_end;
2365
 
      curr_join->tmp_all_fields3= tmp_all_fields3;
2366
 
      curr_join->tmp_fields_list3= tmp_fields_list3;
2367
 
    }
2368
 
    else
2369
 
    {
2370
 
      curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
2371
 
      curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
2372
 
      curr_join->tmp_table_param.copy_field_end=
2373
 
        tmp_table_param.save_copy_field_end;
2374
 
    }
2375
 
    curr_fields_list= &tmp_fields_list3;
2376
 
    curr_all_fields= &tmp_all_fields3;
2377
 
    curr_join->set_items_ref_array(items3);
2378
 
 
2379
 
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2380
 
                                      1, true) || 
2381
 
        setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2382
 
        thd->is_fatal_error)
2383
 
      return;
2384
 
  }
2385
 
  if (curr_join->group_list || curr_join->order)
2386
 
  {
2387
 
    thd_proc_info(thd, "Sorting result");
2388
 
    /* If we have already done the group, add HAVING to sorted table */
2389
 
    if (curr_join->tmp_having && ! curr_join->group_list && 
2390
 
        ! curr_join->sort_and_group)
2391
 
    {
2392
 
      // Some tables may have been const
2393
 
      curr_join->tmp_having->update_used_tables();
2394
 
      JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables];
2395
 
      table_map used_tables= (curr_join->const_table_map |
2396
 
                              curr_table->table->map);
2397
 
 
2398
 
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
2399
 
                                                 used_tables,
2400
 
                                                 used_tables, 0);
2401
 
      if (sort_table_cond)
2402
 
      {
2403
 
        if (!curr_table->select)
2404
 
          if (!(curr_table->select= new SQL_SELECT))
2405
 
            return;
2406
 
        if (!curr_table->select->cond)
2407
 
          curr_table->select->cond= sort_table_cond;
2408
 
        else                                    // This should never happen
2409
 
        {
2410
 
          if (!(curr_table->select->cond=
2411
 
                new Item_cond_and(curr_table->select->cond,
2412
 
                                  sort_table_cond)))
2413
 
            return;
2414
 
          /*
2415
 
            Item_cond_and do not need fix_fields for execution, its parameters
2416
 
            are fixed or do not need fix_fields, too
2417
 
          */
2418
 
          curr_table->select->cond->quick_fix_field();
2419
 
        }
2420
 
        curr_table->select_cond= curr_table->select->cond;
2421
 
        curr_table->select_cond->top_level_item();
2422
 
        curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2423
 
                                                   ~ (table_map) 0,
2424
 
                                                   ~used_tables, 0);
2425
 
      }
2426
 
    }
2427
 
    {
2428
 
      if (group)
2429
 
        curr_join->select_limit= HA_POS_ERROR;
2430
 
      else
2431
 
      {
2432
 
        /*
2433
 
          We can abort sorting after thd->select_limit rows if we there is no
2434
 
          WHERE clause for any tables after the sorted one.
2435
 
        */
2436
 
        JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
2437
 
        JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
2438
 
        for (; curr_table < end_table ; curr_table++)
2439
 
        {
2440
 
          /*
2441
 
            table->keyuse is set in the case there was an original WHERE clause
2442
 
            on the table that was optimized away.
2443
 
          */
2444
 
          if (curr_table->select_cond ||
2445
 
              (curr_table->keyuse && !curr_table->first_inner))
2446
 
          {
2447
 
            /* We have to sort all rows */
2448
 
            curr_join->select_limit= HA_POS_ERROR;
2449
 
            break;
2450
 
          }
2451
 
        }
2452
 
      }
2453
 
      if (curr_join->join_tab == join_tab && save_join_tab())
2454
 
      {
2455
 
        return;
2456
 
      }
2457
 
      /*
2458
 
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
2459
 
        chose FILESORT to be faster than INDEX SCAN or there is no 
2460
 
        suitable index present.
2461
 
        Note, that create_sort_index calls test_if_skip_sort_order and may
2462
 
        finally replace sorting with index scan if there is a LIMIT clause in
2463
 
        the query. XXX: it's never shown in EXPLAIN!
2464
 
        OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
2465
 
      */
2466
 
      if (create_sort_index(thd, curr_join,
2467
 
                            curr_join->group_list ? 
2468
 
                            curr_join->group_list : curr_join->order,
2469
 
                            curr_join->select_limit,
2470
 
                            (select_options & OPTION_FOUND_ROWS ?
2471
 
                             HA_POS_ERROR : unit->select_limit_cnt),
2472
 
                            curr_join->group_list ? true : false))
2473
 
        return;
2474
 
      sortorder= curr_join->sortorder;
2475
 
      if (curr_join->const_tables != curr_join->tables &&
2476
 
          !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
2477
 
      {
2478
 
        /*
2479
 
          If no IO cache exists for the first table then we are using an
2480
 
          INDEX SCAN and no filesort. Thus we should not remove the sorted
2481
 
          attribute on the INDEX SCAN.
2482
 
        */
2483
 
        skip_sort_order= 1;
2484
 
      }
2485
 
    }
2486
 
  }
2487
 
  /* XXX: When can we have here thd->is_error() not zero? */
2488
 
  if (thd->is_error())
2489
 
  {
2490
 
    error= thd->is_error();
2491
 
    return;
2492
 
  }
2493
 
  curr_join->having= curr_join->tmp_having;
2494
 
  curr_join->fields= curr_fields_list;
2495
 
 
2496
 
  {
2497
 
    thd_proc_info(thd, "Sending data");
2498
 
    result->send_fields(*curr_fields_list,
2499
 
                        Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2500
 
    error= do_select(curr_join, curr_fields_list, NULL);
2501
 
    thd->limit_found_rows= curr_join->send_records;
2502
 
  }
2503
 
 
2504
 
  /* Accumulate the counts from all join iterations of all join parts. */
2505
 
  thd->examined_row_count+= curr_join->examined_rows;
2506
 
 
2507
 
  /* 
2508
 
    With EXPLAIN EXTENDED we have to restore original ref_array
2509
 
    for a derived table which is always materialized.
2510
 
    Otherwise we would not be able to print the query  correctly.
2511
 
  */ 
2512
 
  if (items0 &&
2513
 
      (thd->lex->describe & DESCRIBE_EXTENDED) &&
2514
 
      select_lex->linkage == DERIVED_TABLE_TYPE)      
2515
 
    set_items_ref_array(items0);
2516
 
 
2517
 
  return;
2518
 
}
2519
 
 
2520
 
 
2521
 
/**
2522
 
  Clean up join.
2523
 
 
2524
 
  @return
2525
 
    Return error that hold JOIN.
2526
 
*/
2527
 
 
2528
 
int
2529
 
JOIN::destroy()
2530
 
{
2531
 
  select_lex->join= 0;
2532
 
 
2533
 
  if (tmp_join)
2534
 
  {
2535
 
    if (join_tab != tmp_join->join_tab)
2536
 
    {
2537
 
      JOIN_TAB *tab, *end;
2538
 
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
2539
 
        tab->cleanup();
2540
 
    }
2541
 
    tmp_join->tmp_join= 0;
2542
 
    tmp_table_param.copy_field=0;
2543
 
    return(tmp_join->destroy());
2544
 
  }
2545
 
  cond_equal= 0;
2546
 
 
2547
 
  cleanup(1);
2548
 
  if (exec_tmp_table1)
2549
 
    exec_tmp_table1->free_tmp_table(thd);
2550
 
  if (exec_tmp_table2)
2551
 
    exec_tmp_table2->free_tmp_table(thd);
2552
 
  delete select;
2553
 
  delete_dynamic(&keyuse);
2554
 
  return(error);
2555
 
}
2556
 
 
2557
 
 
2558
 
 
2559
315
/**
2560
316
  An entry point to single-unit select (a select without UNION).
2561
317
 
2562
 
  @param thd                  thread handler
 
318
  @param session                  thread handler
2563
319
  @param rref_pointer_array   a reference to ref_pointer_array of
2564
320
                              the top-level select_lex for this query
2565
321
  @param tables               list of all tables used in this query.
2566
322
                              The tables have been pre-opened.
2567
 
  @param wild_num             number of wildcards used in the top level 
 
323
  @param wild_num             number of wildcards used in the top level
2568
324
                              select of this query.
2569
325
                              For example statement
2570
326
                              SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
2580
336
  @param order                linked list of order_st BY agruments
2581
337
  @param group                linked list of GROUP BY arguments
2582
338
  @param having               top level item of HAVING expression
2583
 
  @param proc_param           list of PROCEDUREs
2584
339
  @param select_options       select options (BIG_RESULT, etc)
2585
340
  @param result               an instance of result set handling class.
2586
341
                              This object is responsible for send result
2587
342
                              set rows to the client or inserting them
2588
343
                              into a table.
2589
 
  @param select_lex           the only SELECT_LEX of this query
 
344
  @param select_lex           the only Select_Lex of this query
2590
345
  @param unit                 top-level UNIT of this query
2591
346
                              UNIT is an artificial object created by the
2592
347
                              parser for every SELECT clause.
2599
354
  @retval
2600
355
    true   an error
2601
356
*/
2602
 
 
2603
 
bool
2604
 
mysql_select(THD *thd, Item ***rref_pointer_array,
2605
 
             TableList *tables, uint32_t wild_num, List<Item> &fields,
2606
 
             COND *conds, uint32_t og_num,  order_st *order, order_st *group,
2607
 
             Item *having, order_st *proc_param, uint64_t select_options,
2608
 
             select_result *result, SELECT_LEX_UNIT *unit,
2609
 
             SELECT_LEX *select_lex)
 
357
bool mysql_select(Session *session,
 
358
                  Item ***rref_pointer_array,
 
359
                        TableList *tables, 
 
360
                  uint32_t wild_num, 
 
361
                  List<Item> &fields,
 
362
                        COND *conds, 
 
363
                  uint32_t og_num,  
 
364
                  order_st *order, 
 
365
                  order_st *group,
 
366
                        Item *having, 
 
367
                  uint64_t select_options,
 
368
                        select_result *result, 
 
369
                  Select_Lex_Unit *unit,
 
370
                        Select_Lex *select_lex)
2610
371
{
2611
372
  bool err;
2612
373
  bool free_join= 1;
2621
382
      creation
2622
383
    */
2623
384
    if (select_lex->linkage != DERIVED_TABLE_TYPE ||
2624
 
        (select_options & SELECT_DESCRIBE))
 
385
        (select_options & SELECT_DESCRIBE))
2625
386
    {
2626
387
      if (select_lex->linkage != GLOBAL_OPTIONS_TYPE)
2627
388
      {
2628
 
        //here is EXPLAIN of subselect or derived table
2629
 
        if (join->change_result(result))
2630
 
        {
2631
 
          return(true);
2632
 
        }
 
389
        //here is EXPLAIN of subselect or derived table
 
390
        if (join->change_result(result))
 
391
        {
 
392
          return(true);
 
393
        }
2633
394
      }
2634
395
      else
2635
396
      {
2636
397
        if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2637
 
                               conds, og_num, order, group, having, proc_param,
2638
 
                               select_lex, unit)))
2639
 
        {
2640
 
          goto err;
2641
 
        }
 
398
                               conds, og_num, order, group, having, select_lex, unit)))
 
399
        {
 
400
          goto err;
 
401
        }
2642
402
      }
2643
403
    }
2644
404
    free_join= 0;
2646
406
  }
2647
407
  else
2648
408
  {
2649
 
    if (!(join= new JOIN(thd, fields, select_options, result)))
2650
 
        return(true);
2651
 
    thd_proc_info(thd, "init");
2652
 
    thd->used_tables=0;                         // Updated by setup_fields
 
409
    if (!(join= new JOIN(session, fields, select_options, result)))
 
410
      return(true);
 
411
    session->set_proc_info("init");
 
412
    session->used_tables=0;                         // Updated by setup_fields
2653
413
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2654
 
                           conds, og_num, order, group, having, proc_param,
 
414
                           conds, og_num, order, group, having,
2655
415
                           select_lex, unit)) == true)
2656
416
    {
2657
417
      goto err;
2658
418
    }
2659
419
  }
2660
420
 
2661
 
  /* dump_TableList_graph(select_lex, select_lex->leaf_tables); */
2662
 
  if (join->flatten_subqueries())
2663
 
  {
2664
 
    err= 1;
2665
 
    goto err;
2666
 
  }
2667
 
  /* dump_TableList_struct(select_lex, select_lex->leaf_tables); */
2668
 
 
2669
421
  if ((err= join->optimize()))
2670
422
  {
2671
423
    goto err;                                   // 1
2672
424
  }
2673
425
 
2674
 
  if (thd->lex->describe & DESCRIBE_EXTENDED)
 
426
  if (session->lex->describe & DESCRIBE_EXTENDED)
2675
427
  {
2676
428
    join->conds_history= join->conds;
2677
429
    join->having_history= (join->having?join->having:join->tmp_having);
2678
430
  }
2679
431
 
2680
 
  if (thd->is_error())
 
432
  if (session->is_error())
2681
433
    goto err;
2682
434
 
2683
435
  join->exec();
2684
436
 
2685
 
  if (thd->lex->describe & DESCRIBE_EXTENDED)
 
437
  if (session->lex->describe & DESCRIBE_EXTENDED)
2686
438
  {
2687
439
    select_lex->where= join->conds_history;
2688
440
    select_lex->having= join->having_history;
2691
443
err:
2692
444
  if (free_join)
2693
445
  {
2694
 
    thd_proc_info(thd, "end");
 
446
    session->set_proc_info("end");
2695
447
    err|= select_lex->cleanup();
2696
 
    return(err || thd->is_error());
 
448
    return(err || session->is_error());
2697
449
  }
2698
450
  return(join->error);
2699
451
}
2700
452
 
2701
 
 
2702
 
int subq_sj_candidate_cmp(Item_in_subselect* const *el1, 
2703
 
                          Item_in_subselect* const *el2)
2704
 
{
2705
 
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 : 
2706
 
         ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
2707
 
}
2708
 
 
2709
 
 
2710
 
inline Item * and_items(Item* cond, Item *item)
 
453
inline Item *and_items(Item* cond, Item *item)
2711
454
{
2712
455
  return (cond? (new Item_cond_and(cond, item)) : item);
2713
456
}
2714
457
 
2715
 
 
2716
 
static TableList *alloc_join_nest(THD *thd)
2717
 
{
2718
 
  TableList *tbl;
2719
 
  if (!(tbl= (TableList*) thd->calloc(ALIGN_SIZE(sizeof(TableList))+
2720
 
                                       sizeof(nested_join_st))))
2721
 
    return NULL;
2722
 
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl + 
2723
 
                                    ALIGN_SIZE(sizeof(TableList)));
2724
 
  return tbl;
2725
 
}
2726
 
 
2727
 
 
2728
 
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TableList> *tlist)
 
458
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
2729
459
{
2730
460
  List_iterator<TableList> it(*tlist);
2731
461
  TableList *table;
2738
468
  }
2739
469
}
2740
470
 
2741
 
 
2742
 
/*
2743
 
  Convert a subquery predicate into a TableList semi-join nest
2744
 
 
2745
 
  SYNOPSIS
2746
 
    convert_subq_to_sj()
2747
 
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON 
2748
 
                    clause
2749
 
       subq_pred    Subquery predicate to be converted
2750
 
  
2751
 
  DESCRIPTION
2752
 
    Convert a subquery predicate into a TableList semi-join nest. All the 
2753
 
    prerequisites are already checked, so the conversion is always successfull.
2754
 
 
2755
 
    Prepared Statements: the transformation is permanent:
2756
 
     - Changes in TableList structures are naturally permanent
2757
 
     - Item tree changes are performed on statement MEM_ROOT:
2758
 
        = we activate statement MEM_ROOT 
2759
 
        = this function is called before the first fix_prepare_information
2760
 
          call.
2761
 
 
2762
 
    This is intended because the criteria for subquery-to-sj conversion remain
2763
 
    constant for the lifetime of the Prepared Statement.
2764
 
 
2765
 
  RETURN
2766
 
    false  OK
2767
 
    true   Out of memory error
2768
 
*/
2769
 
 
2770
 
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
2771
 
{
2772
 
  SELECT_LEX *parent_lex= parent_join->select_lex;
2773
 
  TableList *emb_tbl_nest= NULL;
2774
 
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
2775
 
  THD *thd= parent_join->thd;
2776
 
 
2777
 
  /*
2778
 
    1. Find out where to put the predicate into.
2779
 
     Note: for "t1 LEFT JOIN t2" this will be t2, a leaf.
2780
 
  */
2781
 
  if ((void*)subq_pred->expr_join_nest != (void*)1)
2782
 
  {
2783
 
    if (subq_pred->expr_join_nest->nested_join)
2784
 
    {
2785
 
      /*
2786
 
        We're dealing with
2787
 
 
2788
 
          ... [LEFT] JOIN  ( ... ) ON (subquery AND whatever) ...
2789
 
 
2790
 
        The sj-nest will be inserted into the brackets nest.
2791
 
      */
2792
 
      emb_tbl_nest=  subq_pred->expr_join_nest;
2793
 
      emb_join_list= &emb_tbl_nest->nested_join->join_list;
2794
 
    }
2795
 
    else if (!subq_pred->expr_join_nest->outer_join)
2796
 
    {
2797
 
      /*
2798
 
        We're dealing with
2799
 
 
2800
 
          ... INNER JOIN tblX ON (subquery AND whatever) ...
2801
 
 
2802
 
        The sj-nest will be tblX's "sibling", i.e. another child of its
2803
 
        parent. This is ok because tblX is joined as an inner join.
2804
 
      */
2805
 
      emb_tbl_nest= subq_pred->expr_join_nest->embedding;
2806
 
      if (emb_tbl_nest)
2807
 
        emb_join_list= &emb_tbl_nest->nested_join->join_list;
2808
 
    }
2809
 
    else if (!subq_pred->expr_join_nest->nested_join)
2810
 
    {
2811
 
      TableList *outer_tbl= subq_pred->expr_join_nest;      
2812
 
      TableList *wrap_nest;
2813
 
      /*
2814
 
        We're dealing with
2815
 
 
2816
 
          ... LEFT JOIN tbl ON (on_expr AND subq_pred) ...
2817
 
 
2818
 
        we'll need to convert it into:
2819
 
 
2820
 
          ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
2821
 
                        |                      |
2822
 
                        |<----- wrap_nest ---->|
2823
 
        
2824
 
        Q:  other subqueries may be pointing to this element. What to do?
2825
 
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
2826
 
            But we'll need to fix other pointers.
2827
 
        A2: Another way: have TableList::next_ptr so the following
2828
 
            subqueries know the table has been nested.
2829
 
        A3: changes in the TableList::outer_join will make everything work
2830
 
            automatically.
2831
 
      */
2832
 
      if (!(wrap_nest= alloc_join_nest(parent_join->thd)))
2833
 
      {
2834
 
        return(true);
2835
 
      }
2836
 
      wrap_nest->embedding= outer_tbl->embedding;
2837
 
      wrap_nest->join_list= outer_tbl->join_list;
2838
 
      wrap_nest->alias= (char*) "(sj-wrap)";
2839
 
 
2840
 
      wrap_nest->nested_join->join_list.empty();
2841
 
      wrap_nest->nested_join->join_list.push_back(outer_tbl);
2842
 
 
2843
 
      outer_tbl->embedding= wrap_nest;
2844
 
      outer_tbl->join_list= &wrap_nest->nested_join->join_list;
2845
 
 
2846
 
      /*
2847
 
        wrap_nest will take place of outer_tbl, so move the outer join flag
2848
 
        and on_expr
2849
 
      */
2850
 
      wrap_nest->outer_join= outer_tbl->outer_join;
2851
 
      outer_tbl->outer_join= 0;
2852
 
 
2853
 
      wrap_nest->on_expr= outer_tbl->on_expr;
2854
 
      outer_tbl->on_expr= NULL;
2855
 
 
2856
 
      List_iterator<TableList> li(*wrap_nest->join_list);
2857
 
      TableList *tbl;
2858
 
      while ((tbl= li++))
2859
 
      {
2860
 
        if (tbl == outer_tbl)
2861
 
        {
2862
 
          li.replace(wrap_nest);
2863
 
          break;
2864
 
        }
2865
 
      }
2866
 
      /*
2867
 
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the 
2868
 
        semi-join nest into it
2869
 
      */
2870
 
      emb_join_list= &wrap_nest->nested_join->join_list;
2871
 
      emb_tbl_nest=  wrap_nest;
2872
 
    }
2873
 
  }
2874
 
 
2875
 
  TableList *sj_nest;
2876
 
  nested_join_st *nested_join;
2877
 
  if (!(sj_nest= alloc_join_nest(parent_join->thd)))
2878
 
  {
2879
 
    return(true);
2880
 
  }
2881
 
  nested_join= sj_nest->nested_join;
2882
 
 
2883
 
  sj_nest->join_list= emb_join_list;
2884
 
  sj_nest->embedding= emb_tbl_nest;
2885
 
  sj_nest->alias= (char*) "(sj-nest)";
2886
 
  /* Nests do not participate in those 'chains', so: */
2887
 
  /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
2888
 
  emb_join_list->push_back(sj_nest);
2889
 
 
2890
 
  /* 
2891
 
    nested_join->used_tables and nested_join->not_null_tables are
2892
 
    initialized in simplify_joins().
2893
 
  */
2894
 
  
2895
 
  /* 
2896
 
    2. Walk through subquery's top list and set 'embedding' to point to the
2897
 
       sj-nest.
2898
 
  */
2899
 
  st_select_lex *subq_lex= subq_pred->unit->first_select();
2900
 
  nested_join->join_list.empty();
2901
 
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
2902
 
  TableList *tl, *last_leaf;
2903
 
  while ((tl= li++))
2904
 
  {
2905
 
    tl->embedding= sj_nest;
2906
 
    tl->join_list= &nested_join->join_list;
2907
 
    nested_join->join_list.push_back(tl);
2908
 
  }
2909
 
  
2910
 
  /*
2911
 
    Reconnect the next_leaf chain.
2912
 
    TODO: Do we have to put subquery's tables at the end of the chain?
2913
 
          Inserting them at the beginning would be a bit faster.
2914
 
    NOTE: We actually insert them at the front! That's because the order is
2915
 
          reversed in this list.
2916
 
  */
2917
 
  for (tl= parent_lex->leaf_tables; tl->next_leaf; tl= tl->next_leaf) {};
2918
 
  tl->next_leaf= subq_lex->leaf_tables;
2919
 
  last_leaf= tl;
2920
 
 
2921
 
  /*
2922
 
    Same as above for next_local chain
2923
 
    (a theory: a next_local chain always starts with ::leaf_tables
2924
 
     because view's tables are inserted after the view)
2925
 
  */
2926
 
  for (tl= parent_lex->leaf_tables; tl->next_local; tl= tl->next_local) {};
2927
 
  tl->next_local= subq_lex->leaf_tables;
2928
 
 
2929
 
  /* A theory: no need to re-connect the next_global chain */
2930
 
 
2931
 
  /* 3. Remove the original subquery predicate from the WHERE/ON */
2932
 
 
2933
 
  // The subqueries were replaced for Item_int(1) earlier
2934
 
  subq_pred->exec_method= Item_in_subselect::SEMI_JOIN; // for subsequent executions
2935
 
  /*TODO: also reset the 'with_subselect' there. */
2936
 
 
2937
 
  /* n. Adjust the parent_join->tables counter */
2938
 
  uint32_t table_no= parent_join->tables;
2939
 
  /* n. Walk through child's tables and adjust table->map */
2940
 
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
2941
 
  {
2942
 
    tl->table->tablenr= table_no;
2943
 
    tl->table->map= ((table_map)1) << table_no;
2944
 
    SELECT_LEX *old_sl= tl->select_lex;
2945
 
    tl->select_lex= parent_join->select_lex; 
2946
 
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
2947
 
      emb->select_lex= parent_join->select_lex;
2948
 
  }
2949
 
  parent_join->tables += subq_lex->join->tables;
2950
 
 
2951
 
  /* 
2952
 
    Put the subquery's WHERE into semi-join's sj_on_expr
2953
 
    Add the subquery-induced equalities too.
2954
 
  */
2955
 
  SELECT_LEX *save_lex= thd->lex->current_select;
2956
 
  thd->lex->current_select=subq_lex;
2957
 
  if (!subq_pred->left_expr->fixed &&
2958
 
       subq_pred->left_expr->fix_fields(thd, &subq_pred->left_expr))
2959
 
    return(true);
2960
 
  thd->lex->current_select=save_lex;
2961
 
 
2962
 
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
2963
 
  sj_nest->nested_join->sj_depends_on=  subq_pred->used_tables() |
2964
 
                                        subq_pred->left_expr->used_tables();
2965
 
  sj_nest->sj_on_expr= subq_lex->where;
2966
 
 
2967
 
  /*
2968
 
    Create the IN-equalities and inject them into semi-join's ON expression.
2969
 
    Additionally, for InsideOut strategy
2970
 
     - Record the number of IN-equalities.
2971
 
     - Create list of pointers to (oe1, ..., ieN). We'll need the list to
2972
 
       see which of the expressions are bound and which are not (for those
2973
 
       we'll produce a distinct stream of (ie_i1,...ie_ik).
2974
 
 
2975
 
       (TODO: can we just create a list of pointers and hope the expressions
2976
 
       will not substitute themselves on fix_fields()? or we need to wrap
2977
 
       them into Item_direct_view_refs and store pointers to those. The
2978
 
       pointers to Item_direct_view_refs are guaranteed to be stable as 
2979
 
       Item_direct_view_refs doesn't substitute itself with anything in 
2980
 
       Item_direct_view_ref::fix_fields.
2981
 
  */
2982
 
  sj_nest->sj_in_exprs= subq_pred->left_expr->cols();
2983
 
  sj_nest->nested_join->sj_outer_expr_list.empty();
2984
 
 
2985
 
  if (subq_pred->left_expr->cols() == 1)
2986
 
  {
2987
 
    nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr);
2988
 
 
2989
 
    Item *item_eq= new Item_func_eq(subq_pred->left_expr, 
2990
 
                                    subq_lex->ref_pointer_array[0]);
2991
 
    item_eq->name= (char*)subq_sj_cond_name;
2992
 
    sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
2993
 
  }
2994
 
  else
2995
 
  {
2996
 
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
2997
 
    {
2998
 
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
2999
 
                                                element_index(i));
3000
 
      Item *item_eq= 
3001
 
        new Item_func_eq(subq_pred->left_expr->element_index(i), 
3002
 
                         subq_lex->ref_pointer_array[i]);
3003
 
      item_eq->name= (char*)subq_sj_cond_name + (i % 64);
3004
 
      sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
3005
 
    }
3006
 
  }
3007
 
  /* Fix the created equality and AND */
3008
 
  sj_nest->sj_on_expr->fix_fields(parent_join->thd, &sj_nest->sj_on_expr);
3009
 
 
3010
 
  /*
3011
 
    Walk through sj nest's WHERE and ON expressions and call
3012
 
    item->fix_table_changes() for all items.
3013
 
  */
3014
 
  sj_nest->sj_on_expr->fix_after_pullout(parent_lex, &sj_nest->sj_on_expr);
3015
 
  fix_list_after_tbl_changes(parent_lex, &sj_nest->nested_join->join_list);
3016
 
 
3017
 
 
3018
 
  /* Unlink the child select_lex so it doesn't show up in EXPLAIN: */
3019
 
  subq_lex->master_unit()->exclude_level();
3020
 
 
3021
 
  /* Inject sj_on_expr into the parent's WHERE or ON */
3022
 
  if (emb_tbl_nest)
3023
 
  {
3024
 
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr, 
3025
 
                                     sj_nest->sj_on_expr);
3026
 
    emb_tbl_nest->on_expr->fix_fields(parent_join->thd, &emb_tbl_nest->on_expr);
3027
 
  }
3028
 
  else
3029
 
  {
3030
 
    /* Inject into the WHERE */
3031
 
    parent_join->conds= and_items(parent_join->conds, sj_nest->sj_on_expr);
3032
 
    parent_join->conds->fix_fields(parent_join->thd, &parent_join->conds);
3033
 
    parent_join->select_lex->where= parent_join->conds;
3034
 
  }
3035
 
 
3036
 
  return(false);
3037
 
}
3038
 
 
3039
 
 
3040
 
/*
3041
 
  Convert candidate subquery predicates to semi-joins
3042
 
 
3043
 
  SYNOPSIS
3044
 
    JOIN::flatten_subqueries()
3045
 
 
3046
 
  DESCRIPTION
3047
 
    Convert candidate subquery predicates to semi-joins.
3048
 
 
3049
 
  RETURN 
3050
 
    false  OK
3051
 
    true   Error
3052
 
*/
3053
 
 
3054
 
bool JOIN::flatten_subqueries()
3055
 
{
3056
 
  Item_in_subselect **in_subq;
3057
 
  Item_in_subselect **in_subq_end;
3058
 
 
3059
 
  if (sj_subselects.elements() == 0)
3060
 
    return(false);
3061
 
 
3062
 
  /* 1. Fix children subqueries */
3063
 
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back(); 
3064
 
       in_subq != in_subq_end; in_subq++)
3065
 
  {
3066
 
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
3067
 
    child_join->outer_tables = child_join->tables;
3068
 
    if (child_join->flatten_subqueries())
3069
 
      return(true);
3070
 
    (*in_subq)->sj_convert_priority= 
3071
 
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
3072
 
  }
3073
 
 
3074
 
  //dump_TableList_struct(select_lex, select_lex->leaf_tables);
3075
 
  /* 
3076
 
    2. Pick which subqueries to convert:
3077
 
      sort the subquery array
3078
 
      - prefer correlated subqueries over uncorrelated;
3079
 
      - prefer subqueries that have greater number of outer tables;
3080
 
  */
3081
 
  sj_subselects.sort(subq_sj_candidate_cmp);
3082
 
  // #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
3083
 
  /* Replace all subqueries to be flattened with Item_int(1) */
3084
 
  for (in_subq= sj_subselects.front(); 
3085
 
       in_subq != in_subq_end && 
3086
 
       tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3087
 
       in_subq++)
3088
 
  {
3089
 
    if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
3090
 
      return(true);
3091
 
  }
3092
 
 
3093
 
  for (in_subq= sj_subselects.front(); 
3094
 
       in_subq != in_subq_end && 
3095
 
       tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3096
 
       in_subq++)
3097
 
  {
3098
 
    if (convert_subq_to_sj(this, *in_subq))
3099
 
      return(true);
3100
 
  }
3101
 
 
3102
 
  /* 3. Finalize those we didn't convert */
3103
 
  for (; in_subq!= in_subq_end; in_subq++)
3104
 
  {
3105
 
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
3106
 
    Item_subselect::trans_res res;
3107
 
    (*in_subq)->changed= 0;
3108
 
    (*in_subq)->fixed= 0;
3109
 
    res= (*in_subq)->select_transformer(child_join);
3110
 
    if (res == Item_subselect::RES_ERROR)
3111
 
      return(true);
3112
 
 
3113
 
    (*in_subq)->changed= 1;
3114
 
    (*in_subq)->fixed= 1;
3115
 
 
3116
 
    Item *substitute= (*in_subq)->substitution;
3117
 
    bool do_fix_fields= !(*in_subq)->substitution->fixed;
3118
 
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
3119
 
      return(true);
3120
 
 
3121
 
    //if ((*in_subq)->fix_fields(thd, (*in_subq)->ref_ptr))
3122
 
    //  return(true);
3123
 
  }
3124
 
  sj_subselects.clear();
3125
 
  return(false);
3126
 
}
3127
 
 
3128
 
 
3129
 
/**
3130
 
  Setup for execution all subqueries of a query, for which the optimizer
3131
 
  chose hash semi-join.
3132
 
 
3133
 
  @details Iterate over all subqueries of the query, and if they are under an
3134
 
  IN predicate, and the optimizer chose to compute it via hash semi-join:
3135
 
  - try to initialize all data structures needed for the materialized execution
3136
 
    of the IN predicate,
3137
 
  - if this fails, then perform the IN=>EXISTS transformation which was
3138
 
    previously blocked during JOIN::prepare.
3139
 
 
3140
 
  This method is part of the "code generation" query processing phase.
3141
 
 
3142
 
  This phase must be called after substitute_for_best_equal_field() because
3143
 
  that function may replace items with other items from a multiple equality,
3144
 
  and we need to reference the correct items in the index access method of the
3145
 
  IN predicate.
3146
 
 
3147
 
  @return Operation status
3148
 
  @retval false     success.
3149
 
  @retval true      error occurred.
3150
 
*/
3151
 
 
3152
 
bool JOIN::setup_subquery_materialization()
3153
 
{
3154
 
  for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit(); un;
3155
 
       un= un->next_unit())
3156
 
  {
3157
 
    for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
3158
 
    {
3159
 
      Item_subselect *subquery_predicate= sl->master_unit()->item;
3160
 
      if (subquery_predicate &&
3161
 
          subquery_predicate->substype() == Item_subselect::IN_SUBS)
3162
 
      {
3163
 
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
3164
 
        if (in_subs->exec_method == Item_in_subselect::MATERIALIZATION &&
3165
 
            in_subs->setup_engine())
3166
 
          return true;
3167
 
      }
3168
 
    }
3169
 
  }
3170
 
  return false;
3171
 
}
3172
 
 
3173
 
 
3174
 
/*
3175
 
  Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
3176
 
 
3177
 
  SYNOPSIS
3178
 
    find_eq_ref_candidate()
3179
 
      table             Table to be checked
3180
 
      sj_inner_tables   Bitmap of inner tables. eq_ref(inner_table) doesn't
3181
 
                        count.
3182
 
 
3183
 
  DESCRIPTION
3184
 
    Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
3185
 
 
3186
 
  TODO
3187
 
    Check again if it is feasible to factor common parts with constant table
3188
 
    search
3189
 
 
3190
 
  RETURN
3191
 
    true  - There exists an eq_ref(outer-tables) candidate
3192
 
    false - Otherwise
3193
 
*/
3194
 
 
3195
 
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
3196
 
{
3197
 
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
3198
 
  uint32_t key;
3199
 
 
3200
 
  if (keyuse)
3201
 
  {
3202
 
    while (1) /* For each key */
3203
 
    {
3204
 
      key= keyuse->key;
3205
 
      KEY *keyinfo= table->key_info + key;
3206
 
      key_part_map bound_parts= 0;
3207
 
      if ((keyinfo->flags & HA_NOSAME) == HA_NOSAME)
3208
 
      {
3209
 
        do  /* For all equalities on all key parts */
3210
 
        {
3211
 
          /* Check if this is "t.keypart = expr(outer_tables) */
3212
 
          if (!(keyuse->used_tables & sj_inner_tables) &&
3213
 
              !(keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL))
3214
 
          {
3215
 
            bound_parts |= 1 << keyuse->keypart;
3216
 
          }
3217
 
          keyuse++;
3218
 
        } while (keyuse->key == key && keyuse->table == table);
3219
 
 
3220
 
        if (bound_parts == PREV_BITS(uint, keyinfo->key_parts))
3221
 
          return true;
3222
 
        if (keyuse->table != table)
3223
 
          return false;
3224
 
      }
3225
 
      else
3226
 
      {
3227
 
        do
3228
 
        {
3229
 
          keyuse++;
3230
 
          if (keyuse->table != table)
3231
 
            return false;
3232
 
        }
3233
 
        while (keyuse->key == key);
3234
 
      }
3235
 
    }
3236
 
  }
3237
 
  return false;
3238
 
}
3239
 
 
3240
 
 
3241
 
/*
3242
 
  Pull tables out of semi-join nests, if possible
3243
 
 
3244
 
  SYNOPSIS
3245
 
    pull_out_semijoin_tables()
3246
 
      join  The join where to do the semi-join flattening
3247
 
 
3248
 
  DESCRIPTION
3249
 
    Try to pull tables out of semi-join nests.
3250
 
     
3251
 
    PRECONDITIONS
3252
 
    When this function is called, the join may have several semi-join nests
3253
 
    (possibly within different semi-join nests), but it is guaranteed that
3254
 
    one semi-join nest does not contain another.
3255
 
   
3256
 
    ACTION
3257
 
    A table can be pulled out of the semi-join nest if
3258
 
     - It is a constant table
3259
 
     - It is accessed 
3260
 
 
3261
 
    POSTCONDITIONS
3262
 
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
3263
 
       tables)
3264
 
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
3265
 
     * Semi-join nests TableList::sj_inner_tables
3266
 
 
3267
 
    This operation is (and should be) performed at each PS execution since
3268
 
    tables may become/cease to be constant across PS reexecutions.
3269
 
 
3270
 
  RETURN 
3271
 
    0 - OK
3272
 
    1 - Out of memory error
3273
 
*/
3274
 
 
3275
 
int pull_out_semijoin_tables(JOIN *join)
3276
 
{
3277
 
  TableList *sj_nest;
3278
 
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
3279
 
   
3280
 
  /* Try pulling out of the each of the semi-joins */
3281
 
  while ((sj_nest= sj_list_it++))
3282
 
  {
3283
 
    /* Action #1: Mark the constant tables to be pulled out */
3284
 
    table_map pulled_tables= 0;
3285
 
     
3286
 
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
3287
 
    TableList *tbl;
3288
 
    while ((tbl= child_li++))
3289
 
    {
3290
 
      if (tbl->table)
3291
 
      {
3292
 
        tbl->table->reginfo.join_tab->emb_sj_nest= sj_nest;
3293
 
        if (tbl->table->map & join->const_table_map)
3294
 
        {
3295
 
          pulled_tables |= tbl->table->map;
3296
 
        }
3297
 
      }
3298
 
    }
3299
 
    
3300
 
    /*
3301
 
      Action #2: Find which tables we can pull out based on
3302
 
      update_ref_and_keys() data. Note that pulling one table out can allow
3303
 
      us to pull out some other tables too.
3304
 
    */
3305
 
    bool pulled_a_table;
3306
 
    do 
3307
 
    {
3308
 
      pulled_a_table= false;
3309
 
      child_li.rewind();
3310
 
      while ((tbl= child_li++))
3311
 
      {
3312
 
        if (tbl->table && !(pulled_tables & tbl->table->map))
3313
 
        {
3314
 
          if (find_eq_ref_candidate(tbl->table, 
3315
 
                                    sj_nest->nested_join->used_tables & 
3316
 
                                    ~pulled_tables))
3317
 
          {
3318
 
            pulled_a_table= true;
3319
 
            pulled_tables |= tbl->table->map;
3320
 
          }
3321
 
        }
3322
 
      }
3323
 
    } while (pulled_a_table);
3324
 
 
3325
 
    child_li.rewind();
3326
 
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
3327
 
    {
3328
 
      (sj_nest)->sj_inner_tables= 0;
3329
 
      while ((tbl= child_li++))
3330
 
      {
3331
 
        if (tbl->table)
3332
 
          tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
3333
 
      }
3334
 
    }
3335
 
    else
3336
 
    {
3337
 
      /* Record the bitmap of inner tables, mark the inner tables */
3338
 
      table_map inner_tables=(sj_nest)->nested_join->used_tables & 
3339
 
                             ~pulled_tables;
3340
 
      (sj_nest)->sj_inner_tables= inner_tables;
3341
 
      while ((tbl= child_li++))
3342
 
      {
3343
 
        if (tbl->table)
3344
 
        {
3345
 
          if (inner_tables & tbl->table->map)
3346
 
            tbl->table->reginfo.join_tab->emb_sj_nest= (sj_nest);
3347
 
          else
3348
 
            tbl->table->reginfo.join_tab->emb_sj_nest= NULL;
3349
 
        }
3350
 
      }
3351
 
    }
3352
 
  }
3353
 
  return(0);
3354
 
}
3355
 
 
3356
471
/*****************************************************************************
3357
 
  Create JOIN_TABS, make a guess about the table types,
 
472
  Create JoinTableS, make a guess about the table types,
3358
473
  Approximate how many records will be used in each table
3359
474
*****************************************************************************/
3360
 
 
3361
 
 
3362
 
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
3363
 
                                      Table *table,
3364
 
                                      const key_map *keys,ha_rows limit)
 
475
ha_rows get_quick_record_count(Session *session, SQL_SELECT *select, Table *table, const key_map *keys,ha_rows limit)
3365
476
{
3366
477
  int error;
3367
 
  if (check_stack_overrun(thd, STACK_MIN_SIZE, NULL))
 
478
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
3368
479
    return(0);                           // Fatal error flag is set
3369
480
  if (select)
3370
481
  {
3371
482
    select->head=table;
3372
483
    table->reginfo.impossible_range=0;
3373
 
    if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
 
484
    if ((error= select->test_quick_select(session, *(key_map *)keys,(table_map) 0,
3374
485
                                          limit, 0, false)) == 1)
3375
486
      return(select->quick->records);
3376
487
    if (error == -1)
3382
493
  return(HA_POS_ERROR);                 /* This shouldn't happend */
3383
494
}
3384
495
 
3385
 
/*
3386
 
   This structure is used to collect info on potentially sargable
3387
 
   predicates in order to check whether they become sargable after
3388
 
   reading const tables.
3389
 
   We form a bitmap of indexes that can be used for sargable predicates.
3390
 
   Only such indexes are involved in range analysis.
3391
 
*/
3392
 
typedef struct st_sargable_param
3393
 
{
3394
 
  Field *field;              /* field against which to check sargability */
3395
 
  Item **arg_value;          /* values of potential keys for lookups     */
3396
 
  uint32_t num_values;           /* number of values in the above array      */
3397
 
} SARGABLE_PARAM;  
3398
 
 
3399
 
/**
3400
 
  Calculate the best possible join and initialize the join structure.
3401
 
 
3402
 
  @retval
3403
 
    0   ok
3404
 
  @retval
3405
 
    1   Fatal error
3406
 
*/
3407
 
 
3408
 
static bool
3409
 
make_join_statistics(JOIN *join, TableList *tables, COND *conds,
3410
 
                     DYNAMIC_ARRAY *keyuse_array)
3411
 
{
3412
 
  int error;
3413
 
  Table *table;
3414
 
  uint32_t i,table_count,const_count,key;
3415
 
  table_map found_const_table_map, all_table_map, found_ref, refs;
3416
 
  key_map const_ref, eq_part;
3417
 
  Table **table_vector;
3418
 
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
3419
 
  KEYUSE *keyuse,*start_keyuse;
3420
 
  table_map outer_join=0;
3421
 
  SARGABLE_PARAM *sargables= 0;
3422
 
  JOIN_TAB *stat_vector[MAX_TABLES+1];
3423
 
 
3424
 
  table_count=join->tables;
3425
 
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
3426
 
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
3427
 
  table_vector=(Table**) join->thd->alloc(sizeof(Table*)*(table_count*2));
3428
 
  if (!stat || !stat_ref || !table_vector)
3429
 
    return(1);                          // Eom /* purecov: inspected */
3430
 
 
3431
 
  join->best_ref=stat_vector;
3432
 
 
3433
 
  stat_end=stat+table_count;
3434
 
  found_const_table_map= all_table_map=0;
3435
 
  const_count=0;
3436
 
 
3437
 
  for (s= stat, i= 0;
3438
 
       tables;
3439
 
       s++, tables= tables->next_leaf, i++)
3440
 
  {
3441
 
    TableList *embedding= tables->embedding;
3442
 
    stat_vector[i]=s;
3443
 
    s->keys.init();
3444
 
    s->const_keys.init();
3445
 
    s->checked_keys.init();
3446
 
    s->needed_reg.init();
3447
 
    table_vector[i]=s->table=table=tables->table;
3448
 
    table->pos_in_table_list= tables;
3449
 
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
3450
 
    if(error)
3451
 
    {
3452
 
        table->file->print_error(error, MYF(0));
3453
 
        return(1);
3454
 
    }
3455
 
    table->quick_keys.clear_all();
3456
 
    table->reginfo.join_tab=s;
3457
 
    table->reginfo.not_exists_optimize=0;
3458
 
    memset(table->const_key_parts, 0,
3459
 
           sizeof(key_part_map)*table->s->keys);
3460
 
    all_table_map|= table->map;
3461
 
    s->join=join;
3462
 
    s->info=0;                                  // For describe
3463
 
 
3464
 
    s->dependent= tables->dep_tables;
3465
 
    s->key_dependent= 0;
3466
 
    if (tables->schema_table)
3467
 
      table->file->stats.records= 2;
3468
 
    table->quick_condition_rows= table->file->stats.records;
3469
 
 
3470
 
    s->on_expr_ref= &tables->on_expr;
3471
 
    if (*s->on_expr_ref)
3472
 
    {
3473
 
      /* s is the only inner table of an outer join */
3474
 
      if (!table->file->stats.records && !embedding)
3475
 
      {                                         // Empty table
3476
 
        s->dependent= 0;                        // Ignore LEFT JOIN depend.
3477
 
        set_position(join,const_count++,s,(KEYUSE*) 0);
3478
 
        continue;
3479
 
      }
3480
 
      outer_join|= table->map;
3481
 
      s->embedding_map= 0;
3482
 
      for (;embedding; embedding= embedding->embedding)
3483
 
        s->embedding_map|= embedding->nested_join->nj_map;
3484
 
      continue;
3485
 
    }
3486
 
    if (embedding && !(embedding->sj_on_expr && ! embedding->embedding))
3487
 
    {
3488
 
      /* s belongs to a nested join, maybe to several embedded joins */
3489
 
      s->embedding_map= 0;
3490
 
      do
3491
 
      {
3492
 
        nested_join_st *nested_join= embedding->nested_join;
3493
 
        s->embedding_map|=nested_join->nj_map;
3494
 
        s->dependent|= embedding->dep_tables;
3495
 
        embedding= embedding->embedding;
3496
 
        outer_join|= nested_join->used_tables;
3497
 
      }
3498
 
      while (embedding);
3499
 
      continue;
3500
 
    }
3501
 
    if ((table->file->stats.records <= 1) &&
3502
 
        !s->dependent &&
3503
 
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
3504
 
    {
3505
 
      set_position(join,const_count++,s,(KEYUSE*) 0);
3506
 
    }
3507
 
  }
3508
 
  stat_vector[i]=0;
3509
 
  join->outer_join=outer_join;
3510
 
 
3511
 
  if (join->outer_join)
3512
 
  {
3513
 
    /* 
3514
 
       Build transitive closure for relation 'to be dependent on'.
3515
 
       This will speed up the plan search for many cases with outer joins,
3516
 
       as well as allow us to catch illegal cross references/
3517
 
       Warshall's algorithm is used to build the transitive closure.
3518
 
       As we use bitmaps to represent the relation the complexity
3519
 
       of the algorithm is O((number of tables)^2). 
3520
 
    */
3521
 
    for (i= 0, s= stat ; i < table_count ; i++, s++)
3522
 
    {
3523
 
      for (uint32_t j= 0 ; j < table_count ; j++)
3524
 
      {
3525
 
        table= stat[j].table;
3526
 
        if (s->dependent & table->map)
3527
 
          s->dependent |= table->reginfo.join_tab->dependent;
3528
 
      }
3529
 
      if (s->dependent)
3530
 
        s->table->maybe_null= 1;
3531
 
    }
3532
 
    /* Catch illegal cross references for outer joins */
3533
 
    for (i= 0, s= stat ; i < table_count ; i++, s++)
3534
 
    {
3535
 
      if (s->dependent & s->table->map)
3536
 
      {
3537
 
        join->tables=0;                 // Don't use join->table
3538
 
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
3539
 
        return(1);
3540
 
      }
3541
 
      s->key_dependent= s->dependent;
3542
 
    }
3543
 
  }
3544
 
 
3545
 
  if (conds || outer_join)
3546
 
    if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables,
3547
 
                            conds, join->cond_equal,
3548
 
                            ~outer_join, join->select_lex, &sargables))
3549
 
      return(1);
3550
 
 
3551
 
  /* Read tables with 0 or 1 rows (system tables) */
3552
 
  join->const_table_map= 0;
3553
 
 
3554
 
  for (POSITION *p_pos=join->positions, *p_end=p_pos+const_count;
3555
 
       p_pos < p_end ;
3556
 
       p_pos++)
3557
 
  {
3558
 
    int tmp;
3559
 
    s= p_pos->table;
3560
 
    s->type=JT_SYSTEM;
3561
 
    join->const_table_map|=s->table->map;
3562
 
    if ((tmp=join_read_const_table(s, p_pos)))
3563
 
    {
3564
 
      if (tmp > 0)
3565
 
        return(1);                      // Fatal error
3566
 
    }
3567
 
    else
3568
 
      found_const_table_map|= s->table->map;
3569
 
  }
3570
 
 
3571
 
  /* loop until no more const tables are found */
3572
 
  int ref_changed;
3573
 
  do
3574
 
  {
3575
 
  more_const_tables_found:
3576
 
    ref_changed = 0;
3577
 
    found_ref=0;
3578
 
 
3579
 
    /*
3580
 
      We only have to loop from stat_vector + const_count as
3581
 
      set_position() will move all const_tables first in stat_vector
3582
 
    */
3583
 
 
3584
 
    for (JOIN_TAB **pos=stat_vector+const_count ; (s= *pos) ; pos++)
3585
 
    {
3586
 
      table=s->table;
3587
 
 
3588
 
      /* 
3589
 
        If equi-join condition by a key is null rejecting and after a
3590
 
        substitution of a const table the key value happens to be null
3591
 
        then we can state that there are no matches for this equi-join.
3592
 
      */  
3593
 
      if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
3594
 
      {
3595
 
        /* 
3596
 
          When performing an outer join operation if there are no matching rows
3597
 
          for the single row of the outer table all the inner tables are to be
3598
 
          null complemented and thus considered as constant tables.
3599
 
          Here we apply this consideration to the case of outer join operations 
3600
 
          with a single inner table only because the case with nested tables
3601
 
          would require a more thorough analysis.
3602
 
          TODO. Apply single row substitution to null complemented inner tables
3603
 
          for nested outer join operations. 
3604
 
        */              
3605
 
        while (keyuse->table == table)
3606
 
        {
3607
 
          if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
3608
 
              keyuse->val->is_null() && keyuse->null_rejecting)
3609
 
          {
3610
 
            s->type= JT_CONST;
3611
 
            mark_as_null_row(table);
3612
 
            found_const_table_map|= table->map;
3613
 
            join->const_table_map|= table->map;
3614
 
            set_position(join,const_count++,s,(KEYUSE*) 0);
3615
 
            goto more_const_tables_found;
3616
 
           }
3617
 
          keyuse++;
3618
 
        }
3619
 
      }
3620
 
 
3621
 
      if (s->dependent)                         // If dependent on some table
3622
 
      {
3623
 
        // All dep. must be constants
3624
 
        if (s->dependent & ~(found_const_table_map))
3625
 
          continue;
3626
 
        if (table->file->stats.records <= 1L &&
3627
 
            (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
3628
 
            !table->pos_in_table_list->embedding)
3629
 
        {                                       // system table
3630
 
          int tmp= 0;
3631
 
          s->type=JT_SYSTEM;
3632
 
          join->const_table_map|=table->map;
3633
 
          set_position(join,const_count++,s,(KEYUSE*) 0);
3634
 
          if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
3635
 
          {
3636
 
            if (tmp > 0)
3637
 
              return(1);                        // Fatal error
3638
 
          }
3639
 
          else
3640
 
            found_const_table_map|= table->map;
3641
 
          continue;
3642
 
        }
3643
 
      }
3644
 
      /* check if table can be read by key or table only uses const refs */
3645
 
      if ((keyuse=s->keyuse))
3646
 
      {
3647
 
        s->type= JT_REF;
3648
 
        while (keyuse->table == table)
3649
 
        {
3650
 
          start_keyuse=keyuse;
3651
 
          key=keyuse->key;
3652
 
          s->keys.set_bit(key);               // QQ: remove this ?
3653
 
 
3654
 
          refs=0;
3655
 
          const_ref.clear_all();
3656
 
          eq_part.clear_all();
3657
 
          do
3658
 
          {
3659
 
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
3660
 
            {
3661
 
              if (!((~found_const_table_map) & keyuse->used_tables))
3662
 
                const_ref.set_bit(keyuse->keypart);
3663
 
              else
3664
 
                refs|=keyuse->used_tables;
3665
 
              eq_part.set_bit(keyuse->keypart);
3666
 
            }
3667
 
            keyuse++;
3668
 
          } while (keyuse->table == table && keyuse->key == key);
3669
 
 
3670
 
          if (eq_part.is_prefix(table->key_info[key].key_parts) &&
3671
 
              !table->pos_in_table_list->embedding)
3672
 
          {
3673
 
            if ((table->key_info[key].flags & (HA_NOSAME))
3674
 
                 == HA_NOSAME)
3675
 
            {
3676
 
              if (const_ref == eq_part)
3677
 
              {                                 // Found everything for ref.
3678
 
                int tmp;
3679
 
                ref_changed = 1;
3680
 
                s->type= JT_CONST;
3681
 
                join->const_table_map|=table->map;
3682
 
                set_position(join,const_count++,s,start_keyuse);
3683
 
                if (create_ref_for_key(join, s, start_keyuse,
3684
 
                                       found_const_table_map))
3685
 
                  return(1);
3686
 
                if ((tmp=join_read_const_table(s,
3687
 
                                               join->positions+const_count-1)))
3688
 
                {
3689
 
                  if (tmp > 0)
3690
 
                    return(1);                  // Fatal error
3691
 
                }
3692
 
                else
3693
 
                  found_const_table_map|= table->map;
3694
 
                break;
3695
 
              }
3696
 
              else
3697
 
                found_ref|= refs;      // Table is const if all refs are const
3698
 
            }
3699
 
            else if (const_ref == eq_part)
3700
 
              s->const_keys.set_bit(key);
3701
 
          }
3702
 
        }
3703
 
      }
3704
 
    }
3705
 
  } while (join->const_table_map & found_ref && ref_changed);
3706
 
 
3707
 
  /* 
3708
 
    Update info on indexes that can be used for search lookups as
3709
 
    reading const tables may has added new sargable predicates. 
3710
 
  */
3711
 
  if (const_count && sargables)
3712
 
  {
3713
 
    for( ; sargables->field ; sargables++)
3714
 
    {
3715
 
      Field *field= sargables->field;
3716
 
      JOIN_TAB *join_tab= field->table->reginfo.join_tab;
3717
 
      key_map possible_keys= field->key_start;
3718
 
      possible_keys.intersect(field->table->keys_in_use_for_query);
3719
 
      bool is_const= 1;
3720
 
      for (uint32_t j=0; j < sargables->num_values; j++)
3721
 
        is_const&= sargables->arg_value[j]->const_item();
3722
 
      if (is_const)
3723
 
        join_tab[0].const_keys.merge(possible_keys);
3724
 
    }
3725
 
  }
3726
 
 
3727
 
  if (pull_out_semijoin_tables(join))
3728
 
    return(true);
3729
 
 
3730
 
  /* Calc how many (possible) matched records in each table */
3731
 
 
3732
 
  for (s=stat ; s < stat_end ; s++)
3733
 
  {
3734
 
    if (s->type == JT_SYSTEM || s->type == JT_CONST)
3735
 
    {
3736
 
      /* Only one matching row */
3737
 
      s->found_records=s->records=s->read_time=1; s->worst_seeks=1.0;
3738
 
      continue;
3739
 
    }
3740
 
    /* Approximate found rows and time to read them */
3741
 
    s->found_records=s->records=s->table->file->stats.records;
3742
 
    s->read_time=(ha_rows) s->table->file->scan_time();
3743
 
 
3744
 
    /*
3745
 
      Set a max range of how many seeks we can expect when using keys
3746
 
      This is can't be to high as otherwise we are likely to use
3747
 
      table scan.
3748
 
    */
3749
 
    s->worst_seeks= cmin((double) s->found_records / 10,
3750
 
                        (double) s->read_time*3);
3751
 
    if (s->worst_seeks < 2.0)                   // Fix for small tables
3752
 
      s->worst_seeks=2.0;
3753
 
 
3754
 
    /*
3755
 
      Add to stat->const_keys those indexes for which all group fields or
3756
 
      all select distinct fields participate in one index.
3757
 
    */
3758
 
    add_group_and_distinct_keys(join, s);
3759
 
 
3760
 
    if (!s->const_keys.is_clear_all() &&
3761
 
        !s->table->pos_in_table_list->embedding)
3762
 
    {
3763
 
      ha_rows records;
3764
 
      SQL_SELECT *select;
3765
 
      select= make_select(s->table, found_const_table_map,
3766
 
                          found_const_table_map,
3767
 
                          *s->on_expr_ref ? *s->on_expr_ref : conds,
3768
 
                          1, &error);
3769
 
      if (!select)
3770
 
        return(1);
3771
 
      records= get_quick_record_count(join->thd, select, s->table,
3772
 
                                      &s->const_keys, join->row_limit);
3773
 
      s->quick=select->quick;
3774
 
      s->needed_reg=select->needed_reg;
3775
 
      select->quick=0;
3776
 
      if (records == 0 && s->table->reginfo.impossible_range)
3777
 
      {
3778
 
        /*
3779
 
          Impossible WHERE or ON expression
3780
 
          In case of ON, we mark that the we match one empty NULL row.
3781
 
          In case of WHERE, don't set found_const_table_map to get the
3782
 
          caller to abort with a zero row result.
3783
 
        */
3784
 
        join->const_table_map|= s->table->map;
3785
 
        set_position(join,const_count++,s,(KEYUSE*) 0);
3786
 
        s->type= JT_CONST;
3787
 
        if (*s->on_expr_ref)
3788
 
        {
3789
 
          /* Generate empty row */
3790
 
          s->info= "Impossible ON condition";
3791
 
          found_const_table_map|= s->table->map;
3792
 
          s->type= JT_CONST;
3793
 
          mark_as_null_row(s->table);           // All fields are NULL
3794
 
        }
3795
 
      }
3796
 
      if (records != HA_POS_ERROR)
3797
 
      {
3798
 
        s->found_records=records;
3799
 
        s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
3800
 
      }
3801
 
      delete select;
3802
 
    }
3803
 
  }
3804
 
 
3805
 
  join->join_tab=stat;
3806
 
  join->map2table=stat_ref;
3807
 
  join->table= join->all_tables=table_vector;
3808
 
  join->const_tables=const_count;
3809
 
  join->found_const_table_map=found_const_table_map;
3810
 
 
3811
 
  /* Find an optimal join order of the non-constant tables. */
3812
 
  if (join->const_tables != join->tables)
3813
 
  {
3814
 
    optimize_keyuse(join, keyuse_array);
3815
 
    if (choose_plan(join, all_table_map & ~join->const_table_map))
3816
 
      return(true);
3817
 
  }
3818
 
  else
3819
 
  {
3820
 
    memcpy(join->best_positions, join->positions,
3821
 
           sizeof(POSITION)*join->const_tables);
3822
 
    join->best_read=1.0;
3823
 
  }
3824
 
  /* Generate an execution plan from the found optimal join order. */
3825
 
  return(join->thd->killed || get_best_combination(join));
3826
 
}
3827
 
 
3828
 
 
3829
496
/*****************************************************************************
3830
497
  Check with keys are used and with tables references with tables
3831
498
  Updates in stat:
3834
501
          keyuse     Pointer to possible keys
3835
502
*****************************************************************************/
3836
503
 
3837
 
/// Used when finding key fields
3838
 
typedef struct key_field_t {
3839
 
  Field         *field;
3840
 
  Item          *val;                   ///< May be empty if diff constant
3841
 
  uint          level;
3842
 
  uint          optimize; // KEY_OPTIMIZE_*
3843
 
  bool          eq_func;
3844
 
  /**
3845
 
    If true, the condition this struct represents will not be satisfied
3846
 
    when val IS NULL.
3847
 
  */
3848
 
  bool          null_rejecting; 
3849
 
  bool          *cond_guard; /* See KEYUSE::cond_guard */
3850
 
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
3851
 
} KEY_FIELD;
3852
 
 
3853
 
/**
3854
 
  Merge new key definitions to old ones, remove those not used in both.
3855
 
 
3856
 
  This is called for OR between different levels.
3857
 
 
3858
 
  To be able to do 'ref_or_null' we merge a comparison of a column
3859
 
  and 'column IS NULL' to one test.  This is useful for sub select queries
3860
 
  that are internally transformed to something like:.
3861
 
 
3862
 
  @code
3863
 
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL 
3864
 
  @endcode
3865
 
 
3866
 
  KEY_FIELD::null_rejecting is processed as follows: @n
3867
 
  result has null_rejecting=true if it is set for both ORed references.
3868
 
  for example:
3869
 
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
3870
 
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
3871
 
 
3872
 
  @todo
3873
 
    The result of this is that we're missing some 'ref' accesses.
3874
 
    OptimizerTeam: Fix this
3875
 
*/
3876
 
 
3877
 
static KEY_FIELD *
3878
 
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
3879
 
                 uint32_t and_level)
3880
 
{
3881
 
  if (start == new_fields)
3882
 
    return start;                               // Impossible or
3883
 
  if (new_fields == end)
3884
 
    return start;                               // No new fields, skip all
3885
 
 
3886
 
  KEY_FIELD *first_free=new_fields;
3887
 
 
3888
 
  /* Mark all found fields in old array */
3889
 
  for (; new_fields != end ; new_fields++)
3890
 
  {
3891
 
    for (KEY_FIELD *old=start ; old != first_free ; old++)
3892
 
    {
3893
 
      if (old->field == new_fields->field)
3894
 
      {
3895
 
        /*
3896
 
          NOTE: below const_item() call really works as "!used_tables()", i.e.
3897
 
          it can return false where it is feasible to make it return true.
3898
 
          
3899
 
          The cause is as follows: Some of the tables are already known to be
3900
 
          const tables (the detection code is in make_join_statistics(),
3901
 
          above the update_ref_and_keys() call), but we didn't propagate 
3902
 
          information about this: Table::const_table is not set to true, and
3903
 
          Item::update_used_tables() hasn't been called for each item.
3904
 
          The result of this is that we're missing some 'ref' accesses.
3905
 
          TODO: OptimizerTeam: Fix this
3906
 
        */
3907
 
        if (!new_fields->val->const_item())
3908
 
        {
3909
 
          /*
3910
 
            If the value matches, we can use the key reference.
3911
 
            If not, we keep it until we have examined all new values
3912
 
          */
3913
 
          if (old->val->eq(new_fields->val, old->field->binary()))
3914
 
          {
3915
 
            old->level= and_level;
3916
 
            old->optimize= ((old->optimize & new_fields->optimize &
3917
 
                             KEY_OPTIMIZE_EXISTS) |
3918
 
                            ((old->optimize | new_fields->optimize) &
3919
 
                             KEY_OPTIMIZE_REF_OR_NULL));
3920
 
            old->null_rejecting= (old->null_rejecting &&
3921
 
                                  new_fields->null_rejecting);
3922
 
          }
3923
 
        }
3924
 
        else if (old->eq_func && new_fields->eq_func &&
3925
 
                 old->val->eq_by_collation(new_fields->val, 
3926
 
                                           old->field->binary(),
3927
 
                                           old->field->charset()))
3928
 
 
3929
 
        {
3930
 
          old->level= and_level;
3931
 
          old->optimize= ((old->optimize & new_fields->optimize &
3932
 
                           KEY_OPTIMIZE_EXISTS) |
3933
 
                          ((old->optimize | new_fields->optimize) &
3934
 
                           KEY_OPTIMIZE_REF_OR_NULL));
3935
 
          old->null_rejecting= (old->null_rejecting &&
3936
 
                                new_fields->null_rejecting);
3937
 
        }
3938
 
        else if (old->eq_func && new_fields->eq_func &&
3939
 
                 ((old->val->const_item() && old->val->is_null()) || 
3940
 
                  new_fields->val->is_null()))
3941
 
        {
3942
 
          /* field = expression OR field IS NULL */
3943
 
          old->level= and_level;
3944
 
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
3945
 
          /*
3946
 
            Remember the NOT NULL value unless the value does not depend
3947
 
            on other tables.
3948
 
          */
3949
 
          if (!old->val->used_tables() && old->val->is_null())
3950
 
            old->val= new_fields->val;
3951
 
          /* The referred expression can be NULL: */ 
3952
 
          old->null_rejecting= 0;
3953
 
        }
3954
 
        else
3955
 
        {
3956
 
          /*
3957
 
            We are comparing two different const.  In this case we can't
3958
 
            use a key-lookup on this so it's better to remove the value
3959
 
            and let the range optimzier handle it
3960
 
          */
3961
 
          if (old == --first_free)              // If last item
3962
 
            break;
3963
 
          *old= *first_free;                    // Remove old value
3964
 
          old--;                                // Retry this value
3965
 
        }
3966
 
      }
3967
 
    }
3968
 
  }
3969
 
  /* Remove all not used items */
3970
 
  for (KEY_FIELD *old=start ; old != first_free ;)
3971
 
  {
3972
 
    if (old->level != and_level)
3973
 
    {                                           // Not used in all levels
3974
 
      if (old == --first_free)
3975
 
        break;
3976
 
      *old= *first_free;                        // Remove old value
3977
 
      continue;
3978
 
    }
3979
 
    old++;
3980
 
  }
3981
 
  return first_free;
3982
 
}
3983
 
 
3984
 
 
3985
 
/**
3986
 
  Add a possible key to array of possible keys if it's usable as a key
3987
 
 
3988
 
    @param key_fields      Pointer to add key, if usable
3989
 
    @param and_level       And level, to be stored in KEY_FIELD
3990
 
    @param cond            Condition predicate
3991
 
    @param field           Field used in comparision
3992
 
    @param eq_func         True if we used =, <=> or IS NULL
3993
 
    @param value           Value used for comparison with field
3994
 
    @param usable_tables   Tables which can be used for key optimization
3995
 
    @param sargables       IN/OUT Array of found sargable candidates
3996
 
 
3997
 
  @note
3998
 
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
3999
 
    table, we store this to be able to do not exists optimization later.
4000
 
 
4001
 
  @returns
4002
 
    *key_fields is incremented if we stored a key in the array
4003
 
*/
4004
 
 
4005
 
static void
4006
 
add_key_field(KEY_FIELD **key_fields,uint32_t and_level, Item_func *cond,
4007
 
              Field *field, bool eq_func, Item **value, uint32_t num_values,
4008
 
              table_map usable_tables, SARGABLE_PARAM **sargables)
4009
 
{
4010
 
  uint32_t exists_optimize= 0;
4011
 
  if (!(field->flags & PART_KEY_FLAG))
4012
 
  {
4013
 
    // Don't remove column IS NULL on a LEFT JOIN table
4014
 
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
4015
 
        !field->table->maybe_null || field->null_ptr)
4016
 
      return;                                   // Not a key. Skip it
4017
 
    exists_optimize= KEY_OPTIMIZE_EXISTS;
4018
 
    assert(num_values == 1);
4019
 
  }
4020
 
  else
4021
 
  {
4022
 
    table_map used_tables=0;
4023
 
    bool optimizable=0;
4024
 
    for (uint32_t i=0; i<num_values; i++)
4025
 
    {
4026
 
      used_tables|=(value[i])->used_tables();
4027
 
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
4028
 
        optimizable=1;
4029
 
    }
4030
 
    if (!optimizable)
4031
 
      return;
4032
 
    if (!(usable_tables & field->table->map))
4033
 
    {
4034
 
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
4035
 
          !field->table->maybe_null || field->null_ptr)
4036
 
        return;                                 // Can't use left join optimize
4037
 
      exists_optimize= KEY_OPTIMIZE_EXISTS;
4038
 
    }
4039
 
    else
4040
 
    {
4041
 
      JOIN_TAB *stat=field->table->reginfo.join_tab;
4042
 
      key_map possible_keys=field->key_start;
4043
 
      possible_keys.intersect(field->table->keys_in_use_for_query);
4044
 
      stat[0].keys.merge(possible_keys);             // Add possible keys
4045
 
 
4046
 
      /*
4047
 
        Save the following cases:
4048
 
        Field op constant
4049
 
        Field LIKE constant where constant doesn't start with a wildcard
4050
 
        Field = field2 where field2 is in a different table
4051
 
        Field op formula
4052
 
        Field IS NULL
4053
 
        Field IS NOT NULL
4054
 
         Field BETWEEN ...
4055
 
         Field IN ...
4056
 
      */
4057
 
      stat[0].key_dependent|=used_tables;
4058
 
 
4059
 
      bool is_const=1;
4060
 
      for (uint32_t i=0; i<num_values; i++)
4061
 
      {
4062
 
        if (!(is_const&= value[i]->const_item()))
4063
 
          break;
4064
 
      }
4065
 
      if (is_const)
4066
 
        stat[0].const_keys.merge(possible_keys);
4067
 
      else if (!eq_func)
4068
 
      {
4069
 
        /* 
4070
 
          Save info to be able check whether this predicate can be 
4071
 
          considered as sargable for range analisis after reading const tables.
4072
 
          We do not save info about equalities as update_const_equal_items
4073
 
          will take care of updating info on keys from sargable equalities. 
4074
 
        */
4075
 
        (*sargables)--;
4076
 
        (*sargables)->field= field;
4077
 
        (*sargables)->arg_value= value;
4078
 
        (*sargables)->num_values= num_values;
4079
 
      }
4080
 
      /*
4081
 
        We can't always use indexes when comparing a string index to a
4082
 
        number. cmp_type() is checked to allow compare of dates to numbers.
4083
 
        eq_func is NEVER true when num_values > 1
4084
 
       */
4085
 
      if (!eq_func)
4086
 
      {
4087
 
        /* 
4088
 
          Additional optimization: if we're processing
4089
 
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
4090
 
          "t.key = c1".
4091
 
          TODO: This is a very limited fix. A more generic fix is possible. 
4092
 
          There are 2 options:
4093
 
          A) Make equality propagation code be able to handle BETWEEN
4094
 
             (including cases like t1.key BETWEEN t2.key AND t3.key)
4095
 
          B) Make range optimizer to infer additional "t.key = c" equalities
4096
 
             and use them in equality propagation process (see details in
4097
 
             OptimizerKBAndTodo)
4098
 
        */
4099
 
        if ((cond->functype() != Item_func::BETWEEN) ||
4100
 
            ((Item_func_between*) cond)->negated ||
4101
 
            !value[0]->eq(value[1], field->binary()))
4102
 
          return;
4103
 
        eq_func= true;
4104
 
      }
4105
 
 
4106
 
      if (field->result_type() == STRING_RESULT)
4107
 
      {
4108
 
        if ((*value)->result_type() != STRING_RESULT)
4109
 
        {
4110
 
          if (field->cmp_type() != (*value)->result_type())
4111
 
            return;
4112
 
        }
4113
 
        else
4114
 
        {
4115
 
          /*
4116
 
            We can't use indexes if the effective collation
4117
 
            of the operation differ from the field collation.
4118
 
          */
4119
 
          if (field->cmp_type() == STRING_RESULT &&
4120
 
              ((Field_str*)field)->charset() != cond->compare_collation())
4121
 
            return;
4122
 
        }
4123
 
      }
4124
 
    }
4125
 
  }
4126
 
  /*
4127
 
    For the moment eq_func is always true. This slot is reserved for future
4128
 
    extensions where we want to remembers other things than just eq comparisons
4129
 
  */
4130
 
  assert(eq_func);
4131
 
  /* Store possible eq field */
4132
 
  (*key_fields)->field=         field;
4133
 
  (*key_fields)->eq_func=       eq_func;
4134
 
  (*key_fields)->val=           *value;
4135
 
  (*key_fields)->level=         and_level;
4136
 
  (*key_fields)->optimize=      exists_optimize;
4137
 
  /*
4138
 
    If the condition has form "tbl.keypart = othertbl.field" and 
4139
 
    othertbl.field can be NULL, there will be no matches if othertbl.field 
4140
 
    has NULL value.
4141
 
    We use null_rejecting in add_not_null_conds() to add
4142
 
    'othertbl.field IS NOT NULL' to tab->select_cond.
4143
 
  */
4144
 
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
4145
 
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
4146
 
                                  ((*value)->type() == Item::FIELD_ITEM) &&
4147
 
                                  ((Item_field*)*value)->field->maybe_null());
4148
 
  (*key_fields)->cond_guard= NULL;
4149
 
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name && 
4150
 
                              cond->name < subq_sj_cond_name + 64)? 
4151
 
                              cond->name - subq_sj_cond_name: UINT_MAX;
4152
 
  (*key_fields)++;
4153
 
}
4154
 
 
4155
 
/**
4156
 
  Add possible keys to array of possible keys originated from a simple
4157
 
  predicate.
4158
 
 
4159
 
    @param  key_fields     Pointer to add key, if usable
4160
 
    @param  and_level      And level, to be stored in KEY_FIELD
4161
 
    @param  cond           Condition predicate
4162
 
    @param  field          Field used in comparision
4163
 
    @param  eq_func        True if we used =, <=> or IS NULL
4164
 
    @param  value          Value used for comparison with field
4165
 
                           Is NULL for BETWEEN and IN    
4166
 
    @param  usable_tables  Tables which can be used for key optimization
4167
 
    @param  sargables      IN/OUT Array of found sargable candidates
4168
 
 
4169
 
  @note
4170
 
    If field items f1 and f2 belong to the same multiple equality and
4171
 
    a key is added for f1, the the same key is added for f2.
4172
 
 
4173
 
  @returns
4174
 
    *key_fields is incremented if we stored a key in the array
4175
 
*/
4176
 
 
4177
 
static void
4178
 
add_key_equal_fields(KEY_FIELD **key_fields, uint32_t and_level,
4179
 
                     Item_func *cond, Item_field *field_item,
4180
 
                     bool eq_func, Item **val,
4181
 
                     uint32_t num_values, table_map usable_tables,
4182
 
                     SARGABLE_PARAM **sargables)
4183
 
{
4184
 
  Field *field= field_item->field;
4185
 
  add_key_field(key_fields, and_level, cond, field,
4186
 
                eq_func, val, num_values, usable_tables, sargables);
4187
 
  Item_equal *item_equal= field_item->item_equal;
4188
 
  if (item_equal)
4189
 
  { 
4190
 
    /*
4191
 
      Add to the set of possible key values every substitution of
4192
 
      the field for an equal field included into item_equal
4193
 
    */
4194
 
    Item_equal_iterator it(*item_equal);
4195
 
    Item_field *item;
4196
 
    while ((item= it++))
4197
 
    {
4198
 
      if (!field->eq(item->field))
4199
 
      {
4200
 
        add_key_field(key_fields, and_level, cond, item->field,
4201
 
                      eq_func, val, num_values, usable_tables,
4202
 
                      sargables);
4203
 
      }
4204
 
    }
4205
 
  }
4206
 
}
4207
 
 
4208
 
static void
4209
 
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint32_t *and_level,
4210
 
               COND *cond, table_map usable_tables,
4211
 
               SARGABLE_PARAM **sargables)
4212
 
{
4213
 
  if (cond->type() == Item_func::COND_ITEM)
4214
 
  {
4215
 
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
4216
 
    KEY_FIELD *org_key_fields= *key_fields;
4217
 
 
4218
 
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
4219
 
    {
4220
 
      Item *item;
4221
 
      while ((item=li++))
4222
 
        add_key_fields(join, key_fields, and_level, item, usable_tables,
4223
 
                       sargables);
4224
 
      for (; org_key_fields != *key_fields ; org_key_fields++)
4225
 
        org_key_fields->level= *and_level;
4226
 
    }
4227
 
    else
4228
 
    {
4229
 
      (*and_level)++;
4230
 
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
4231
 
                     sargables);
4232
 
      Item *item;
4233
 
      while ((item=li++))
4234
 
      {
4235
 
        KEY_FIELD *start_key_fields= *key_fields;
4236
 
        (*and_level)++;
4237
 
        add_key_fields(join, key_fields, and_level, item, usable_tables,
4238
 
                       sargables);
4239
 
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
4240
 
                                     *key_fields,++(*and_level));
4241
 
      }
4242
 
    }
4243
 
    return;
4244
 
  }
4245
 
 
4246
 
  /* 
4247
 
    Subquery optimization: Conditions that are pushed down into subqueries
4248
 
    are wrapped into Item_func_trig_cond. We process the wrapped condition
4249
 
    but need to set cond_guard for KEYUSE elements generated from it.
4250
 
  */
4251
 
  {
4252
 
    if (cond->type() == Item::FUNC_ITEM &&
4253
 
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
4254
 
    {
4255
 
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
4256
 
      if (!join->group_list && !join->order &&
4257
 
          join->unit->item && 
4258
 
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
4259
 
          !join->unit->is_union())
4260
 
      {
4261
 
        KEY_FIELD *save= *key_fields;
4262
 
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
4263
 
                       sargables);
4264
 
        // Indicate that this ref access candidate is for subquery lookup:
4265
 
        for (; save != *key_fields; save++)
4266
 
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
4267
 
      }
4268
 
      return;
4269
 
    }
4270
 
  }
4271
 
 
4272
 
  /* If item is of type 'field op field/constant' add it to key_fields */
4273
 
  if (cond->type() != Item::FUNC_ITEM)
4274
 
    return;
4275
 
  Item_func *cond_func= (Item_func*) cond;
4276
 
  switch (cond_func->select_optimize()) {
4277
 
  case Item_func::OPTIMIZE_NONE:
4278
 
    break;
4279
 
  case Item_func::OPTIMIZE_KEY:
4280
 
  {
4281
 
    Item **values;
4282
 
    // BETWEEN, IN, NE
4283
 
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
4284
 
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
4285
 
    {
4286
 
      values= cond_func->arguments()+1;
4287
 
      if (cond_func->functype() == Item_func::NE_FUNC &&
4288
 
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
4289
 
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
4290
 
        values--;
4291
 
      assert(cond_func->functype() != Item_func::IN_FUNC ||
4292
 
                  cond_func->argument_count() != 2);
4293
 
      add_key_equal_fields(key_fields, *and_level, cond_func,
4294
 
                           (Item_field*) (cond_func->key_item()->real_item()),
4295
 
                           0, values, 
4296
 
                           cond_func->argument_count()-1,
4297
 
                           usable_tables, sargables);
4298
 
    }
4299
 
    if (cond_func->functype() == Item_func::BETWEEN)
4300
 
    {
4301
 
      values= cond_func->arguments();
4302
 
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
4303
 
      {
4304
 
        Item_field *field_item;
4305
 
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
4306
 
            &&
4307
 
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
4308
 
        {
4309
 
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
4310
 
          add_key_equal_fields(key_fields, *and_level, cond_func,
4311
 
                               field_item, 0, values, 1, usable_tables, 
4312
 
                               sargables);
4313
 
        }
4314
 
      }  
4315
 
    }
4316
 
    break;
4317
 
  }
4318
 
  case Item_func::OPTIMIZE_OP:
4319
 
  {
4320
 
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
4321
 
                     cond_func->functype() == Item_func::EQUAL_FUNC);
4322
 
 
4323
 
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
4324
 
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
4325
 
    {
4326
 
      add_key_equal_fields(key_fields, *and_level, cond_func,
4327
 
                        (Item_field*) (cond_func->arguments()[0])->real_item(),
4328
 
                           equal_func,
4329
 
                           cond_func->arguments()+1, 1, usable_tables,
4330
 
                           sargables);
4331
 
    }
4332
 
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
4333
 
        cond_func->functype() != Item_func::LIKE_FUNC &&
4334
 
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
4335
 
    {
4336
 
      add_key_equal_fields(key_fields, *and_level, cond_func, 
4337
 
                       (Item_field*) (cond_func->arguments()[1])->real_item(),
4338
 
                           equal_func,
4339
 
                           cond_func->arguments(),1,usable_tables,
4340
 
                           sargables);
4341
 
    }
4342
 
    break;
4343
 
  }
4344
 
  case Item_func::OPTIMIZE_NULL:
4345
 
    /* column_name IS [NOT] NULL */
4346
 
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
4347
 
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
4348
 
    {
4349
 
      Item *tmp=new Item_null;
4350
 
      if (unlikely(!tmp))                       // Should never be true
4351
 
        return;
4352
 
      add_key_equal_fields(key_fields, *and_level, cond_func,
4353
 
                    (Item_field*) (cond_func->arguments()[0])->real_item(),
4354
 
                    cond_func->functype() == Item_func::ISNULL_FUNC,
4355
 
                           &tmp, 1, usable_tables, sargables);
4356
 
    }
4357
 
    break;
4358
 
  case Item_func::OPTIMIZE_EQUAL:
4359
 
    Item_equal *item_equal= (Item_equal *) cond;
4360
 
    Item *const_item= item_equal->get_const();
4361
 
    Item_equal_iterator it(*item_equal);
4362
 
    Item_field *item;
4363
 
    if (const_item)
4364
 
    {
4365
 
      /*
4366
 
        For each field field1 from item_equal consider the equality 
4367
 
        field1=const_item as a condition allowing an index access of the table
4368
 
        with field1 by the keys value of field1.
4369
 
      */   
4370
 
      while ((item= it++))
4371
 
      {
4372
 
        add_key_field(key_fields, *and_level, cond_func, item->field,
4373
 
                      true, &const_item, 1, usable_tables, sargables);
4374
 
      }
4375
 
    }
4376
 
    else 
4377
 
    {
4378
 
      /*
4379
 
        Consider all pairs of different fields included into item_equal.
4380
 
        For each of them (field1, field1) consider the equality 
4381
 
        field1=field2 as a condition allowing an index access of the table
4382
 
        with field1 by the keys value of field2.
4383
 
      */   
4384
 
      Item_equal_iterator fi(*item_equal);
4385
 
      while ((item= fi++))
4386
 
      {
4387
 
        Field *field= item->field;
4388
 
        while ((item= it++))
4389
 
        {
4390
 
          if (!field->eq(item->field))
4391
 
          {
4392
 
            add_key_field(key_fields, *and_level, cond_func, field,
4393
 
                          true, (Item **) &item, 1, usable_tables,
4394
 
                          sargables);
4395
 
          }
4396
 
        }
4397
 
        it.rewind();
4398
 
      }
4399
 
    }
4400
 
    break;
4401
 
  }
4402
 
}
4403
504
 
4404
505
/**
4405
506
  Add all keys with uses 'field' for some keypart.
4406
507
 
4407
508
  If field->and_level != and_level then only mark key_part as const_part.
4408
509
*/
4409
 
 
4410
 
static uint
4411
 
max_part_bit(key_part_map bits)
 
510
uint32_t max_part_bit(key_part_map bits)
4412
511
{
4413
512
  uint32_t found;
4414
513
  for (found=0; bits & 1 ; found++,bits>>=1) ;
4415
514
  return found;
4416
515
}
4417
516
 
4418
 
static void
4419
 
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
4420
 
{
4421
 
  Field *field=key_field->field;
4422
 
  Table *form= field->table;
4423
 
  KEYUSE keyuse;
4424
 
 
4425
 
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
4426
 
  {
4427
 
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
4428
 
    {
4429
 
      if (!(form->keys_in_use_for_query.is_set(key)))
4430
 
        continue;
4431
 
 
4432
 
      uint32_t key_parts= (uint) form->key_info[key].key_parts;
4433
 
      for (uint32_t part=0 ; part <  key_parts ; part++)
4434
 
      {
4435
 
        if (field->eq(form->key_info[key].key_part[part].field))
4436
 
        {
4437
 
          keyuse.table= field->table;
4438
 
          keyuse.val =  key_field->val;
4439
 
          keyuse.key =  key;
4440
 
          keyuse.keypart=part;
4441
 
          keyuse.keypart_map= (key_part_map) 1 << part;
4442
 
          keyuse.used_tables=key_field->val->used_tables();
4443
 
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
4444
 
          keyuse.null_rejecting= key_field->null_rejecting;
4445
 
          keyuse.cond_guard= key_field->cond_guard;
4446
 
          keyuse.sj_pred_no= key_field->sj_pred_no;
4447
 
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
4448
 
        }
4449
 
      }
4450
 
    }
4451
 
  }
4452
 
}
4453
 
 
4454
 
static int
4455
 
sort_keyuse(KEYUSE *a,KEYUSE *b)
 
517
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b)
4456
518
{
4457
519
  int res;
4458
 
  if (a->table->tablenr != b->table->tablenr)
4459
 
    return (int) (a->table->tablenr - b->table->tablenr);
4460
 
  if (a->key != b->key)
4461
 
    return (int) (a->key - b->key);
4462
 
  if (a->keypart != b->keypart)
4463
 
    return (int) (a->keypart - b->keypart);
 
520
  if (a->getTable()->tablenr != b->getTable()->tablenr)
 
521
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
 
522
  if (a->getKey() != b->getKey())
 
523
    return static_cast<int>((a->getKey() - b->getKey()));
 
524
  if (a->getKeypart() != b->getKeypart())
 
525
    return static_cast<int>((a->getKeypart() - b->getKeypart()));
4464
526
  // Place const values before other ones
4465
 
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
4466
 
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
 
527
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
 
528
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
4467
529
    return res;
4468
530
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
4469
 
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
4470
 
                (b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
4471
 
}
4472
 
 
4473
 
 
4474
 
/*
4475
 
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
4476
 
 
4477
 
    This function populates KEY_FIELD array with entries generated from the 
4478
 
    ON condition of the given nested join, and does the same for nested joins 
4479
 
    contained within this nested join.
4480
 
 
4481
 
  @param[in]      nested_join_table   Nested join pseudo-table to process
4482
 
  @param[in,out]  end                 End of the key field array
4483
 
  @param[in,out]  and_level           And-level
4484
 
  @param[in,out]  sargables           Array of found sargable candidates
4485
 
 
4486
 
 
4487
 
  @note
4488
 
    We can add accesses to the tables that are direct children of this nested 
4489
 
    join (1), and are not inner tables w.r.t their neighbours (2).
4490
 
    
4491
 
    Example for #1 (outer brackets pair denotes nested join this function is 
4492
 
    invoked for):
4493
 
    @code
4494
 
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
4495
 
    @endcode
4496
 
    Example for #2:
4497
 
    @code
4498
 
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
4499
 
    @endcode
4500
 
    In examples 1-2 for condition cond, we can add 'ref' access candidates to 
4501
 
    t1 only.
4502
 
    Example #3:
4503
 
    @code
4504
 
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
4505
 
    @endcode
4506
 
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
4507
 
*/
4508
 
 
4509
 
static void add_key_fields_for_nj(JOIN *join, TableList *nested_join_table,
4510
 
                                  KEY_FIELD **end, uint32_t *and_level,
4511
 
                                  SARGABLE_PARAM **sargables)
4512
 
{
4513
 
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
4514
 
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
4515
 
  bool have_another = false;
4516
 
  table_map tables= 0;
4517
 
  TableList *table;
4518
 
  assert(nested_join_table->nested_join);
4519
 
 
4520
 
  while ((table= li++) || (have_another && (li=li2, have_another=false,
4521
 
                                            (table= li++))))
4522
 
  {
4523
 
    if (table->nested_join)
4524
 
    {
4525
 
      if (!table->on_expr)
4526
 
      {
4527
 
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
4528
 
        have_another= true;
4529
 
        li2= li;
4530
 
        li= List_iterator<TableList>(table->nested_join->join_list); 
4531
 
      }
4532
 
      else
4533
 
        add_key_fields_for_nj(join, table, end, and_level, sargables);
4534
 
    }
4535
 
    else
4536
 
      if (!table->on_expr)
4537
 
        tables |= table->table->map;
4538
 
  }
4539
 
  if (nested_join_table->on_expr)
4540
 
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
4541
 
                   sargables);
 
531
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
 
532
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
4542
533
}
4543
534
 
4544
535
 
4545
536
/**
4546
537
  Update keyuse array with all possible keys we can use to fetch rows.
4547
 
  
4548
 
  @param       thd 
4549
 
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
 
538
 
 
539
  @param       session
 
540
  @param[out]  keyuse         Put here ordered array of KeyUse structures
4550
541
  @param       join_tab       Array in tablenr_order
4551
542
  @param       tables         Number of tables in join
4552
543
  @param       cond           WHERE condition (note that the function analyzes
4555
546
                              for which we can make ref access based the WHERE
4556
547
                              clause)
4557
548
  @param       select_lex     current SELECT
4558
 
  @param[out]  sargables      Array of found sargable candidates
4559
 
      
 
549
  @param[out]  sargables      std::vector of found sargable candidates
 
550
 
4560
551
   @retval
4561
552
     0  OK
4562
553
   @retval
4563
554
     1  Out of memory.
4564
555
*/
4565
 
 
4566
 
static bool
4567
 
update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
4568
 
                    uint32_t tables, COND *cond,
4569
 
                    COND_EQUAL *cond_equal __attribute__((unused)),
4570
 
                    table_map normal_tables, SELECT_LEX *select_lex,
4571
 
                    SARGABLE_PARAM **sargables)
 
556
bool update_ref_and_keys(Session *session,
 
557
                         DYNAMIC_ARRAY *keyuse,
 
558
                         JoinTable *join_tab,
 
559
                         uint32_t tables,
 
560
                         COND *cond, 
 
561
                         COND_EQUAL *,
 
562
                         table_map normal_tables,
 
563
                         Select_Lex *select_lex,
 
564
                         vector<optimizer::SargableParam> &sargables)
4572
565
{
4573
566
  uint  and_level,i,found_eq_constant;
4574
 
  KEY_FIELD *key_fields, *end, *field;
 
567
  optimizer::KeyField *key_fields, *end, *field;
4575
568
  uint32_t sz;
4576
 
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
4577
 
  
4578
 
  /* 
4579
 
    We use the same piece of memory to store both  KEY_FIELD 
4580
 
    and SARGABLE_PARAM structure.
4581
 
    KEY_FIELD values are placed at the beginning this memory
4582
 
    while  SARGABLE_PARAM values are put at the end.
4583
 
    All predicates that are used to fill arrays of KEY_FIELD
4584
 
    and SARGABLE_PARAM structures have at most 2 arguments
4585
 
    except BETWEEN predicates that have 3 arguments and 
 
569
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
 
570
 
 
571
  /*
 
572
    All predicates that are used to fill arrays of KeyField
 
573
    and SargableParam classes have at most 2 arguments
 
574
    except BETWEEN predicates that have 3 arguments and
4586
575
    IN predicates.
4587
 
    This any predicate if it's not BETWEEN/IN can be used 
4588
 
    directly to fill at most 2 array elements, either of KEY_FIELD
4589
 
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
 
576
    This any predicate if it's not BETWEEN/IN can be used
 
577
    directly to fill at most 2 array elements, either of KeyField 
 
578
    or SargableParam type. For a BETWEEN predicate 3 elements
4590
579
    can be filled as this predicate is considered as
4591
580
    saragable with respect to each of its argument.
4592
581
    An IN predicate can require at most 1 element as currently
4593
582
    it is considered as sargable only for its first argument.
4594
583
    Multiple equality can add  elements that are filled after
4595
584
    substitution of field arguments by equal fields. There
4596
 
    can be not more than select_lex->max_equal_elems such 
 
585
    can be not more than select_lex->max_equal_elems such
4597
586
    substitutions.
4598
 
  */ 
4599
 
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
4600
 
      (((thd->lex->current_select->cond_count+1)*2 +
4601
 
        thd->lex->current_select->between_count)*m+1);
4602
 
  if (!(key_fields=(KEY_FIELD*) thd->alloc(sz)))
4603
 
    return true; /* purecov: inspected */
 
587
  */
 
588
  sz= sizeof(optimizer::KeyField) *
 
589
      (((session->lex->current_select->cond_count+1) +
 
590
        session->lex->current_select->between_count)*m+1);
 
591
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
 
592
    return true;
4604
593
  and_level= 0;
4605
594
  field= end= key_fields;
4606
 
  *sargables= (SARGABLE_PARAM *) key_fields + 
4607
 
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
4608
 
  /* set a barrier for the array of SARGABLE_PARAM */
4609
 
  (*sargables)[0].field= 0; 
4610
595
 
4611
 
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
 
596
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
4612
597
    return true;
4613
598
  if (cond)
4614
599
  {
4615
600
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
4616
601
                   sargables);
4617
 
    for (; field != end ; field++)
 
602
    for (; field != end; field++)
4618
603
    {
4619
 
      add_key_part(keyuse,field);
 
604
      add_key_part(keyuse, field);
4620
605
      /* Mark that we can optimize LEFT JOIN */
4621
 
      if (field->val->type() == Item::NULL_ITEM &&
4622
 
          !field->field->real_maybe_null())
4623
 
        field->field->table->reginfo.not_exists_optimize=1;
 
606
      if (field->getValue()->type() == Item::NULL_ITEM &&
 
607
          ! field->getField()->real_maybe_null())
 
608
      {
 
609
        field->getField()->table->reginfo.not_exists_optimize= 1;
 
610
      }
4624
611
    }
4625
612
  }
4626
 
  for (i=0 ; i < tables ; i++)
 
613
  for (i= 0; i < tables; i++)
4627
614
  {
4628
615
    /*
4629
616
      Block the creation of keys for inner tables of outer joins.
4633
620
      In the future when we introduce conditional accesses
4634
621
      for inner tables in outer joins these keys will be taken
4635
622
      into account as well.
4636
 
    */ 
 
623
    */
4637
624
    if (*join_tab[i].on_expr_ref)
4638
 
      add_key_fields(join_tab->join, &end, &and_level, 
 
625
      add_key_fields(join_tab->join, &end, &and_level,
4639
626
                     *join_tab[i].on_expr_ref,
4640
627
                     join_tab[i].table->map, sargables);
4641
628
  }
4647
634
    while ((table= li++))
4648
635
    {
4649
636
      if (table->nested_join)
4650
 
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level, 
 
637
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
4651
638
                              sargables);
4652
639
    }
4653
640
  }
4667
654
  */
4668
655
  if (keyuse->elements)
4669
656
  {
4670
 
    KEYUSE key_end,*prev,*save_pos,*use;
 
657
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
4671
658
 
4672
 
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
 
659
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
4673
660
          (qsort_cmp) sort_keyuse);
4674
661
 
4675
662
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
4676
663
    insert_dynamic(keyuse,(unsigned char*) &key_end);
4677
664
 
4678
 
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
 
665
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
4679
666
    prev= &key_end;
4680
 
    found_eq_constant=0;
4681
 
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
 
667
    found_eq_constant= 0;
 
668
    for (i= 0; i < keyuse->elements-1; i++, use++)
4682
669
    {
4683
 
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
4684
 
        use->table->const_key_parts[use->key]|= use->keypart_map;
 
670
      if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
 
671
        use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
672
      if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
4685
673
      {
4686
 
        if (use->key == prev->key && use->table == prev->table)
4687
 
        {
4688
 
          if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
4689
 
            continue;                           /* remove */
4690
 
        }
4691
 
        else if (use->keypart != 0)             // First found must be 0
4692
 
          continue;
 
674
        if (prev->getKeypart() + 1 < use->getKeypart() || 
 
675
            ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
 
676
          continue;                             /* remove */
4693
677
      }
 
678
      else if (use->getKeypart() != 0)          // First found must be 0
 
679
        continue;
4694
680
 
4695
681
#ifdef HAVE_purify
4696
682
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
4698
684
#endif
4699
685
        *save_pos= *use;
4700
686
      prev=use;
4701
 
      found_eq_constant= !use->used_tables;
 
687
      found_eq_constant= ! use->getUsedTables();
4702
688
      /* Save ptr to first use */
4703
 
      if (!use->table->reginfo.join_tab->keyuse)
4704
 
        use->table->reginfo.join_tab->keyuse=save_pos;
4705
 
      use->table->reginfo.join_tab->checked_keys.set_bit(use->key);
 
689
      if (! use->getTable()->reginfo.join_tab->keyuse)
 
690
        use->getTable()->reginfo.join_tab->keyuse= save_pos;
 
691
      use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
4706
692
      save_pos++;
4707
693
    }
4708
 
    i=(uint) (save_pos-(KEYUSE*) keyuse->buffer);
4709
 
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
4710
 
    keyuse->elements=i;
 
694
    i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
 
695
    set_dynamic(keyuse, (unsigned char*) &key_end, i);
 
696
    keyuse->elements= i;
4711
697
  }
4712
698
  return false;
4713
699
}
4715
701
/**
4716
702
  Update some values in keyuse for faster choose_plan() loop.
4717
703
*/
4718
 
 
4719
 
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
 
704
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
4720
705
{
4721
 
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);
 
706
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
 
707
                                                  0, 
 
708
                                                  optimizer::KeyUse*);
4722
709
 
4723
710
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
4724
711
  {
4731
718
      Constant tables are ignored.
4732
719
      To avoid bad matches, we don't make ref_table_rows less than 100.
4733
720
    */
4734
 
    keyuse->ref_table_rows= ~(ha_rows) 0;       // If no ref
4735
 
    if (keyuse->used_tables &
4736
 
        (map= (keyuse->used_tables & ~join->const_table_map &
4737
 
               ~OUTER_REF_TABLE_BIT)))
 
721
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
 
722
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
4738
723
    {
4739
724
      uint32_t tablenr;
4740
725
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
4741
726
      if (map == 1)                     // Only one table
4742
727
      {
4743
 
        Table *tmp_table=join->all_tables[tablenr];
4744
 
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
 
728
        Table *tmp_table=join->all_tables[tablenr];
 
729
        keyuse->setTableRows(max(tmp_table->file->stats.records, (ha_rows)100));
4745
730
      }
4746
731
    }
4747
732
    /*
4748
733
      Outer reference (external field) is constant for single executing
4749
734
      of subquery
4750
735
    */
4751
 
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
4752
 
      keyuse->ref_table_rows= 1;
 
736
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
 
737
      keyuse->setTableRows(1);
4753
738
  }
4754
739
}
4755
740
 
4771
756
  @return
4772
757
    None
4773
758
*/
4774
 
 
4775
 
static void
4776
 
add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab)
 
759
void add_group_and_distinct_keys(JOIN *join, JoinTable *join_tab)
4777
760
{
4778
761
  List<Item_field> indexed_fields;
4779
762
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
4804
787
 
4805
788
  /* Intersect the keys of all group fields. */
4806
789
  cur_item= indexed_fields_it++;
4807
 
  possible_keys.merge(cur_item->field->part_of_key);
 
790
  possible_keys|= cur_item->field->part_of_key;
4808
791
  while ((cur_item= indexed_fields_it++))
4809
792
  {
4810
 
    possible_keys.intersect(cur_item->field->part_of_key);
4811
 
  }
4812
 
 
4813
 
  if (!possible_keys.is_clear_all())
4814
 
    join_tab->const_keys.merge(possible_keys);
4815
 
}
4816
 
 
4817
 
 
4818
 
/*****************************************************************************
4819
 
  Go through all combinations of not marked tables and find the one
4820
 
  which uses least records
4821
 
*****************************************************************************/
4822
 
 
4823
 
/** Save const tables first as used tables. */
4824
 
 
4825
 
static void
4826
 
set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
4827
 
{
4828
 
  join->positions[idx].table= table;
4829
 
  join->positions[idx].key=key;
4830
 
  join->positions[idx].records_read=1.0;        /* This is a const table */
4831
 
  join->positions[idx].ref_depend_map= 0;
4832
 
 
4833
 
  /* Move the const table as down as possible in best_ref */
4834
 
  JOIN_TAB **pos=join->best_ref+idx+1;
4835
 
  JOIN_TAB *next=join->best_ref[idx];
4836
 
  for (;next != table ; pos++)
4837
 
  {
4838
 
    JOIN_TAB *tmp=pos[0];
4839
 
    pos[0]=next;
4840
 
    next=tmp;
4841
 
  }
4842
 
  join->best_ref[idx]=table;
4843
 
}
4844
 
 
4845
 
 
4846
 
/*
4847
 
  Given a semi-join nest, find out which of the IN-equalities are bound
4848
 
 
4849
 
  SYNOPSIS
4850
 
    get_bound_sj_equalities()
4851
 
      sj_nest           Semi-join nest
4852
 
      remaining_tables  Tables that are not yet bound
4853
 
 
4854
 
  DESCRIPTION
4855
 
    Given a semi-join nest, find out which of the IN-equalities have their
4856
 
    left part expression bound (i.e. the said expression doesn't refer to
4857
 
    any of remaining_tables and can be evaluated).
4858
 
 
4859
 
  RETURN
4860
 
    Bitmap of bound IN-equalities.
4861
 
*/
4862
 
 
4863
 
uint64_t get_bound_sj_equalities(TableList *sj_nest, 
4864
 
                                  table_map remaining_tables)
4865
 
{
4866
 
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
4867
 
  Item *item;
4868
 
  uint32_t i= 0;
4869
 
  uint64_t res= 0;
4870
 
  while ((item= li++))
4871
 
  {
4872
 
    /*
4873
 
      Q: should this take into account equality propagation and how?
4874
 
      A: If e->outer_side is an Item_field, walk over the equality
4875
 
         class and see if there is an element that is bound?
4876
 
      (this is an optional feature)
4877
 
    */
4878
 
    if (!(item->used_tables() & remaining_tables))
4879
 
    {
4880
 
      res |= 1UL < i;
4881
 
    }
4882
 
  }
4883
 
  return res;
4884
 
}
4885
 
 
4886
 
 
4887
 
/**
4888
 
  Find the best access path for an extension of a partial execution
4889
 
  plan and add this path to the plan.
4890
 
 
4891
 
  The function finds the best access path to table 's' from the passed
4892
 
  partial plan where an access path is the general term for any means to
4893
 
  access the data in 's'. An access path may use either an index or a scan,
4894
 
  whichever is cheaper. The input partial plan is passed via the array
4895
 
  'join->positions' of length 'idx'. The chosen access method for 's' and its
4896
 
  cost are stored in 'join->positions[idx]'.
4897
 
 
4898
 
  @param join             pointer to the structure providing all context info
4899
 
                          for the query
4900
 
  @param s                the table to be joined by the function
4901
 
  @param thd              thread for the connection that submitted the query
4902
 
  @param remaining_tables set of tables not included into the partial plan yet
4903
 
  @param idx              the length of the partial plan
4904
 
  @param record_count     estimate for the number of records returned by the
4905
 
                          partial plan
4906
 
  @param read_time        the cost of the partial plan
4907
 
 
4908
 
  @return
4909
 
    None
4910
 
*/
4911
 
 
4912
 
static void
4913
 
best_access_path(JOIN      *join,
4914
 
                 JOIN_TAB  *s,
4915
 
                 THD       *thd,
4916
 
                 table_map remaining_tables,
4917
 
                 uint32_t      idx,
4918
 
                 double    record_count,
4919
 
                 double    read_time __attribute__((unused)))
4920
 
{
4921
 
  KEYUSE *best_key=         0;
4922
 
  uint32_t best_max_key_part=   0;
4923
 
  bool found_constraint= 0;
4924
 
  double best=              DBL_MAX;
4925
 
  double best_time=         DBL_MAX;
4926
 
  double records=           DBL_MAX;
4927
 
  table_map best_ref_depends_map= 0;
4928
 
  double tmp;
4929
 
  ha_rows rec;
4930
 
  uint32_t best_is_sj_inside_out=    0;
4931
 
 
4932
 
  if (s->keyuse)
4933
 
  {                                            /* Use key if possible */
4934
 
    Table *table= s->table;
4935
 
    KEYUSE *keyuse,*start_key=0;
4936
 
    double best_records= DBL_MAX;
4937
 
    uint32_t max_key_part=0;
4938
 
    uint64_t bound_sj_equalities= 0;
4939
 
    bool try_sj_inside_out= false;
4940
 
    /*
4941
 
      Discover the bound equalites. We need to do this, if
4942
 
        1. The next table is an SJ-inner table, and
4943
 
        2. It is the first table from that semijoin, and
4944
 
        3. We're not within a semi-join range (i.e. all semi-joins either have
4945
 
           all or none of their tables in join_table_map), except
4946
 
           s->emb_sj_nest (which we've just entered).
4947
 
        3. All correlation references from this sj-nest are bound
4948
 
    */
4949
 
    if (s->emb_sj_nest &&                                                 // (1)
4950
 
        s->emb_sj_nest->sj_in_exprs < 64 && 
4951
 
        ((remaining_tables & s->emb_sj_nest->sj_inner_tables) ==           // (2)
4952
 
         s->emb_sj_nest->sj_inner_tables) &&                               // (2)
4953
 
        join->cur_emb_sj_nests == s->emb_sj_nest->sj_inner_tables &&       // (3)
4954
 
        !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables)) // (4)
4955
 
    {
4956
 
      /* This table is an InsideOut scan candidate */
4957
 
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest, 
4958
 
                                                   remaining_tables);
4959
 
      try_sj_inside_out= true;
4960
 
    }
4961
 
 
4962
 
    /* Test how we can use keys */
4963
 
    rec= s->records/MATCHING_ROWS_IN_OTHER_TABLE;  // Assumed records/key
4964
 
    for (keyuse=s->keyuse ; keyuse->table == table ;)
4965
 
    {
4966
 
      key_part_map found_part= 0;
4967
 
      table_map found_ref= 0;
4968
 
      uint32_t key= keyuse->key;
4969
 
      KEY *keyinfo= table->key_info+key;
4970
 
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
4971
 
      key_part_map const_part= 0;
4972
 
      /* The or-null keypart in ref-or-null access: */
4973
 
      key_part_map ref_or_null_part= 0;
4974
 
 
4975
 
      /* Calculate how many key segments of the current key we can use */
4976
 
      start_key= keyuse;
4977
 
      uint64_t handled_sj_equalities=0;
4978
 
      key_part_map sj_insideout_map= 0;
4979
 
 
4980
 
      do /* For each keypart */
4981
 
      {
4982
 
        uint32_t keypart= keyuse->keypart;
4983
 
        table_map best_part_found_ref= 0;
4984
 
        double best_prev_record_reads= DBL_MAX;
4985
 
        
4986
 
        do /* For each way to access the keypart */
4987
 
        {
4988
 
 
4989
 
          /*
4990
 
            if 1. expression doesn't refer to forward tables
4991
 
               2. we won't get two ref-or-null's
4992
 
          */
4993
 
          if (!(remaining_tables & keyuse->used_tables) &&
4994
 
              !(ref_or_null_part && (keyuse->optimize &
4995
 
                                     KEY_OPTIMIZE_REF_OR_NULL)))
4996
 
          {
4997
 
            found_part|= keyuse->keypart_map;
4998
 
            if (!(keyuse->used_tables & ~join->const_table_map))
4999
 
              const_part|= keyuse->keypart_map;
5000
 
 
5001
 
            double tmp2= prev_record_reads(join, idx, (found_ref |
5002
 
                                                      keyuse->used_tables));
5003
 
            if (tmp2 < best_prev_record_reads)
5004
 
            {
5005
 
              best_part_found_ref= keyuse->used_tables & ~join->const_table_map;
5006
 
              best_prev_record_reads= tmp2;
5007
 
            }
5008
 
            if (rec > keyuse->ref_table_rows)
5009
 
              rec= keyuse->ref_table_rows;
5010
 
            /*
5011
 
              If there is one 'key_column IS NULL' expression, we can
5012
 
              use this ref_or_null optimisation of this field
5013
 
            */
5014
 
            if (keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL)
5015
 
              ref_or_null_part |= keyuse->keypart_map;
5016
 
          }
5017
 
 
5018
 
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
5019
 
          {
5020
 
            if (!(remaining_tables & keyuse->used_tables))
5021
 
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
5022
 
            else
5023
 
            {
5024
 
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
5025
 
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
5026
 
            }
5027
 
          }
5028
 
 
5029
 
          keyuse++;
5030
 
        } while (keyuse->table == table && keyuse->key == key &&
5031
 
                 keyuse->keypart == keypart);
5032
 
        found_ref|= best_part_found_ref;
5033
 
      } while (keyuse->table == table && keyuse->key == key);
5034
 
 
5035
 
      /*
5036
 
        Assume that that each key matches a proportional part of table.
5037
 
      */
5038
 
      if (!found_part && !handled_sj_equalities)
5039
 
        continue;                               // Nothing usable found
5040
 
 
5041
 
      if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
5042
 
        rec= MATCHING_ROWS_IN_OTHER_TABLE;      // Fix for small tables
5043
 
 
5044
 
      bool sj_inside_out_scan= false;
5045
 
      {
5046
 
        found_constraint= 1;
5047
 
        /*
5048
 
          Check if InsideOut scan is applicable:
5049
 
          1. All IN-equalities are either "bound" or "handled"
5050
 
          2. Index keyparts are 
5051
 
             ...
5052
 
        */
5053
 
        if (try_sj_inside_out && 
5054
 
            table->covering_keys.is_set(key) &&
5055
 
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
5056
 
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
5057
 
        {
5058
 
          uint32_t n_fixed_parts= max_part_bit(found_part);
5059
 
          if (n_fixed_parts != keyinfo->key_parts &&
5060
 
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
5061
 
               PREV_BITS(uint, keyinfo->key_parts))
5062
 
          {
5063
 
            /*
5064
 
              Not all parts are fixed. Produce bitmap of remaining bits and
5065
 
              check if all of them are covered.
5066
 
            */
5067
 
            sj_inside_out_scan= true;
5068
 
            if (!n_fixed_parts)
5069
 
            {
5070
 
              /*
5071
 
                It's a confluent ref scan.
5072
 
 
5073
 
                That is, all found KEYUSE elements refer to IN-equalities,
5074
 
                and there is really no ref access because there is no
5075
 
                  t.keypart0 = {bound expression}
5076
 
 
5077
 
                Calculate the cost of complete loose index scan.
5078
 
              */
5079
 
              records= (double)s->table->file->stats.records;
5080
 
 
5081
 
              /* The cost is entire index scan cost (divided by 2) */
5082
 
              best_time= s->table->file->index_only_read_time(key, records);
5083
 
 
5084
 
              /* Now figure how many different keys we will get */
5085
 
              ulong rpc;
5086
 
              if ((rpc= keyinfo->rec_per_key[keyinfo->key_parts-1]))
5087
 
                records= records / rpc;
5088
 
              start_key= NULL;
5089
 
            }
5090
 
          }
5091
 
        }
5092
 
 
5093
 
        /*
5094
 
          Check if we found full key
5095
 
        */
5096
 
        if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
5097
 
            !ref_or_null_part)
5098
 
        {                                         /* use eq key */
5099
 
          max_key_part= UINT32_MAX;
5100
 
          if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)
5101
 
          {
5102
 
            tmp = prev_record_reads(join, idx, found_ref);
5103
 
            records=1.0;
5104
 
          }
5105
 
          else
5106
 
          {
5107
 
            if (!found_ref)
5108
 
            {                                     /* We found a const key */
5109
 
              /*
5110
 
                ReuseRangeEstimateForRef-1:
5111
 
                We get here if we've found a ref(const) (c_i are constants):
5112
 
                  "(keypart1=c1) AND ... AND (keypartN=cN)"   [ref_const_cond]
5113
 
                
5114
 
                If range optimizer was able to construct a "range" 
5115
 
                access on this index, then its condition "quick_cond" was
5116
 
                eqivalent to ref_const_cond (*), and we can re-use E(#rows)
5117
 
                from the range optimizer.
5118
 
                
5119
 
                Proof of (*): By properties of range and ref optimizers 
5120
 
                quick_cond will be equal or tighther than ref_const_cond. 
5121
 
                ref_const_cond already covers "smallest" possible interval - 
5122
 
                a singlepoint interval over all keyparts. Therefore, 
5123
 
                quick_cond is equivalent to ref_const_cond (if it was an 
5124
 
                empty interval we wouldn't have got here).
5125
 
              */
5126
 
              if (table->quick_keys.is_set(key))
5127
 
                records= (double) table->quick_rows[key];
5128
 
              else
5129
 
              {
5130
 
                /* quick_range couldn't use key! */
5131
 
                records= (double) s->records/rec;
5132
 
              }
5133
 
            }
5134
 
            else
5135
 
            {
5136
 
              if (!(records=keyinfo->rec_per_key[keyinfo->key_parts-1]))
5137
 
              {                                   /* Prefer longer keys */
5138
 
                records=
5139
 
                  ((double) s->records / (double) rec *
5140
 
                   (1.0 +
5141
 
                    ((double) (table->s->max_key_length-keyinfo->key_length) /
5142
 
                     (double) table->s->max_key_length)));
5143
 
                if (records < 2.0)
5144
 
                  records=2.0;               /* Can't be as good as a unique */
5145
 
              }
5146
 
              /*
5147
 
                ReuseRangeEstimateForRef-2:  We get here if we could not reuse
5148
 
                E(#rows) from range optimizer. Make another try:
5149
 
                
5150
 
                If range optimizer produced E(#rows) for a prefix of the ref
5151
 
                access we're considering, and that E(#rows) is lower then our
5152
 
                current estimate, make an adjustment. The criteria of when we
5153
 
                can make an adjustment is a special case of the criteria used
5154
 
                in ReuseRangeEstimateForRef-3.
5155
 
              */
5156
 
              if (table->quick_keys.is_set(key) &&
5157
 
                  const_part & (1 << table->quick_key_parts[key]) &&
5158
 
                  table->quick_n_ranges[key] == 1 &&
5159
 
                  records > (double) table->quick_rows[key])
5160
 
              {
5161
 
                records= (double) table->quick_rows[key];
5162
 
              }
5163
 
            }
5164
 
            /* Limit the number of matched rows */
5165
 
            tmp= records;
5166
 
            set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
5167
 
            if (table->covering_keys.is_set(key))
5168
 
            {
5169
 
              /* we can use only index tree */
5170
 
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5171
 
            }
5172
 
            else
5173
 
              tmp= record_count*cmin(tmp,s->worst_seeks);
5174
 
          }
5175
 
        }
5176
 
        else
5177
 
        {
5178
 
          /*
5179
 
            Use as much key-parts as possible and a uniq key is better
5180
 
            than a not unique key
5181
 
            Set tmp to (previous record count) * (records / combination)
5182
 
          */
5183
 
          if ((found_part & 1) &&
5184
 
              (!(table->file->index_flags(key, 0, 0) & HA_ONLY_WHOLE_INDEX) ||
5185
 
               found_part == PREV_BITS(uint,keyinfo->key_parts)))
5186
 
          {
5187
 
            max_key_part= max_part_bit(found_part);
5188
 
            /*
5189
 
              ReuseRangeEstimateForRef-3:
5190
 
              We're now considering a ref[or_null] access via
5191
 
              (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR  
5192
 
              (same-as-above but with one cond replaced 
5193
 
               with "t.keypart_i IS NULL")]  (**)
5194
 
              
5195
 
              Try re-using E(#rows) from "range" optimizer:
5196
 
              We can do so if "range" optimizer used the same intervals as
5197
 
              in (**). The intervals used by range optimizer may be not 
5198
 
              available at this point (as "range" access might have choosen to
5199
 
              create quick select over another index), so we can't compare
5200
 
              them to (**). We'll make indirect judgements instead.
5201
 
              The sufficient conditions for re-use are:
5202
 
              (C1) All e_i in (**) are constants, i.e. found_ref==false. (if
5203
 
                   this is not satisfied we have no way to know which ranges
5204
 
                   will be actually scanned by 'ref' until we execute the 
5205
 
                   join)
5206
 
              (C2) max #key parts in 'range' access == K == max_key_part (this
5207
 
                   is apparently a necessary requirement)
5208
 
 
5209
 
              We also have a property that "range optimizer produces equal or 
5210
 
              tighter set of scan intervals than ref(const) optimizer". Each
5211
 
              of the intervals in (**) are "tightest possible" intervals when 
5212
 
              one limits itself to using keyparts 1..K (which we do in #2).              
5213
 
              From here it follows that range access used either one, or
5214
 
              both of the (I1) and (I2) intervals:
5215
 
              
5216
 
               (t.keypart1=c1 AND ... AND t.keypartK=eK)  (I1) 
5217
 
               (same-as-above but with one cond replaced  
5218
 
                with "t.keypart_i IS NULL")               (I2)
5219
 
 
5220
 
              The remaining part is to exclude the situation where range
5221
 
              optimizer used one interval while we're considering
5222
 
              ref-or-null and looking for estimate for two intervals. This
5223
 
              is done by last limitation:
5224
 
 
5225
 
              (C3) "range optimizer used (have ref_or_null?2:1) intervals"
5226
 
            */
5227
 
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
5228
 
                table->quick_key_parts[key] == max_key_part &&          //(C2)
5229
 
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
5230
 
            {
5231
 
              tmp= records= (double) table->quick_rows[key];
5232
 
            }
5233
 
            else
5234
 
            {
5235
 
              /* Check if we have statistic about the distribution */
5236
 
              if ((records= keyinfo->rec_per_key[max_key_part-1]))
5237
 
              {
5238
 
                /* 
5239
 
                  Fix for the case where the index statistics is too
5240
 
                  optimistic: If 
5241
 
                  (1) We're considering ref(const) and there is quick select
5242
 
                      on the same index, 
5243
 
                  (2) and that quick select uses more keyparts (i.e. it will
5244
 
                      scan equal/smaller interval then this ref(const))
5245
 
                  (3) and E(#rows) for quick select is higher then our
5246
 
                      estimate,
5247
 
                  Then 
5248
 
                    We'll use E(#rows) from quick select.
5249
 
 
5250
 
                  Q: Why do we choose to use 'ref'? Won't quick select be
5251
 
                  cheaper in some cases ?
5252
 
                  TODO: figure this out and adjust the plan choice if needed.
5253
 
                */
5254
 
                if (!found_ref && table->quick_keys.is_set(key) &&    // (1)
5255
 
                    table->quick_key_parts[key] > max_key_part &&     // (2)
5256
 
                    records < (double)table->quick_rows[key])         // (3)
5257
 
                  records= (double)table->quick_rows[key];
5258
 
 
5259
 
                tmp= records;
5260
 
              }
5261
 
              else
5262
 
              {
5263
 
                /*
5264
 
                  Assume that the first key part matches 1% of the file
5265
 
                  and that the whole key matches 10 (duplicates) or 1
5266
 
                  (unique) records.
5267
 
                  Assume also that more key matches proportionally more
5268
 
                  records
5269
 
                  This gives the formula:
5270
 
                  records = (x * (b-a) + a*c-b)/(c-1)
5271
 
 
5272
 
                  b = records matched by whole key
5273
 
                  a = records matched by first key part (1% of all records?)
5274
 
                  c = number of key parts in key
5275
 
                  x = used key parts (1 <= x <= c)
5276
 
                */
5277
 
                double rec_per_key;
5278
 
                if (!(rec_per_key=(double)
5279
 
                      keyinfo->rec_per_key[keyinfo->key_parts-1]))
5280
 
                  rec_per_key=(double) s->records/rec+1;
5281
 
 
5282
 
                if (!s->records)
5283
 
                  tmp = 0;
5284
 
                else if (rec_per_key/(double) s->records >= 0.01)
5285
 
                  tmp = rec_per_key;
5286
 
                else
5287
 
                {
5288
 
                  double a=s->records*0.01;
5289
 
                  if (keyinfo->key_parts > 1)
5290
 
                    tmp= (max_key_part * (rec_per_key - a) +
5291
 
                          a*keyinfo->key_parts - rec_per_key)/
5292
 
                         (keyinfo->key_parts-1);
5293
 
                  else
5294
 
                    tmp= a;
5295
 
                  set_if_bigger(tmp,1.0);
5296
 
                }
5297
 
                records = (ulong) tmp;
5298
 
              }
5299
 
 
5300
 
              if (ref_or_null_part)
5301
 
              {
5302
 
                /* We need to do two key searches to find key */
5303
 
                tmp *= 2.0;
5304
 
                records *= 2.0;
5305
 
              }
5306
 
 
5307
 
              /*
5308
 
                ReuseRangeEstimateForRef-4:  We get here if we could not reuse
5309
 
                E(#rows) from range optimizer. Make another try:
5310
 
                
5311
 
                If range optimizer produced E(#rows) for a prefix of the ref 
5312
 
                access we're considering, and that E(#rows) is lower then our
5313
 
                current estimate, make the adjustment.
5314
 
 
5315
 
                The decision whether we can re-use the estimate from the range
5316
 
                optimizer is the same as in ReuseRangeEstimateForRef-3,
5317
 
                applied to first table->quick_key_parts[key] key parts.
5318
 
              */
5319
 
              if (table->quick_keys.is_set(key) &&
5320
 
                  table->quick_key_parts[key] <= max_key_part &&
5321
 
                  const_part & (1 << table->quick_key_parts[key]) &&
5322
 
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
5323
 
                                                     const_part) ? 1 : 0) &&
5324
 
                  records > (double) table->quick_rows[key])
5325
 
              {
5326
 
                tmp= records= (double) table->quick_rows[key];
5327
 
              }
5328
 
            }
5329
 
 
5330
 
            /* Limit the number of matched rows */
5331
 
            set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
5332
 
            if (table->covering_keys.is_set(key))
5333
 
            {
5334
 
              /* we can use only index tree */
5335
 
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5336
 
            }
5337
 
            else
5338
 
              tmp= record_count * cmin(tmp,s->worst_seeks);
5339
 
          }
5340
 
          else
5341
 
            tmp= best_time;                    // Do nothing
5342
 
        }
5343
 
 
5344
 
        if (sj_inside_out_scan && !start_key)
5345
 
        {
5346
 
          tmp= tmp/2;
5347
 
          if (records)
5348
 
            records= records/2;
5349
 
        }
5350
 
 
5351
 
      }
5352
 
      if (tmp < best_time - records/(double) TIME_FOR_COMPARE)
5353
 
      {
5354
 
        best_time= tmp + records/(double) TIME_FOR_COMPARE;
5355
 
        best= tmp;
5356
 
        best_records= records;
5357
 
        best_key= start_key;
5358
 
        best_max_key_part= max_key_part;
5359
 
        best_ref_depends_map= found_ref;
5360
 
        best_is_sj_inside_out= sj_inside_out_scan;
5361
 
      }
5362
 
    }
5363
 
    records= best_records;
5364
 
  }
5365
 
 
5366
 
  /*
5367
 
    Don't test table scan if it can't be better.
5368
 
    Prefer key lookup if we would use the same key for scanning.
5369
 
 
5370
 
    Don't do a table scan on InnoDB tables, if we can read the used
5371
 
    parts of the row from any of the used index.
5372
 
    This is because table scans uses index and we would not win
5373
 
    anything by using a table scan.
5374
 
 
5375
 
    A word for word translation of the below if-statement in sergefp's
5376
 
    understanding: we check if we should use table scan if:
5377
 
    (1) The found 'ref' access produces more records than a table scan
5378
 
        (or index scan, or quick select), or 'ref' is more expensive than
5379
 
        any of them.
5380
 
    (2) This doesn't hold: the best way to perform table scan is to to perform
5381
 
        'range' access using index IDX, and the best way to perform 'ref' 
5382
 
        access is to use the same index IDX, with the same or more key parts.
5383
 
        (note: it is not clear how this rule is/should be extended to 
5384
 
        index_merge quick selects)
5385
 
    (3) See above note about InnoDB.
5386
 
    (4) NOT ("FORCE INDEX(...)" is used for table and there is 'ref' access
5387
 
             path, but there is no quick select)
5388
 
        If the condition in the above brackets holds, then the only possible
5389
 
        "table scan" access method is ALL/index (there is no quick select).
5390
 
        Since we have a 'ref' access path, and FORCE INDEX instructs us to
5391
 
        choose it over ALL/index, there is no need to consider a full table
5392
 
        scan.
5393
 
  */
5394
 
  if ((records >= s->found_records || best > s->read_time) &&            // (1)
5395
 
      !(s->quick && best_key && s->quick->index == best_key->key &&      // (2)
5396
 
        best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2)
5397
 
      !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) &&   // (3)
5398
 
        ! s->table->covering_keys.is_clear_all() && best_key && !s->quick) &&// (3)
5399
 
      !(s->table->force_index && best_key && !s->quick))                 // (4)
5400
 
  {                                             // Check full join
5401
 
    ha_rows rnd_records= s->found_records;
5402
 
    /*
5403
 
      If there is a filtering condition on the table (i.e. ref analyzer found
5404
 
      at least one "table.keyXpartY= exprZ", where exprZ refers only to tables
5405
 
      preceding this table in the join order we're now considering), then 
5406
 
      assume that 25% of the rows will be filtered out by this condition.
5407
 
 
5408
 
      This heuristic is supposed to force tables used in exprZ to be before
5409
 
      this table in join order.
5410
 
    */
5411
 
    if (found_constraint)
5412
 
      rnd_records-= rnd_records/4;
5413
 
 
5414
 
    /*
5415
 
      If applicable, get a more accurate estimate. Don't use the two
5416
 
      heuristics at once.
5417
 
    */
5418
 
    if (s->table->quick_condition_rows != s->found_records)
5419
 
      rnd_records= s->table->quick_condition_rows;
5420
 
 
5421
 
    /*
5422
 
      Range optimizer never proposes a RANGE if it isn't better
5423
 
      than FULL: so if RANGE is present, it's always preferred to FULL.
5424
 
      Here we estimate its cost.
5425
 
    */
5426
 
    if (s->quick)
5427
 
    {
5428
 
      /*
5429
 
        For each record we:
5430
 
        - read record range through 'quick'
5431
 
        - skip rows which does not satisfy WHERE constraints
5432
 
        TODO: 
5433
 
        We take into account possible use of join cache for ALL/index
5434
 
        access (see first else-branch below), but we don't take it into 
5435
 
        account here for range/index_merge access. Find out why this is so.
5436
 
      */
5437
 
      tmp= record_count *
5438
 
        (s->quick->read_time +
5439
 
         (s->found_records - rnd_records)/(double) TIME_FOR_COMPARE);
5440
 
    }
5441
 
    else
5442
 
    {
5443
 
      /* Estimate cost of reading table. */
5444
 
      tmp= s->table->file->scan_time();
5445
 
      if (s->table->map & join->outer_join)     // Can't use join cache
5446
 
      {
5447
 
        /*
5448
 
          For each record we have to:
5449
 
          - read the whole table record 
5450
 
          - skip rows which does not satisfy join condition
5451
 
        */
5452
 
        tmp= record_count *
5453
 
          (tmp +
5454
 
           (s->records - rnd_records)/(double) TIME_FOR_COMPARE);
5455
 
      }
5456
 
      else
5457
 
      {
5458
 
        /* We read the table as many times as join buffer becomes full. */
5459
 
        tmp*= (1.0 + floor((double) cache_record_length(join,idx) *
5460
 
                           record_count /
5461
 
                           (double) thd->variables.join_buff_size));
5462
 
        /* 
5463
 
            We don't make full cartesian product between rows in the scanned
5464
 
           table and existing records because we skip all rows from the
5465
 
           scanned table, which does not satisfy join condition when 
5466
 
           we read the table (see flush_cached_records for details). Here we
5467
 
           take into account cost to read and skip these records.
5468
 
        */
5469
 
        tmp+= (s->records - rnd_records)/(double) TIME_FOR_COMPARE;
5470
 
      }
5471
 
    }
5472
 
 
5473
 
    /*
5474
 
      We estimate the cost of evaluating WHERE clause for found records
5475
 
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
5476
 
      tmp give us total cost of using Table SCAN
5477
 
    */
5478
 
    if (best == DBL_MAX ||
5479
 
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
5480
 
         best + record_count/(double) TIME_FOR_COMPARE*records))
5481
 
    {
5482
 
      /*
5483
 
        If the table has a range (s->quick is set) make_join_select()
5484
 
        will ensure that this will be used
5485
 
      */
5486
 
      best= tmp;
5487
 
      records= rows2double(rnd_records);
5488
 
      best_key= 0;
5489
 
      /* range/index_merge/ALL/index access method are "independent", so: */
5490
 
      best_ref_depends_map= 0;
5491
 
      best_is_sj_inside_out= false;
5492
 
    }
5493
 
  }
5494
 
 
5495
 
  /* Update the cost information for the current partial plan */
5496
 
  join->positions[idx].records_read= records;
5497
 
  join->positions[idx].read_time=    best;
5498
 
  join->positions[idx].key=          best_key;
5499
 
  join->positions[idx].table=        s;
5500
 
  join->positions[idx].ref_depend_map= best_ref_depends_map;
5501
 
  join->positions[idx].use_insideout_scan= best_is_sj_inside_out;
5502
 
 
5503
 
  if (!best_key &&
5504
 
      idx == join->const_tables &&
5505
 
      s->table == join->sort_by_table &&
5506
 
      join->unit->select_limit_cnt >= records)
5507
 
    join->sort_by_table= (Table*) 1;  // Must use temporary table
5508
 
 
5509
 
  return;
5510
 
}
5511
 
 
5512
 
 
5513
 
/**
5514
 
  Selects and invokes a search strategy for an optimal query plan.
5515
 
 
5516
 
  The function checks user-configurable parameters that control the search
5517
 
  strategy for an optimal plan, selects the search method and then invokes
5518
 
  it. Each specific optimization procedure stores the final optimal plan in
5519
 
  the array 'join->best_positions', and the cost of the plan in
5520
 
  'join->best_read'.
5521
 
 
5522
 
  @param join         pointer to the structure providing all context info for
5523
 
                      the query
5524
 
  @param join_tables  set of the tables in the query
5525
 
 
5526
 
  @todo
5527
 
    'MAX_TABLES+2' denotes the old implementation of find_best before
5528
 
    the greedy version. Will be removed when greedy_search is approved.
5529
 
 
5530
 
  @retval
5531
 
    false       ok
5532
 
  @retval
5533
 
    true        Fatal error
5534
 
*/
5535
 
 
5536
 
static bool
5537
 
choose_plan(JOIN *join, table_map join_tables)
5538
 
{
5539
 
  uint32_t search_depth= join->thd->variables.optimizer_search_depth;
5540
 
  uint32_t prune_level=  join->thd->variables.optimizer_prune_level;
5541
 
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
5542
 
 
5543
 
  join->cur_embedding_map= 0;
5544
 
  reset_nj_counters(join->join_list);
5545
 
  /*
5546
 
    if (SELECT_STRAIGHT_JOIN option is set)
5547
 
      reorder tables so dependent tables come after tables they depend 
5548
 
      on, otherwise keep tables in the order they were specified in the query 
5549
 
    else
5550
 
      Apply heuristic: pre-sort all access plans with respect to the number of
5551
 
      records accessed.
5552
 
  */
5553
 
  my_qsort(join->best_ref + join->const_tables,
5554
 
           join->tables - join->const_tables, sizeof(JOIN_TAB*),
5555
 
           straight_join ? join_tab_cmp_straight : join_tab_cmp);
5556
 
  join->cur_emb_sj_nests= 0;
5557
 
  if (straight_join)
5558
 
  {
5559
 
    optimize_straight_join(join, join_tables);
5560
 
  }
5561
 
  else
5562
 
  {
5563
 
    if (search_depth == MAX_TABLES+2)
5564
 
    { /*
5565
 
        TODO: 'MAX_TABLES+2' denotes the old implementation of find_best before
5566
 
        the greedy version. Will be removed when greedy_search is approved.
5567
 
      */
5568
 
      join->best_read= DBL_MAX;
5569
 
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
5570
 
        return(true);
5571
 
    } 
5572
 
    else
5573
 
    {
5574
 
      if (search_depth == 0)
5575
 
        /* Automatically determine a reasonable value for 'search_depth' */
5576
 
        search_depth= determine_search_depth(join);
5577
 
      if (greedy_search(join, join_tables, search_depth, prune_level))
5578
 
        return(true);
5579
 
    }
5580
 
  }
5581
 
 
5582
 
  /* 
5583
 
    Store the cost of this query into a user variable
5584
 
    Don't update last_query_cost for statements that are not "flat joins" :
5585
 
    i.e. they have subqueries, unions or call stored procedures.
5586
 
    TODO: calculate a correct cost for a query with subqueries and UNIONs.
5587
 
  */
5588
 
  if (join->thd->lex->is_single_level_stmt())
5589
 
    join->thd->status_var.last_query_cost= join->best_read;
5590
 
  return(false);
5591
 
}
5592
 
 
5593
 
 
5594
 
/**
5595
 
  Compare two JOIN_TAB objects based on the number of accessed records.
5596
 
 
5597
 
  @param ptr1 pointer to first JOIN_TAB object
5598
 
  @param ptr2 pointer to second JOIN_TAB object
 
793
    possible_keys&= cur_item->field->part_of_key;
 
794
  }
 
795
 
 
796
  if (possible_keys.any())
 
797
    join_tab->const_keys|= possible_keys;
 
798
}
 
799
 
 
800
/**
 
801
  Compare two JoinTable objects based on the number of accessed records.
 
802
 
 
803
  @param ptr1 pointer to first JoinTable object
 
804
  @param ptr2 pointer to second JoinTable object
5599
805
 
5600
806
  NOTES
5601
807
    The order relation implemented by join_tab_cmp() is not transitive,
5607
813
      a: dependent = 0x0 table->map = 0x1 found_records = 3 ptr = 0x907e6b0
5608
814
      b: dependent = 0x0 table->map = 0x2 found_records = 3 ptr = 0x907e838
5609
815
      c: dependent = 0x6 table->map = 0x10 found_records = 2 ptr = 0x907ecd0
5610
 
     
 
816
 
5611
817
  @retval
5612
818
    1  if first is bigger
5613
819
  @retval
5615
821
  @retval
5616
822
    0  if equal
5617
823
*/
5618
 
 
5619
 
static int
5620
 
join_tab_cmp(const void* ptr1, const void* ptr2)
 
824
int join_tab_cmp(const void* ptr1, const void* ptr2)
5621
825
{
5622
 
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
5623
 
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
 
826
  JoinTable *jt1= *(JoinTable**) ptr1;
 
827
  JoinTable *jt2= *(JoinTable**) ptr2;
5624
828
 
5625
829
  if (jt1->dependent & jt2->table->map)
5626
830
    return 1;
5627
831
  if (jt2->dependent & jt1->table->map)
5628
 
    return -1;  
 
832
    return -1;
5629
833
  if (jt1->found_records > jt2->found_records)
5630
834
    return 1;
5631
835
  if (jt1->found_records < jt2->found_records)
5632
 
    return -1; 
 
836
    return -1;
5633
837
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
5634
838
}
5635
839
 
5636
 
 
5637
840
/**
5638
841
  Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN.
5639
842
*/
5640
 
 
5641
 
static int
5642
 
join_tab_cmp_straight(const void* ptr1, const void* ptr2)
 
843
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
5643
844
{
5644
 
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
5645
 
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
 
845
  JoinTable *jt1= *(JoinTable**) ptr1;
 
846
  JoinTable *jt2= *(JoinTable**) ptr2;
5646
847
 
5647
848
  if (jt1->dependent & jt2->table->map)
5648
849
    return 1;
5652
853
}
5653
854
 
5654
855
/**
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->thd, 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
 
  THD *thd= join->thd;
6031
 
  if (thd->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, thd, 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
 
  THD *thd= join->thd;
6156
 
  if (thd->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, thd, 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
 
/**
6223
856
  Find how much space the prevous read not const tables takes in cache.
6224
857
*/
6225
 
 
6226
 
static void calc_used_field_length(THD *thd __attribute__((unused)),
6227
 
                                   JOIN_TAB *join_tab)
 
858
void calc_used_field_length(Session *, JoinTable *join_tab)
6228
859
{
6229
860
  uint32_t null_fields,blobs,fields,rec_length;
6230
861
  Field **f_ptr,*field;
6231
 
  MY_BITMAP *read_set= join_tab->table->read_set;;
6232
862
 
6233
863
  null_fields= blobs= fields= rec_length=0;
6234
864
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
6235
865
  {
6236
 
    if (bitmap_is_set(read_set, field->field_index))
 
866
    if (field->isReadSet())
6237
867
    {
6238
868
      uint32_t flags=field->flags;
6239
869
      fields++;
6240
870
      rec_length+=field->pack_length();
6241
871
      if (flags & BLOB_FLAG)
6242
 
        blobs++;
 
872
        blobs++;
6243
873
      if (!(flags & NOT_NULL_FLAG))
6244
 
        null_fields++;
 
874
        null_fields++;
6245
875
    }
6246
876
  }
6247
877
  if (null_fields)
6250
880
    rec_length+=sizeof(bool);
6251
881
  if (blobs)
6252
882
  {
6253
 
    uint32_t blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
6254
 
                             (join_tab->table->getRecordLength()- rec_length));
6255
 
    rec_length+=(uint) cmax((uint)4,blob_length);
6256
 
  }
6257
 
  join_tab->used_fields=fields;
6258
 
  join_tab->used_fieldlength=rec_length;
6259
 
  join_tab->used_blobs=blobs;
6260
 
}
6261
 
 
6262
 
 
6263
 
static uint
6264
 
cache_record_length(JOIN *join,uint32_t idx)
6265
 
{
6266
 
  uint32_t length=0;
6267
 
  JOIN_TAB **pos,**end;
6268
 
  THD *thd=join->thd;
6269
 
 
6270
 
  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
6271
 
       pos != end ;
6272
 
       pos++)
6273
 
  {
6274
 
    JOIN_TAB *join_tab= *pos;
6275
 
    if (!join_tab->used_fieldlength)            /* Not calced yet */
6276
 
      calc_used_field_length(thd, join_tab);
6277
 
    length+=join_tab->used_fieldlength;
6278
 
  }
6279
 
  return length;
6280
 
}
6281
 
 
6282
 
 
6283
 
/*
6284
 
  Get the number of different row combinations for subset of partial join
6285
 
 
6286
 
  SYNOPSIS
6287
 
    prev_record_reads()
6288
 
      join       The join structure
6289
 
      idx        Number of tables in the partial join order (i.e. the
6290
 
                 partial join order is in join->positions[0..idx-1])
6291
 
      found_ref  Bitmap of tables for which we need to find # of distinct
6292
 
                 row combinations.
6293
 
 
6294
 
  DESCRIPTION
6295
 
    Given a partial join order (in join->positions[0..idx-1]) and a subset of
6296
 
    tables within that join order (specified in found_ref), find out how many
6297
 
    distinct row combinations of subset tables will be in the result of the
6298
 
    partial join order.
6299
 
     
6300
 
    This is used as follows: Suppose we have a table accessed with a ref-based
6301
 
    method. The ref access depends on current rows of tables in found_ref.
6302
 
    We want to count # of different ref accesses. We assume two ref accesses
6303
 
    will be different if at least one of access parameters is different.
6304
 
    Example: consider a query
6305
 
 
6306
 
    SELECT * FROM t1, t2, t3 WHERE t1.key=c1 AND t2.key=c2 AND t3.key=t1.field
6307
 
 
6308
 
    and a join order:
6309
 
      t1,  ref access on t1.key=c1
6310
 
      t2,  ref access on t2.key=c2       
6311
 
      t3,  ref access on t3.key=t1.field 
6312
 
    
6313
 
    For t1: n_ref_scans = 1, n_distinct_ref_scans = 1
6314
 
    For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1
6315
 
    For t3: n_ref_scans = records_read(t1)*records_read(t2)
6316
 
            n_distinct_ref_scans = #records_read(t1)
6317
 
    
6318
 
    The reason for having this function (at least the latest version of it)
6319
 
    is that we need to account for buffering in join execution. 
6320
 
    
6321
 
    An edge-case example: if we have a non-first table in join accessed via
6322
 
    ref(const) or ref(param) where there is a small number of different
6323
 
    values of param, then the access will likely hit the disk cache and will
6324
 
    not require any disk seeks.
6325
 
    
6326
 
    The proper solution would be to assume an LRU disk cache of some size,
6327
 
    calculate probability of cache hits, etc. For now we just count
6328
 
    identical ref accesses as one.
6329
 
 
6330
 
  RETURN 
6331
 
    Expected number of row combinations
6332
 
*/
6333
 
 
6334
 
static double
6335
 
prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
6336
 
{
6337
 
  double found=1.0;
6338
 
  POSITION *pos_end= join->positions - 1;
6339
 
  for (POSITION *pos= join->positions + idx - 1; pos != pos_end; pos--)
6340
 
  {
6341
 
    if (pos->table->table->map & found_ref)
6342
 
    {
6343
 
      found_ref|= pos->ref_depend_map;
6344
 
      /* 
6345
 
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table 
6346
 
        with no matching row we will get position[t2].records_read==0. 
6347
 
        Actually the size of output is one null-complemented row, therefore 
6348
 
        we will use value of 1 whenever we get records_read==0.
6349
 
 
6350
 
        Note
6351
 
        - the above case can't occur if inner part of outer join has more 
6352
 
          than one table: table with no matches will not be marked as const.
6353
 
 
6354
 
        - Ideally we should add 1 to records_read for every possible null-
6355
 
          complemented row. We're not doing it because: 1. it will require
6356
 
          non-trivial code and add overhead. 2. The value of records_read
6357
 
          is an inprecise estimate and adding 1 (or, in the worst case,
6358
 
          #max_nested_outer_joins=64-1) will not make it any more precise.
6359
 
      */
6360
 
      if (pos->records_read > DBL_EPSILON)
6361
 
        found*= pos->records_read;
6362
 
    }
6363
 
  }
6364
 
  return found;
6365
 
}
6366
 
 
 
883
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
 
884
                                     (join_tab->table->getRecordLength()- rec_length));
 
885
    rec_length+= max((uint32_t)4,blob_length);
 
886
  }
 
887
  join_tab->used_fields= fields;
 
888
  join_tab->used_fieldlength= rec_length;
 
889
  join_tab->used_blobs= blobs;
 
890
}
 
891
 
 
892
StoredKey *get_store_key(Session *session,
 
893
                         optimizer::KeyUse *keyuse,
 
894
                         table_map used_tables,
 
895
                         KEY_PART_INFO *key_part,
 
896
                         unsigned char *key_buff,
 
897
                         uint32_t maybe_null)
 
898
{
 
899
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
 
900
  Item_ref **dir_val= reinterpret_cast<Item_ref **>(key_use_val->ref);
 
901
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
902
  {
 
903
    return new store_key_const_item(session,
 
904
                                    key_part->field,
 
905
                                    key_buff + maybe_null,
 
906
                                    maybe_null ? key_buff : 0,
 
907
                                    key_part->length,
 
908
                                    key_use_val);
 
909
  }
 
910
  else if (key_use_val->type() == Item::FIELD_ITEM ||
 
911
           (key_use_val->type() == Item::REF_ITEM &&
 
912
            key_use_val->ref_type() == Item_ref::OUTER_REF &&
 
913
            (*dir_val)->ref_type() == Item_ref::DIRECT_REF &&
 
914
            key_use_val->real_item()->type() == Item::FIELD_ITEM))
 
915
  {
 
916
    return new store_key_field(session,
 
917
                               key_part->field,
 
918
                               key_buff + maybe_null,
 
919
                               maybe_null ? key_buff : 0,
 
920
                               key_part->length,
 
921
                               ((Item_field*) key_use_val->real_item())->field,
 
922
                               key_use_val->full_name());
 
923
  }
 
924
  return new store_key_item(session,
 
925
                            key_part->field,
 
926
                            key_buff + maybe_null,
 
927
                            maybe_null ? key_buff : 0,
 
928
                            key_part->length,
 
929
                            key_use_val);
 
930
}
6367
931
 
6368
932
/**
6369
 
  Set up join struct according to best position.
 
933
  This function is only called for const items on fields which are keys.
 
934
 
 
935
  @return
 
936
    returns 1 if there was some conversion made when the field was stored.
6370
937
*/
6371
 
 
6372
 
static bool
6373
 
get_best_combination(JOIN *join)
6374
 
{
6375
 
  uint32_t i,tablenr;
6376
 
  table_map used_tables;
6377
 
  JOIN_TAB *join_tab,*j;
6378
 
  KEYUSE *keyuse;
6379
 
  uint32_t table_count;
6380
 
  THD *thd=join->thd;
6381
 
 
6382
 
  table_count=join->tables;
6383
 
  if (!(join->join_tab=join_tab=
6384
 
        (JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)*table_count)))
6385
 
    return(true);
6386
 
 
6387
 
  join->full_join=0;
6388
 
 
6389
 
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
6390
 
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
 
938
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
 
939
{
 
940
  bool error;
 
941
  Table *table= field->table;
 
942
  Session *session= table->in_use;
 
943
  ha_rows cuted_fields=session->cuted_fields;
 
944
 
 
945
  /*
 
946
    we should restore old value of count_cuted_fields because
 
947
    store_val_in_field can be called from mysql_insert
 
948
    with select_insert, which make count_cuted_fields= 1
 
949
   */
 
950
  enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
 
951
  session->count_cuted_fields= check_flag;
 
952
  error= item->save_in_field(field, 1);
 
953
  session->count_cuted_fields= old_count_cuted_fields;
 
954
  return error || cuted_fields != session->cuted_fields;
 
955
}
 
956
 
 
957
inline void add_cond_and_fix(Item **e1, Item *e2)
 
958
{
 
959
  if (*e1)
6391
960
  {
6392
 
    Table *form;
6393
 
    *j= *join->best_positions[tablenr].table;
6394
 
    form=join->table[tablenr]=j->table;
6395
 
    used_tables|= form->map;
6396
 
    form->reginfo.join_tab=j;
6397
 
    if (!*j->on_expr_ref)
6398
 
      form->reginfo.not_exists_optimize=0;      // Only with LEFT JOIN
6399
 
    if (j->type == JT_CONST)
6400
 
      continue;                                 // Handled in make_join_stat..
6401
 
 
6402
 
    j->ref.key = -1;
6403
 
    j->ref.key_parts=0;
6404
 
 
6405
 
    if (j->type == JT_SYSTEM)
6406
 
      continue;
6407
 
    if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key))
 
961
    Item *res;
 
962
    if ((res= new Item_cond_and(*e1, e2)))
6408
963
    {
6409
 
      j->type=JT_ALL;
6410
 
      if (tablenr != join->const_tables)
6411
 
        join->full_join=1;
 
964
      *e1= res;
 
965
      res->quick_fix_field();
6412
966
    }
6413
 
    else if (create_ref_for_key(join, j, keyuse, used_tables))
6414
 
      return(true);                        // Something went wrong
6415
967
  }
6416
 
 
6417
 
  for (i=0 ; i < table_count ; i++)
6418
 
    join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i;
6419
 
  update_depend_map(join);
6420
 
  return(0);
 
968
  else
 
969
    *e1= e2;
6421
970
}
6422
971
 
6423
 
 
6424
 
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
6425
 
                               table_map used_tables)
 
972
bool create_ref_for_key(JOIN *join, 
 
973
                        JoinTable *j, 
 
974
                        optimizer::KeyUse *org_keyuse,
 
975
                        table_map used_tables)
6426
976
{
6427
 
  KEYUSE *keyuse=org_keyuse;
6428
 
  THD  *thd= join->thd;
6429
 
  uint32_t keyparts,length,key;
6430
 
  Table *table;
6431
 
  KEY *keyinfo;
 
977
  optimizer::KeyUse *keyuse= org_keyuse;
 
978
  Session  *session= join->session;
 
979
  uint32_t keyparts;
 
980
  uint32_t length;
 
981
  uint32_t key;
 
982
  Table *table= NULL;
 
983
  KEY *keyinfo= NULL;
6432
984
 
6433
985
  /*  Use best key from find_best */
6434
 
  table=j->table;
6435
 
  key=keyuse->key;
6436
 
  keyinfo=table->key_info+key;
 
986
  table= j->table;
 
987
  key= keyuse->getKey();
 
988
  keyinfo= table->key_info + key;
6437
989
 
6438
990
  {
6439
 
    keyparts=length=0;
 
991
    keyparts= length= 0;
6440
992
    uint32_t found_part_ref_or_null= 0;
6441
993
    /*
6442
994
      Calculate length for the used key
6445
997
    */
6446
998
    do
6447
999
    {
6448
 
      if (!(~used_tables & keyuse->used_tables))
 
1000
      if (! (~used_tables & keyuse->getUsedTables()))
6449
1001
      {
6450
 
        if (keyparts == keyuse->keypart &&
6451
 
            !(found_part_ref_or_null & keyuse->optimize))
6452
 
        {
6453
 
          keyparts++;
6454
 
          length+= keyinfo->key_part[keyuse->keypart].store_length;
6455
 
          found_part_ref_or_null|= keyuse->optimize;
6456
 
        }
 
1002
        if (keyparts == keyuse->getKeypart() &&
 
1003
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
 
1004
        {
 
1005
          keyparts++;
 
1006
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
 
1007
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
 
1008
        }
6457
1009
      }
6458
1010
      keyuse++;
6459
 
    } while (keyuse->table == table && keyuse->key == key);
 
1011
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
6460
1012
  }
6461
1013
 
6462
1014
  /* set up fieldref */
6464
1016
  j->ref.key_parts=keyparts;
6465
1017
  j->ref.key_length=length;
6466
1018
  j->ref.key=(int) key;
6467
 
  if (!(j->ref.key_buff= (unsigned char*) thd->calloc(ALIGN_SIZE(length)*2)) ||
6468
 
      !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) *
6469
 
                                                   (keyparts+1)))) ||
6470
 
      !(j->ref.items=    (Item**) thd->alloc(sizeof(Item*)*keyparts)) ||
6471
 
      !(j->ref.cond_guards= (bool**) thd->alloc(sizeof(uint*)*keyparts)))
 
1019
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
 
1020
      !(j->ref.key_copy= (StoredKey**) session->alloc((sizeof(StoredKey*) *
 
1021
               (keyparts+1)))) ||
 
1022
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
 
1023
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
6472
1024
  {
6473
1025
    return(true);
6474
1026
  }
6478
1030
  j->ref.disable_cache= false;
6479
1031
  keyuse=org_keyuse;
6480
1032
 
6481
 
  store_key **ref_key= j->ref.key_copy;
6482
 
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
 
1033
  StoredKey **ref_key= j->ref.key_copy;
 
1034
  unsigned char *key_buff= j->ref.key_buff, *null_ref_key= 0;
6483
1035
  bool keyuse_uses_no_tables= true;
6484
1036
  {
6485
 
    uint32_t i;
6486
 
    for (i=0 ; i < keyparts ; keyuse++,i++)
 
1037
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
6487
1038
    {
6488
 
      while (keyuse->keypart != i ||
6489
 
             ((~used_tables) & keyuse->used_tables))
6490
 
        keyuse++;                               /* Skip other parts */
 
1039
      while (keyuse->getKeypart() != i ||
 
1040
             ((~used_tables) & keyuse->getUsedTables()))
 
1041
        keyuse++;       /* Skip other parts */
6491
1042
 
6492
1043
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
6493
 
      j->ref.items[i]=keyuse->val;              // Save for cond removal
6494
 
      j->ref.cond_guards[i]= keyuse->cond_guard;
6495
 
      if (keyuse->null_rejecting) 
 
1044
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
 
1045
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
 
1046
      if (keyuse->isNullRejected())
6496
1047
        j->ref.null_rejecting |= 1 << i;
6497
 
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
6498
 
      if (!keyuse->used_tables &&
6499
 
          !(join->select_options & SELECT_DESCRIBE))
6500
 
      {                                 // Compare against constant
6501
 
        store_key_item tmp(thd, keyinfo->key_part[i].field,
 
1048
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
 
1049
      if (! keyuse->getUsedTables() &&  !(join->select_options & SELECT_DESCRIBE))
 
1050
      {         // Compare against constant
 
1051
        store_key_item tmp(session, keyinfo->key_part[i].field,
6502
1052
                           key_buff + maybe_null,
6503
1053
                           maybe_null ?  key_buff : 0,
6504
 
                           keyinfo->key_part[i].length, keyuse->val);
6505
 
        if (thd->is_fatal_error)
6506
 
          return(true);
6507
 
        tmp.copy();
 
1054
                           keyinfo->key_part[i].length, keyuse->getVal());
 
1055
        if (session->is_fatal_error)
 
1056
          return(true);
 
1057
        tmp.copy();
6508
1058
      }
6509
1059
      else
6510
 
        *ref_key++= get_store_key(thd,
6511
 
                                  keyuse,join->const_table_map,
6512
 
                                  &keyinfo->key_part[i],
6513
 
                                  key_buff, maybe_null);
 
1060
        *ref_key++= get_store_key(session,
 
1061
          keyuse,join->const_table_map,
 
1062
          &keyinfo->key_part[i],
 
1063
          key_buff, maybe_null);
6514
1064
      /*
6515
 
        Remember if we are going to use REF_OR_NULL
6516
 
        But only if field _really_ can be null i.e. we force JT_REF
6517
 
        instead of JT_REF_OR_NULL in case if field can't be null
 
1065
        Remember if we are going to use REF_OR_NULL
 
1066
        But only if field _really_ can be null i.e. we force AM_REF
 
1067
        instead of AM_REF_OR_NULL in case if field can't be null
6518
1068
      */
6519
 
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
6520
 
        null_ref_key= key_buff;
 
1069
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
1070
        null_ref_key= key_buff;
6521
1071
      key_buff+=keyinfo->key_part[i].store_length;
6522
1072
    }
6523
1073
  }
6524
 
  *ref_key=0;                           // end_marker
6525
 
  if (j->type == JT_CONST)
 
1074
  *ref_key= 0;       // end_marker
 
1075
  if (j->type == AM_CONST)
6526
1076
    j->table->const_table= 1;
6527
1077
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
6528
1078
           keyparts != keyinfo->key_parts || null_ref_key)
6529
1079
  {
6530
1080
    /* Must read with repeat */
6531
 
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
 
1081
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
6532
1082
    j->ref.null_ref_key= null_ref_key;
6533
1083
  }
6534
1084
  else if (keyuse_uses_no_tables)
6540
1090
      Here we should not mark the table as a 'const' as a field may
6541
1091
      have a 'normal' value or a NULL value.
6542
1092
    */
6543
 
    j->type=JT_CONST;
6544
 
  }
6545
 
  else
6546
 
    j->type=JT_EQ_REF;
6547
 
  return(0);
6548
 
}
6549
 
 
6550
 
 
6551
 
 
6552
 
static store_key *
6553
 
get_store_key(THD *thd, KEYUSE *keyuse, table_map used_tables,
6554
 
              KEY_PART_INFO *key_part, unsigned char *key_buff, uint32_t maybe_null)
6555
 
{
6556
 
  if (!((~used_tables) & keyuse->used_tables))          // if const item
6557
 
  {
6558
 
    return new store_key_const_item(thd,
6559
 
                                    key_part->field,
6560
 
                                    key_buff + maybe_null,
6561
 
                                    maybe_null ? key_buff : 0,
6562
 
                                    key_part->length,
6563
 
                                    keyuse->val);
6564
 
  }
6565
 
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
6566
 
           (keyuse->val->type() == Item::REF_ITEM &&
6567
 
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
6568
 
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
6569
 
             Item_ref::DIRECT_REF && 
6570
 
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
6571
 
    return new store_key_field(thd,
6572
 
                               key_part->field,
6573
 
                               key_buff + maybe_null,
6574
 
                               maybe_null ? key_buff : 0,
6575
 
                               key_part->length,
6576
 
                               ((Item_field*) keyuse->val->real_item())->field,
6577
 
                               keyuse->val->full_name());
6578
 
  return new store_key_item(thd,
6579
 
                            key_part->field,
6580
 
                            key_buff + maybe_null,
6581
 
                            maybe_null ? key_buff : 0,
6582
 
                            key_part->length,
6583
 
                            keyuse->val);
6584
 
}
6585
 
 
6586
 
/**
6587
 
  This function is only called for const items on fields which are keys.
6588
 
 
6589
 
  @return
6590
 
    returns 1 if there was some conversion made when the field was stored.
6591
 
*/
6592
 
 
6593
 
bool
6594
 
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
6595
 
{
6596
 
  bool error;
6597
 
  Table *table= field->table;
6598
 
  THD *thd= table->in_use;
6599
 
  ha_rows cuted_fields=thd->cuted_fields;
6600
 
 
6601
 
  /*
6602
 
    we should restore old value of count_cuted_fields because
6603
 
    store_val_in_field can be called from mysql_insert 
6604
 
    with select_insert, which make count_cuted_fields= 1
6605
 
   */
6606
 
  enum_check_fields old_count_cuted_fields= thd->count_cuted_fields;
6607
 
  thd->count_cuted_fields= check_flag;
6608
 
  error= item->save_in_field(field, 1);
6609
 
  thd->count_cuted_fields= old_count_cuted_fields;
6610
 
  return error || cuted_fields != thd->cuted_fields;
6611
 
}
6612
 
 
6613
 
 
6614
 
static bool
6615
 
make_simple_join(JOIN *join,Table *tmp_table)
6616
 
{
6617
 
  Table **tableptr;
6618
 
  JOIN_TAB *join_tab;
6619
 
 
6620
 
  /*
6621
 
    Reuse Table * and JOIN_TAB if already allocated by a previous call
6622
 
    to this function through JOIN::exec (may happen for sub-queries).
6623
 
  */
6624
 
  if (!join->table_reexec)
6625
 
  {
6626
 
    if (!(join->table_reexec= (Table**) join->thd->alloc(sizeof(Table*))))
6627
 
      return(true);                        /* purecov: inspected */
6628
 
    if (join->tmp_join)
6629
 
      join->tmp_join->table_reexec= join->table_reexec;
6630
 
  }
6631
 
  if (!join->join_tab_reexec)
6632
 
  {
6633
 
    if (!(join->join_tab_reexec=
6634
 
          (JOIN_TAB*) join->thd->alloc(sizeof(JOIN_TAB))))
6635
 
      return(true);                        /* purecov: inspected */
6636
 
    if (join->tmp_join)
6637
 
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
6638
 
  }
6639
 
  tableptr= join->table_reexec;
6640
 
  join_tab= join->join_tab_reexec;
6641
 
 
6642
 
  join->join_tab=join_tab;
6643
 
  join->table=tableptr; tableptr[0]=tmp_table;
6644
 
  join->tables=1;
6645
 
  join->const_tables=0;
6646
 
  join->const_table_map=0;
6647
 
  join->tmp_table_param.field_count= join->tmp_table_param.sum_func_count=
6648
 
    join->tmp_table_param.func_count=0;
6649
 
  join->tmp_table_param.copy_field=join->tmp_table_param.copy_field_end=0;
6650
 
  join->first_record=join->sort_and_group=0;
6651
 
  join->send_records=(ha_rows) 0;
6652
 
  join->group=0;
6653
 
  join->row_limit=join->unit->select_limit_cnt;
6654
 
  join->do_send_rows = (join->row_limit) ? 1 : 0;
6655
 
 
6656
 
  join_tab->cache.buff=0;                       /* No caching */
6657
 
  join_tab->table=tmp_table;
6658
 
  join_tab->select=0;
6659
 
  join_tab->select_cond=0;
6660
 
  join_tab->quick=0;
6661
 
  join_tab->type= JT_ALL;                       /* Map through all records */
6662
 
  join_tab->keys.init();
6663
 
  join_tab->keys.set_all();                     /* test everything in quick */
6664
 
  join_tab->info=0;
6665
 
  join_tab->on_expr_ref=0;
6666
 
  join_tab->last_inner= 0;
6667
 
  join_tab->first_unmatched= 0;
6668
 
  join_tab->ref.key = -1;
6669
 
  join_tab->not_used_in_distinct=0;
6670
 
  join_tab->read_first_record= join_init_read_record;
6671
 
  join_tab->join=join;
6672
 
  join_tab->ref.key_parts= 0;
6673
 
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
6674
 
  join_tab->do_firstmatch= NULL;
6675
 
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
6676
 
  tmp_table->status=0;
6677
 
  tmp_table->null_row=0;
6678
 
  return(false);
6679
 
}
6680
 
 
6681
 
 
6682
 
inline void add_cond_and_fix(Item **e1, Item *e2)
6683
 
{
6684
 
  if (*e1)
6685
 
  {
6686
 
    Item *res;
6687
 
    if ((res= new Item_cond_and(*e1, e2)))
6688
 
    {
6689
 
      *e1= res;
6690
 
      res->quick_fix_field();
6691
 
    }
6692
 
  }
6693
 
  else
6694
 
    *e1= e2;
6695
 
}
6696
 
 
 
1093
    j->type= AM_CONST;
 
1094
  }
 
1095
  else
 
1096
    j->type= AM_EQ_REF;
 
1097
  return 0;
 
1098
}
6697
1099
 
6698
1100
/**
6699
1101
  Add to join_tab->select_cond[i] "table.field IS NOT NULL" conditions
6708
1110
    add "t1.field IS NOT NULL" to t1's table condition. @n
6709
1111
 
6710
1112
    Description of the optimization:
6711
 
    
 
1113
 
6712
1114
      We look through equalities choosen to perform ref/eq_ref access,
6713
1115
      pick equalities that have form "tbl.part_of_key = othertbl.field"
6714
1116
      (where othertbl is a non-const table and othertbl.field may be NULL)
6736
1138
      This optimization doesn't affect the choices that ref, range, or join
6737
1139
      optimizer make. This was intentional because this was added after 4.1
6738
1140
      was GA.
6739
 
      
 
1141
 
6740
1142
    Implementation overview
6741
1143
      1. update_ref_and_keys() accumulates info about null-rejecting
6742
 
         predicates in in KEY_FIELD::null_rejecting
6743
 
      1.1 add_key_part saves these to KEYUSE.
6744
 
      2. create_ref_for_key copies them to TABLE_REF.
 
1144
         predicates in in KeyField::null_rejecting
 
1145
      1.1 add_key_part saves these to KeyUse.
 
1146
      2. create_ref_for_key copies them to table_reference_st.
6745
1147
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
6746
 
         appropiate JOIN_TAB members.
 
1148
         appropiate JoinTable members.
6747
1149
*/
6748
 
 
6749
 
static void add_not_null_conds(JOIN *join)
 
1150
void add_not_null_conds(JOIN *join)
6750
1151
{
6751
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
1152
  for (uint32_t i= join->const_tables; i < join->tables; i++)
6752
1153
  {
6753
 
    JOIN_TAB *tab=join->join_tab+i;
6754
 
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF || 
6755
 
         tab->type == JT_REF_OR_NULL) &&
 
1154
    JoinTable *tab=join->join_tab+i;
 
1155
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
 
1156
         tab->type == AM_REF_OR_NULL) &&
6756
1157
        !tab->table->maybe_null)
6757
1158
    {
6758
1159
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
6763
1164
          Item *notnull;
6764
1165
          assert(item->type() == Item::FIELD_ITEM);
6765
1166
          Item_field *not_null_item= (Item_field*)item;
6766
 
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
 
1167
          JoinTable *referred_tab= not_null_item->field->table->reginfo.join_tab;
6767
1168
          /*
6768
1169
            For UPDATE queries such as:
6769
1170
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
6775
1176
            return;
6776
1177
          /*
6777
1178
            We need to do full fix_fields() call here in order to have correct
6778
 
            notnull->const_item(). This is needed e.g. by test_quick_select 
6779
 
            when it is called from make_join_select after this function is 
 
1179
            notnull->const_item(). This is needed e.g. by test_quick_select
 
1180
            when it is called from make_join_select after this function is
6780
1181
            called.
6781
1182
          */
6782
 
          if (notnull->fix_fields(join->thd, &notnull))
 
1183
          if (notnull->fix_fields(join->session, &notnull))
6783
1184
            return;
6784
1185
          add_cond_and_fix(&referred_tab->select_cond, notnull);
6785
1186
        }
6804
1205
    -  pointer to the guarded predicate, if success
6805
1206
    -  0, otherwise
6806
1207
*/
6807
 
 
6808
 
static COND*
6809
 
add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab)
 
1208
COND *add_found_match_trig_cond(JoinTable *tab, COND *cond, JoinTable *root_tab)
6810
1209
{
6811
1210
  COND *tmp;
6812
1211
  assert(cond != 0);
6822
1221
  return tmp;
6823
1222
}
6824
1223
 
6825
 
 
6826
 
/**
6827
 
  Fill in outer join related info for the execution plan structure.
6828
 
 
6829
 
    For each outer join operation left after simplification of the
6830
 
    original query the function set up the following pointers in the linear
6831
 
    structure join->join_tab representing the selected execution plan.
6832
 
    The first inner table t0 for the operation is set to refer to the last
6833
 
    inner table tk through the field t0->last_inner.
6834
 
    Any inner table ti for the operation are set to refer to the first
6835
 
    inner table ti->first_inner.
6836
 
    The first inner table t0 for the operation is set to refer to the
6837
 
    first inner table of the embedding outer join operation, if there is any,
6838
 
    through the field t0->first_upper.
6839
 
    The on expression for the outer join operation is attached to the
6840
 
    corresponding first inner table through the field t0->on_expr_ref.
6841
 
    Here ti are structures of the JOIN_TAB type.
6842
 
 
6843
 
  EXAMPLE. For the query: 
6844
 
  @code
6845
 
        SELECT * FROM t1
6846
 
                      LEFT JOIN
6847
 
                      (t2, t3 LEFT JOIN t4 ON t3.a=t4.a)
6848
 
                      ON (t1.a=t2.a AND t1.b=t3.b)
6849
 
          WHERE t1.c > 5,
6850
 
  @endcode
6851
 
 
6852
 
    given the execution plan with the table order t1,t2,t3,t4
6853
 
    is selected, the following references will be set;
6854
 
    t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2]
6855
 
    t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2],
6856
 
    on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to 
6857
 
    *t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref.
6858
 
 
6859
 
  @param join   reference to the info fully describing the query
6860
 
 
6861
 
  @note
6862
 
    The function assumes that the simplification procedure has been
6863
 
    already applied to the join query (see simplify_joins).
6864
 
    This function can be called only after the execution plan
6865
 
    has been chosen.
6866
 
*/
6867
 
 
6868
 
static void
6869
 
make_outerjoin_info(JOIN *join)
6870
 
{
6871
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
6872
 
  {
6873
 
    JOIN_TAB *tab=join->join_tab+i;
6874
 
    Table *table=tab->table;
6875
 
    TableList *tbl= table->pos_in_table_list;
6876
 
    TableList *embedding= tbl->embedding;
6877
 
 
6878
 
    if (tbl->outer_join)
6879
 
    {
6880
 
      /* 
6881
 
        Table tab is the only one inner table for outer join.
6882
 
        (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a
6883
 
        is in the query above.)
6884
 
      */
6885
 
      tab->last_inner= tab->first_inner= tab;
6886
 
      tab->on_expr_ref= &tbl->on_expr;
6887
 
      tab->cond_equal= tbl->cond_equal;
6888
 
      if (embedding)
6889
 
        tab->first_upper= embedding->nested_join->first_nested;
6890
 
    }    
6891
 
    for ( ; embedding ; embedding= embedding->embedding)
6892
 
    {
6893
 
      /* Ignore sj-nests: */
6894
 
      if (!embedding->on_expr)
6895
 
        continue;
6896
 
      nested_join_st *nested_join= embedding->nested_join;
6897
 
      if (!nested_join->counter_)
6898
 
      {
6899
 
        /* 
6900
 
          Table tab is the first inner table for nested_join.
6901
 
          Save reference to it in the nested join structure.
6902
 
        */ 
6903
 
        nested_join->first_nested= tab;
6904
 
        tab->on_expr_ref= &embedding->on_expr;
6905
 
        tab->cond_equal= tbl->cond_equal;
6906
 
        if (embedding->embedding)
6907
 
          tab->first_upper= embedding->embedding->nested_join->first_nested;
6908
 
      }
6909
 
      if (!tab->first_inner)  
6910
 
        tab->first_inner= nested_join->first_nested;
6911
 
      if (++nested_join->counter_ < nested_join->join_list.elements)
6912
 
        break;
6913
 
      /* Table tab is the last inner table for nested join. */
6914
 
      nested_join->first_nested->last_inner= tab;
6915
 
    }
6916
 
  }
6917
 
  return;
6918
 
}
6919
 
 
6920
 
 
6921
 
static bool
6922
 
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
6923
 
{
6924
 
  THD *thd= join->thd;
6925
 
  if (select)
6926
 
  {
6927
 
    add_not_null_conds(join);
6928
 
    table_map used_tables;
6929
 
    if (cond)                /* Because of QUICK_GROUP_MIN_MAX_SELECT */
6930
 
    {                        /* there may be a select without a cond. */    
6931
 
      if (join->tables > 1)
6932
 
        cond->update_used_tables();             // Tablenr may have changed
6933
 
      if (join->const_tables == join->tables &&
6934
 
          thd->lex->current_select->master_unit() ==
6935
 
          &thd->lex->unit)              // not upper level SELECT
6936
 
        join->const_table_map|=RAND_TABLE_BIT;
6937
 
      {                                         // Check const tables
6938
 
        COND *const_cond=
6939
 
          make_cond_for_table(cond,
6940
 
                              join->const_table_map,
6941
 
                              (table_map) 0, 1);
6942
 
        for (JOIN_TAB *tab= join->join_tab+join->const_tables;
6943
 
             tab < join->join_tab+join->tables ; tab++)
6944
 
        {
6945
 
          if (*tab->on_expr_ref)
6946
 
          {
6947
 
            JOIN_TAB *cond_tab= tab->first_inner;
6948
 
            COND *tmp= make_cond_for_table(*tab->on_expr_ref,
6949
 
                                           join->const_table_map,
6950
 
                                           (  table_map) 0, 0);
6951
 
            if (!tmp)
6952
 
              continue;
6953
 
            tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
6954
 
            if (!tmp)
6955
 
              return(1);
6956
 
            tmp->quick_fix_field();
6957
 
            cond_tab->select_cond= !cond_tab->select_cond ? tmp :
6958
 
                                    new Item_cond_and(cond_tab->select_cond,
6959
 
                                                      tmp);
6960
 
            if (!cond_tab->select_cond)
6961
 
              return(1);
6962
 
            cond_tab->select_cond->quick_fix_field();
6963
 
          }       
6964
 
        }
6965
 
        if (const_cond && !const_cond->val_int())
6966
 
        {
6967
 
          return(1);     // Impossible const condition
6968
 
        }
6969
 
      }
6970
 
    }
6971
 
    used_tables=((select->const_tables=join->const_table_map) |
6972
 
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
6973
 
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
6974
 
    {
6975
 
      JOIN_TAB *tab=join->join_tab+i;
6976
 
      /*
6977
 
        first_inner is the X in queries like:
6978
 
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
6979
 
      */
6980
 
      JOIN_TAB *first_inner_tab= tab->first_inner; 
6981
 
      table_map current_map= tab->table->map;
6982
 
      bool use_quick_range=0;
6983
 
      COND *tmp;
6984
 
 
6985
 
      /*
6986
 
        Following force including random expression in last table condition.
6987
 
        It solve problem with select like SELECT * FROM t1 WHERE rand() > 0.5
6988
 
      */
6989
 
      if (i == join->tables-1)
6990
 
        current_map|= OUTER_REF_TABLE_BIT | RAND_TABLE_BIT;
6991
 
      used_tables|=current_map;
6992
 
 
6993
 
      if (tab->type == JT_REF && tab->quick &&
6994
 
          (uint) tab->ref.key == tab->quick->index &&
6995
 
          tab->ref.key_length < tab->quick->max_used_key_length)
6996
 
      {
6997
 
        /* Range uses longer key;  Use this instead of ref on key */
6998
 
        tab->type=JT_ALL;
6999
 
        use_quick_range=1;
7000
 
        tab->use_quick=1;
7001
 
        tab->ref.key= -1;
7002
 
        tab->ref.key_parts=0;           // Don't use ref key.
7003
 
        join->best_positions[i].records_read= rows2double(tab->quick->records);
7004
 
        /* 
7005
 
          We will use join cache here : prevent sorting of the first
7006
 
          table only and sort at the end.
7007
 
        */
7008
 
        if (i != join->const_tables && join->tables > join->const_tables + 1)
7009
 
          join->full_join= 1;
7010
 
      }
7011
 
 
7012
 
      tmp= NULL;
7013
 
      if (cond)
7014
 
        tmp= make_cond_for_table(cond,used_tables,current_map, 0);
7015
 
      if (cond && !tmp && tab->quick)
7016
 
      {                                         // Outer join
7017
 
        if (tab->type != JT_ALL)
7018
 
        {
7019
 
          /*
7020
 
            Don't use the quick method
7021
 
            We come here in the case where we have 'key=constant' and
7022
 
            the test is removed by make_cond_for_table()
7023
 
          */
7024
 
          delete tab->quick;
7025
 
          tab->quick= 0;
7026
 
        }
7027
 
        else
7028
 
        {
7029
 
          /*
7030
 
            Hack to handle the case where we only refer to a table
7031
 
            in the ON part of an OUTER JOIN. In this case we want the code
7032
 
            below to check if we should use 'quick' instead.
7033
 
          */
7034
 
          tmp= new Item_int((int64_t) 1,1);     // Always true
7035
 
        }
7036
 
 
7037
 
      }
7038
 
      if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
7039
 
          tab->type == JT_EQ_REF)
7040
 
      {
7041
 
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
7042
 
                                       thd->memdup((unsigned char*) select,
7043
 
                                                   sizeof(*select)));
7044
 
        if (!sel)
7045
 
          return(1);                    // End of memory
7046
 
        /*
7047
 
          If tab is an inner table of an outer join operation,
7048
 
          add a match guard to the pushed down predicate.
7049
 
          The guard will turn the predicate on only after
7050
 
          the first match for outer tables is encountered.
7051
 
        */        
7052
 
        if (cond && tmp)
7053
 
        {
7054
 
          /*
7055
 
            Because of QUICK_GROUP_MIN_MAX_SELECT there may be a select without
7056
 
            a cond, so neutralize the hack above.
7057
 
          */
7058
 
          if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
7059
 
            return(1);
7060
 
          tab->select_cond=sel->cond=tmp;
7061
 
          /* Push condition to storage engine if this is enabled
7062
 
             and the condition is not guarded */
7063
 
          tab->table->file->pushed_cond= NULL;
7064
 
          if (thd->variables.engine_condition_pushdown)
7065
 
          {
7066
 
            COND *push_cond= 
7067
 
              make_cond_for_table(tmp, current_map, current_map, 0);
7068
 
            if (push_cond)
7069
 
            {
7070
 
              /* Push condition to handler */
7071
 
              if (!tab->table->file->cond_push(push_cond))
7072
 
                tab->table->file->pushed_cond= push_cond;
7073
 
            }
7074
 
          }
7075
 
        }
7076
 
        else
7077
 
          tab->select_cond= sel->cond= NULL;
7078
 
 
7079
 
        sel->head=tab->table;
7080
 
        if (tab->quick)
7081
 
        {
7082
 
          /* Use quick key read if it's a constant and it's not used
7083
 
             with key reading */
7084
 
          if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
7085
 
              && (tab->type != JT_REF || (uint) tab->ref.key == tab->quick->index))
7086
 
          {
7087
 
            sel->quick=tab->quick;              // Use value from get_quick_...
7088
 
            sel->quick_keys.clear_all();
7089
 
            sel->needed_reg.clear_all();
7090
 
          }
7091
 
          else
7092
 
          {
7093
 
            delete tab->quick;
7094
 
          }
7095
 
          tab->quick=0;
7096
 
        }
7097
 
        uint32_t ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
7098
 
        if (i == join->const_tables && ref_key)
7099
 
        {
7100
 
          if (!tab->const_keys.is_clear_all() &&
7101
 
              tab->table->reginfo.impossible_range)
7102
 
            return(1);
7103
 
        }
7104
 
        else if (tab->type == JT_ALL && ! use_quick_range)
7105
 
        {
7106
 
          if (!tab->const_keys.is_clear_all() &&
7107
 
              tab->table->reginfo.impossible_range)
7108
 
            return(1);                          // Impossible range
7109
 
          /*
7110
 
            We plan to scan all rows.
7111
 
            Check again if we should use an index.
7112
 
            We could have used an column from a previous table in
7113
 
            the index if we are using limit and this is the first table
7114
 
          */
7115
 
 
7116
 
          if ((cond && (!tab->keys.is_subset(tab->const_keys) && i > 0)) ||
7117
 
              (!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)))
7118
 
          {
7119
 
            /* Join with outer join condition */
7120
 
            COND *orig_cond=sel->cond;
7121
 
            sel->cond= and_conds(sel->cond, *tab->on_expr_ref);
7122
 
 
7123
 
            /*
7124
 
              We can't call sel->cond->fix_fields,
7125
 
              as it will break tab->on_expr if it's AND condition
7126
 
              (fix_fields currently removes extra AND/OR levels).
7127
 
              Yet attributes of the just built condition are not needed.
7128
 
              Thus we call sel->cond->quick_fix_field for safety.
7129
 
            */
7130
 
            if (sel->cond && !sel->cond->fixed)
7131
 
              sel->cond->quick_fix_field();
7132
 
 
7133
 
            if (sel->test_quick_select(thd, tab->keys,
7134
 
                                       used_tables & ~ current_map,
7135
 
                                       (join->select_options &
7136
 
                                        OPTION_FOUND_ROWS ?
7137
 
                                        HA_POS_ERROR :
7138
 
                                        join->unit->select_limit_cnt), 0,
7139
 
                                        false) < 0)
7140
 
            {
7141
 
              /*
7142
 
                Before reporting "Impossible WHERE" for the whole query
7143
 
                we have to check isn't it only "impossible ON" instead
7144
 
              */
7145
 
              sel->cond=orig_cond;
7146
 
              if (!*tab->on_expr_ref ||
7147
 
                  sel->test_quick_select(thd, tab->keys,
7148
 
                                         used_tables & ~ current_map,
7149
 
                                         (join->select_options &
7150
 
                                          OPTION_FOUND_ROWS ?
7151
 
                                          HA_POS_ERROR :
7152
 
                                          join->unit->select_limit_cnt),0,
7153
 
                                          false) < 0)
7154
 
                return(1);                      // Impossible WHERE
7155
 
            }
7156
 
            else
7157
 
              sel->cond=orig_cond;
7158
 
 
7159
 
            /* Fix for EXPLAIN */
7160
 
            if (sel->quick)
7161
 
              join->best_positions[i].records_read= (double)sel->quick->records;
7162
 
          }
7163
 
          else
7164
 
          {
7165
 
            sel->needed_reg=tab->needed_reg;
7166
 
            sel->quick_keys.clear_all();
7167
 
          }
7168
 
          if (!sel->quick_keys.is_subset(tab->checked_keys) ||
7169
 
              !sel->needed_reg.is_subset(tab->checked_keys))
7170
 
          {
7171
 
            tab->keys=sel->quick_keys;
7172
 
            tab->keys.merge(sel->needed_reg);
7173
 
            tab->use_quick= (!sel->needed_reg.is_clear_all() &&
7174
 
                             (select->quick_keys.is_clear_all() ||
7175
 
                              (select->quick &&
7176
 
                               (select->quick->records >= 100L)))) ?
7177
 
              2 : 1;
7178
 
            sel->read_tables= used_tables & ~current_map;
7179
 
          }
7180
 
          if (i != join->const_tables && tab->use_quick != 2)
7181
 
          {                                     /* Read with cache */
7182
 
            if (cond &&
7183
 
                (tmp=make_cond_for_table(cond,
7184
 
                                         join->const_table_map |
7185
 
                                         current_map,
7186
 
                                         current_map, 0)))
7187
 
            {
7188
 
              tab->cache.select=(SQL_SELECT*)
7189
 
                thd->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
7190
 
              tab->cache.select->cond=tmp;
7191
 
              tab->cache.select->read_tables=join->const_table_map;
7192
 
            }
7193
 
          }
7194
 
        }
7195
 
      }
7196
 
      
7197
 
      /* 
7198
 
        Push down conditions from all on expressions.
7199
 
        Each of these conditions are guarded by a variable
7200
 
        that turns if off just before null complemented row for
7201
 
        outer joins is formed. Thus, the condition from an
7202
 
        'on expression' are guaranteed not to be checked for
7203
 
        the null complemented row.
7204
 
      */ 
7205
 
 
7206
 
      /* First push down constant conditions from on expressions */
7207
 
      for (JOIN_TAB *join_tab= join->join_tab+join->const_tables;
7208
 
           join_tab < join->join_tab+join->tables ; join_tab++)
7209
 
      {
7210
 
        if (*join_tab->on_expr_ref)
7211
 
        {
7212
 
          JOIN_TAB *cond_tab= join_tab->first_inner;
7213
 
          COND *tmp= make_cond_for_table(*join_tab->on_expr_ref,
7214
 
                                         join->const_table_map,
7215
 
                                         (table_map) 0, 0);
7216
 
          if (!tmp)
7217
 
            continue;
7218
 
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
7219
 
          if (!tmp)
7220
 
            return(1);
7221
 
          tmp->quick_fix_field();
7222
 
          cond_tab->select_cond= !cond_tab->select_cond ? tmp :
7223
 
                                    new Item_cond_and(cond_tab->select_cond,tmp);
7224
 
          if (!cond_tab->select_cond)
7225
 
            return(1);
7226
 
          cond_tab->select_cond->quick_fix_field();
7227
 
        }       
7228
 
      }
7229
 
 
7230
 
      /* Push down non-constant conditions from on expressions */
7231
 
      JOIN_TAB *last_tab= tab;
7232
 
      while (first_inner_tab && first_inner_tab->last_inner == last_tab)
7233
 
      {  
7234
 
        /* 
7235
 
          Table tab is the last inner table of an outer join.
7236
 
          An on expression is always attached to it.
7237
 
        */     
7238
 
        COND *on_expr= *first_inner_tab->on_expr_ref;
7239
 
 
7240
 
        table_map used_tables2= (join->const_table_map |
7241
 
                                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
7242
 
        for (tab= join->join_tab+join->const_tables; tab <= last_tab ; tab++)
7243
 
        {
7244
 
          current_map= tab->table->map;
7245
 
          used_tables2|= current_map;
7246
 
          COND *tmp_cond= make_cond_for_table(on_expr, used_tables2,
7247
 
                                              current_map, 0);
7248
 
          if (tmp_cond)
7249
 
          {
7250
 
            JOIN_TAB *cond_tab= tab < first_inner_tab ? first_inner_tab : tab;
7251
 
            /*
7252
 
              First add the guards for match variables of
7253
 
              all embedding outer join operations.
7254
 
            */
7255
 
            if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner,
7256
 
                                                     tmp_cond,
7257
 
                                                     first_inner_tab)))
7258
 
              return(1);
7259
 
            /* 
7260
 
              Now add the guard turning the predicate off for 
7261
 
              the null complemented row.
7262
 
            */ 
7263
 
            tmp_cond= new Item_func_trig_cond(tmp_cond,
7264
 
                                              &first_inner_tab->
7265
 
                                              not_null_compl);
7266
 
            if (tmp_cond)
7267
 
              tmp_cond->quick_fix_field();
7268
 
            /* Add the predicate to other pushed down predicates */
7269
 
            cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond :
7270
 
                                  new Item_cond_and(cond_tab->select_cond,
7271
 
                                                    tmp_cond);
7272
 
            if (!cond_tab->select_cond)
7273
 
              return(1);
7274
 
            cond_tab->select_cond->quick_fix_field();
7275
 
          }              
7276
 
        }
7277
 
        first_inner_tab= first_inner_tab->first_upper;       
7278
 
      }
7279
 
    }
7280
 
  }
7281
 
  return(0);
7282
 
}
7283
 
 
7284
 
 
7285
 
/* 
 
1224
/*
7286
1225
  Check if given expression uses only table fields covered by the given index
7287
1226
 
7288
1227
  SYNOPSIS
7295
1234
  DESCRIPTION
7296
1235
    Check if given expression only uses fields covered by index #keyno in the
7297
1236
    table tbl. The expression can use any fields in any other tables.
7298
 
    
7299
 
    The expression is guaranteed not to be AND or OR - those constructs are 
 
1237
 
 
1238
    The expression is guaranteed not to be AND or OR - those constructs are
7300
1239
    handled outside of this function.
7301
1240
 
7302
1241
  RETURN
7303
1242
    true   Yes
7304
1243
    false  No
7305
1244
*/
7306
 
 
7307
 
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, 
7308
 
                            bool other_tbls_ok)
 
1245
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
7309
1246
{
7310
1247
  if (item->const_item())
7311
1248
    return true;
7312
1249
 
7313
 
  /* 
7314
 
    Don't push down the triggered conditions. Nested outer joins execution 
 
1250
  /*
 
1251
    Don't push down the triggered conditions. Nested outer joins execution
7315
1252
    code may need to evaluate a condition several times (both triggered and
7316
1253
    untriggered), and there is no way to put thi
7317
1254
    TODO: Consider cloning the triggered condition and using the copies for:
7318
1255
      1. push the first copy down, to have most restrictive index condition
7319
1256
         possible
7320
 
      2. Put the second copy into tab->select_cond. 
 
1257
      2. Put the second copy into tab->select_cond.
7321
1258
  */
7322
 
  if (item->type() == Item::FUNC_ITEM && 
 
1259
  if (item->type() == Item::FUNC_ITEM &&
7323
1260
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
7324
1261
    return false;
7325
1262
 
7345
1282
    {
7346
1283
      /* This is a function, apply condition recursively to arguments */
7347
1284
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
7348
 
      Item *item;
7349
 
      while ((item=li++))
 
1285
      Item *list_item;
 
1286
      while ((list_item=li++))
7350
1287
      {
7351
1288
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
7352
1289
          return false;
7356
1293
  case Item::FIELD_ITEM:
7357
1294
    {
7358
1295
      Item_field *item_field= (Item_field*)item;
7359
 
      if (item_field->field->table != tbl) 
 
1296
      if (item_field->field->table != tbl)
7360
1297
        return true;
7361
 
      return item_field->field->part_of_key.is_set(keyno);
 
1298
      return item_field->field->part_of_key.test(keyno);
7362
1299
    }
7363
1300
  case Item::REF_ITEM:
7364
1301
    return uses_index_fields_only(item->real_item(), tbl, keyno,
7368
1305
  }
7369
1306
}
7370
1307
 
7371
 
 
7372
1308
#define ICP_COND_USES_INDEX_ONLY 10
7373
1309
 
7374
1310
/*
7383
1319
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
7384
1320
 
7385
1321
  DESCRIPTION
7386
 
    Get a part of the condition that can be checked when for the given table 
 
1322
    Get a part of the condition that can be checked when for the given table
7387
1323
    we have values only of fields covered by some index. The condition may
7388
 
    refer to other tables, it is assumed that we have values of all of their 
 
1324
    refer to other tables, it is assumed that we have values of all of their
7389
1325
    fields.
7390
1326
 
7391
1327
    Example:
7392
1328
      make_cond_for_index(
7393
1329
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
7394
 
          t2, keyno(t2.key1)) 
 
1330
          t2, keyno(t2.key1))
7395
1331
      will return
7396
1332
        "cond(t1.field) AND cond(t2.key2)"
7397
1333
 
7398
1334
  RETURN
7399
1335
    Index condition, or NULL if no condition could be inferred.
7400
1336
*/
7401
 
 
7402
 
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno,
7403
 
                          bool other_tbls_ok)
 
1337
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
7404
1338
{
7405
1339
  if (!cond)
7406
1340
    return NULL;
7411
1345
    {
7412
1346
      Item_cond_and *new_cond=new Item_cond_and;
7413
1347
      if (!new_cond)
7414
 
        return (COND*) 0;
 
1348
        return (COND*) 0;
7415
1349
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
7416
1350
      Item *item;
7417
1351
      while ((item=li++))
7418
1352
      {
7419
 
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
7420
 
        if (fix)
7421
 
          new_cond->argument_list()->push_back(fix);
 
1353
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1354
        if (fix)
 
1355
          new_cond->argument_list()->push_back(fix);
7422
1356
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
7423
1357
      }
7424
1358
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
7425
1359
        cond->marker= ICP_COND_USES_INDEX_ONLY;
7426
1360
      switch (new_cond->argument_list()->elements) {
7427
1361
      case 0:
7428
 
        return (COND*) 0;
 
1362
        return (COND*) 0;
7429
1363
      case 1:
7430
 
        return new_cond->argument_list()->head();
 
1364
        return new_cond->argument_list()->head();
7431
1365
      default:
7432
 
        new_cond->quick_fix_field();
7433
 
        return new_cond;
 
1366
        new_cond->quick_fix_field();
 
1367
        return new_cond;
7434
1368
      }
7435
1369
    }
7436
1370
    else /* It's OR */
7437
1371
    {
7438
1372
      Item_cond_or *new_cond=new Item_cond_or;
7439
1373
      if (!new_cond)
7440
 
        return (COND*) 0;
 
1374
        return (COND*) 0;
7441
1375
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
7442
1376
      Item *item;
7443
1377
      while ((item=li++))
7444
1378
      {
7445
 
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
7446
 
        if (!fix)
7447
 
          return (COND*) 0;
7448
 
        new_cond->argument_list()->push_back(fix);
 
1379
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1380
        if (!fix)
 
1381
          return (COND*) 0;
 
1382
        new_cond->argument_list()->push_back(fix);
7449
1383
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
7450
1384
      }
7451
1385
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
7463
1397
}
7464
1398
 
7465
1399
 
7466
 
Item *make_cond_remainder(Item *cond, bool exclude_index)
 
1400
static Item *make_cond_remainder(Item *cond, bool exclude_index)
7467
1401
{
7468
1402
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
7469
1403
    return 0; /* Already checked */
7476
1410
      /* Create new top level AND item */
7477
1411
      Item_cond_and *new_cond=new Item_cond_and;
7478
1412
      if (!new_cond)
7479
 
        return (COND*) 0;
 
1413
        return (COND*) 0;
7480
1414
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
7481
1415
      Item *item;
7482
1416
      while ((item=li++))
7483
1417
      {
7484
 
        Item *fix= make_cond_remainder(item, exclude_index);
7485
 
        if (fix)
 
1418
        Item *fix= make_cond_remainder(item, exclude_index);
 
1419
        if (fix)
7486
1420
        {
7487
 
          new_cond->argument_list()->push_back(fix);
 
1421
          new_cond->argument_list()->push_back(fix);
7488
1422
          tbl_map |= fix->used_tables();
7489
1423
        }
7490
1424
      }
7491
1425
      switch (new_cond->argument_list()->elements) {
7492
1426
      case 0:
7493
 
        return (COND*) 0;
 
1427
        return (COND*) 0;
7494
1428
      case 1:
7495
 
        return new_cond->argument_list()->head();
 
1429
        return new_cond->argument_list()->head();
7496
1430
      default:
7497
 
        new_cond->quick_fix_field();
 
1431
        new_cond->quick_fix_field();
7498
1432
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
7499
 
        return new_cond;
 
1433
        return new_cond;
7500
1434
      }
7501
1435
    }
7502
1436
    else /* It's OR */
7503
1437
    {
7504
1438
      Item_cond_or *new_cond=new Item_cond_or;
7505
1439
      if (!new_cond)
7506
 
        return (COND*) 0;
 
1440
        return (COND*) 0;
7507
1441
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
7508
1442
      Item *item;
7509
1443
      while ((item=li++))
7510
1444
      {
7511
 
        Item *fix= make_cond_remainder(item, false);
7512
 
        if (!fix)
7513
 
          return (COND*) 0;
7514
 
        new_cond->argument_list()->push_back(fix);
 
1445
        Item *fix= make_cond_remainder(item, false);
 
1446
        if (!fix)
 
1447
          return (COND*) 0;
 
1448
        new_cond->argument_list()->push_back(fix);
7515
1449
        tbl_map |= fix->used_tables();
7516
1450
      }
7517
1451
      new_cond->quick_fix_field();
7523
1457
  return cond;
7524
1458
}
7525
1459
 
7526
 
 
7527
 
/*
7528
 
  Try to extract and push the index condition
7529
 
 
7530
 
  SYNOPSIS
7531
 
    push_index_cond()
7532
 
      tab            A join tab that has tab->table->file and its condition
7533
 
                     in tab->select_cond
7534
 
      keyno          Index for which extract and push the condition
7535
 
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
7536
 
 
7537
 
  DESCRIPTION
7538
 
    Try to extract and push the index condition down to table handler
7539
 
*/
7540
 
 
7541
 
static void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
7542
 
{
7543
 
  Item *idx_cond;
7544
 
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
7545
 
      tab->join->thd->variables.engine_condition_pushdown)
7546
 
  {
7547
 
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
7548
 
                                  other_tbls_ok);
7549
 
 
7550
 
    if (idx_cond)
7551
 
    {
7552
 
      tab->pre_idx_push_select_cond= tab->select_cond;
7553
 
      Item *idx_remainder_cond= 
7554
 
        tab->table->file->idx_cond_push(keyno, idx_cond);
7555
 
 
7556
 
      /*
7557
 
        Disable eq_ref's "lookup cache" if we've pushed down an index
7558
 
        condition. 
7559
 
        TODO: This check happens to work on current ICP implementations, but
7560
 
        there may exist a compliant implementation that will not work 
7561
 
        correctly with it. Sort this out when we stabilize the condition
7562
 
        pushdown APIs.
7563
 
      */
7564
 
      if (idx_remainder_cond != idx_cond)
7565
 
        tab->ref.disable_cache= true;
7566
 
 
7567
 
      Item *row_cond= make_cond_remainder(tab->select_cond, true);
7568
 
 
7569
 
      if (row_cond)
7570
 
      {
7571
 
        if (!idx_remainder_cond)
7572
 
          tab->select_cond= row_cond;
7573
 
        else
7574
 
        {
7575
 
          tab->select_cond= new Item_cond_and(row_cond, idx_remainder_cond);
7576
 
          tab->select_cond->quick_fix_field();
7577
 
          ((Item_cond_and*)tab->select_cond)->used_tables_cache= 
7578
 
            row_cond->used_tables() | idx_remainder_cond->used_tables();
7579
 
        }
7580
 
      }
7581
 
      else
7582
 
        tab->select_cond= idx_remainder_cond;
7583
 
      if (tab->select)
7584
 
      {
7585
 
        tab->select->cond= tab->select_cond;
7586
 
      }
7587
 
    }
7588
 
  }
7589
 
  return;
7590
 
}
7591
 
 
7592
 
 
7593
 
 
7594
 
    /*
7595
 
      Determine if the set is already ordered for order_st BY, so it can 
7596
 
      disable join cache because it will change the ordering of the results.
7597
 
      Code handles sort table that is at any location (not only first after 
7598
 
      the const tables) despite the fact that it's currently prohibited.
7599
 
      We must disable join cache if the first non-const table alone is
7600
 
      ordered. If there is a temp table the ordering is done as a last
7601
 
      operation and doesn't prevent join cache usage.
7602
 
    */
7603
 
uint32_t make_join_orderinfo(JOIN *join)
7604
 
{
7605
 
  uint32_t i;
7606
 
  if (join->need_tmp)
7607
 
    return join->tables;
7608
 
 
7609
 
  for (i=join->const_tables ; i < join->tables ; i++)
7610
 
  {
7611
 
    JOIN_TAB *tab=join->join_tab+i;
7612
 
    Table *table=tab->table;
7613
 
    if ((table == join->sort_by_table && 
7614
 
         (!join->order || join->skip_sort_order)) ||
7615
 
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
7616
 
    {
7617
 
      break;
7618
 
    }
7619
 
  }
7620
 
  return i;
7621
 
}
7622
 
 
7623
 
 
7624
 
/*
7625
 
  Plan refinement stage: do various set ups for the executioner
7626
 
 
7627
 
  SYNOPSIS
7628
 
    make_join_readinfo()
7629
 
      join           Join being processed
7630
 
      options        Join's options (checking for SELECT_DESCRIBE, 
7631
 
                     SELECT_NO_JOIN_CACHE)
7632
 
      no_jbuf_after  Don't use join buffering after table with this number.
7633
 
 
7634
 
  DESCRIPTION
7635
 
    Plan refinement stage: do various set ups for the executioner
7636
 
      - set up use of join buffering
7637
 
      - push index conditions
7638
 
      - increment counters
7639
 
      - etc
7640
 
 
7641
 
  RETURN 
7642
 
    false - OK
7643
 
    true  - Out of memory
7644
 
*/
7645
 
 
7646
 
static bool
7647
 
make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
7648
 
{
7649
 
  uint32_t i;
7650
 
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
7651
 
  bool sorted= 1;
7652
 
 
7653
 
  for (i=join->const_tables ; i < join->tables ; i++)
7654
 
  {
7655
 
    JOIN_TAB *tab=join->join_tab+i;
7656
 
    Table *table=tab->table;
7657
 
    bool using_join_cache;
7658
 
    tab->read_record.table= table;
7659
 
    tab->read_record.file=table->file;
7660
 
    tab->next_select=sub_select;                /* normal select */
7661
 
    /* 
7662
 
      TODO: don't always instruct first table's ref/range access method to 
7663
 
      produce sorted output.
7664
 
    */
7665
 
    tab->sorted= sorted;
7666
 
    sorted= 0;                                  // only first must be sorted
7667
 
    if (tab->insideout_match_tab)
7668
 
    {
7669
 
      if (!(tab->insideout_buf= (unsigned char*)join->thd->alloc(tab->table->key_info
7670
 
                                                         [tab->index].
7671
 
                                                         key_length)))
7672
 
        return true;
7673
 
    }
7674
 
    switch (tab->type) {
7675
 
    case JT_SYSTEM:                             // Only happens with left join
7676
 
      table->status=STATUS_NO_RECORD;
7677
 
      tab->read_first_record= join_read_system;
7678
 
      tab->read_record.read_record= join_no_more_records;
7679
 
      break;
7680
 
    case JT_CONST:                              // Only happens with left join
7681
 
      table->status=STATUS_NO_RECORD;
7682
 
      tab->read_first_record= join_read_const;
7683
 
      tab->read_record.read_record= join_no_more_records;
7684
 
      if (table->covering_keys.is_set(tab->ref.key) &&
7685
 
          !table->no_keyread)
7686
 
      {
7687
 
        table->key_read=1;
7688
 
        table->file->extra(HA_EXTRA_KEYREAD);
7689
 
      }
7690
 
      break;
7691
 
    case JT_EQ_REF:
7692
 
      table->status=STATUS_NO_RECORD;
7693
 
      if (tab->select)
7694
 
      {
7695
 
        delete tab->select->quick;
7696
 
        tab->select->quick=0;
7697
 
      }
7698
 
      delete tab->quick;
7699
 
      tab->quick=0;
7700
 
      tab->read_first_record= join_read_key;
7701
 
      tab->read_record.read_record= join_no_more_records;
7702
 
      if (table->covering_keys.is_set(tab->ref.key) &&
7703
 
          !table->no_keyread)
7704
 
      {
7705
 
        table->key_read=1;
7706
 
        table->file->extra(HA_EXTRA_KEYREAD);
7707
 
      }
7708
 
      else
7709
 
        push_index_cond(tab, tab->ref.key, true);
7710
 
      break;
7711
 
    case JT_REF_OR_NULL:
7712
 
    case JT_REF:
7713
 
      table->status=STATUS_NO_RECORD;
7714
 
      if (tab->select)
7715
 
      {
7716
 
        delete tab->select->quick;
7717
 
        tab->select->quick=0;
7718
 
      }
7719
 
      delete tab->quick;
7720
 
      tab->quick=0;
7721
 
      if (table->covering_keys.is_set(tab->ref.key) &&
7722
 
          !table->no_keyread)
7723
 
      {
7724
 
        table->key_read=1;
7725
 
        table->file->extra(HA_EXTRA_KEYREAD);
7726
 
      }
7727
 
      else
7728
 
        push_index_cond(tab, tab->ref.key, true);
7729
 
      if (tab->type == JT_REF)
7730
 
      {
7731
 
        tab->read_first_record= join_read_always_key;
7732
 
        tab->read_record.read_record= tab->insideout_match_tab? 
7733
 
           join_read_next_same_diff : join_read_next_same;
7734
 
      }
7735
 
      else
7736
 
      {
7737
 
        tab->read_first_record= join_read_always_key_or_null;
7738
 
        tab->read_record.read_record= join_read_next_same_or_null;
7739
 
      }
7740
 
      break;
7741
 
    case JT_ALL:
7742
 
      /*
7743
 
        If previous table use cache
7744
 
        If the incoming data set is already sorted don't use cache.
7745
 
      */
7746
 
      table->status=STATUS_NO_RECORD;
7747
 
      using_join_cache= false;
7748
 
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
7749
 
          tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
7750
 
          !tab->insideout_match_tab)
7751
 
      {
7752
 
        if ((options & SELECT_DESCRIBE) ||
7753
 
            !join_init_cache(join->thd,join->join_tab+join->const_tables,
7754
 
                             i-join->const_tables))
7755
 
        {
7756
 
          using_join_cache= true;
7757
 
          tab[-1].next_select=sub_select_cache; /* Patch previous */
7758
 
        }
7759
 
      }
7760
 
      /* These init changes read_record */
7761
 
      if (tab->use_quick == 2)
7762
 
      {
7763
 
        join->thd->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
7764
 
        tab->read_first_record= join_init_quick_read_record;
7765
 
        if (statistics)
7766
 
          status_var_increment(join->thd->status_var.select_range_check_count);
7767
 
      }
7768
 
      else
7769
 
      {
7770
 
        tab->read_first_record= join_init_read_record;
7771
 
        if (i == join->const_tables)
7772
 
        {
7773
 
          if (tab->select && tab->select->quick)
7774
 
          {
7775
 
            if (statistics)
7776
 
              status_var_increment(join->thd->status_var.select_range_count);
7777
 
          }
7778
 
          else
7779
 
          {
7780
 
            join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
7781
 
            if (statistics)
7782
 
              status_var_increment(join->thd->status_var.select_scan_count);
7783
 
          }
7784
 
        }
7785
 
        else
7786
 
        {
7787
 
          if (tab->select && tab->select->quick)
7788
 
          {
7789
 
            if (statistics)
7790
 
              status_var_increment(join->thd->status_var.select_full_range_join_count);
7791
 
          }
7792
 
          else
7793
 
          {
7794
 
            join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
7795
 
            if (statistics)
7796
 
              status_var_increment(join->thd->status_var.select_full_join_count);
7797
 
          }
7798
 
        }
7799
 
        if (!table->no_keyread)
7800
 
        {
7801
 
          if (tab->select && tab->select->quick &&
7802
 
              tab->select->quick->index != MAX_KEY && //not index_merge
7803
 
              table->covering_keys.is_set(tab->select->quick->index))
7804
 
          {
7805
 
            table->key_read=1;
7806
 
            table->file->extra(HA_EXTRA_KEYREAD);
7807
 
          }
7808
 
          else if (!table->covering_keys.is_clear_all() &&
7809
 
                   !(tab->select && tab->select->quick))
7810
 
          {                                     // Only read index tree
7811
 
            if (!tab->insideout_match_tab)
7812
 
            {
7813
 
              /*
7814
 
                See bug #26447: "Using the clustered index for a table scan
7815
 
                is always faster than using a secondary index".
7816
 
              */
7817
 
              if (table->s->primary_key != MAX_KEY &&
7818
 
                  table->file->primary_key_is_clustered())
7819
 
                tab->index= table->s->primary_key;
7820
 
              else
7821
 
                tab->index= table->find_shortest_key(&table->covering_keys);
7822
 
            }
7823
 
            tab->read_first_record= join_read_first;
7824
 
            tab->type=JT_NEXT;          // Read with index_first / index_next
7825
 
          }
7826
 
        }
7827
 
        if (tab->select && tab->select->quick &&
7828
 
            tab->select->quick->index != MAX_KEY && ! tab->table->key_read)
7829
 
          push_index_cond(tab, tab->select->quick->index, !using_join_cache);
7830
 
      }
7831
 
      break;
7832
 
    default:
7833
 
      break;                                    /* purecov: deadcode */
7834
 
    case JT_UNKNOWN:
7835
 
    case JT_MAYBE_REF:
7836
 
      abort();                                  /* purecov: deadcode */
7837
 
    }
7838
 
  }
7839
 
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
7840
 
  return(false);
7841
 
}
7842
 
 
7843
 
 
7844
 
/**
7845
 
  Give error if we some tables are done with a full join.
7846
 
 
7847
 
  This is used by multi_table_update and multi_table_delete when running
7848
 
  in safe mode.
7849
 
 
7850
 
  @param join           Join condition
7851
 
 
7852
 
  @retval
7853
 
    0   ok
7854
 
  @retval
7855
 
    1   Error (full join used)
7856
 
*/
7857
 
 
7858
 
bool error_if_full_join(JOIN *join)
7859
 
{
7860
 
  for (JOIN_TAB *tab=join->join_tab, *end=join->join_tab+join->tables;
7861
 
       tab < end;
7862
 
       tab++)
7863
 
  {
7864
 
    if (tab->type == JT_ALL && (!tab->select || !tab->select->quick))
7865
 
    {
7866
 
      my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE,
7867
 
                 ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0));
7868
 
      return(1);
7869
 
    }
7870
 
  }
7871
 
  return(0);
7872
 
}
7873
 
 
7874
 
 
7875
 
/**
7876
 
  cleanup JOIN_TAB.
7877
 
*/
7878
 
 
7879
 
void JOIN_TAB::cleanup()
 
1460
/**
 
1461
  cleanup JoinTable.
 
1462
*/
 
1463
void JoinTable::cleanup()
7880
1464
{
7881
1465
  delete select;
7882
1466
  select= 0;
7903
1487
  end_read_record(&read_record);
7904
1488
}
7905
1489
 
7906
 
 
7907
 
/**
7908
 
  Partially cleanup JOIN after it has executed: close index or rnd read
7909
 
  (table cursors), free quick selects.
7910
 
 
7911
 
    This function is called in the end of execution of a JOIN, before the used
7912
 
    tables are unlocked and closed.
7913
 
 
7914
 
    For a join that is resolved using a temporary table, the first sweep is
7915
 
    performed against actual tables and an intermediate result is inserted
7916
 
    into the temprorary table.
7917
 
    The last sweep is performed against the temporary table. Therefore,
7918
 
    the base tables and associated buffers used to fill the temporary table
7919
 
    are no longer needed, and this function is called to free them.
7920
 
 
7921
 
    For a join that is performed without a temporary table, this function
7922
 
    is called after all rows are sent, but before EOF packet is sent.
7923
 
 
7924
 
    For a simple SELECT with no subqueries this function performs a full
7925
 
    cleanup of the JOIN and calls mysql_unlock_read_tables to free used base
7926
 
    tables.
7927
 
 
7928
 
    If a JOIN is executed for a subquery or if it has a subquery, we can't
7929
 
    do the full cleanup and need to do a partial cleanup only.
7930
 
    - If a JOIN is not the top level join, we must not unlock the tables
7931
 
    because the outer select may not have been evaluated yet, and we
7932
 
    can't unlock only selected tables of a query.
7933
 
    - Additionally, if this JOIN corresponds to a correlated subquery, we
7934
 
    should not free quick selects and join buffers because they will be
7935
 
    needed for the next execution of the correlated subquery.
7936
 
    - However, if this is a JOIN for a [sub]select, which is not
7937
 
    a correlated subquery itself, but has subqueries, we can free it
7938
 
    fully and also free JOINs of all its subqueries. The exception
7939
 
    is a subquery in SELECT list, e.g: @n
7940
 
    SELECT a, (select cmax(b) from t1) group by c @n
7941
 
    This subquery will not be evaluated at first sweep and its value will
7942
 
    not be inserted into the temporary table. Instead, it's evaluated
7943
 
    when selecting from the temporary table. Therefore, it can't be freed
7944
 
    here even though it's not correlated.
7945
 
 
7946
 
  @todo
7947
 
    Unlock tables even if the join isn't top level select in the tree
7948
 
*/
7949
 
 
7950
 
void JOIN::join_free()
7951
 
{
7952
 
  SELECT_LEX_UNIT *tmp_unit;
7953
 
  SELECT_LEX *sl;
7954
 
  /*
7955
 
    Optimization: if not EXPLAIN and we are done with the JOIN,
7956
 
    free all tables.
7957
 
  */
7958
 
  bool full= (!select_lex->uncacheable && !thd->lex->describe);
7959
 
  bool can_unlock= full;
7960
 
 
7961
 
  cleanup(full);
7962
 
 
7963
 
  for (tmp_unit= select_lex->first_inner_unit();
7964
 
       tmp_unit;
7965
 
       tmp_unit= tmp_unit->next_unit())
7966
 
    for (sl= tmp_unit->first_select(); sl; sl= sl->next_select())
7967
 
    {
7968
 
      Item_subselect *subselect= sl->master_unit()->item;
7969
 
      bool full_local= full && (!subselect || subselect->is_evaluated());
7970
 
      /*
7971
 
        If this join is evaluated, we can fully clean it up and clean up all
7972
 
        its underlying joins even if they are correlated -- they will not be
7973
 
        used any more anyway.
7974
 
        If this join is not yet evaluated, we still must clean it up to
7975
 
        close its table cursors -- it may never get evaluated, as in case of
7976
 
        ... HAVING false OR a IN (SELECT ...))
7977
 
        but all table cursors must be closed before the unlock.
7978
 
      */
7979
 
      sl->cleanup_all_joins(full_local);
7980
 
      /* Can't unlock if at least one JOIN is still needed */
7981
 
      can_unlock= can_unlock && full_local;
7982
 
    }
7983
 
 
7984
 
  /*
7985
 
    We are not using tables anymore
7986
 
    Unlock all tables. We may be in an INSERT .... SELECT statement.
7987
 
  */
7988
 
  if (can_unlock && lock && thd->lock &&
7989
 
      !(select_options & SELECT_NO_UNLOCK) &&
7990
 
      !select_lex->subquery_in_having &&
7991
 
      (select_lex == (thd->lex->unit.fake_select_lex ?
7992
 
                      thd->lex->unit.fake_select_lex : &thd->lex->select_lex)))
7993
 
  {
7994
 
    /*
7995
 
      TODO: unlock tables even if the join isn't top level select in the
7996
 
      tree.
7997
 
    */
7998
 
    mysql_unlock_read_tables(thd, lock);           // Don't free join->lock
7999
 
    lock= 0;
8000
 
  }
8001
 
 
8002
 
  return;
8003
 
}
8004
 
 
8005
 
 
8006
 
/**
8007
 
  Free resources of given join.
8008
 
 
8009
 
  @param fill   true if we should free all resources, call with full==1
8010
 
                should be last, before it this function can be called with
8011
 
                full==0
8012
 
 
8013
 
  @note
8014
 
    With subquery this function definitely will be called several times,
8015
 
    but even for simple query it can be called several times.
8016
 
*/
8017
 
 
8018
 
void JOIN::cleanup(bool full)
8019
 
{
8020
 
  if (table)
8021
 
  {
8022
 
    JOIN_TAB *tab,*end;
8023
 
    /*
8024
 
      Only a sorted table may be cached.  This sorted table is always the
8025
 
      first non const table in join->table
8026
 
    */
8027
 
    if (tables > const_tables) // Test for not-const tables
8028
 
    {
8029
 
      free_io_cache(table[const_tables]);
8030
 
      filesort_free_buffers(table[const_tables],full);
8031
 
    }
8032
 
 
8033
 
    if (full)
8034
 
    {
8035
 
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
8036
 
        tab->cleanup();
8037
 
      table= 0;
8038
 
    }
8039
 
    else
8040
 
    {
8041
 
      for (tab= join_tab, end= tab+tables; tab != end; tab++)
8042
 
      {
8043
 
        if (tab->table)
8044
 
          tab->table->file->ha_index_or_rnd_end();
8045
 
      }
8046
 
    }
8047
 
    cleanup_sj_tmp_tables(this);//
8048
 
  }
8049
 
  /*
8050
 
    We are not using tables anymore
8051
 
    Unlock all tables. We may be in an INSERT .... SELECT statement.
8052
 
  */
8053
 
  if (full)
8054
 
  {
8055
 
    if (tmp_join)
8056
 
      tmp_table_param.copy_field= 0;
8057
 
    group_fields.delete_elements();
8058
 
    /*
8059
 
      We can't call delete_elements() on copy_funcs as this will cause
8060
 
      problems in free_elements() as some of the elements are then deleted.
8061
 
    */
8062
 
    tmp_table_param.copy_funcs.empty();
8063
 
    /*
8064
 
      If we have tmp_join and 'this' JOIN is not tmp_join and
8065
 
      tmp_table_param.copy_field's  of them are equal then we have to remove
8066
 
      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
8067
 
      be removed in tmp_table_param.cleanup().
8068
 
    */
8069
 
    if (tmp_join &&
8070
 
        tmp_join != this &&
8071
 
        tmp_join->tmp_table_param.copy_field ==
8072
 
        tmp_table_param.copy_field)
8073
 
    {
8074
 
      tmp_join->tmp_table_param.copy_field=
8075
 
        tmp_join->tmp_table_param.save_copy_field= 0;
8076
 
    }
8077
 
    tmp_table_param.cleanup();
8078
 
  }
8079
 
  return;
8080
 
}
8081
 
 
 
1490
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
 
1491
{
 
1492
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
 
1493
  {
 
1494
    if (tables & 1 && !eq_ref_table(join, order, *tab))
 
1495
      return 0;
 
1496
  }
 
1497
  return 1;
 
1498
}
8082
1499
 
8083
1500
/**
8084
1501
  Remove the following expressions from order_st BY and GROUP BY:
8099
1516
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
8100
1517
  @endcode
8101
1518
*/
8102
 
 
8103
 
static bool
8104
 
eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
 
1519
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
8105
1520
{
8106
1521
  if (tab->cached_eq_ref_table)                 // If cached
8107
1522
    return tab->eq_ref_table;
8108
1523
  tab->cached_eq_ref_table=1;
8109
1524
  /* We can skip const tables only if not an outer table */
8110
 
  if (tab->type == JT_CONST && !tab->first_inner)
8111
 
    return (tab->eq_ref_table=1);               /* purecov: inspected */
8112
 
  if (tab->type != JT_EQ_REF || tab->table->maybe_null)
 
1525
  if (tab->type == AM_CONST && !tab->first_inner)
 
1526
    return (tab->eq_ref_table=1);
 
1527
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
8113
1528
    return (tab->eq_ref_table=0);               // We must use this
8114
1529
  Item **ref_item=tab->ref.items;
8115
1530
  Item **end=ref_item+tab->ref.key_parts;
8123
1538
      order_st *order;
8124
1539
      for (order=start_order ; order ; order=order->next)
8125
1540
      {
8126
 
        if ((*ref_item)->eq(order->item[0],0))
8127
 
          break;
 
1541
        if ((*ref_item)->eq(order->item[0],0))
 
1542
          break;
8128
1543
      }
8129
1544
      if (order)
8130
1545
      {
8131
 
        found++;
8132
 
        assert(!(order->used & map));
8133
 
        order->used|=map;
8134
 
        continue;                               // Used in order_st BY
 
1546
        found++;
 
1547
        assert(!(order->used & map));
 
1548
        order->used|=map;
 
1549
        continue;                               // Used in order_st BY
8135
1550
      }
8136
1551
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
8137
 
        return (tab->eq_ref_table=0);
 
1552
        return (tab->eq_ref_table= 0);
8138
1553
    }
8139
1554
  }
8140
1555
  /* Check that there was no reference to table before sort order */
8146
1561
      continue;
8147
1562
    }
8148
1563
    if (start_order->depend_map & map)
8149
 
      return (tab->eq_ref_table=0);
8150
 
  }
8151
 
  return tab->eq_ref_table=1;
8152
 
}
8153
 
 
8154
 
 
8155
 
static bool
8156
 
only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
8157
 
{
8158
 
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
8159
 
  {
8160
 
    if (tables & 1 && !eq_ref_table(join, order, *tab))
8161
 
      return 0;
8162
 
  }
8163
 
  return 1;
8164
 
}
8165
 
 
8166
 
 
8167
 
/** Update the dependency map for the tables. */
8168
 
 
8169
 
static void update_depend_map(JOIN *join)
8170
 
{
8171
 
  JOIN_TAB *join_tab=join->join_tab, *end=join_tab+join->tables;
8172
 
 
8173
 
  for (; join_tab != end ; join_tab++)
8174
 
  {
8175
 
    TABLE_REF *ref= &join_tab->ref;
8176
 
    table_map depend_map=0;
8177
 
    Item **item=ref->items;
8178
 
    uint32_t i;
8179
 
    for (i=0 ; i < ref->key_parts ; i++,item++)
8180
 
      depend_map|=(*item)->used_tables();
8181
 
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
8182
 
    depend_map&= ~OUTER_REF_TABLE_BIT;
8183
 
    for (JOIN_TAB **tab=join->map2table;
8184
 
         depend_map ;
8185
 
         tab++,depend_map>>=1 )
8186
 
    {
8187
 
      if (depend_map & 1)
8188
 
        ref->depend_map|=(*tab)->ref.depend_map;
8189
 
    }
8190
 
  }
8191
 
}
8192
 
 
8193
 
 
8194
 
/** Update the dependency map for the sort order. */
8195
 
 
8196
 
static void update_depend_map(JOIN *join, order_st *order)
8197
 
{
8198
 
  for (; order ; order=order->next)
8199
 
  {
8200
 
    table_map depend_map;
8201
 
    order->item[0]->update_used_tables();
8202
 
    order->depend_map=depend_map=order->item[0]->used_tables();
8203
 
    // Not item_sum(), RAND() and no reference to table outside of sub select
8204
 
    if (!(order->depend_map & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT))
8205
 
        && !order->item[0]->with_sum_func)
8206
 
    {
8207
 
      for (JOIN_TAB **tab=join->map2table;
8208
 
           depend_map ;
8209
 
           tab++, depend_map>>=1)
8210
 
      {
8211
 
        if (depend_map & 1)
8212
 
          order->depend_map|=(*tab)->ref.depend_map;
8213
 
      }
8214
 
    }
8215
 
  }
8216
 
}
8217
 
 
8218
 
 
8219
 
/**
8220
 
  Remove all constants and check if order_st only contains simple
8221
 
  expressions.
8222
 
 
8223
 
  simple_order is set to 1 if sort_order only uses fields from head table
8224
 
  and the head table is not a LEFT JOIN table.
8225
 
 
8226
 
  @param join                   Join handler
8227
 
  @param first_order            List of SORT or GROUP order
8228
 
  @param cond                   WHERE statement
8229
 
  @param change_list            Set to 1 if we should remove things from list.
8230
 
                               If this is not set, then only simple_order is
8231
 
                               calculated.
8232
 
  @param simple_order           Set to 1 if we are only using simple expressions
8233
 
 
8234
 
  @return
8235
 
    Returns new sort order
8236
 
*/
8237
 
 
8238
 
static order_st *
8239
 
remove_const(JOIN *join,order_st *first_order, COND *cond,
8240
 
             bool change_list, bool *simple_order)
8241
 
{
8242
 
  if (join->tables == join->const_tables)
8243
 
    return change_list ? 0 : first_order;               // No need to sort
8244
 
 
8245
 
  order_st *order,**prev_ptr;
8246
 
  table_map first_table= join->join_tab[join->const_tables].table->map;
8247
 
  table_map not_const_tables= ~join->const_table_map;
8248
 
  table_map ref;
8249
 
 
8250
 
  prev_ptr= &first_order;
8251
 
  *simple_order= *join->join_tab[join->const_tables].on_expr_ref ? 0 : 1;
8252
 
 
8253
 
  /* NOTE: A variable of not_const_tables ^ first_table; breaks gcc 2.7 */
8254
 
 
8255
 
  update_depend_map(join, first_order);
8256
 
  for (order=first_order; order ; order=order->next)
8257
 
  {
8258
 
    table_map order_tables=order->item[0]->used_tables();
8259
 
    if (order->item[0]->with_sum_func)
8260
 
      *simple_order=0;                          // Must do a temp table to sort
8261
 
    else if (!(order_tables & not_const_tables))
8262
 
    {
8263
 
      if (order->item[0]->with_subselect)
8264
 
        order->item[0]->val_str(&order->item[0]->str_value);
8265
 
      continue;                                 // skip const item
8266
 
    }
8267
 
    else
8268
 
    {
8269
 
      if (order_tables & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT))
8270
 
        *simple_order=0;
8271
 
      else
8272
 
      {
8273
 
        Item *comp_item=0;
8274
 
        if (cond && const_expression_in_where(cond,order->item[0], &comp_item))
8275
 
        {
8276
 
          continue;
8277
 
        }
8278
 
        if ((ref=order_tables & (not_const_tables ^ first_table)))
8279
 
        {
8280
 
          if (!(order_tables & first_table) &&
8281
 
              only_eq_ref_tables(join,first_order, ref))
8282
 
          {
8283
 
            continue;
8284
 
          }
8285
 
          *simple_order=0;                      // Must do a temp table to sort
8286
 
        }
8287
 
      }
8288
 
    }
8289
 
    if (change_list)
8290
 
      *prev_ptr= order;                         // use this entry
8291
 
    prev_ptr= &order->next;
8292
 
  }
8293
 
  if (change_list)
8294
 
    *prev_ptr=0;
8295
 
  if (prev_ptr == &first_order)                 // Nothing to sort/group
8296
 
    *simple_order=1;
8297
 
  return(first_order);
8298
 
}
8299
 
 
8300
 
 
8301
 
static int
8302
 
return_zero_rows(JOIN *join, select_result *result,TableList *tables,
8303
 
                 List<Item> &fields, bool send_row, uint64_t select_options,
8304
 
                 const char *info, Item *having)
8305
 
{
8306
 
  if (select_options & SELECT_DESCRIBE)
8307
 
  {
8308
 
    select_describe(join, false, false, false, info);
8309
 
    return(0);
8310
 
  }
8311
 
 
8312
 
  join->join_free();
8313
 
 
8314
 
  if (send_row)
8315
 
  {
8316
 
    for (TableList *table= tables; table; table= table->next_leaf)
8317
 
      mark_as_null_row(table->table);           // All fields are NULL
8318
 
    if (having && having->val_int() == 0)
8319
 
      send_row=0;
8320
 
  }
8321
 
  if (!(result->send_fields(fields,
8322
 
                              Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)))
8323
 
  {
8324
 
    if (send_row)
8325
 
    {
8326
 
      List_iterator_fast<Item> it(fields);
8327
 
      Item *item;
8328
 
      while ((item= it++))
8329
 
        item->no_rows_in_result();
8330
 
      result->send_data(fields);
8331
 
    }
8332
 
    result->send_eof();                         // Should be safe
8333
 
  }
8334
 
  /* Update results for FOUND_ROWS */
8335
 
  join->thd->limit_found_rows= join->thd->examined_row_count= 0;
8336
 
  return(0);
8337
 
}
8338
 
 
8339
 
/*
8340
 
  used only in JOIN::clear
8341
 
*/
8342
 
static void clear_tables(JOIN *join)
8343
 
{
8344
 
  /* 
8345
 
    must clear only the non-const tables, as const tables
8346
 
    are not re-calculated.
8347
 
  */
8348
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
8349
 
    mark_as_null_row(join->table[i]);           // All fields are NULL
8350
 
}
8351
 
 
8352
 
/*****************************************************************************
8353
 
  Make som simple condition optimization:
8354
 
  If there is a test 'field = const' change all refs to 'field' to 'const'
8355
 
  Remove all dummy tests 'item = item', 'const op const'.
8356
 
  Remove all 'item is NULL', when item can never be null!
8357
 
  item->marker should be 0 for all items on entry
8358
 
  Return in cond_value false if condition is impossible (1 = 2)
8359
 
*****************************************************************************/
8360
 
 
8361
 
class COND_CMP :public ilink {
8362
 
public:
8363
 
  static void *operator new(size_t size)
8364
 
  {
8365
 
    return (void*) sql_alloc((uint) size);
8366
 
  }
8367
 
  static void operator delete(void *ptr __attribute__((unused)),
8368
 
                              size_t size __attribute__((unused)))
8369
 
  { TRASH(ptr, size); }
8370
 
 
8371
 
  Item *and_level;
8372
 
  Item_func *cmp_func;
8373
 
  COND_CMP(Item *a,Item_func *b) :and_level(a),cmp_func(b) {}
8374
 
};
8375
 
 
8376
 
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
8377
 
template class I_List<COND_CMP>;
8378
 
template class I_List_iterator<COND_CMP>;
8379
 
#endif
8380
 
 
 
1564
      return (tab->eq_ref_table= 0);
 
1565
  }
 
1566
  return tab->eq_ref_table= 1;
 
1567
}
8381
1568
 
8382
1569
/**
8383
1570
  Find the multiple equality predicate containing a field.
8397
1584
    - Item_equal for the found multiple equality predicate if a success;
8398
1585
    - NULL otherwise.
8399
1586
*/
8400
 
 
8401
 
Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field,
8402
 
                            bool *inherited_fl)
 
1587
static Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
8403
1588
{
8404
1589
  Item_equal *item= 0;
8405
1590
  bool in_upper_level= false;
8420
1605
  return item;
8421
1606
}
8422
1607
 
8423
 
  
8424
1608
/**
8425
1609
  Check whether an equality can be used to build multiple equalities.
8426
1610
 
8447
1631
    the check_equality will be called for the following equality
8448
1632
    predicates a=b, b=c, b=2 and f=e.
8449
1633
    - For a=b it will be called with *cond_equal=(0,[]) and will transform
8450
 
      *cond_equal into (0,[Item_equal(a,b)]). 
 
1634
      *cond_equal into (0,[Item_equal(a,b)]).
8451
1635
    - For b=c it will be called with *cond_equal=(0,[Item_equal(a,b)])
8452
1636
      and will transform *cond_equal into CE=(0,[Item_equal(a,b,c)]).
8453
1637
    - For b=2 it will be called with *cond_equal=(ptr(CE),[])
8460
1644
    the Field::eq_def method) are placed to the same multiple equalities.
8461
1645
    Because of this some equality predicates are not eliminated and
8462
1646
    can be used in the constant propagation procedure.
8463
 
    We could weeken the equlity test as soon as at least one of the 
8464
 
    equal fields is to be equal to a constant. It would require a 
 
1647
    We could weeken the equlity test as soon as at least one of the
 
1648
    equal fields is to be equal to a constant. It would require a
8465
1649
    more complicated implementation: we would have to store, in
8466
1650
    general case, its own constant for each fields from the multiple
8467
1651
    equality. But at the same time it would allow us to get rid
8479
1663
    containing just field1 and field2 is added to the existing
8480
1664
    multiple equalities.
8481
1665
    If the function processes the predicate of the form field1=const,
8482
 
    it looks for a multiple equality containing field1. If found, the 
 
1666
    it looks for a multiple equality containing field1. If found, the
8483
1667
    function checks the constant of the multiple equality. If the value
8484
1668
    is unknown, it is setup to const. Otherwise the value is compared with
8485
1669
    const and the evaluation of the equality predicate is performed.
8502
1686
  @retval
8503
1687
    false   otherwise
8504
1688
*/
8505
 
 
8506
 
static bool check_simple_equality(Item *left_item, Item *right_item,
8507
 
                                  Item *item, COND_EQUAL *cond_equal)
 
1689
static bool check_simple_equality(Item *left_item,
 
1690
                                  Item *right_item,
 
1691
                                  Item *item,
 
1692
                                  COND_EQUAL *cond_equal)
8508
1693
{
8509
 
  if (left_item->type() == Item::REF_ITEM &&
8510
 
      ((Item_ref*)left_item)->ref_type() == Item_ref::VIEW_REF)
8511
 
  {
8512
 
    if (((Item_ref*)left_item)->depended_from)
8513
 
      return false;
8514
 
    left_item= left_item->real_item();
8515
 
  }
8516
 
  if (right_item->type() == Item::REF_ITEM &&
8517
 
      ((Item_ref*)right_item)->ref_type() == Item_ref::VIEW_REF)
8518
 
  {
8519
 
    if (((Item_ref*)right_item)->depended_from)
8520
 
      return false;
8521
 
    right_item= right_item->real_item();
8522
 
  }
8523
1694
  if (left_item->type() == Item::FIELD_ITEM &&
8524
1695
      right_item->type() == Item::FIELD_ITEM &&
8525
1696
      !((Item_field*)left_item)->depended_from &&
8537
1708
    bool left_copyfl, right_copyfl;
8538
1709
    Item_equal *left_item_equal=
8539
1710
               find_item_equal(cond_equal, left_field, &left_copyfl);
8540
 
    Item_equal *right_item_equal= 
 
1711
    Item_equal *right_item_equal=
8541
1712
               find_item_equal(cond_equal, right_field, &right_copyfl);
8542
1713
 
8543
1714
    /* As (NULL=NULL) != true we can't just remove the predicate f=f */
8544
1715
    if (left_field->eq(right_field)) /* f = f */
8545
 
      return (!(left_field->maybe_null() && !left_item_equal)); 
 
1716
      return (!(left_field->maybe_null() && !left_item_equal));
8546
1717
 
8547
1718
    if (left_item_equal && left_item_equal == right_item_equal)
8548
1719
    {
8549
 
      /* 
 
1720
      /*
8550
1721
        The equality predicate is inference of one of the existing
8551
1722
        multiple equalities, i.e the condition is already covered
8552
1723
        by upper level equalities
8553
1724
      */
8554
1725
       return true;
8555
1726
    }
8556
 
    
8557
 
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name && 
 
1727
 
 
1728
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name &&
8558
1729
                              item->name < subq_sj_cond_name + 64);
8559
1730
    /* Copy the found multiple equalities at the current level if needed */
8560
1731
    if (left_copyfl)
8575
1746
    }
8576
1747
 
8577
1748
    if (left_item_equal)
8578
 
    { 
 
1749
    {
8579
1750
      /* left item was found in the current or one of the upper levels */
8580
1751
      if (! right_item_equal)
8581
1752
        left_item_equal->add((Item_field *) right_item);
8590
1761
      }
8591
1762
    }
8592
1763
    else
8593
 
    { 
 
1764
    {
8594
1765
      /* left item was not found neither the current nor in upper levels  */
8595
1766
      if (right_item_equal)
8596
1767
      {
8598
1769
        if (copy_item_name)
8599
1770
          right_item_equal->name = item->name;
8600
1771
      }
8601
 
      else 
 
1772
      else
8602
1773
      {
8603
1774
        /* None of the fields was found in multiple equalities */
8604
1775
        Item_equal *item_equal= new Item_equal((Item_field *) left_item,
8646
1817
          eq_item->set_cmp_func();
8647
1818
          eq_item->quick_fix_field();
8648
1819
          item= eq_item;
8649
 
        }  
 
1820
        }
8650
1821
        if ((cs != ((Item_func *) item)->compare_collation()) ||
8651
1822
            !cs->coll->propagate(cs, 0, 0))
8652
1823
          return false;
8661
1832
      }
8662
1833
      if (item_equal)
8663
1834
      {
8664
 
        /* 
 
1835
        /*
8665
1836
          The flag cond_false will be set to 1 after this, if item_equal
8666
1837
          already contains a constant and its value is  not equal to
8667
1838
          the value of const_item.
8679
1850
  return false;
8680
1851
}
8681
1852
 
8682
 
 
8683
1853
/**
8684
1854
  Convert row equalities into a conjunction of regular equalities.
8685
1855
 
8692
1862
    simple equality nor a row equality the item for this predicate is added
8693
1863
    to eq_list.
8694
1864
 
8695
 
  @param thd        thread handle
 
1865
  @param session        thread handle
8696
1866
  @param left_row   left term of the row equality to be processed
8697
1867
  @param right_row  right term of the row equality to be processed
8698
1868
  @param cond_equal multiple equalities that must hold together with the
8705
1875
  @retval
8706
1876
    false   otherwise
8707
1877
*/
8708
 
 
8709
 
static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row,
8710
 
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
8711
 
 
1878
static bool check_row_equality(Session *session,
 
1879
                               Item *left_row, 
 
1880
                               Item_row *right_row,
 
1881
                               COND_EQUAL *cond_equal,
 
1882
                               List<Item>* eq_list)
 
1883
{
8712
1884
  uint32_t n= left_row->cols();
8713
1885
  for (uint32_t i= 0 ; i < n; i++)
8714
1886
  {
8718
1890
    if (left_item->type() == Item::ROW_ITEM &&
8719
1891
        right_item->type() == Item::ROW_ITEM)
8720
1892
    {
8721
 
      is_converted= check_row_equality(thd, 
 
1893
      is_converted= check_row_equality(session,
8722
1894
                                       (Item_row *) left_item,
8723
1895
                                       (Item_row *) right_item,
8724
1896
                                       cond_equal, eq_list);
8725
1897
      if (!is_converted)
8726
 
        thd->lex->current_select->cond_count++;      
 
1898
        session->lex->current_select->cond_count++;
8727
1899
    }
8728
1900
    else
8729
 
    { 
 
1901
    {
8730
1902
      is_converted= check_simple_equality(left_item, right_item, 0, cond_equal);
8731
 
      thd->lex->current_select->cond_count++;
8732
 
    }  
8733
 
 
 
1903
      session->lex->current_select->cond_count++;
 
1904
    }
 
1905
 
8734
1906
    if (!is_converted)
8735
1907
    {
8736
1908
      Item_func_eq *eq_item;
8744
1916
  return true;
8745
1917
}
8746
1918
 
8747
 
 
8748
1919
/**
8749
1920
  Eliminate row equalities and form multiple equalities predicates.
8750
1921
 
8759
1930
    equalities which are treated in the same way as original equality
8760
1931
    predicates.
8761
1932
 
8762
 
  @param thd        thread handle
 
1933
  @param session        thread handle
8763
1934
  @param item       predicate to process
8764
1935
  @param cond_equal multiple equalities that must hold together with the
8765
1936
                    predicate
8774
1945
           or, if the equality is neither a simple one nor a row equality,
8775
1946
           or, if the procedure fails by a fatal error.
8776
1947
*/
8777
 
 
8778
 
static bool check_equality(THD *thd, Item *item, COND_EQUAL *cond_equal,
8779
 
                           List<Item> *eq_list)
 
1948
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal, List<Item> *eq_list)
8780
1949
{
8781
1950
  if (item->type() == Item::FUNC_ITEM &&
8782
1951
         ((Item_func*) item)->functype() == Item_func::EQ_FUNC)
8787
1956
    if (left_item->type() == Item::ROW_ITEM &&
8788
1957
        right_item->type() == Item::ROW_ITEM)
8789
1958
    {
8790
 
      thd->lex->current_select->cond_count--;
8791
 
      return check_row_equality(thd,
 
1959
      session->lex->current_select->cond_count--;
 
1960
      return check_row_equality(session,
8792
1961
                                (Item_row *) left_item,
8793
1962
                                (Item_row *) right_item,
8794
1963
                                cond_equal, eq_list);
8795
1964
    }
8796
 
    else 
 
1965
    else
8797
1966
      return check_simple_equality(left_item, right_item, item, cond_equal);
8798
 
  } 
 
1967
  }
8799
1968
  return false;
8800
1969
}
8801
1970
 
8802
 
                          
8803
1971
/**
8804
1972
  Replace all equality predicates in a condition by multiple equality items.
8805
1973
 
8806
1974
    At each 'and' level the function detects items for equality predicates
8807
1975
    and replaced them by a set of multiple equality items of class Item_equal,
8808
 
    taking into account inherited equalities from upper levels. 
 
1976
    taking into account inherited equalities from upper levels.
8809
1977
    If an equality predicate is used not in a conjunction it's just
8810
1978
    replaced by a multiple equality predicate.
8811
1979
    For each 'and' level the function set a pointer to the inherited
8812
1980
    multiple equalities in the cond_equal field of the associated
8813
 
    object of the type Item_cond_and.   
 
1981
    object of the type Item_cond_and.
8814
1982
    The function also traverses the cond tree and and for each field reference
8815
1983
    sets a pointer to the multiple equality item containing the field, if there
8816
1984
    is any. If this multiple equality equates fields to a constant the
8817
 
    function replaces the field reference by the constant in the cases 
 
1985
    function replaces the field reference by the constant in the cases
8818
1986
    when the field is not of a string type or when the field reference is
8819
1987
    just an argument of a comparison predicate.
8820
 
    The function also determines the maximum number of members in 
 
1988
    The function also determines the maximum number of members in
8821
1989
    equality lists of each Item_cond_and object assigning it to
8822
 
    thd->lex->current_select->max_equal_elems.
 
1990
    session->lex->current_select->max_equal_elems.
8823
1991
 
8824
1992
  @note
8825
1993
    Multiple equality predicate =(f1,..fn) is equivalent to the conjuction of
8831
1999
    in a conjuction for a minimal set of multiple equality predicates.
8832
2000
    This set can be considered as a canonical representation of the
8833
2001
    sub-conjunction of the equality predicates.
8834
 
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by 
 
2002
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by
8835
2003
    (=(t1.a,t2.b,t3.c) AND t2.b>5), not by
8836
2004
    (=(t1.a,t2.b) AND =(t1.a,t3.c) AND t2.b>5);
8837
2005
    while (t1.a=t2.b AND t2.b>5 AND t3.c=t4.d) is replaced by
8842
2010
    The function performs the substitution in a recursive descent by
8843
2011
    the condtion tree, passing to the next AND level a chain of multiple
8844
2012
    equality predicates which have been built at the upper levels.
8845
 
    The Item_equal items built at the level are attached to other 
 
2013
    The Item_equal items built at the level are attached to other
8846
2014
    non-equality conjucts as a sublist. The pointer to the inherited
8847
2015
    multiple equalities is saved in the and condition object (Item_cond_and).
8848
 
    This chain allows us for any field reference occurence easyly to find a 
 
2016
    This chain allows us for any field reference occurence easyly to find a
8849
2017
    multiple equality that must be held for this occurence.
8850
2018
    For each AND level we do the following:
8851
2019
    - scan it for all equality predicate (=) items
8852
2020
    - join them into disjoint Item_equal() groups
8853
 
    - process the included OR conditions recursively to do the same for 
8854
 
      lower AND levels. 
 
2021
    - process the included OR conditions recursively to do the same for
 
2022
      lower AND levels.
8855
2023
 
8856
2024
    We need to do things in this order as lower AND levels need to know about
8857
2025
    all possible Item_equal objects in upper levels.
8858
2026
 
8859
 
  @param thd        thread handle
 
2027
  @param session        thread handle
8860
2028
  @param cond       condition(expression) where to make replacement
8861
2029
  @param inherited  path to all inherited multiple equality items
8862
2030
 
8863
2031
  @return
8864
2032
    pointer to the transformed condition
8865
2033
*/
8866
 
 
8867
 
static COND *build_equal_items_for_cond(THD *thd, COND *cond,
8868
 
                                        COND_EQUAL *inherited)
 
2034
static COND *build_equal_items_for_cond(Session *session, COND *cond, COND_EQUAL *inherited)
8869
2035
{
8870
2036
  Item_equal *item_equal;
8871
2037
  COND_EQUAL cond_equal;
8877
2043
    bool and_level= ((Item_cond*) cond)->functype() ==
8878
2044
      Item_func::COND_AND_FUNC;
8879
2045
    List<Item> *args= ((Item_cond*) cond)->argument_list();
8880
 
    
 
2046
 
8881
2047
    List_iterator<Item> li(*args);
8882
2048
    Item *item;
8883
2049
 
8886
2052
      /*
8887
2053
         Retrieve all conjucts of this level detecting the equality
8888
2054
         that are subject to substitution by multiple equality items and
8889
 
         removing each such predicate from the conjunction after having 
 
2055
         removing each such predicate from the conjunction after having
8890
2056
         found/created a multiple equality whose inference the predicate is.
8891
 
     */      
 
2057
     */
8892
2058
      while ((item= li++))
8893
2059
      {
8894
2060
        /*
8896
2062
          structure here because it's restored before each
8897
2063
          re-execution of any prepared statement/stored procedure.
8898
2064
        */
8899
 
        if (check_equality(thd, item, &cond_equal, &eq_list))
 
2065
        if (check_equality(session, item, &cond_equal, &eq_list))
8900
2066
          li.remove();
8901
2067
      }
8902
2068
 
8905
2071
      {
8906
2072
        item_equal->fix_length_and_dec();
8907
2073
        item_equal->update_used_tables();
8908
 
        set_if_bigger(thd->lex->current_select->max_equal_elems,
8909
 
                      item_equal->members());  
 
2074
        set_if_bigger(session->lex->current_select->max_equal_elems,
 
2075
                      item_equal->members());
8910
2076
      }
8911
2077
 
8912
2078
      ((Item_cond_and*)cond)->cond_equal= cond_equal;
8918
2084
    */
8919
2085
    li.rewind();
8920
2086
    while ((item= li++))
8921
 
    { 
 
2087
    {
8922
2088
      Item *new_item;
8923
 
      if ((new_item= build_equal_items_for_cond(thd, item, inherited)) != item)
 
2089
      if ((new_item= build_equal_items_for_cond(session, item, inherited)) != item)
8924
2090
      {
8925
2091
        /* This replacement happens only for standalone equalities */
8926
2092
        /*
8948
2114
      (b=5) and (a=c) are standalone equalities.
8949
2115
      In general we can't leave alone standalone eqalities:
8950
2116
      for WHERE a=b AND c=d AND (b=c OR d=5)
8951
 
      b=c is replaced by =(a,b,c,d).  
 
2117
      b=c is replaced by =(a,b,c,d).
8952
2118
     */
8953
 
    if (check_equality(thd, cond, &cond_equal, &eq_list))
 
2119
    if (check_equality(session, cond, &cond_equal, &eq_list))
8954
2120
    {
8955
2121
      int n= cond_equal.current_level.elements + eq_list.elements;
8956
2122
      if (n == 0)
8961
2127
        {
8962
2128
          item_equal->fix_length_and_dec();
8963
2129
          item_equal->update_used_tables();
8964
 
        }
 
2130
        }
8965
2131
        else
8966
2132
          item_equal= (Item_equal *) eq_list.pop();
8967
 
        set_if_bigger(thd->lex->current_select->max_equal_elems,
8968
 
                      item_equal->members());  
 
2133
        set_if_bigger(session->lex->current_select->max_equal_elems,
 
2134
                      item_equal->members());
8969
2135
        return item_equal;
8970
2136
      }
8971
2137
      else
8972
2138
      {
8973
 
        /* 
 
2139
        /*
8974
2140
          Here a new AND level must be created. It can happen only
8975
2141
          when a row equality is processed as a standalone predicate.
8976
 
        */
 
2142
        */
8977
2143
        Item_cond_and *and_cond= new Item_cond_and(eq_list);
8978
2144
        and_cond->quick_fix_field();
8979
2145
        List<Item> *args= and_cond->argument_list();
8982
2148
        {
8983
2149
          item_equal->fix_length_and_dec();
8984
2150
          item_equal->update_used_tables();
8985
 
          set_if_bigger(thd->lex->current_select->max_equal_elems,
8986
 
                        item_equal->members());  
 
2151
          set_if_bigger(session->lex->current_select->max_equal_elems,
 
2152
                        item_equal->members());
8987
2153
        }
8988
2154
        and_cond->cond_equal= cond_equal;
8989
2155
        args->concat((List<Item> *)&cond_equal.current_level);
8990
 
        
 
2156
 
8991
2157
        return and_cond;
8992
2158
      }
8993
2159
    }
8994
 
    /* 
 
2160
    /*
8995
2161
      For each field reference in cond, not from equal item predicates,
8996
2162
      set a pointer to the multiple equality it belongs to (if there is any)
8997
2163
      as soon the field is not of a string type or the field reference is
8998
 
      an argument of a comparison predicate. 
8999
 
    */ 
 
2164
      an argument of a comparison predicate.
 
2165
    */
9000
2166
    unsigned char *is_subst_valid= (unsigned char *) 1;
9001
2167
    cond= cond->compile(&Item::subst_argument_checker,
9002
 
                        &is_subst_valid, 
 
2168
                        &is_subst_valid,
9003
2169
                        &Item::equal_fields_propagator,
9004
2170
                        (unsigned char *) inherited);
9005
2171
    cond->update_used_tables();
9007
2173
  return cond;
9008
2174
}
9009
2175
 
9010
 
 
9011
2176
/**
9012
2177
  Build multiple equalities for a condition and all on expressions that
9013
2178
  inherit these multiple equalities.
9053
2218
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t2.a=t4.a AND t3.a=t4.a
9054
2219
        WHERE t1.a=t2.a
9055
2220
    @endcode
9056
 
    that is equivalent to:   
 
2221
    that is equivalent to:
9057
2222
    @code
9058
2223
      SELECT * FROM (t2 LEFT JOIN (t3,t4)ON t2.a=t4.a AND t3.a=t4.a), t1
9059
2224
        WHERE t1.a=t2.a
9060
2225
    @endcode
9061
2226
    Thus, applying equalities from the where condition we basically
9062
2227
    can get more freedom in performing join operations.
9063
 
    Althogh we don't use this property now, it probably makes sense to use 
9064
 
    it in the future.    
9065
 
  @param thd                  Thread handler
 
2228
    Althogh we don't use this property now, it probably makes sense to use
 
2229
    it in the future.
 
2230
  @param session                      Thread handler
9066
2231
  @param cond                condition to build the multiple equalities for
9067
2232
  @param inherited           path to all inherited multiple equality items
9068
2233
  @param join_list           list of join tables to which the condition
9073
2238
  @return
9074
2239
    pointer to the transformed condition containing multiple equalities
9075
2240
*/
9076
 
   
9077
 
static COND *build_equal_items(THD *thd, COND *cond,
 
2241
static COND *build_equal_items(Session *session, COND *cond,
9078
2242
                               COND_EQUAL *inherited,
9079
2243
                               List<TableList> *join_list,
9080
2244
                               COND_EQUAL **cond_equal_ref)
9081
2245
{
9082
2246
  COND_EQUAL *cond_equal= 0;
9083
2247
 
9084
 
  if (cond) 
 
2248
  if (cond)
9085
2249
  {
9086
 
    cond= build_equal_items_for_cond(thd, cond, inherited);
 
2250
    cond= build_equal_items_for_cond(session, cond, inherited);
9087
2251
    cond->update_used_tables();
9088
2252
    if (cond->type() == Item::COND_ITEM &&
9089
2253
        ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
9117
2281
          We can modify table->on_expr because its old value will
9118
2282
          be restored before re-execution of PS/SP.
9119
2283
        */
9120
 
        table->on_expr= build_equal_items(thd, table->on_expr, inherited,
 
2284
        table->on_expr= build_equal_items(session, table->on_expr, inherited,
9121
2285
                                          nested_join_list,
9122
2286
                                          &table->cond_equal);
9123
2287
      }
9125
2289
  }
9126
2290
 
9127
2291
  return cond;
9128
 
}    
9129
 
 
 
2292
}
9130
2293
 
9131
2294
/**
9132
2295
  Compare field items by table order in the execution plan.
9133
2296
 
9134
2297
    field1 considered as better than field2 if the table containing
9135
 
    field1 is accessed earlier than the table containing field2.   
 
2298
    field1 is accessed earlier than the table containing field2.
9136
2299
    The function finds out what of two fields is better according
9137
2300
    this criteria.
9138
2301
 
9147
2310
  @retval
9148
2311
    0  otherwise
9149
2312
*/
9150
 
 
9151
2313
static int compare_fields_by_table_order(Item_field *field1,
9152
 
                                  Item_field *field2,
9153
 
                                  void *table_join_idx)
 
2314
                                         Item_field *field2,
 
2315
                                         void *table_join_idx)
9154
2316
{
9155
2317
  int cmp= 0;
9156
2318
  bool outer_ref= 0;
9157
2319
  if (field2->used_tables() & OUTER_REF_TABLE_BIT)
9158
 
  {  
 
2320
  {
9159
2321
    outer_ref= 1;
9160
2322
    cmp= -1;
9161
2323
  }
9166
2328
  }
9167
2329
  if (outer_ref)
9168
2330
    return cmp;
9169
 
  JOIN_TAB **idx= (JOIN_TAB **) table_join_idx;
 
2331
  JoinTable **idx= (JoinTable **) table_join_idx;
9170
2332
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
9171
2333
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
9172
2334
}
9173
2335
 
9174
 
 
9175
2336
/**
9176
2337
  Generate minimal set of simple equalities equivalent to a multiple equality.
9177
2338
 
9211
2372
    a pointer to the simple generated equality, if success.
9212
2373
    - 0, otherwise.
9213
2374
*/
9214
 
 
9215
 
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels,
9216
 
                                  Item_equal *item_equal)
 
2375
static Item *eliminate_item_equal(COND *cond, COND_EQUAL *upper_levels, Item_equal *item_equal)
9217
2376
{
9218
2377
  List<Item> eq_list;
9219
2378
  Item_func_eq *eq_item= 0;
9220
2379
  if (((Item *) item_equal)->const_item() && !item_equal->val_int())
9221
 
    return new Item_int((int64_t) 0,1); 
 
2380
    return new Item_int((int64_t) 0,1);
9222
2381
  Item *item_const= item_equal->get_const();
9223
2382
  Item_equal_iterator it(*item_equal);
9224
2383
  Item *head;
9235
2394
    Item_equal *upper= item_field->find_item_equal(upper_levels);
9236
2395
    Item_field *item= item_field;
9237
2396
    if (upper)
9238
 
    { 
 
2397
    {
9239
2398
      if (item_const && upper->get_const())
9240
2399
        item= 0;
9241
2400
      else
9279
2438
 
9280
2439
  cond->quick_fix_field();
9281
2440
  cond->update_used_tables();
9282
 
   
 
2441
 
9283
2442
  return cond;
9284
2443
}
9285
2444
 
9286
 
 
9287
2445
/**
9288
2446
  Substitute every field reference in a condition by the best equal field
9289
2447
  and eliminate all multiple equality predicates.
9292
2450
    multiple equality predicate it sorts the field references in it
9293
2451
    according to the order of tables specified by the table_join_idx
9294
2452
    parameter. Then it eliminates the multiple equality predicate it
9295
 
    replacing it by the conjunction of simple equality predicates 
 
2453
    replacing it by the conjunction of simple equality predicates
9296
2454
    equating every field from the multiple equality to the first
9297
2455
    field in it, or to the constant, if there is any.
9298
2456
    After this the function retrieves all other conjuncted
9311
2469
  @return
9312
2470
    The transformed condition
9313
2471
*/
9314
 
 
9315
 
static COND* substitute_for_best_equal_field(COND *cond,
9316
 
                                             COND_EQUAL *cond_equal,
9317
 
                                             void *table_join_idx)
 
2472
COND* substitute_for_best_equal_field(COND *cond, COND_EQUAL *cond_equal, void *table_join_idx)
9318
2473
{
9319
2474
  Item_equal *item_equal;
9320
2475
 
9329
2484
      cond_equal= &((Item_cond_and *) cond)->cond_equal;
9330
2485
      cond_list->disjoin((List<Item> *) &cond_equal->current_level);
9331
2486
 
9332
 
      List_iterator_fast<Item_equal> it(cond_equal->current_level);      
 
2487
      List_iterator_fast<Item_equal> it(cond_equal->current_level);
9333
2488
      while ((item_equal= it++))
9334
2489
      {
9335
2490
        item_equal->sort(&compare_fields_by_table_order, table_join_idx);
9336
2491
      }
9337
2492
    }
9338
 
    
 
2493
 
9339
2494
    List_iterator<Item> li(*cond_list);
9340
2495
    Item *item;
9341
2496
    while ((item= li++))
9368
2523
      cond= new Item_int((int32_t)cond->val_bool());
9369
2524
 
9370
2525
  }
9371
 
  else if (cond->type() == Item::FUNC_ITEM && 
 
2526
  else if (cond->type() == Item::FUNC_ITEM &&
9372
2527
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
9373
2528
  {
9374
2529
    item_equal= (Item_equal *) cond;
9382
2537
  return cond;
9383
2538
}
9384
2539
 
9385
 
 
9386
2540
/**
9387
2541
  Check appearance of new constant items in multiple equalities
9388
2542
  of a condition after reading a constant table.
9395
2549
  @param cond       condition whose multiple equalities are to be checked
9396
2550
  @param table      constant table that has been read
9397
2551
*/
9398
 
 
9399
 
static void update_const_equal_items(COND *cond, JOIN_TAB *tab)
 
2552
static void update_const_equal_items(COND *cond, JoinTable *tab)
9400
2553
{
9401
2554
  if (!(cond->used_tables() & tab->table->map))
9402
2555
    return;
9403
2556
 
9404
2557
  if (cond->type() == Item::COND_ITEM)
9405
2558
  {
9406
 
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list(); 
 
2559
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list();
9407
2560
    List_iterator_fast<Item> li(*cond_list);
9408
2561
    Item *item;
9409
2562
    while ((item= li++))
9410
2563
      update_const_equal_items(item, tab);
9411
2564
  }
9412
 
  else if (cond->type() == Item::FUNC_ITEM && 
 
2565
  else if (cond->type() == Item::FUNC_ITEM &&
9413
2566
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
9414
2567
  {
9415
2568
    Item_equal *item_equal= (Item_equal *) cond;
9423
2576
      while ((item_field= it++))
9424
2577
      {
9425
2578
        Field *field= item_field->field;
9426
 
        JOIN_TAB *stat= field->table->reginfo.join_tab;
 
2579
        JoinTable *stat= field->table->reginfo.join_tab;
9427
2580
        key_map possible_keys= field->key_start;
9428
 
        possible_keys.intersect(field->table->keys_in_use_for_query);
9429
 
        stat[0].const_keys.merge(possible_keys);
 
2581
        possible_keys&= field->table->keys_in_use_for_query;
 
2582
        stat[0].const_keys|= possible_keys;
9430
2583
 
9431
2584
        /*
9432
 
          For each field in the multiple equality (for which we know that it 
9433
 
          is a constant) we have to find its corresponding key part, and set 
 
2585
          For each field in the multiple equality (for which we know that it
 
2586
          is a constant) we have to find its corresponding key part, and set
9434
2587
          that key part in const_key_parts.
9435
 
        */  
9436
 
        if (!possible_keys.is_clear_all())
 
2588
        */
 
2589
        if (possible_keys.any())
9437
2590
        {
9438
 
          Table *tab= field->table;
9439
 
          KEYUSE *use;
9440
 
          for (use= stat->keyuse; use && use->table == tab; use++)
9441
 
            if (possible_keys.is_set(use->key) && 
9442
 
                tab->key_info[use->key].key_part[use->keypart].field ==
 
2591
          Table *field_tab= field->table;
 
2592
          optimizer::KeyUse *use;
 
2593
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
 
2594
            if (possible_keys.test(use->getKey()) &&
 
2595
                field_tab->key_info[use->getKey()].key_part[use->getKeypart()].field ==
9443
2596
                field)
9444
 
              tab->const_key_parts[use->key]|= use->keypart_map;
 
2597
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
9445
2598
        }
9446
2599
      }
9447
2600
    }
9448
2601
  }
9449
2602
}
9450
2603
 
9451
 
 
9452
2604
/*
9453
2605
  change field = field to field = const for each found field = const in the
9454
2606
  and_level
9455
2607
*/
9456
 
 
9457
 
static void
9458
 
change_cond_ref_to_const(THD *thd, I_List<COND_CMP> *save_list,
9459
 
                         Item *and_father, Item *cond,
9460
 
                         Item *field, Item *value)
 
2608
static void change_cond_ref_to_const(Session *session,
 
2609
                                     vector<COND_CMP>& save_list,
 
2610
                                     Item *and_father,
 
2611
                                     Item *cond,
 
2612
                                     Item *field,
 
2613
                                     Item *value)
9461
2614
{
9462
2615
  if (cond->type() == Item::COND_ITEM)
9463
2616
  {
9464
 
    bool and_level= ((Item_cond*) cond)->functype() ==
9465
 
      Item_func::COND_AND_FUNC;
 
2617
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
9466
2618
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
9467
2619
    Item *item;
9468
2620
    while ((item=li++))
9469
 
      change_cond_ref_to_const(thd, save_list,and_level ? cond : item, item,
9470
 
                               field, value);
 
2621
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
9471
2622
    return;
9472
2623
  }
9473
2624
  if (cond->eq_cmp_result() == Item::COND_OK)
9487
2638
  {
9488
2639
    Item *tmp=value->clone_item();
9489
2640
    tmp->collation.set(right_item->collation);
9490
 
    
 
2641
 
9491
2642
    if (tmp)
9492
2643
    {
9493
 
      thd->change_item_tree(args + 1, tmp);
 
2644
      session->change_item_tree(args + 1, tmp);
9494
2645
      func->update_used_tables();
9495
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
9496
 
          && and_father != cond && !left_item->const_item())
 
2646
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
 
2647
                and_father != cond && 
 
2648
          ! left_item->const_item())
9497
2649
      {
9498
 
        cond->marker=1;
9499
 
        COND_CMP *tmp2;
9500
 
        if ((tmp2=new COND_CMP(and_father,func)))
9501
 
          save_list->push_back(tmp2);
 
2650
        cond->marker=1;
 
2651
        save_list.push_back( COND_CMP(and_father, func) );
9502
2652
      }
9503
2653
      func->set_cmp_func();
9504
2654
    }
9511
2661
  {
9512
2662
    Item *tmp= value->clone_item();
9513
2663
    tmp->collation.set(left_item->collation);
9514
 
    
 
2664
 
9515
2665
    if (tmp)
9516
2666
    {
9517
 
      thd->change_item_tree(args, tmp);
 
2667
      session->change_item_tree(args, tmp);
9518
2668
      value= tmp;
9519
2669
      func->update_used_tables();
9520
 
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
9521
 
          && and_father != cond && !right_item->const_item())
 
2670
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
 
2671
          and_father != cond && 
 
2672
          ! right_item->const_item())
9522
2673
      {
9523
2674
        args[0]= args[1];                       // For easy check
9524
 
        thd->change_item_tree(args + 1, value);
9525
 
        cond->marker=1;
9526
 
        COND_CMP *tmp2;
9527
 
        if ((tmp2=new COND_CMP(and_father,func)))
9528
 
          save_list->push_back(tmp2);
 
2675
        session->change_item_tree(args + 1, value);
 
2676
        cond->marker=1;
 
2677
        save_list.push_back( COND_CMP(and_father, func) );
9529
2678
      }
9530
2679
      func->set_cmp_func();
9531
2680
    }
9540
2689
  @return
9541
2690
    new conditions
9542
2691
*/
9543
 
 
9544
 
static Item *remove_additional_cond(Item* conds)
 
2692
Item *remove_additional_cond(Item* conds)
9545
2693
{
9546
2694
  if (conds->name == in_additional_cond)
9547
2695
    return 0;
9564
2712
  return conds;
9565
2713
}
9566
2714
 
9567
 
static void
9568
 
propagate_cond_constants(THD *thd, I_List<COND_CMP> *save_list,
9569
 
                         COND *and_father, COND *cond)
 
2715
static void propagate_cond_constants(Session *session, 
 
2716
                                     vector<COND_CMP>& save_list, 
 
2717
                                     COND *and_father, 
 
2718
                                     COND *cond)
9570
2719
{
9571
2720
  if (cond->type() == Item::COND_ITEM)
9572
2721
  {
9573
 
    bool and_level= ((Item_cond*) cond)->functype() ==
9574
 
      Item_func::COND_AND_FUNC;
 
2722
    bool and_level= ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC;
9575
2723
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
9576
2724
    Item *item;
9577
 
    I_List<COND_CMP> save;
 
2725
    vector<COND_CMP> save;
9578
2726
    while ((item=li++))
9579
2727
    {
9580
 
      propagate_cond_constants(thd, &save,and_level ? cond : item, item);
 
2728
      propagate_cond_constants(session, save, and_level ? cond : item, item);
9581
2729
    }
9582
2730
    if (and_level)
9583
 
    {                                           // Handle other found items
9584
 
      I_List_iterator<COND_CMP> cond_itr(save);
9585
 
      COND_CMP *cond_cmp;
9586
 
      while ((cond_cmp=cond_itr++))
 
2731
    {
 
2732
      // Handle other found items
 
2733
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
9587
2734
      {
9588
 
        Item **args= cond_cmp->cmp_func->arguments();
 
2735
        Item **args= iter->cmp_func->arguments();
9589
2736
        if (!args[0]->const_item())
9590
 
          change_cond_ref_to_const(thd, &save,cond_cmp->and_level,
9591
 
                                   cond_cmp->and_level, args[0], args[1]);
 
2737
        {
 
2738
          change_cond_ref_to_const( session, save, iter->and_level,
 
2739
                                    iter->and_level, args[0], args[1] );
 
2740
        }
9592
2741
      }
9593
2742
    }
9594
2743
  }
9595
2744
  else if (and_father != cond && !cond->marker)         // In a AND group
9596
2745
  {
9597
2746
    if (cond->type() == Item::FUNC_ITEM &&
9598
 
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
9599
 
         ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
 
2747
        (((Item_func*) cond)->functype() == Item_func::EQ_FUNC ||
 
2748
        ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC))
9600
2749
    {
9601
2750
      Item_func_eq *func=(Item_func_eq*) cond;
9602
2751
      Item **args= func->arguments();
9605
2754
      if (!(left_const && right_const) &&
9606
2755
          args[0]->result_type() == args[1]->result_type())
9607
2756
      {
9608
 
        if (right_const)
9609
 
        {
9610
 
          resolve_const_item(thd, &args[1], args[0]);
9611
 
          func->update_used_tables();
9612
 
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
9613
 
                                   args[0], args[1]);
9614
 
        }
9615
 
        else if (left_const)
9616
 
        {
9617
 
          resolve_const_item(thd, &args[0], args[1]);
9618
 
          func->update_used_tables();
9619
 
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
9620
 
                                   args[1], args[0]);
9621
 
        }
9622
 
      }
9623
 
    }
9624
 
  }
9625
 
}
9626
 
 
9627
 
 
9628
 
/**
9629
 
  Simplify joins replacing outer joins by inner joins whenever it's
9630
 
  possible.
9631
 
 
9632
 
    The function, during a retrieval of join_list,  eliminates those
9633
 
    outer joins that can be converted into inner join, possibly nested.
9634
 
    It also moves the on expressions for the converted outer joins
9635
 
    and from inner joins to conds.
9636
 
    The function also calculates some attributes for nested joins:
9637
 
    - used_tables    
9638
 
    - not_null_tables
9639
 
    - dep_tables.
9640
 
    - on_expr_dep_tables
9641
 
    The first two attributes are used to test whether an outer join can
9642
 
    be substituted for an inner join. The third attribute represents the
9643
 
    relation 'to be dependent on' for tables. If table t2 is dependent
9644
 
    on table t1, then in any evaluated execution plan table access to
9645
 
    table t2 must precede access to table t2. This relation is used also
9646
 
    to check whether the query contains  invalid cross-references.
9647
 
    The forth attribute is an auxiliary one and is used to calculate
9648
 
    dep_tables.
9649
 
    As the attribute dep_tables qualifies possibles orders of tables in the
9650
 
    execution plan, the dependencies required by the straight join
9651
 
    modifiers are reflected in this attribute as well.
9652
 
    The function also removes all braces that can be removed from the join
9653
 
    expression without changing its meaning.
9654
 
 
9655
 
  @note
9656
 
    An outer join can be replaced by an inner join if the where condition
9657
 
    or the on expression for an embedding nested join contains a conjunctive
9658
 
    predicate rejecting null values for some attribute of the inner tables.
9659
 
 
9660
 
    E.g. in the query:    
9661
 
    @code
9662
 
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
9663
 
    @endcode
9664
 
    the predicate t2.b < 5 rejects nulls.
9665
 
    The query is converted first to:
9666
 
    @code
9667
 
      SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
9668
 
    @endcode
9669
 
    then to the equivalent form:
9670
 
    @code
9671
 
      SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a
9672
 
    @endcode
9673
 
 
9674
 
 
9675
 
    Similarly the following query:
9676
 
    @code
9677
 
      SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b
9678
 
        WHERE t2.c < 5  
9679
 
    @endcode
9680
 
    is converted to:
9681
 
    @code
9682
 
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b 
9683
 
 
9684
 
    @endcode
9685
 
 
9686
 
    One conversion might trigger another:
9687
 
    @code
9688
 
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a
9689
 
                       LEFT JOIN t3 ON t3.b=t2.b
9690
 
        WHERE t3 IS NOT NULL =>
9691
 
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3
9692
 
        WHERE t3 IS NOT NULL AND t3.b=t2.b => 
9693
 
      SELECT * FROM t1, t2, t3
9694
 
        WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a
9695
 
  @endcode
9696
 
 
9697
 
    The function removes all unnecessary braces from the expression
9698
 
    produced by the conversions.
9699
 
    E.g.
9700
 
    @code
9701
 
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
9702
 
    @endcode
9703
 
    finally is converted to: 
9704
 
    @code
9705
 
      SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
9706
 
 
9707
 
    @endcode
9708
 
 
9709
 
 
9710
 
    It also will remove braces from the following queries:
9711
 
    @code
9712
 
      SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b
9713
 
      SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b.
9714
 
    @endcode
9715
 
 
9716
 
    The benefit of this simplification procedure is that it might return 
9717
 
    a query for which the optimizer can evaluate execution plan with more
9718
 
    join orders. With a left join operation the optimizer does not
9719
 
    consider any plan where one of the inner tables is before some of outer
9720
 
    tables.
9721
 
 
9722
 
  IMPLEMENTATION
9723
 
    The function is implemented by a recursive procedure.  On the recursive
9724
 
    ascent all attributes are calculated, all outer joins that can be
9725
 
    converted are replaced and then all unnecessary braces are removed.
9726
 
    As join list contains join tables in the reverse order sequential
9727
 
    elimination of outer joins does not require extra recursive calls.
9728
 
 
9729
 
  SEMI-JOIN NOTES
9730
 
    Remove all semi-joins that have are within another semi-join (i.e. have
9731
 
    an "ancestor" semi-join nest)
9732
 
 
9733
 
  EXAMPLES
9734
 
    Here is an example of a join query with invalid cross references:
9735
 
    @code
9736
 
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b 
9737
 
    @endcode
9738
 
 
9739
 
  @param join        reference to the query info
9740
 
  @param join_list   list representation of the join to be converted
9741
 
  @param conds       conditions to add on expressions for converted joins
9742
 
  @param top         true <=> conds is the where condition
9743
 
 
9744
 
  @return
9745
 
    - The new condition, if success
9746
 
    - 0, otherwise
9747
 
*/
9748
 
 
9749
 
static COND *
9750
 
simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top,
9751
 
               bool in_sj)
9752
 
{
9753
 
  TableList *table;
9754
 
  nested_join_st *nested_join;
9755
 
  TableList *prev_table= 0;
9756
 
  List_iterator<TableList> li(*join_list);
9757
 
 
9758
 
  /* 
9759
 
    Try to simplify join operations from join_list.
9760
 
    The most outer join operation is checked for conversion first. 
9761
 
  */
9762
 
  while ((table= li++))
9763
 
  {
9764
 
    table_map used_tables;
9765
 
    table_map not_null_tables= (table_map) 0;
9766
 
 
9767
 
    if ((nested_join= table->nested_join))
9768
 
    {
9769
 
      /* 
9770
 
         If the element of join_list is a nested join apply
9771
 
         the procedure to its nested join list first.
9772
 
      */
9773
 
      if (table->on_expr)
9774
 
      {
9775
 
        Item *expr= table->on_expr;
9776
 
        /* 
9777
 
           If an on expression E is attached to the table, 
9778
 
           check all null rejected predicates in this expression.
9779
 
           If such a predicate over an attribute belonging to
9780
 
           an inner table of an embedded outer join is found,
9781
 
           the outer join is converted to an inner join and
9782
 
           the corresponding on expression is added to E. 
9783
 
        */ 
9784
 
        expr= simplify_joins(join, &nested_join->join_list,
9785
 
                             expr, false, in_sj || table->sj_on_expr);
9786
 
 
9787
 
        if (!table->prep_on_expr || expr != table->on_expr)
9788
 
        {
9789
 
          assert(expr);
9790
 
 
9791
 
          table->on_expr= expr;
9792
 
          table->prep_on_expr= expr->copy_andor_structure(join->thd);
9793
 
        }
9794
 
      }
9795
 
      nested_join->used_tables= (table_map) 0;
9796
 
      nested_join->not_null_tables=(table_map) 0;
9797
 
      conds= simplify_joins(join, &nested_join->join_list, conds, top, 
9798
 
                            in_sj || table->sj_on_expr);
9799
 
      used_tables= nested_join->used_tables;
9800
 
      not_null_tables= nested_join->not_null_tables;  
9801
 
    }
9802
 
    else
9803
 
    {
9804
 
      if (!table->prep_on_expr)
9805
 
        table->prep_on_expr= table->on_expr;
9806
 
      used_tables= table->table->map;
9807
 
      if (conds)
9808
 
        not_null_tables= conds->not_null_tables();
9809
 
    }
9810
 
      
9811
 
    if (table->embedding)
9812
 
    {
9813
 
      table->embedding->nested_join->used_tables|= used_tables;
9814
 
      table->embedding->nested_join->not_null_tables|= not_null_tables;
9815
 
    }
9816
 
 
9817
 
    if (!table->outer_join || (used_tables & not_null_tables))
9818
 
    {
9819
 
      /* 
9820
 
        For some of the inner tables there are conjunctive predicates
9821
 
        that reject nulls => the outer join can be replaced by an inner join.
9822
 
      */
9823
 
      table->outer_join= 0;
9824
 
      if (table->on_expr)
9825
 
      {
9826
 
        /* Add ON expression to the WHERE or upper-level ON condition. */
9827
 
        if (conds)
9828
 
        {
9829
 
          conds= and_conds(conds, table->on_expr);
9830
 
          conds->top_level_item();
9831
 
          /* conds is always a new item as both cond and on_expr existed */
9832
 
          assert(!conds->fixed);
9833
 
          conds->fix_fields(join->thd, &conds);
9834
 
        }
9835
 
        else
9836
 
          conds= table->on_expr; 
9837
 
        table->prep_on_expr= table->on_expr= 0;
9838
 
      }
9839
 
    }
9840
 
    
9841
 
    if (!top)
9842
 
      continue;
9843
 
 
9844
 
    /* 
9845
 
      Only inner tables of non-convertible outer joins
9846
 
      remain with on_expr.
9847
 
    */ 
9848
 
    if (table->on_expr)
9849
 
    {
9850
 
      table->dep_tables|= table->on_expr->used_tables(); 
9851
 
      if (table->embedding)
9852
 
      {
9853
 
        table->dep_tables&= ~table->embedding->nested_join->used_tables;   
9854
 
        /*
9855
 
           Embedding table depends on tables used
9856
 
           in embedded on expressions. 
9857
 
        */
9858
 
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
9859
 
      }
9860
 
      else
9861
 
        table->dep_tables&= ~table->table->map;
9862
 
    }
9863
 
 
9864
 
    if (prev_table)
9865
 
    {
9866
 
      /* The order of tables is reverse: prev_table follows table */
9867
 
      if (prev_table->straight)
9868
 
        prev_table->dep_tables|= used_tables;
9869
 
      if (prev_table->on_expr)
9870
 
      {
9871
 
        prev_table->dep_tables|= table->on_expr_dep_tables;
9872
 
        table_map prev_used_tables= prev_table->nested_join ?
9873
 
                                    prev_table->nested_join->used_tables :
9874
 
                                    prev_table->table->map;
9875
 
        /* 
9876
 
          If on expression contains only references to inner tables
9877
 
          we still make the inner tables dependent on the outer tables.
9878
 
          It would be enough to set dependency only on one outer table
9879
 
          for them. Yet this is really a rare case.
9880
 
        */  
9881
 
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
9882
 
          prev_table->dep_tables|= used_tables;
9883
 
      }
9884
 
    }
9885
 
    prev_table= table;
9886
 
  }
9887
 
    
9888
 
  /* 
9889
 
    Flatten nested joins that can be flattened.
9890
 
    no ON expression and not a semi-join => can be flattened.
9891
 
  */
9892
 
  li.rewind();
9893
 
  while ((table= li++))
9894
 
  {
9895
 
    nested_join= table->nested_join;
9896
 
    if (table->sj_on_expr && !in_sj)
9897
 
    {
9898
 
       /*
9899
 
         If this is a semi-join that is not contained within another semi-join, 
9900
 
         leave it intact (otherwise it is flattened)
9901
 
       */
9902
 
      join->select_lex->sj_nests.push_back(table);
9903
 
    }
9904
 
    else if (nested_join && !table->on_expr)
9905
 
    {
9906
 
      TableList *tbl;
9907
 
      List_iterator<TableList> it(nested_join->join_list);
9908
 
      while ((tbl= it++))
9909
 
      {
9910
 
        tbl->embedding= table->embedding;
9911
 
        tbl->join_list= table->join_list;
9912
 
      }      
9913
 
      li.replace(nested_join->join_list);
9914
 
    }
9915
 
  }
9916
 
  return(conds); 
9917
 
}
9918
 
 
9919
 
 
9920
 
/**
9921
 
  Assign each nested join structure a bit in nested_join_map.
9922
 
 
9923
 
    Assign each nested join structure (except "confluent" ones - those that
9924
 
    embed only one element) a bit in nested_join_map.
9925
 
 
9926
 
  @param join          Join being processed
9927
 
  @param join_list     List of tables
9928
 
  @param first_unused  Number of first unused bit in nested_join_map before the
9929
 
                       call
9930
 
 
9931
 
  @note
9932
 
    This function is called after simplify_joins(), when there are no
9933
 
    redundant nested joins, #non_confluent_nested_joins <= #tables_in_join so
9934
 
    we will not run out of bits in nested_join_map.
9935
 
 
9936
 
  @return
9937
 
    First unused bit in nested_join_map after the call.
9938
 
*/
9939
 
 
9940
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, 
9941
 
                                          uint32_t first_unused)
9942
 
{
9943
 
  List_iterator<TableList> li(*join_list);
9944
 
  TableList *table;
9945
 
  while ((table= li++))
9946
 
  {
9947
 
    nested_join_st *nested_join;
9948
 
    if ((nested_join= table->nested_join))
9949
 
    {
9950
 
      /*
9951
 
        It is guaranteed by simplify_joins() function that a nested join
9952
 
        that has only one child is either
9953
 
         - a single-table view (the child is the underlying table), or 
9954
 
         - a single-table semi-join nest
9955
 
 
9956
 
        We don't assign bits to such sj-nests because 
9957
 
        1. it is redundant (a "sequence" of one table cannot be interleaved 
9958
 
            with anything)
9959
 
        2. we could run out bits in nested_join_map otherwise.
9960
 
      */
9961
 
      if (nested_join->join_list.elements != 1)
9962
 
      {
9963
 
        /* Don't assign bits to sj-nests */
9964
 
        if (table->on_expr)
9965
 
          nested_join->nj_map= (nested_join_map) 1 << first_unused++;
9966
 
        first_unused= build_bitmap_for_nested_joins(&nested_join->join_list,
9967
 
                                                    first_unused);
9968
 
      }
9969
 
    }
9970
 
  }
9971
 
  return(first_unused);
9972
 
}
9973
 
 
9974
 
 
9975
 
/**
9976
 
  Set nested_join_st::counter=0 in all nested joins in passed list.
9977
 
 
9978
 
    Recursively set nested_join_st::counter=0 for all nested joins contained in
9979
 
    the passed join_list.
9980
 
 
9981
 
  @param join_list  List of nested joins to process. It may also contain base
9982
 
                    tables which will be ignored.
9983
 
*/
9984
 
 
9985
 
static void reset_nj_counters(List<TableList> *join_list)
9986
 
{
9987
 
  List_iterator<TableList> li(*join_list);
9988
 
  TableList *table;
9989
 
  while ((table= li++))
9990
 
  {
9991
 
    nested_join_st *nested_join;
9992
 
    if ((nested_join= table->nested_join))
9993
 
    {
9994
 
      nested_join->counter_= 0;
9995
 
      reset_nj_counters(&nested_join->join_list);
9996
 
    }
9997
 
  }
9998
 
  return;
9999
 
}
10000
 
 
 
2757
        if (right_const)
 
2758
        {
 
2759
                resolve_const_item(session, &args[1], args[0]);
 
2760
          func->update_used_tables();
 
2761
                change_cond_ref_to_const(session, save_list, and_father, and_father,
 
2762
                                        args[0], args[1]);
 
2763
        }
 
2764
        else if (left_const)
 
2765
        {
 
2766
                resolve_const_item(session, &args[0], args[1]);
 
2767
          func->update_used_tables();
 
2768
                change_cond_ref_to_const(session, save_list, and_father, and_father,
 
2769
                                        args[1], args[0]);
 
2770
        }
 
2771
      }
 
2772
    }
 
2773
  }
 
2774
}
10001
2775
 
10002
2776
/**
10003
2777
  Check interleaving with an inner tables of an outer join for
10004
2778
  extension table.
10005
2779
 
10006
 
    Check if table next_tab can be added to current partial join order, and 
 
2780
    Check if table next_tab can be added to current partial join order, and
10007
2781
    if yes, record that it has been added.
10008
2782
 
10009
2783
    The function assumes that both current partial join order and its
10010
2784
    extension with next_tab are valid wrt table dependencies.
10011
2785
 
10012
2786
  @verbatim
10013
 
     IMPLEMENTATION 
 
2787
     IMPLEMENTATION
10014
2788
       LIMITATIONS ON JOIN order_st
10015
2789
         The nested [outer] joins executioner algorithm imposes these limitations
10016
2790
         on join order:
10017
 
         1. "Outer tables first" -  any "outer" table must be before any 
 
2791
         1. "Outer tables first" -  any "outer" table must be before any
10018
2792
             corresponding "inner" table.
10019
2793
         2. "No interleaving" - tables inside a nested join must form a continuous
10020
 
            sequence in join order (i.e. the sequence must not be interrupted by 
 
2794
            sequence in join order (i.e. the sequence must not be interrupted by
10021
2795
            tables that are outside of this nested join).
10022
2796
 
10023
2797
         #1 is checked elsewhere, this function checks #2 provided that #1 has
10024
2798
         been already checked.
10025
2799
 
10026
2800
       WHY NEED NON-INTERLEAVING
10027
 
         Consider an example: 
 
2801
         Consider an example:
10028
2802
 
10029
2803
           select * from t0 join t1 left join (t2 join t3) on cond1
10030
2804
 
10048
2822
         The limitations on join order can be rephrased as follows: for valid
10049
2823
         join order one must be able to:
10050
2824
           1. write down the used tables in the join order on one line.
10051
 
           2. for each nested join, put one '(' and one ')' on the said line        
 
2825
           2. for each nested join, put one '(' and one ')' on the said line
10052
2826
           3. write "LEFT JOIN" and "ON (...)" where appropriate
10053
2827
           4. get a query equivalent to the query we're trying to execute.
10054
2828
 
10055
2829
         Calls to check_interleaving_with_nj() are equivalent to writing the
10056
 
         above described line from left to right. 
10057
 
         A single check_interleaving_with_nj(A,B) call is equivalent to writing 
 
2830
         above described line from left to right.
 
2831
         A single check_interleaving_with_nj(A,B) call is equivalent to writing
10058
2832
         table B and appropriate brackets on condition that table A and
10059
2833
         appropriate brackets is the last what was written. Graphically the
10060
2834
         transition is as follows:
10067
2841
                                                      position.
10068
2842
 
10069
2843
         Notes about the position:
10070
 
           The caller guarantees that there is no more then one X-bracket by 
10071
 
           checking "!(remaining_tables & s->dependent)" before calling this 
 
2844
           The caller guarantees that there is no more then one X-bracket by
 
2845
           checking "!(remaining_tables & s->dependent)" before calling this
10072
2846
           function. X-bracket may have a pair in Y-bracket.
10073
2847
 
10074
2848
         When "writing" we store/update this auxilary info about the current
10091
2865
  @retval
10092
2866
    true   Requested join order extension not allowed.
10093
2867
*/
10094
 
 
10095
 
static bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
 
2868
bool check_interleaving_with_nj(JoinTable *last_tab, JoinTable *next_tab)
10096
2869
{
10097
2870
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
10098
2871
  JOIN *join= last_tab->join;
10099
2872
 
10100
 
  if (join->cur_embedding_map & ~next_tab->embedding_map)
 
2873
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
10101
2874
  {
10102
 
    /* 
 
2875
    /*
10103
2876
      next_tab is outside of the "pair of brackets" we're currently in.
10104
2877
      Cannot add it.
10105
2878
    */
10106
2879
    return true;
10107
2880
  }
10108
 
   
 
2881
 
10109
2882
  /*
10110
2883
    Do update counters for "pairs of brackets" that we've left (marked as
10111
2884
    X,Y,Z in the above picture)
10115
2888
    next_emb->nested_join->counter_++;
10116
2889
    if (next_emb->nested_join->counter_ == 1)
10117
2890
    {
10118
 
      /* 
 
2891
      /*
10119
2892
        next_emb is the first table inside a nested join we've "entered". In
10120
2893
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
10121
2894
        X bracket might have Y pair bracket.
10122
2895
      */
10123
2896
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
10124
2897
    }
10125
 
    
 
2898
 
10126
2899
    if (next_emb->nested_join->join_list.elements !=
10127
2900
        next_emb->nested_join->counter_)
10128
2901
      break;
10136
2909
  return false;
10137
2910
}
10138
2911
 
10139
 
 
10140
 
/**
10141
 
  Nested joins perspective: Remove the last table from the join order.
10142
 
 
10143
 
    Remove the last table from the partial join order and update the nested
10144
 
    joins counters and join->cur_embedding_map. It is ok to call this 
10145
 
    function for the first table in join order (for which 
10146
 
    check_interleaving_with_nj has not been called)
10147
 
 
10148
 
  @param last  join table to remove, it is assumed to be the last in current
10149
 
               partial join order.
10150
 
*/
10151
 
 
10152
 
static void restore_prev_nj_state(JOIN_TAB *last)
10153
 
{
10154
 
  TableList *last_emb= last->table->pos_in_table_list->embedding;
10155
 
  JOIN *join= last->join;
10156
 
  while (last_emb)
10157
 
  {
10158
 
    if (last_emb->on_expr)
10159
 
    {
10160
 
      if (!(--last_emb->nested_join->counter_))
10161
 
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
10162
 
      else if (last_emb->nested_join->join_list.elements-1 ==
10163
 
               last_emb->nested_join->counter_) 
10164
 
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
10165
 
      else
10166
 
        break;
10167
 
    }
10168
 
    last_emb= last_emb->embedding;
10169
 
  }
10170
 
}
10171
 
 
10172
 
 
10173
 
 
10174
 
static 
10175
 
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
10176
 
{
10177
 
  TableList *emb_sj_nest;
10178
 
  if ((emb_sj_nest= tab->emb_sj_nest))
10179
 
  {
10180
 
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
10181
 
    /* Remove the sj_nest if all of its SJ-inner tables are in cur_table_map */
10182
 
    if (!(remaining_tables & emb_sj_nest->sj_inner_tables))
10183
 
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
10184
 
  }
10185
 
}
10186
 
 
10187
 
 
10188
 
/*
10189
 
  we assume remaining_tables doesnt contain @tab.
10190
 
*/
10191
 
 
10192
 
static void restore_prev_sj_state(const table_map remaining_tables, 
10193
 
                                  const JOIN_TAB *tab)
10194
 
{
10195
 
  TableList *emb_sj_nest;
10196
 
  if ((emb_sj_nest= tab->emb_sj_nest))
10197
 
  {
10198
 
    /* If we're removing the last SJ-inner table, remove the sj-nest */
10199
 
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) == 
10200
 
        (emb_sj_nest->sj_inner_tables & ~tab->table->map))
10201
 
    {
10202
 
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
10203
 
    }
10204
 
  }
10205
 
}
10206
 
 
10207
 
 
10208
 
static COND *
10209
 
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
10210
 
              Item::cond_result *cond_value)
10211
 
{
10212
 
  THD *thd= join->thd;
 
2912
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
 
2913
{
 
2914
  Session *session= join->session;
10213
2915
 
10214
2916
  if (!conds)
10215
2917
    *cond_value= Item::COND_TRUE;
10216
2918
  else
10217
2919
  {
10218
 
    /* 
 
2920
    /*
10219
2921
      Build all multiple equality predicates and eliminate equality
10220
2922
      predicates that can be inferred from these multiple equalities.
10221
2923
      For each reference of a field included into a multiple equality
10222
2924
      that occurs in a function set a pointer to the multiple equality
10223
2925
      predicate. Substitute a constant instead of this field if the
10224
2926
      multiple equality contains a constant.
10225
 
    */ 
10226
 
    conds= build_equal_items(join->thd, conds, NULL, join_list,
 
2927
    */
 
2928
    conds= build_equal_items(join->session, conds, NULL, join_list,
10227
2929
                             &join->cond_equal);
10228
2930
 
10229
2931
    /* change field = field to field = const for each found field = const */
10230
 
    propagate_cond_constants(thd, (I_List<COND_CMP> *) 0, conds, conds);
 
2932
    vector<COND_CMP> temp;
 
2933
    propagate_cond_constants(session, temp, conds, conds);
10231
2934
    /*
10232
2935
      Remove all instances of item == item
10233
2936
      Remove all and-levels where CONST item != CONST item
10234
2937
    */
10235
 
    conds= remove_eq_conds(thd, conds, cond_value) ;
 
2938
    conds= remove_eq_conds(session, conds, cond_value) ;
10236
2939
  }
10237
2940
  return(conds);
10238
2941
}
10239
2942
 
10240
 
 
10241
2943
/**
10242
2944
  Remove const and eq items.
10243
2945
 
10248
2950
    - COND_TRUE   : always true ( 1 = 1 )
10249
2951
    - COND_FALSE  : always false        ( 1 = 2 )
10250
2952
*/
10251
 
 
10252
 
COND *
10253
 
remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value)
 
2953
COND *remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
10254
2954
{
10255
2955
  if (cond->type() == Item::COND_ITEM)
10256
2956
  {
10257
 
    bool and_level= ((Item_cond*) cond)->functype()
10258
 
      == Item_func::COND_AND_FUNC;
 
2957
    bool and_level= (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC);
 
2958
 
10259
2959
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10260
2960
    Item::cond_result tmp_cond_value;
10261
 
    bool should_fix_fields=0;
 
2961
    bool should_fix_fields= false;
10262
2962
 
10263
 
    *cond_value=Item::COND_UNDEF;
 
2963
    *cond_value= Item::COND_UNDEF;
10264
2964
    Item *item;
10265
 
    while ((item=li++))
 
2965
    while ((item= li++))
10266
2966
    {
10267
 
      Item *new_item=remove_eq_conds(thd, item, &tmp_cond_value);
10268
 
      if (!new_item)
10269
 
        li.remove();
 
2967
      Item *new_item= remove_eq_conds(session, item, &tmp_cond_value);
 
2968
      if (! new_item)
 
2969
              li.remove();
10270
2970
      else if (item != new_item)
10271
2971
      {
10272
 
        li.replace(new_item);
10273
 
        should_fix_fields=1;
 
2972
        li.replace(new_item);
 
2973
        should_fix_fields= true;
10274
2974
      }
10275
2975
      if (*cond_value == Item::COND_UNDEF)
10276
 
        *cond_value=tmp_cond_value;
10277
 
      switch (tmp_cond_value) {
10278
 
      case Item::COND_OK:                       // Not true or false
10279
 
        if (and_level || *cond_value == Item::COND_FALSE)
10280
 
          *cond_value=tmp_cond_value;
10281
 
        break;
10282
 
      case Item::COND_FALSE:
10283
 
        if (and_level)
10284
 
        {
10285
 
          *cond_value=tmp_cond_value;
10286
 
          return (COND*) 0;                     // Always false
10287
 
        }
10288
 
        break;
10289
 
      case Item::COND_TRUE:
10290
 
        if (!and_level)
10291
 
        {
10292
 
          *cond_value= tmp_cond_value;
10293
 
          return (COND*) 0;                     // Always true
10294
 
        }
10295
 
        break;
10296
 
      case Item::COND_UNDEF:                    // Impossible
10297
 
        break; /* purecov: deadcode */
 
2976
              *cond_value= tmp_cond_value;
 
2977
 
 
2978
      switch (tmp_cond_value) 
 
2979
      {
 
2980
        case Item::COND_OK:                     /* Not true or false */
 
2981
          if (and_level || (*cond_value == Item::COND_FALSE))
 
2982
            *cond_value= tmp_cond_value;
 
2983
          break;
 
2984
        case Item::COND_FALSE:
 
2985
          if (and_level)
 
2986
          {
 
2987
            *cond_value= tmp_cond_value;
 
2988
            return (COND *) NULL;                       /* Always false */
 
2989
          }
 
2990
          break;
 
2991
        case Item::COND_TRUE:
 
2992
          if (! and_level)
 
2993
          {
 
2994
            *cond_value= tmp_cond_value;
 
2995
            return (COND *) NULL;                       /* Always true */
 
2996
          }
 
2997
          break;
 
2998
        case Item::COND_UNDEF:                  /* Impossible */
 
2999
          break;
10298
3000
      }
10299
3001
    }
 
3002
 
10300
3003
    if (should_fix_fields)
10301
3004
      cond->update_used_tables();
10302
3005
 
10303
 
    if (!((Item_cond*) cond)->argument_list()->elements ||
10304
 
        *cond_value != Item::COND_OK)
10305
 
      return (COND*) 0;
 
3006
    if (! ((Item_cond*) cond)->argument_list()->elements || *cond_value != Item::COND_OK)
 
3007
      return (COND*) NULL;
 
3008
 
10306
3009
    if (((Item_cond*) cond)->argument_list()->elements == 1)
10307
 
    {                                           // Remove list
 
3010
    {                                           
 
3011
      /* Argument list contains only one element, so reduce it so a single item, then remove list */
10308
3012
      item= ((Item_cond*) cond)->argument_list()->head();
10309
3013
      ((Item_cond*) cond)->argument_list()->empty();
10310
3014
      return item;
10311
3015
    }
10312
3016
  }
10313
 
  else if (cond->type() == Item::FUNC_ITEM &&
10314
 
           ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
 
3017
  else if (cond->type() == Item::FUNC_ITEM && ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
10315
3018
  {
10316
3019
    /*
10317
3020
      Handles this special case for some ODBC applications:
10323
3026
      SELECT * from table_name where auto_increment_column = LAST_INSERT_ID
10324
3027
    */
10325
3028
 
10326
 
    Item_func_isnull *func=(Item_func_isnull*) cond;
 
3029
    Item_func_isnull *func= (Item_func_isnull*) cond;
10327
3030
    Item **args= func->arguments();
10328
3031
    if (args[0]->type() == Item::FIELD_ITEM)
10329
3032
    {
10330
 
      Field *field=((Item_field*) args[0])->field;
10331
 
      if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null &&
10332
 
          (thd->options & OPTION_AUTO_IS_NULL) &&
10333
 
          (thd->first_successful_insert_id_in_prev_stmt > 0 &&
10334
 
           thd->substitute_null_with_insert_id))
 
3033
      Field *field= ((Item_field*) args[0])->field;
 
3034
      if (field->flags & AUTO_INCREMENT_FLAG 
 
3035
          && ! field->table->maybe_null 
 
3036
          && session->options & OPTION_AUTO_IS_NULL
 
3037
          && (
 
3038
            session->first_successful_insert_id_in_prev_stmt > 0 
 
3039
            && session->substitute_null_with_insert_id
 
3040
            )
 
3041
          )
10335
3042
      {
10336
 
        COND *new_cond;
10337
 
        if ((new_cond= new Item_func_eq(args[0],
10338
 
                                        new Item_int("last_insert_id()",
10339
 
                                                     thd->read_first_successful_insert_id_in_prev_stmt(),
10340
 
                                                     MY_INT64_NUM_DECIMAL_DIGITS))))
10341
 
        {
10342
 
          cond=new_cond;
 
3043
        COND *new_cond;
 
3044
        if ((new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()",
 
3045
                                                          session->read_first_successful_insert_id_in_prev_stmt(),
 
3046
                                                          MY_INT64_NUM_DECIMAL_DIGITS))))
 
3047
        {
 
3048
          cond= new_cond;
10343
3049
          /*
10344
3050
            Item_func_eq can't be fixed after creation so we do not check
10345
3051
            cond->fixed, also it do not need tables so we use 0 as second
10346
3052
            argument.
10347
3053
          */
10348
 
          cond->fix_fields(thd, &cond);
10349
 
        }
 
3054
          cond->fix_fields(session, &cond);
 
3055
        }
10350
3056
        /*
10351
3057
          IS NULL should be mapped to LAST_INSERT_ID only for first row, so
10352
3058
          clear for next row
10353
3059
        */
10354
 
        thd->substitute_null_with_insert_id= false;
 
3060
        session->substitute_null_with_insert_id= false;
10355
3061
      }
 
3062
#ifdef NOTDEFINED
10356
3063
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
10357
 
      else if (((field->type() == DRIZZLE_TYPE_NEWDATE) ||
10358
 
                (field->type() == DRIZZLE_TYPE_DATETIME)) &&
10359
 
                (field->flags & NOT_NULL_FLAG) &&
10360
 
               !field->table->maybe_null)
 
3064
      else if (
 
3065
          ((field->type() == DRIZZLE_TYPE_DATE) || (field->type() == DRIZZLE_TYPE_DATETIME)) 
 
3066
          && (field->flags & NOT_NULL_FLAG) 
 
3067
          && ! field->table->maybe_null)
10361
3068
      {
10362
 
        COND *new_cond;
10363
 
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
10364
 
        {
10365
 
          cond=new_cond;
 
3069
        COND *new_cond;
 
3070
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
 
3071
        {
 
3072
          cond= new_cond;
10366
3073
          /*
10367
3074
            Item_func_eq can't be fixed after creation so we do not check
10368
3075
            cond->fixed, also it do not need tables so we use 0 as second
10369
3076
            argument.
10370
3077
          */
10371
 
          cond->fix_fields(thd, &cond);
10372
 
        }
 
3078
          cond->fix_fields(session, &cond);
 
3079
        }
10373
3080
      }
 
3081
#endif /* NOTDEFINED */
10374
3082
    }
10375
3083
    if (cond->const_item())
10376
3084
    {
10377
3085
      *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10378
 
      return (COND*) 0;
 
3086
      return (COND *) NULL;
10379
3087
    }
10380
3088
  }
10381
3089
  else if (cond->const_item() && !cond->is_expensive())
10391
3099
  */
10392
3100
  {
10393
3101
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10394
 
    return (COND*) 0;
 
3102
    return (COND *) NULL;
10395
3103
  }
10396
3104
  else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
10397
 
  {                                             // boolan compare function
 
3105
  {                                             
 
3106
    /* boolan compare function */
10398
3107
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
10399
3108
    Item *right_item= ((Item_func*) cond)->arguments()[1];
10400
3109
    if (left_item->eq(right_item,1))
10401
3110
    {
10402
 
      if (!left_item->maybe_null ||
10403
 
          ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
10404
 
        return (COND*) 0;                       // Compare of identical items
 
3111
      if (!left_item->maybe_null || ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
 
3112
              return (COND*) NULL;                      /* Comparison of identical items */
10405
3113
    }
10406
3114
  }
10407
 
  *cond_value=Item::COND_OK;
10408
 
  return cond;                                  // Point at next and level
 
3115
  *cond_value= Item::COND_OK;
 
3116
  return cond;                                  /* Point at next and return into recursion */
10409
3117
}
10410
3118
 
10411
 
/* 
 
3119
/*
10412
3120
  Check if equality can be used in removing components of GROUP BY/DISTINCT
10413
 
  
 
3121
 
10414
3122
  SYNOPSIS
10415
3123
    test_if_equality_guarantees_uniqueness()
10416
3124
      l          the left comparison argument (a field if any)
10417
3125
      r          the right comparison argument (a const of any)
10418
 
  
10419
 
  DESCRIPTION    
10420
 
    Checks if an equality predicate can be used to take away 
10421
 
    DISTINCT/GROUP BY because it is known to be true for exactly one 
 
3126
 
 
3127
  DESCRIPTION
 
3128
    Checks if an equality predicate can be used to take away
 
3129
    DISTINCT/GROUP BY because it is known to be true for exactly one
10422
3130
    distinct value (e.g. <expr> == <const>).
10423
 
    Arguments must be of the same type because e.g. 
10424
 
    <string_field> = <int_const> may match more than 1 distinct value from 
10425
 
    the column. 
10426
 
    We must take into consideration and the optimization done for various 
 
3131
    Arguments must be of the same type because e.g.
 
3132
    <string_field> = <int_const> may match more than 1 distinct value from
 
3133
    the column.
 
3134
    We must take into consideration and the optimization done for various
10427
3135
    string constants when compared to dates etc (see Item_int_with_ref) as
10428
3136
    well as the collation of the arguments.
10429
 
  
10430
 
  RETURN VALUE  
 
3137
 
 
3138
  RETURN VALUE
10431
3139
    true    can be used
10432
3140
    false   cannot be used
10433
3141
*/
10434
 
static bool
10435
 
test_if_equality_guarantees_uniqueness(Item *l, Item *r)
 
3142
static bool test_if_equality_guarantees_uniqueness(Item *l, Item *r)
10436
3143
{
10437
3144
  return r->const_item() &&
10438
3145
    /* elements must be compared as dates */
10447
3154
/**
10448
3155
  Return true if the item is a const value in all the WHERE clause.
10449
3156
*/
10450
 
 
10451
 
static bool
10452
 
const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
 
3157
bool const_expression_in_where(COND *cond, Item *comp_item, Item **const_item)
10453
3158
{
10454
3159
  if (cond->type() == Item::COND_ITEM)
10455
3160
  {
10462
3167
      bool res=const_expression_in_where(item, comp_item, const_item);
10463
3168
      if (res)                                  // Is a const value
10464
3169
      {
10465
 
        if (and_level)
10466
 
          return 1;
 
3170
        if (and_level)
 
3171
          return 1;
10467
3172
      }
10468
3173
      else if (!and_level)
10469
 
        return 0;
 
3174
        return 0;
10470
3175
    }
10471
3176
    return and_level ? 0 : 1;
10472
3177
  }
10474
3179
  {                                             // boolan compare function
10475
3180
    Item_func* func= (Item_func*) cond;
10476
3181
    if (func->functype() != Item_func::EQUAL_FUNC &&
10477
 
        func->functype() != Item_func::EQ_FUNC)
 
3182
              func->functype() != Item_func::EQ_FUNC)
10478
3183
      return 0;
10479
3184
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
10480
3185
    Item *right_item= ((Item_func*) cond)->arguments()[1];
10482
3187
    {
10483
3188
      if (test_if_equality_guarantees_uniqueness (left_item, right_item))
10484
3189
      {
10485
 
        if (*const_item)
10486
 
          return right_item->eq(*const_item, 1);
10487
 
        *const_item=right_item;
10488
 
        return 1;
 
3190
        if (*const_item)
 
3191
          return right_item->eq(*const_item, 1);
 
3192
        *const_item=right_item;
 
3193
        return 1;
10489
3194
      }
10490
3195
    }
10491
3196
    else if (right_item->eq(comp_item,1))
10492
3197
    {
10493
3198
      if (test_if_equality_guarantees_uniqueness (right_item, left_item))
10494
3199
      {
10495
 
        if (*const_item)
10496
 
          return left_item->eq(*const_item, 1);
10497
 
        *const_item=left_item;
10498
 
        return 1;
 
3200
        if (*const_item)
 
3201
          return left_item->eq(*const_item, 1);
 
3202
        *const_item=left_item;
 
3203
        return 1;
10499
3204
      }
10500
3205
    }
10501
3206
  }
10502
3207
  return 0;
10503
3208
}
10504
3209
 
10505
 
 
10506
3210
/**
10507
3211
  @details
10508
3212
  Rows produced by a join sweep may end up in a temporary table or be sent
10514
3218
  @return
10515
3219
    end_select function to use. This function can't fail.
10516
3220
*/
10517
 
 
10518
3221
Next_select_func setup_end_select_func(JOIN *join)
10519
3222
{
10520
3223
  Table *table= join->tmp_table;
10521
 
  TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param;
 
3224
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
10522
3225
  Next_select_func end_select;
10523
3226
 
10524
3227
  /* Set up select_end */
10525
3228
  if (table)
10526
3229
  {
10527
 
    if (table->group && tmp_tbl->sum_func_count && 
 
3230
    if (table->group && tmp_tbl->sum_func_count &&
10528
3231
        !tmp_tbl->precomputed_group_by)
10529
3232
    {
10530
3233
      if (table->s->keys)
10531
3234
      {
10532
 
        end_select=end_update;
 
3235
        end_select= end_update;
10533
3236
      }
10534
3237
      else
10535
3238
      {
10536
 
        end_select=end_unique_update;
 
3239
        end_select= end_unique_update;
10537
3240
      }
10538
3241
    }
10539
3242
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
10548
3251
        /*
10549
3252
          A preceding call to create_tmp_table in the case when loose
10550
3253
          index scan is used guarantees that
10551
 
          TMP_TABLE_PARAM::items_to_copy has enough space for the group
 
3254
          Tmp_Table_Param::items_to_copy has enough space for the group
10552
3255
          by functions. It is OK here to use memcpy since we copy
10553
3256
          Item_sum pointers into an array of Item pointers.
10554
3257
        */
10570
3273
  return end_select;
10571
3274
}
10572
3275
 
10573
 
 
10574
3276
/**
10575
3277
  Make a join of all tables and write it on socket or to table.
10576
3278
 
10581
3283
  @retval
10582
3284
    -1  if error should be sent
10583
3285
*/
10584
 
 
10585
 
static int
10586
 
do_select(JOIN *join,List<Item> *fields,Table *table)
 
3286
int do_select(JOIN *join, List<Item> *fields, Table *table)
10587
3287
{
10588
3288
  int rc= 0;
10589
3289
  enum_nested_loop_state error= NESTED_LOOP_OK;
10590
 
  JOIN_TAB *join_tab= NULL;
10591
 
  
 
3290
  JoinTable *join_tab= NULL;
 
3291
 
10592
3292
  join->tmp_table= table;                       /* Save for easy recursion */
10593
3293
  join->fields= fields;
10594
3294
 
10595
3295
  if (table)
10596
3296
  {
10597
3297
    table->file->extra(HA_EXTRA_WRITE_CACHE);
10598
 
    empty_record(table);
 
3298
    table->emptyRecord();
10599
3299
    if (table->group && join->tmp_table_param.sum_func_count &&
10600
3300
        table->s->keys && !table->file->inited)
10601
3301
      table->file->ha_index_init(0, 0);
10619
3319
    {
10620
3320
      error= (*end_select)(join, 0, 0);
10621
3321
      if (error == NESTED_LOOP_OK || error == NESTED_LOOP_QUERY_LIMIT)
10622
 
        error= (*end_select)(join, 0, 1);
 
3322
              error= (*end_select)(join, 0, 1);
10623
3323
 
10624
3324
      /*
10625
3325
        If we don't go through evaluate_join_record(), do the counting
10627
3327
        so we don't touch it here.
10628
3328
      */
10629
3329
      join->examined_rows++;
10630
 
      join->thd->row_count++;
 
3330
      join->session->row_count++;
10631
3331
      assert(join->examined_rows <= 1);
10632
3332
    }
10633
3333
    else if (join->send_row_on_empty_set())
10657
3357
    if (!table)                                 // If sending data to client
10658
3358
    {
10659
3359
      /*
10660
 
        The following will unlock all cursors if the command wasn't an
10661
 
        update command
 
3360
        The following will unlock all cursors if the command wasn't an
 
3361
        update command
10662
3362
      */
10663
3363
      join->join_free();                        // Unlock all cursors
10664
3364
      if (join->result->send_eof())
10665
 
        rc= 1;                                  // Don't send error
 
3365
        rc= 1;                                  // Don't send error
10666
3366
    }
10667
3367
  }
10668
3368
  else
10681
3381
    if (new_errno)
10682
3382
      table->file->print_error(new_errno,MYF(0));
10683
3383
  }
10684
 
  return(join->thd->is_error() ? -1 : rc);
 
3384
  return(join->session->is_error() ? -1 : rc);
10685
3385
}
10686
3386
 
10687
 
 
10688
 
enum_nested_loop_state
10689
 
sub_select_cache(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
 
3387
enum_nested_loop_state sub_select_cache(JOIN *join, JoinTable *join_tab, bool end_of_records)
10690
3388
{
10691
3389
  enum_nested_loop_state rc;
10692
3390
 
10697
3395
      rc= sub_select(join,join_tab,end_of_records);
10698
3396
    return rc;
10699
3397
  }
10700
 
  if (join->thd->killed)                // If aborted by user
 
3398
  if (join->session->killed)            // If aborted by user
10701
3399
  {
10702
 
    join->thd->send_kill_message();
10703
 
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
 
3400
    join->session->send_kill_message();
 
3401
    return NESTED_LOOP_KILLED;
10704
3402
  }
10705
3403
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
10706
3404
  {
10707
 
    if (!store_record_in_cache(&join_tab->cache))
 
3405
    if (! store_record_in_cache(&join_tab->cache))
10708
3406
      return NESTED_LOOP_OK;                     // There is more room in cache
10709
3407
    return flush_cached_records(join,join_tab,false);
10710
3408
  }
10717
3415
/**
10718
3416
  Retrieve records ends with a given beginning from the result of a join.
10719
3417
 
10720
 
    For a given partial join record consisting of records from the tables 
 
3418
    For a given partial join record consisting of records from the tables
10721
3419
    preceding the table join_tab in the execution plan, the function
10722
3420
    retrieves all matching full records from the result set and
10723
 
    send them to the result set stream. 
 
3421
    send them to the result set stream.
10724
3422
 
10725
3423
  @note
10726
3424
    The function effectively implements the  final (n-k) nested loops
10760
3458
    first row with t3.a=t1.a has been encountered.
10761
3459
    Thus, the second predicate P2 is supplied with a guarded value that are
10762
3460
    stored in the field 'found' of the first inner table for the outer join
10763
 
    (table t2). When the first row with t3.a=t1.a for the  current row 
 
3461
    (table t2). When the first row with t3.a=t1.a for the  current row
10764
3462
    of table t1  appears, the value becomes true. For now on the predicate
10765
3463
    is evaluated immediately after the row of table t2 has been read.
10766
3464
    When the first row with t3.a=t1.a has been encountered all
10768
3466
    Only when all of them are true the row is sent to the output stream.
10769
3467
    If not, the function returns to the lowest nest level that has a false
10770
3468
    attached condition.
10771
 
    The predicates from on expressions are also pushed down. If in the 
 
3469
    The predicates from on expressions are also pushed down. If in the
10772
3470
    the above example the on expression were (t3.a=t1.a AND t2.a=t1.a),
10773
3471
    then t1.a=t2.a would be pushed down to table t2, and without any
10774
3472
    guard.
10778
3476
    is complemented by nulls  for t2 and t3. Then the pushed down predicates
10779
3477
    are checked for the composed row almost in the same way as it had
10780
3478
    been done for the first row with a match. The only difference is
10781
 
    the predicates from on expressions are not checked. 
 
3479
    the predicates from on expressions are not checked.
10782
3480
 
10783
3481
  @par
10784
3482
  @b IMPLEMENTATION
10794
3492
    and a pointer to a guarding boolean variable.
10795
3493
    When the value of the guard variable is true the value of the object
10796
3494
    is the same as the value of the predicate, otherwise it's just returns
10797
 
    true. 
10798
 
    To carry out a return to a nested loop level of join table t the pointer 
 
3495
    true.
 
3496
    To carry out a return to a nested loop level of join table t the pointer
10799
3497
    to t is remembered in the field 'return_tab' of the join structure.
10800
3498
    Consider the following query:
10801
3499
    @code
10812
3510
    t5.a=t3.a is found, the pushed down predicate t4.b=2 OR t4.b IS NULL
10813
3511
    becomes 'activated', as well the predicate t4.a=t2.a. But
10814
3512
    the predicate (t2.b=5 OR t2.b IS NULL) can not be checked until
10815
 
    t4.a=t2.a becomes true. 
 
3513
    t4.a=t2.a becomes true.
10816
3514
    In order not to re-evaluate the predicates that were already evaluated
10817
3515
    as attached pushed down predicates, a pointer to the the first
10818
3516
    most inner unmatched table is maintained in join_tab->first_unmatched.
10819
3517
    Thus, when the first row from t5 with t5.a=t3.a is found
10820
 
    this pointer for t5 is changed from t4 to t2.             
 
3518
    this pointer for t5 is changed from t4 to t2.
10821
3519
 
10822
3520
    @par
10823
3521
    @b STRUCTURE @b NOTES
10828
3526
  @param join      pointer to the structure providing all context info for
10829
3527
                   the query
10830
3528
  @param join_tab  the first next table of the execution plan to be retrieved
10831
 
  @param end_records  true when we need to perform final steps of retrival   
 
3529
  @param end_records  true when we need to perform final steps of retrival
10832
3530
 
10833
3531
  @return
10834
3532
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
10835
3533
*/
10836
 
int do_sj_reset(SJ_TMP_TABLE *sj_tbl);
10837
 
 
10838
 
enum_nested_loop_state
10839
 
sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
 
3534
enum_nested_loop_state sub_select(JOIN *join, JoinTable *join_tab, bool end_of_records)
10840
3535
{
10841
3536
  join_tab->table->null_row=0;
10842
3537
  if (end_of_records)
10846
3541
  enum_nested_loop_state rc;
10847
3542
  READ_RECORD *info= &join_tab->read_record;
10848
3543
 
10849
 
  if (join_tab->flush_weedout_table)
10850
 
  {
10851
 
    do_sj_reset(join_tab->flush_weedout_table);
10852
 
  }
10853
 
 
10854
3544
  if (join->resume_nested_loop)
10855
3545
  {
10856
3546
    /* If not the last table, plunge down the nested loop */
10877
3567
      /* Set first_unmatched for the last inner table of this group */
10878
3568
      join_tab->last_inner->first_unmatched= join_tab;
10879
3569
    }
10880
 
    join->thd->row_count= 0;
 
3570
    join->session->row_count= 0;
10881
3571
 
10882
3572
    error= (*join_tab->read_first_record)(join_tab);
10883
3573
    rc= evaluate_join_record(join, join_tab, error);
10884
3574
  }
10885
 
  
10886
 
  /* 
10887
 
    Note: psergey has added the 2nd part of the following condition; the 
 
3575
 
 
3576
  /*
 
3577
    Note: psergey has added the 2nd part of the following condition; the
10888
3578
    change should probably be made in 5.1, too.
10889
3579
  */
10890
3580
  while (rc == NESTED_LOOP_OK && join->return_tab >= join_tab)
10902
3592
  return rc;
10903
3593
}
10904
3594
 
10905
 
 
10906
 
 
10907
 
 
10908
 
/*
10909
 
  SemiJoinDuplicateElimination: Weed out duplicate row combinations
10910
 
 
10911
 
  SYNPOSIS
10912
 
    do_sj_dups_weedout()
10913
 
      
10914
 
  RETURN
10915
 
    -1  Error
10916
 
    1   The row combination is a duplicate (discard it)
10917
 
    0   The row combination is not a duplicate (continue)
10918
 
*/
10919
 
 
10920
 
int do_sj_dups_weedout(THD *thd, SJ_TMP_TABLE *sjtbl) 
10921
 
{
10922
 
  int error;
10923
 
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
10924
 
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
10925
 
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
10926
 
  unsigned char *nulls_ptr= ptr;
10927
 
  
10928
 
  /* Put the the rowids tuple into table->record[0]: */
10929
 
 
10930
 
  // 1. Store the length 
10931
 
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
10932
 
  {
10933
 
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
10934
 
    ptr++;
10935
 
  }
10936
 
  else
10937
 
  {
10938
 
    int2store(ptr, sjtbl->rowid_len + sjtbl->null_bytes);
10939
 
    ptr += 2;
10940
 
  }
10941
 
 
10942
 
  // 2. Zero the null bytes 
10943
 
  if (sjtbl->null_bytes)
10944
 
  {
10945
 
    memset(ptr, 0, sjtbl->null_bytes);
10946
 
    ptr += sjtbl->null_bytes; 
10947
 
  }
10948
 
 
10949
 
  // 3. Put the rowids
10950
 
  for (uint32_t i=0; tab != tab_end; tab++, i++)
10951
 
  {
10952
 
    handler *h= tab->join_tab->table->file;
10953
 
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
10954
 
    {
10955
 
      /* It's a NULL-complemented row */
10956
 
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
10957
 
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
10958
 
    }
10959
 
    else
10960
 
    {
10961
 
      /* Copy the rowid value */
10962
 
      if (tab->join_tab->rowid_keep_flags & JOIN_TAB::CALL_POSITION)
10963
 
        h->position(tab->join_tab->table->record[0]);
10964
 
      memcpy(ptr + tab->rowid_offset, h->ref, h->ref_length);
10965
 
    }
10966
 
  }
10967
 
 
10968
 
  error= sjtbl->tmp_table->file->ha_write_row(sjtbl->tmp_table->record[0]);
10969
 
  if (error)
10970
 
  {
10971
 
    /* create_myisam_from_heap will generate error if needed */
10972
 
    if (sjtbl->tmp_table->file->is_fatal_error(error, HA_CHECK_DUP) &&
10973
 
        create_myisam_from_heap(thd, sjtbl->tmp_table, sjtbl->start_recinfo, 
10974
 
                                &sjtbl->recinfo, error, 1))
10975
 
      return -1;
10976
 
    //return (error == HA_ERR_FOUND_DUPP_KEY || error== HA_ERR_FOUND_DUPP_UNIQUE) ? 1: -1;
10977
 
    return 1;
10978
 
  }
10979
 
  return 0;
10980
 
}
10981
 
 
10982
 
 
10983
 
/*
10984
 
  SemiJoinDuplicateElimination: Reset the temporary table
10985
 
*/
10986
 
 
10987
 
int do_sj_reset(SJ_TMP_TABLE *sj_tbl)
10988
 
{
10989
 
  if (sj_tbl->tmp_table)
10990
 
    return sj_tbl->tmp_table->file->ha_delete_all_rows();
10991
 
  return 0;
10992
 
}
10993
 
 
10994
 
/*
10995
 
  Process one record of the nested loop join.
10996
 
 
10997
 
    This function will evaluate parts of WHERE/ON clauses that are
10998
 
    applicable to the partial record on hand and in case of success
10999
 
    submit this record to the next level of the nested loop.
11000
 
*/
11001
 
 
11002
 
static enum_nested_loop_state
11003
 
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
11004
 
                     int error)
11005
 
{
11006
 
  bool not_used_in_distinct=join_tab->not_used_in_distinct;
11007
 
  ha_rows found_records=join->found_records;
11008
 
  COND *select_cond= join_tab->select_cond;
11009
 
 
11010
 
  if (error > 0 || (join->thd->is_error()))     // Fatal error
11011
 
    return NESTED_LOOP_ERROR;
11012
 
  if (error < 0)
11013
 
    return NESTED_LOOP_NO_MORE_ROWS;
11014
 
  if (join->thd->killed)                        // Aborted by user
11015
 
  {
11016
 
    join->thd->send_kill_message();
11017
 
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
11018
 
  }
11019
 
  if (!select_cond || select_cond->val_int())
11020
 
  {
11021
 
    /*
11022
 
      There is no select condition or the attached pushed down
11023
 
      condition is true => a match is found.
11024
 
    */
11025
 
    bool found= 1;
11026
 
    while (join_tab->first_unmatched && found)
11027
 
    {
11028
 
      /*
11029
 
        The while condition is always false if join_tab is not
11030
 
        the last inner join table of an outer join operation.
11031
 
      */
11032
 
      JOIN_TAB *first_unmatched= join_tab->first_unmatched;
11033
 
      /*
11034
 
        Mark that a match for current outer table is found.
11035
 
        This activates push down conditional predicates attached
11036
 
        to the all inner tables of the outer join.
11037
 
      */
11038
 
      first_unmatched->found= 1;
11039
 
      for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
11040
 
      {
11041
 
        if (tab->table->reginfo.not_exists_optimize)
11042
 
          return NESTED_LOOP_NO_MORE_ROWS;
11043
 
        /* Check all predicates that has just been activated. */
11044
 
        /*
11045
 
          Actually all predicates non-guarded by first_unmatched->found
11046
 
          will be re-evaluated again. It could be fixed, but, probably,
11047
 
          it's not worth doing now.
11048
 
        */
11049
 
        if (tab->select_cond && !tab->select_cond->val_int())
11050
 
        {
11051
 
          /* The condition attached to table tab is false */
11052
 
          if (tab == join_tab)
11053
 
            found= 0;
11054
 
          else
11055
 
          {
11056
 
            /*
11057
 
              Set a return point if rejected predicate is attached
11058
 
              not to the last table of the current nest level.
11059
 
            */
11060
 
            join->return_tab= tab;
11061
 
            return NESTED_LOOP_OK;
11062
 
          }
11063
 
        }
11064
 
      }
11065
 
      /*
11066
 
        Check whether join_tab is not the last inner table
11067
 
        for another embedding outer join.
11068
 
      */
11069
 
      if ((first_unmatched= first_unmatched->first_upper) &&
11070
 
          first_unmatched->last_inner != join_tab)
11071
 
        first_unmatched= 0;
11072
 
      join_tab->first_unmatched= first_unmatched;
11073
 
    }
11074
 
 
11075
 
    JOIN_TAB *return_tab= join->return_tab;
11076
 
    join_tab->found_match= true;
11077
 
    if (join_tab->check_weed_out_table)
11078
 
    {
11079
 
      int res= do_sj_dups_weedout(join->thd, join_tab->check_weed_out_table);
11080
 
      if (res == -1)
11081
 
        return NESTED_LOOP_ERROR;
11082
 
      if (res == 1)
11083
 
        return NESTED_LOOP_OK;
11084
 
    }
11085
 
    else if (join_tab->do_firstmatch)
11086
 
    {
11087
 
      /* 
11088
 
        We should return to the join_tab->do_firstmatch after we have 
11089
 
        enumerated all the suffixes for current prefix row combination
11090
 
      */
11091
 
      return_tab= join_tab->do_firstmatch;
11092
 
    }
11093
 
 
11094
 
    /*
11095
 
      It was not just a return to lower loop level when one
11096
 
      of the newly activated predicates is evaluated as false
11097
 
      (See above join->return_tab= tab).
11098
 
    */
11099
 
    join->examined_rows++;
11100
 
    join->thd->row_count++;
11101
 
 
11102
 
    if (found)
11103
 
    {
11104
 
      enum enum_nested_loop_state rc;
11105
 
      /* A match from join_tab is found for the current partial join. */
11106
 
      rc= (*join_tab->next_select)(join, join_tab+1, 0);
11107
 
      if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
11108
 
        return rc;
11109
 
      if (return_tab < join->return_tab)
11110
 
        join->return_tab= return_tab;
11111
 
 
11112
 
      if (join->return_tab < join_tab)
11113
 
        return NESTED_LOOP_OK;
11114
 
      /*
11115
 
        Test if this was a SELECT DISTINCT query on a table that
11116
 
        was not in the field list;  In this case we can abort if
11117
 
        we found a row, as no new rows can be added to the result.
11118
 
      */
11119
 
      if (not_used_in_distinct && found_records != join->found_records)
11120
 
        return NESTED_LOOP_NO_MORE_ROWS;
11121
 
    }
11122
 
    else
11123
 
      join_tab->read_record.file->unlock_row();
11124
 
  }
11125
 
  else
11126
 
  {
11127
 
    /*
11128
 
      The condition pushed down to the table join_tab rejects all rows
11129
 
      with the beginning coinciding with the current partial join.
11130
 
    */
11131
 
    join->examined_rows++;
11132
 
    join->thd->row_count++;
11133
 
    join_tab->read_record.file->unlock_row();
11134
 
  }
11135
 
  return NESTED_LOOP_OK;
11136
 
}
11137
 
 
11138
 
 
11139
 
/**
11140
 
 
11141
 
  @details
11142
 
    Construct a NULL complimented partial join record and feed it to the next
11143
 
    level of the nested loop. This function is used in case we have
11144
 
    an OUTER join and no matching record was found.
11145
 
*/
11146
 
 
11147
 
static enum_nested_loop_state
11148
 
evaluate_null_complemented_join_record(JOIN *join, JOIN_TAB *join_tab)
11149
 
{
11150
 
  /*
11151
 
    The table join_tab is the first inner table of a outer join operation
11152
 
    and no matches has been found for the current outer row.
11153
 
  */
11154
 
  JOIN_TAB *last_inner_tab= join_tab->last_inner;
11155
 
  /* Cache variables for faster loop */
11156
 
  COND *select_cond;
11157
 
  for ( ; join_tab <= last_inner_tab ; join_tab++)
11158
 
  {
11159
 
    /* Change the the values of guard predicate variables. */
11160
 
    join_tab->found= 1;
11161
 
    join_tab->not_null_compl= 0;
11162
 
    /* The outer row is complemented by nulls for each inner tables */
11163
 
    restore_record(join_tab->table,s->default_values);  // Make empty record
11164
 
    mark_as_null_row(join_tab->table);       // For group by without error
11165
 
    select_cond= join_tab->select_cond;
11166
 
    /* Check all attached conditions for inner table rows. */
11167
 
    if (select_cond && !select_cond->val_int())
11168
 
      return NESTED_LOOP_OK;
11169
 
  }
11170
 
  join_tab--;
11171
 
  /*
11172
 
    The row complemented by nulls might be the first row
11173
 
    of embedding outer joins.
11174
 
    If so, perform the same actions as in the code
11175
 
    for the first regular outer join row above.
11176
 
  */
11177
 
  for ( ; ; )
11178
 
  {
11179
 
    JOIN_TAB *first_unmatched= join_tab->first_unmatched;
11180
 
    if ((first_unmatched= first_unmatched->first_upper) &&
11181
 
        first_unmatched->last_inner != join_tab)
11182
 
      first_unmatched= 0;
11183
 
    join_tab->first_unmatched= first_unmatched;
11184
 
    if (!first_unmatched)
11185
 
      break;
11186
 
    first_unmatched->found= 1;
11187
 
    for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
11188
 
    {
11189
 
      if (tab->select_cond && !tab->select_cond->val_int())
11190
 
      {
11191
 
        join->return_tab= tab;
11192
 
        return NESTED_LOOP_OK;
11193
 
      }
11194
 
    }
11195
 
  }
11196
 
  /*
11197
 
    The row complemented by nulls satisfies all conditions
11198
 
    attached to inner tables.
11199
 
    Send the row complemented by nulls to be joined with the
11200
 
    remaining tables.
11201
 
  */
11202
 
  return (*join_tab->next_select)(join, join_tab+1, 0);
11203
 
}
11204
 
 
11205
 
 
11206
 
static enum_nested_loop_state
11207
 
flush_cached_records(JOIN *join,JOIN_TAB *join_tab,bool skip_last)
11208
 
{
11209
 
  enum_nested_loop_state rc= NESTED_LOOP_OK;
11210
 
  int error;
11211
 
  READ_RECORD *info;
11212
 
 
11213
 
  join_tab->table->null_row= 0;
11214
 
  if (!join_tab->cache.records)
11215
 
    return NESTED_LOOP_OK;                      /* Nothing to do */
11216
 
  if (skip_last)
11217
 
    (void) store_record_in_cache(&join_tab->cache); // Must save this for later
11218
 
  if (join_tab->use_quick == 2)
11219
 
  {
11220
 
    if (join_tab->select->quick)
11221
 
    {                                   /* Used quick select last. reset it */
11222
 
      delete join_tab->select->quick;
11223
 
      join_tab->select->quick=0;
11224
 
    }
11225
 
  }
11226
 
 /* read through all records */
11227
 
  if ((error=join_init_read_record(join_tab)))
11228
 
  {
11229
 
    reset_cache_write(&join_tab->cache);
11230
 
    return error < 0 ? NESTED_LOOP_NO_MORE_ROWS: NESTED_LOOP_ERROR;
11231
 
  }
11232
 
 
11233
 
  for (JOIN_TAB *tmp=join->join_tab; tmp != join_tab ; tmp++)
11234
 
  {
11235
 
    tmp->status=tmp->table->status;
11236
 
    tmp->table->status=0;
11237
 
  }
11238
 
 
11239
 
  info= &join_tab->read_record;
11240
 
  do
11241
 
  {
11242
 
    if (join->thd->killed)
11243
 
    {
11244
 
      join->thd->send_kill_message();
11245
 
      return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */
11246
 
    }
11247
 
    SQL_SELECT *select=join_tab->select;
11248
 
    if (rc == NESTED_LOOP_OK &&
11249
 
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
11250
 
    {
11251
 
      uint32_t i;
11252
 
      reset_cache_read(&join_tab->cache);
11253
 
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
11254
 
      {
11255
 
        read_cached_record(join_tab);
11256
 
        if (!select || !select->skip_record())
11257
 
        {
11258
 
          int res= 0;
11259
 
          if (!join_tab->check_weed_out_table || 
11260
 
              !(res= do_sj_dups_weedout(join->thd, join_tab->check_weed_out_table)))
11261
 
          {
11262
 
            rc= (join_tab->next_select)(join,join_tab+1,0);
11263
 
            if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
11264
 
            {
11265
 
              reset_cache_write(&join_tab->cache);
11266
 
              return rc;
11267
 
            }
11268
 
          }
11269
 
          if (res == -1)
11270
 
            return NESTED_LOOP_ERROR;
11271
 
        }
11272
 
      }
11273
 
    }
11274
 
  } while (!(error=info->read_record(info)));
11275
 
 
11276
 
  if (skip_last)
11277
 
    read_cached_record(join_tab);               // Restore current record
11278
 
  reset_cache_write(&join_tab->cache);
11279
 
  if (error > 0)                                // Fatal error
11280
 
    return NESTED_LOOP_ERROR;                   /* purecov: inspected */
11281
 
  for (JOIN_TAB *tmp2=join->join_tab; tmp2 != join_tab ; tmp2++)
11282
 
    tmp2->table->status=tmp2->status;
11283
 
  return NESTED_LOOP_OK;
11284
 
}
11285
 
 
11286
 
int safe_index_read(JOIN_TAB *tab)
 
3595
int safe_index_read(JoinTable *tab)
11287
3596
{
11288
3597
  int error;
11289
3598
  Table *table= tab->table;
11295
3604
  return 0;
11296
3605
}
11297
3606
 
11298
 
 
11299
 
static int
11300
 
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
 
3607
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
11301
3608
{
11302
3609
  int error;
11303
3610
  Table *table=tab->table;
11304
3611
  table->const_table=1;
11305
3612
  table->null_row=0;
11306
3613
  table->status=STATUS_NO_RECORD;
11307
 
  
11308
 
  if (tab->type == JT_SYSTEM)
 
3614
 
 
3615
  if (tab->type == AM_SYSTEM)
11309
3616
  {
11310
3617
    if ((error=join_read_system(tab)))
11311
3618
    {                                           // Info for DESCRIBE
11312
3619
      tab->info="const row not found";
11313
3620
      /* Mark for EXPLAIN that the row was not found */
11314
 
      pos->records_read=0.0;
11315
 
      pos->ref_depend_map= 0;
11316
 
      if (!table->maybe_null || error > 0)
11317
 
        return(error);
 
3621
      pos->setFanout(0.0);
 
3622
      pos->clearRefDependMap();
 
3623
      if (! table->maybe_null || error > 0)
 
3624
        return(error);
11318
3625
    }
11319
3626
  }
11320
3627
  else
11321
3628
  {
11322
 
    if (!table->key_read && table->covering_keys.is_set(tab->ref.key) &&
11323
 
        !table->no_keyread &&
11324
 
        (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY)
 
3629
    if (! table->key_read && 
 
3630
        table->covering_keys.test(tab->ref.key) && 
 
3631
        ! table->no_keyread &&
 
3632
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
11325
3633
    {
11326
3634
      table->key_read=1;
11327
3635
      table->file->extra(HA_EXTRA_KEYREAD);
11337
3645
    {
11338
3646
      tab->info="unique row not found";
11339
3647
      /* Mark for EXPLAIN that the row was not found */
11340
 
      pos->records_read=0.0;
11341
 
      pos->ref_depend_map= 0;
 
3648
      pos->setFanout(0.0);
 
3649
      pos->clearRefDependMap();
11342
3650
      if (!table->maybe_null || error > 0)
11343
 
        return(error);
 
3651
        return(error);
11344
3652
    }
11345
3653
  }
11346
3654
  if (*tab->on_expr_ref && !table->null_row)
11347
3655
  {
11348
3656
    if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0)))
11349
 
      mark_as_null_row(table);  
 
3657
      table->mark_as_null_row();
11350
3658
  }
11351
3659
  if (!table->null_row)
11352
3660
    table->maybe_null=0;
11374
3682
  return(0);
11375
3683
}
11376
3684
 
11377
 
 
11378
 
static int
11379
 
join_read_system(JOIN_TAB *tab)
 
3685
int join_read_system(JoinTable *tab)
11380
3686
{
11381
3687
  Table *table= tab->table;
11382
3688
  int error;
11386
3692
                                           table->s->primary_key)))
11387
3693
    {
11388
3694
      if (error != HA_ERR_END_OF_FILE)
11389
 
        return table->report_error(error);
11390
 
      mark_as_null_row(tab->table);
11391
 
      empty_record(table);                      // Make empty record
 
3695
        return table->report_error(error);
 
3696
      tab->table->mark_as_null_row();
 
3697
      table->emptyRecord();                     // Make empty record
11392
3698
      return -1;
11393
3699
    }
11394
 
    store_record(table,record[1]);
 
3700
    table->storeRecord();
11395
3701
  }
11396
3702
  else if (!table->status)                      // Only happens with left join
11397
 
    restore_record(table,record[1]);                    // restore old record
 
3703
    table->restoreRecord();                     // restore old record
11398
3704
  table->null_row=0;
11399
3705
  return table->status ? -1 : 0;
11400
3706
}
11401
3707
 
11402
 
 
11403
3708
/**
11404
3709
  Read a (constant) table when there is at most one matching row.
11405
3710
 
11412
3717
  @retval
11413
3718
    1   Got an error (other than row not found) during read
11414
3719
*/
11415
 
 
11416
 
static int
11417
 
join_read_const(JOIN_TAB *tab)
 
3720
int join_read_const(JoinTable *tab)
11418
3721
{
11419
3722
  int error;
11420
3723
  Table *table= tab->table;
11421
3724
  if (table->status & STATUS_GARBAGE)           // If first read
11422
3725
  {
11423
3726
    table->status= 0;
11424
 
    if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
11425
 
      error=HA_ERR_KEY_NOT_FOUND;
 
3727
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
 
3728
      error= HA_ERR_KEY_NOT_FOUND;
11426
3729
    else
11427
3730
    {
11428
3731
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
11433
3736
    if (error)
11434
3737
    {
11435
3738
      table->status= STATUS_NOT_FOUND;
11436
 
      mark_as_null_row(tab->table);
11437
 
      empty_record(table);
 
3739
      tab->table->mark_as_null_row();
 
3740
      table->emptyRecord();
11438
3741
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11439
 
        return table->report_error(error);
 
3742
        return table->report_error(error);
11440
3743
      return -1;
11441
3744
    }
11442
 
    store_record(table,record[1]);
 
3745
    table->storeRecord();
11443
3746
  }
11444
3747
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
11445
3748
  {
11446
3749
    table->status=0;
11447
 
    restore_record(table,record[1]);                    // restore old record
 
3750
    table->restoreRecord();                     // restore old record
11448
3751
  }
11449
3752
  table->null_row=0;
11450
3753
  return table->status ? -1 : 0;
11451
3754
}
11452
3755
 
11453
 
 
11454
3756
/*
11455
3757
  eq_ref access method implementation: "read_first" function
11456
3758
 
11457
3759
  SYNOPSIS
11458
3760
    join_read_key()
11459
 
      tab  JOIN_TAB of the accessed table
 
3761
      tab  JoinTable of the accessed table
11460
3762
 
11461
3763
  DESCRIPTION
11462
3764
    This is "read_fist" function for the "ref" access method. The difference
11464
3766
 
11465
3767
  RETURN
11466
3768
    0  - Ok
11467
 
   -1  - Row not found 
 
3769
   -1  - Row not found
11468
3770
    1  - Error
11469
3771
*/
11470
 
 
11471
 
static int
11472
 
join_read_key(JOIN_TAB *tab)
 
3772
int join_read_key(JoinTable *tab)
11473
3773
{
11474
3774
  int error;
11475
3775
  Table *table= tab->table;
11499
3799
  return table->status ? -1 : 0;
11500
3800
}
11501
3801
 
11502
 
 
11503
3802
/*
11504
3803
  ref access method implementation: "read_first" function
11505
3804
 
11506
3805
  SYNOPSIS
11507
3806
    join_read_always_key()
11508
 
      tab  JOIN_TAB of the accessed table
 
3807
      tab  JoinTable of the accessed table
11509
3808
 
11510
3809
  DESCRIPTION
11511
 
    This is "read_fist" function for the "ref" access method.
11512
 
   
 
3810
    This is "read_first" function for the "ref" access method.
 
3811
 
11513
3812
    The functon must leave the index initialized when it returns.
11514
3813
    ref_or_null access implementation depends on that.
11515
3814
 
11516
3815
  RETURN
11517
3816
    0  - Ok
11518
 
   -1  - Row not found 
 
3817
   -1  - Row not found
11519
3818
    1  - Error
11520
3819
*/
11521
 
 
11522
 
static int
11523
 
join_read_always_key(JOIN_TAB *tab)
 
3820
int join_read_always_key(JoinTable *tab)
11524
3821
{
11525
3822
  int error;
11526
3823
  Table *table= tab->table;
11528
3825
  /* Initialize the index first */
11529
3826
  if (!table->file->inited)
11530
3827
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11531
 
 
 
3828
 
11532
3829
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
11533
3830
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
11534
3831
  {
11536
3833
        return -1;
11537
3834
  }
11538
3835
 
11539
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
3836
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
11540
3837
    return -1;
11541
3838
  if ((error=table->file->index_read_map(table->record[0],
11542
3839
                                         tab->ref.key_buff,
11545
3842
  {
11546
3843
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11547
3844
      return table->report_error(error);
11548
 
    return -1; /* purecov: inspected */
 
3845
    return -1;
11549
3846
  }
 
3847
 
11550
3848
  return 0;
11551
3849
}
11552
3850
 
11553
 
 
11554
3851
/**
11555
 
  This function is used when optimizing away order_st BY in 
 
3852
  This function is used when optimizing away order_st BY in
11556
3853
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
11557
3854
*/
11558
 
  
11559
 
static int
11560
 
join_read_last_key(JOIN_TAB *tab)
 
3855
int join_read_last_key(JoinTable *tab)
11561
3856
{
11562
3857
  int error;
11563
3858
  Table *table= tab->table;
11564
3859
 
11565
3860
  if (!table->file->inited)
11566
3861
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11567
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
3862
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
11568
3863
    return -1;
11569
3864
  if ((error=table->file->index_read_last_map(table->record[0],
11570
3865
                                              tab->ref.key_buff,
11572
3867
  {
11573
3868
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11574
3869
      return table->report_error(error);
11575
 
    return -1; /* purecov: inspected */
 
3870
    return -1;
11576
3871
  }
11577
3872
  return 0;
11578
3873
}
11579
3874
 
11580
 
 
11581
 
        /* ARGSUSED */
11582
 
static int
11583
 
join_no_more_records(READ_RECORD *info __attribute__((unused)))
 
3875
int join_no_more_records(READ_RECORD *)
11584
3876
{
11585
3877
  return -1;
11586
3878
}
11587
3879
 
11588
 
static int
11589
 
join_read_next_same_diff(READ_RECORD *info)
 
3880
int join_read_next_same_diff(READ_RECORD *info)
11590
3881
{
11591
3882
  Table *table= info->table;
11592
 
  JOIN_TAB *tab=table->reginfo.join_tab;
 
3883
  JoinTable *tab=table->reginfo.join_tab;
11593
3884
  if (tab->insideout_match_tab->found_match)
11594
3885
  {
11595
3886
    KEY *key= tab->table->key_info + tab->index;
11596
 
    do 
 
3887
    do
11597
3888
    {
11598
3889
      int error;
11599
3890
      /* Save index tuple from record to the buffer */
11608
3899
        table->status= STATUS_GARBAGE;
11609
3900
        return -1;
11610
3901
      }
11611
 
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
 
3902
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
11612
3903
                      tab->insideout_buf, key->key_length));
11613
3904
    tab->insideout_match_tab->found_match= 0;
11614
3905
    return 0;
11617
3908
    return join_read_next_same(info);
11618
3909
}
11619
3910
 
11620
 
static int
11621
 
join_read_next_same(READ_RECORD *info)
 
3911
int join_read_next_same(READ_RECORD *info)
11622
3912
{
11623
3913
  int error;
11624
3914
  Table *table= info->table;
11625
 
  JOIN_TAB *tab=table->reginfo.join_tab;
 
3915
  JoinTable *tab=table->reginfo.join_tab;
11626
3916
 
11627
3917
  if ((error=table->file->index_next_same(table->record[0],
11628
3918
                                          tab->ref.key_buff,
11633
3923
    table->status= STATUS_GARBAGE;
11634
3924
    return -1;
11635
3925
  }
 
3926
 
11636
3927
  return 0;
11637
3928
}
11638
3929
 
11639
 
 
11640
 
static int
11641
 
join_read_prev_same(READ_RECORD *info)
 
3930
int join_read_prev_same(READ_RECORD *info)
11642
3931
{
11643
3932
  int error;
11644
3933
  Table *table= info->table;
11645
 
  JOIN_TAB *tab=table->reginfo.join_tab;
 
3934
  JoinTable *tab=table->reginfo.join_tab;
11646
3935
 
11647
3936
  if ((error=table->file->index_prev(table->record[0])))
11648
3937
    return table->report_error(error);
11655
3944
  return error;
11656
3945
}
11657
3946
 
11658
 
 
11659
 
static int
11660
 
join_init_quick_read_record(JOIN_TAB *tab)
 
3947
int join_init_quick_read_record(JoinTable *tab)
11661
3948
{
11662
3949
  if (test_if_quick_select(tab) == -1)
11663
3950
    return -1;                                  /* No possible records */
11664
3951
  return join_init_read_record(tab);
11665
3952
}
11666
3953
 
11667
 
 
11668
3954
int rr_sequential(READ_RECORD *info);
11669
 
int init_read_record_seq(JOIN_TAB *tab)
 
3955
int init_read_record_seq(JoinTable *tab)
11670
3956
{
11671
3957
  tab->read_record.read_record= rr_sequential;
11672
3958
  if (tab->read_record.file->ha_rnd_init(1))
11674
3960
  return (*tab->read_record.read_record)(&tab->read_record);
11675
3961
}
11676
3962
 
11677
 
static int
11678
 
test_if_quick_select(JOIN_TAB *tab)
 
3963
int test_if_quick_select(JoinTable *tab)
11679
3964
{
11680
3965
  delete tab->select->quick;
11681
 
  tab->select->quick=0;
11682
 
  return tab->select->test_quick_select(tab->join->thd, tab->keys,
11683
 
                                        (table_map) 0, HA_POS_ERROR, 0,
11684
 
                                        false);
 
3966
  tab->select->quick= 0;
 
3967
  return tab->select->test_quick_select(tab->join->session, tab->keys,
 
3968
                                        (table_map) 0, HA_POS_ERROR, 0, false);
11685
3969
}
11686
3970
 
11687
 
 
11688
 
static int
11689
 
join_init_read_record(JOIN_TAB *tab)
 
3971
int join_init_read_record(JoinTable *tab)
11690
3972
{
11691
3973
  if (tab->select && tab->select->quick && tab->select->quick->reset())
11692
3974
    return 1;
11693
 
  init_read_record(&tab->read_record, tab->join->thd, tab->table,
 
3975
  init_read_record(&tab->read_record, tab->join->session, tab->table,
11694
3976
                   tab->select,1,1);
11695
3977
  return (*tab->read_record.read_record)(&tab->read_record);
11696
3978
}
11697
3979
 
11698
 
 
11699
 
static int
11700
 
join_read_first(JOIN_TAB *tab)
 
3980
int join_read_first(JoinTable *tab)
11701
3981
{
11702
3982
  int error;
11703
3983
  Table *table=tab->table;
11704
 
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
 
3984
  if (!table->key_read && table->covering_keys.test(tab->index) &&
11705
3985
      !table->no_keyread)
11706
3986
  {
11707
3987
    table->key_read=1;
11732
4012
      table->report_error(error);
11733
4013
    return -1;
11734
4014
  }
 
4015
 
11735
4016
  return 0;
11736
4017
}
11737
4018
 
11738
 
 
11739
 
static int
11740
 
join_read_next_different(READ_RECORD *info)
 
4019
int join_read_next_different(READ_RECORD *info)
11741
4020
{
11742
 
  JOIN_TAB *tab= info->do_insideout_scan;
 
4021
  JoinTable *tab= info->do_insideout_scan;
11743
4022
  if (tab->insideout_match_tab->found_match)
11744
4023
  {
11745
4024
    KEY *key= tab->table->key_info + tab->index;
11746
 
    do 
 
4025
    do
11747
4026
    {
11748
4027
      int error;
11749
4028
      /* Save index tuple from record to the buffer */
11751
4030
 
11752
4031
      if ((error=info->file->index_next(info->record)))
11753
4032
        return info->table->report_error(error);
11754
 
      
11755
 
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
 
4033
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
11756
4034
                      tab->insideout_buf, key->key_length));
11757
4035
    tab->insideout_match_tab->found_match= 0;
11758
4036
    return 0;
11761
4039
    return join_read_next(info);
11762
4040
}
11763
4041
 
11764
 
 
11765
 
static int
11766
 
join_read_next(READ_RECORD *info)
 
4042
int join_read_next(READ_RECORD *info)
11767
4043
{
11768
4044
  int error;
11769
4045
  if ((error=info->file->index_next(info->record)))
11771
4047
  return 0;
11772
4048
}
11773
4049
 
11774
 
 
11775
 
static int
11776
 
join_read_last(JOIN_TAB *tab)
 
4050
int join_read_last(JoinTable *tab)
11777
4051
{
11778
4052
  Table *table=tab->table;
11779
4053
  int error;
11780
 
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
 
4054
  if (!table->key_read && table->covering_keys.test(tab->index) &&
11781
4055
      !table->no_keyread)
11782
4056
  {
11783
4057
    table->key_read=1;
11793
4067
    table->file->ha_index_init(tab->index, 1);
11794
4068
  if ((error= tab->table->file->index_last(tab->table->record[0])))
11795
4069
    return table->report_error(error);
 
4070
 
11796
4071
  return 0;
11797
4072
}
11798
4073
 
11799
 
 
11800
 
static int
11801
 
join_read_prev(READ_RECORD *info)
 
4074
int join_read_prev(READ_RECORD *info)
11802
4075
{
11803
4076
  int error;
11804
4077
  if ((error= info->file->index_prev(info->record)))
11805
4078
    return info->table->report_error(error);
 
4079
 
11806
4080
  return 0;
11807
4081
}
11808
4082
 
11809
4083
/**
11810
4084
  Reading of key with key reference and one part that may be NULL.
11811
4085
*/
11812
 
 
11813
 
int
11814
 
join_read_always_key_or_null(JOIN_TAB *tab)
 
4086
int join_read_always_key_or_null(JoinTable *tab)
11815
4087
{
11816
4088
  int res;
11817
4089
 
11825
4097
  return safe_index_read(tab);
11826
4098
}
11827
4099
 
11828
 
 
11829
 
int
11830
 
join_read_next_same_or_null(READ_RECORD *info)
 
4100
int join_read_next_same_or_null(READ_RECORD *info)
11831
4101
{
11832
4102
  int error;
11833
4103
  if ((error= join_read_next_same(info)) >= 0)
11834
4104
    return error;
11835
 
  JOIN_TAB *tab= info->table->reginfo.join_tab;
 
4105
  JoinTable *tab= info->table->reginfo.join_tab;
11836
4106
 
11837
4107
  /* Test if we have already done a read after null key */
11838
4108
  if (*tab->ref.null_ref_key)
11841
4111
  return safe_index_read(tab);                  // then read null keys
11842
4112
}
11843
4113
 
11844
 
 
11845
 
/*****************************************************************************
11846
 
  DESCRIPTION
11847
 
    Functions that end one nested loop iteration. Different functions
11848
 
    are used to support GROUP BY clause and to redirect records
11849
 
    to a table (e.g. in case of SELECT into a temporary table) or to the
11850
 
    network client.
11851
 
 
11852
 
  RETURN VALUES
11853
 
    NESTED_LOOP_OK           - the record has been successfully handled
11854
 
    NESTED_LOOP_ERROR        - a fatal error (like table corruption)
11855
 
                               was detected
11856
 
    NESTED_LOOP_KILLED       - thread shutdown was requested while processing
11857
 
                               the record
11858
 
    NESTED_LOOP_QUERY_LIMIT  - the record has been successfully handled;
11859
 
                               additionally, the nested loop produced the
11860
 
                               number of rows specified in the LIMIT clause
11861
 
                               for the query
11862
 
    NESTED_LOOP_CURSOR_LIMIT - the record has been successfully handled;
11863
 
                               additionally, there is a cursor and the nested
11864
 
                               loop algorithm produced the number of rows
11865
 
                               that is specified for current cursor fetch
11866
 
                               operation.
11867
 
   All return values except NESTED_LOOP_OK abort the nested loop.
11868
 
*****************************************************************************/
11869
 
 
11870
 
/* ARGSUSED */
11871
 
static enum_nested_loop_state
11872
 
end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
11873
 
         bool end_of_records)
11874
 
{
11875
 
  if (!end_of_records)
11876
 
  {
11877
 
    int error;
11878
 
    if (join->having && join->having->val_int() == 0)
11879
 
      return(NESTED_LOOP_OK);               // Didn't match having
11880
 
    error=0;
11881
 
    if (join->do_send_rows)
11882
 
      error=join->result->send_data(*join->fields);
11883
 
    if (error)
11884
 
      return(NESTED_LOOP_ERROR); /* purecov: inspected */
11885
 
    if (++join->send_records >= join->unit->select_limit_cnt &&
11886
 
        join->do_send_rows)
11887
 
    {
11888
 
      if (join->select_options & OPTION_FOUND_ROWS)
11889
 
      {
11890
 
        JOIN_TAB *jt=join->join_tab;
11891
 
        if ((join->tables == 1) && !join->tmp_table && !join->sort_and_group
11892
 
            && !join->send_group_parts && !join->having && !jt->select_cond &&
11893
 
            !(jt->select && jt->select->quick) &&
11894
 
            (jt->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
11895
 
            (jt->ref.key < 0))
11896
 
        {
11897
 
          /* Join over all rows in table;  Return number of found rows */
11898
 
          Table *table=jt->table;
11899
 
 
11900
 
          join->select_options ^= OPTION_FOUND_ROWS;
11901
 
          if (table->sort.record_pointers ||
11902
 
              (table->sort.io_cache && my_b_inited(table->sort.io_cache)))
11903
 
          {
11904
 
            /* Using filesort */
11905
 
            join->send_records= table->sort.found_records;
11906
 
          }
11907
 
          else
11908
 
          {
11909
 
            table->file->info(HA_STATUS_VARIABLE);
11910
 
            join->send_records= table->file->stats.records;
11911
 
          }
11912
 
        }
11913
 
        else 
11914
 
        {
11915
 
          join->do_send_rows= 0;
11916
 
          if (join->unit->fake_select_lex)
11917
 
            join->unit->fake_select_lex->select_limit= 0;
11918
 
          return(NESTED_LOOP_OK);
11919
 
        }
11920
 
      }
11921
 
      return(NESTED_LOOP_QUERY_LIMIT);      // Abort nicely
11922
 
    }
11923
 
    else if (join->send_records >= join->fetch_limit)
11924
 
    {
11925
 
      /*
11926
 
        There is a server side cursor and all rows for
11927
 
        this fetch request are sent.
11928
 
      */
11929
 
      return(NESTED_LOOP_CURSOR_LIMIT);
11930
 
    }
11931
 
  }
11932
 
 
11933
 
  return(NESTED_LOOP_OK);
11934
 
}
11935
 
 
11936
 
 
11937
 
        /* ARGSUSED */
11938
 
enum_nested_loop_state
11939
 
end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
11940
 
               bool end_of_records)
 
4114
enum_nested_loop_state end_send_group(JOIN *join, JoinTable *, bool end_of_records)
11941
4115
{
11942
4116
  int idx= -1;
11943
4117
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
11945
4119
  if (!join->first_record || end_of_records ||
11946
4120
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
11947
4121
  {
11948
 
    if (join->first_record || 
 
4122
    if (join->first_record ||
11949
4123
        (end_of_records && !join->group && !join->group_optimized_away))
11950
4124
    {
11951
4125
      if (idx < (int) join->send_group_parts)
11952
4126
      {
11953
 
        int error=0;
11954
 
        {
11955
 
          if (!join->first_record)
11956
 
          {
11957
 
            List_iterator_fast<Item> it(*join->fields);
11958
 
            Item *item;
11959
 
            /* No matching rows for group function */
11960
 
            join->clear();
 
4127
        int error=0;
 
4128
        {
 
4129
          if (!join->first_record)
 
4130
          {
 
4131
                  List_iterator_fast<Item> it(*join->fields);
 
4132
                  Item *item;
 
4133
            /* No matching rows for group function */
 
4134
            join->clear();
11961
4135
 
11962
4136
            while ((item= it++))
11963
4137
              item->no_rows_in_result();
11964
 
          }
11965
 
          if (join->having && join->having->val_int() == 0)
11966
 
            error= -1;                          // Didn't satisfy having
11967
 
          else
11968
 
          {
11969
 
            if (join->do_send_rows)
11970
 
              error=join->result->send_data(*join->fields) ? 1 : 0;
11971
 
            join->send_records++;
11972
 
          }
11973
 
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
11974
 
          {
11975
 
            if (join->rollup_send_data((uint) (idx+1)))
11976
 
              error= 1;
11977
 
          }
11978
 
        }
11979
 
        if (error > 0)
11980
 
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
11981
 
        if (end_of_records)
11982
 
          return(NESTED_LOOP_OK);
11983
 
        if (join->send_records >= join->unit->select_limit_cnt &&
11984
 
            join->do_send_rows)
11985
 
        {
11986
 
          if (!(join->select_options & OPTION_FOUND_ROWS))
11987
 
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
11988
 
          join->do_send_rows=0;
11989
 
          join->unit->select_limit_cnt = HA_POS_ERROR;
 
4138
          }
 
4139
          if (join->having && join->having->val_int() == 0)
 
4140
            error= -1;                          // Didn't satisfy having
 
4141
          else
 
4142
          {
 
4143
            if (join->do_send_rows)
 
4144
              error=join->result->send_data(*join->fields) ? 1 : 0;
 
4145
            join->send_records++;
 
4146
          }
 
4147
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
 
4148
          {
 
4149
            if (join->rollup_send_data((uint32_t) (idx+1)))
 
4150
              error= 1;
 
4151
          }
 
4152
        }
 
4153
        if (error > 0)
 
4154
          return(NESTED_LOOP_ERROR);
 
4155
        if (end_of_records)
 
4156
          return(NESTED_LOOP_OK);
 
4157
        if (join->send_records >= join->unit->select_limit_cnt &&
 
4158
            join->do_send_rows)
 
4159
        {
 
4160
          if (!(join->select_options & OPTION_FOUND_ROWS))
 
4161
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
 
4162
          join->do_send_rows=0;
 
4163
          join->unit->select_limit_cnt = HA_POS_ERROR;
11990
4164
        }
11991
4165
        else if (join->send_records >= join->fetch_limit)
11992
4166
        {
12005
4179
    else
12006
4180
    {
12007
4181
      if (end_of_records)
12008
 
        return(NESTED_LOOP_OK);
 
4182
        return(NESTED_LOOP_OK);
12009
4183
      join->first_record=1;
12010
4184
      test_if_item_cache_changed(join->group_fields);
12011
4185
    }
12017
4191
      */
12018
4192
      copy_fields(&join->tmp_table_param);
12019
4193
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
12020
 
        return(NESTED_LOOP_ERROR);
 
4194
        return(NESTED_LOOP_ERROR);
12021
4195
      return(ok_code);
12022
4196
    }
12023
4197
  }
12026
4200
  return(NESTED_LOOP_OK);
12027
4201
}
12028
4202
 
12029
 
 
12030
 
        /* ARGSUSED */
12031
 
enum_nested_loop_state
12032
 
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12033
 
          bool end_of_records)
12034
 
{
12035
 
  Table *table=join->tmp_table;
12036
 
 
12037
 
  if (join->thd->killed)                        // Aborted by user
12038
 
  {
12039
 
    join->thd->send_kill_message();
12040
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12041
 
  }
12042
 
  if (!end_of_records)
12043
 
  {
12044
 
    copy_fields(&join->tmp_table_param);
12045
 
    copy_funcs(join->tmp_table_param.items_to_copy);
12046
 
#ifdef TO_BE_DELETED
12047
 
    if (!table->uniques)                        // If not unique handling
12048
 
    {
12049
 
      /* Copy null values from group to row */
12050
 
      order_st   *group;
12051
 
      for (group=table->group ; group ; group=group->next)
12052
 
      {
12053
 
        Item *item= *group->item;
12054
 
        if (item->maybe_null)
12055
 
        {
12056
 
          Field *field=item->get_tmp_table_field();
12057
 
          field->ptr[-1]= (unsigned char) (field->is_null() ? 1 : 0);
12058
 
        }
12059
 
      }
12060
 
    }
12061
 
#endif
12062
 
    if (!join->having || join->having->val_int())
12063
 
    {
12064
 
      int error;
12065
 
      join->found_records++;
12066
 
      if ((error=table->file->ha_write_row(table->record[0])))
12067
 
      {
12068
 
        if (!table->file->is_fatal_error(error, HA_CHECK_DUP))
12069
 
          goto end;
12070
 
        if (create_myisam_from_heap(join->thd, table,
12071
 
                                    join->tmp_table_param.start_recinfo,
12072
 
                                    &join->tmp_table_param.recinfo,
12073
 
                                    error, 1))
12074
 
          return(NESTED_LOOP_ERROR);        // Not a table_is_full error
12075
 
        table->s->uniques=0;                    // To ensure rows are the same
12076
 
      }
12077
 
      if (++join->send_records >= join->tmp_table_param.end_write_records &&
12078
 
          join->do_send_rows)
12079
 
      {
12080
 
        if (!(join->select_options & OPTION_FOUND_ROWS))
12081
 
          return(NESTED_LOOP_QUERY_LIMIT);
12082
 
        join->do_send_rows=0;
12083
 
        join->unit->select_limit_cnt = HA_POS_ERROR;
12084
 
        return(NESTED_LOOP_OK);
12085
 
      }
12086
 
    }
12087
 
  }
12088
 
end:
12089
 
  return(NESTED_LOOP_OK);
12090
 
}
12091
 
 
12092
 
/* ARGSUSED */
12093
 
/** Group by searching after group record and updating it if possible. */
12094
 
 
12095
 
static enum_nested_loop_state
12096
 
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12097
 
           bool end_of_records)
12098
 
{
12099
 
  Table *table=join->tmp_table;
12100
 
  order_st   *group;
12101
 
  int     error;
12102
 
 
12103
 
  if (end_of_records)
12104
 
    return(NESTED_LOOP_OK);
12105
 
  if (join->thd->killed)                        // Aborted by user
12106
 
  {
12107
 
    join->thd->send_kill_message();
12108
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12109
 
  }
12110
 
 
12111
 
  join->found_records++;
12112
 
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
12113
 
  /* Make a key of group index */
12114
 
  for (group=table->group ; group ; group=group->next)
12115
 
  {
12116
 
    Item *item= *group->item;
12117
 
    item->save_org_in_field(group->field);
12118
 
    /* Store in the used key if the field was 0 */
12119
 
    if (item->maybe_null)
12120
 
      group->buff[-1]= (char) group->field->is_null();
12121
 
  }
12122
 
  if (!table->file->index_read_map(table->record[1],
12123
 
                                   join->tmp_table_param.group_buff,
12124
 
                                   HA_WHOLE_KEY,
12125
 
                                   HA_READ_KEY_EXACT))
12126
 
  {                                             /* Update old record */
12127
 
    restore_record(table,record[1]);
12128
 
    update_tmptable_sum_func(join->sum_funcs,table);
12129
 
    if ((error=table->file->ha_update_row(table->record[1],
12130
 
                                          table->record[0])))
12131
 
    {
12132
 
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12133
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
12134
 
    }
12135
 
    return(NESTED_LOOP_OK);
12136
 
  }
12137
 
 
12138
 
  /*
12139
 
    Copy null bits from group key to table
12140
 
    We can't copy all data as the key may have different format
12141
 
    as the row data (for example as with VARCHAR keys)
12142
 
  */
12143
 
  KEY_PART_INFO *key_part;
12144
 
  for (group=table->group,key_part=table->key_info[0].key_part;
12145
 
       group ;
12146
 
       group=group->next,key_part++)
12147
 
  {
12148
 
    if (key_part->null_bit)
12149
 
      memcpy(table->record[0]+key_part->offset, group->buff, 1);
12150
 
  }
12151
 
  init_tmptable_sum_functions(join->sum_funcs);
12152
 
  copy_funcs(join->tmp_table_param.items_to_copy);
12153
 
  if ((error=table->file->ha_write_row(table->record[0])))
12154
 
  {
12155
 
    if (create_myisam_from_heap(join->thd, table,
12156
 
                                join->tmp_table_param.start_recinfo,
12157
 
                                &join->tmp_table_param.recinfo,
12158
 
                                error, 0))
12159
 
      return(NESTED_LOOP_ERROR);            // Not a table_is_full error
12160
 
    /* Change method to update rows */
12161
 
    table->file->ha_index_init(0, 0);
12162
 
    join->join_tab[join->tables-1].next_select=end_unique_update;
12163
 
  }
12164
 
  join->send_records++;
12165
 
  return(NESTED_LOOP_OK);
12166
 
}
12167
 
 
12168
 
 
12169
 
/** Like end_update, but this is done with unique constraints instead of keys.  */
12170
 
 
12171
 
static enum_nested_loop_state
12172
 
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12173
 
                  bool end_of_records)
12174
 
{
12175
 
  Table *table=join->tmp_table;
12176
 
  int     error;
12177
 
 
12178
 
  if (end_of_records)
12179
 
    return(NESTED_LOOP_OK);
12180
 
  if (join->thd->killed)                        // Aborted by user
12181
 
  {
12182
 
    join->thd->send_kill_message();
12183
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12184
 
  }
12185
 
 
12186
 
  init_tmptable_sum_functions(join->sum_funcs);
12187
 
  copy_fields(&join->tmp_table_param);          // Groups are copied twice.
12188
 
  copy_funcs(join->tmp_table_param.items_to_copy);
12189
 
 
12190
 
  if (!(error=table->file->ha_write_row(table->record[0])))
12191
 
    join->send_records++;                       // New group
12192
 
  else
12193
 
  {
12194
 
    if ((int) table->file->get_dup_key(error) < 0)
12195
 
    {
12196
 
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12197
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
12198
 
    }
12199
 
    if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
12200
 
    {
12201
 
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12202
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
12203
 
    }
12204
 
    restore_record(table,record[1]);
12205
 
    update_tmptable_sum_func(join->sum_funcs,table);
12206
 
    if ((error=table->file->ha_update_row(table->record[1],
12207
 
                                          table->record[0])))
12208
 
    {
12209
 
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12210
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
12211
 
    }
12212
 
  }
12213
 
  return(NESTED_LOOP_OK);
12214
 
}
12215
 
 
12216
 
 
12217
 
        /* ARGSUSED */
12218
 
enum_nested_loop_state
12219
 
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12220
 
                bool end_of_records)
 
4203
enum_nested_loop_state end_write_group(JOIN *join, JoinTable *, bool end_of_records)
12221
4204
{
12222
4205
  Table *table=join->tmp_table;
12223
4206
  int     idx= -1;
12224
4207
 
12225
 
  if (join->thd->killed)
 
4208
  if (join->session->killed)
12226
4209
  {                                             // Aborted by user
12227
 
    join->thd->send_kill_message();
12228
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
4210
    join->session->send_kill_message();
 
4211
    return NESTED_LOOP_KILLED;
12229
4212
  }
12230
4213
  if (!join->first_record || end_of_records ||
12231
4214
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
12235
4218
      int send_group_parts= join->send_group_parts;
12236
4219
      if (idx < send_group_parts)
12237
4220
      {
12238
 
        if (!join->first_record)
12239
 
        {
12240
 
          /* No matching rows for group function */
12241
 
          join->clear();
12242
 
        }
12243
 
        copy_sum_funcs(join->sum_funcs,
12244
 
                       join->sum_funcs_end[send_group_parts]);
12245
 
        if (!join->having || join->having->val_int())
12246
 
        {
 
4221
        if (!join->first_record)
 
4222
        {
 
4223
          /* No matching rows for group function */
 
4224
          join->clear();
 
4225
        }
 
4226
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
 
4227
        if (!join->having || join->having->val_int())
 
4228
        {
12247
4229
          int error= table->file->ha_write_row(table->record[0]);
12248
 
          if (error && create_myisam_from_heap(join->thd, table,
12249
 
                                               join->tmp_table_param.start_recinfo,
 
4230
          if (error && create_myisam_from_heap(join->session, table,
 
4231
                                              join->tmp_table_param.start_recinfo,
12250
4232
                                                &join->tmp_table_param.recinfo,
12251
 
                                               error, 0))
12252
 
            return(NESTED_LOOP_ERROR);
 
4233
                                              error, 0))
 
4234
          return NESTED_LOOP_ERROR;
12253
4235
        }
12254
4236
        if (join->rollup.state != ROLLUP::STATE_NONE)
12255
 
        {
12256
 
          if (join->rollup_write_data((uint) (idx+1), table))
12257
 
            return(NESTED_LOOP_ERROR);
12258
 
        }
12259
 
        if (end_of_records)
12260
 
          return(NESTED_LOOP_OK);
 
4237
        {
 
4238
          if (join->rollup_write_data((uint32_t) (idx+1), table))
 
4239
            return NESTED_LOOP_ERROR;
 
4240
        }
 
4241
        if (end_of_records)
 
4242
          return NESTED_LOOP_OK;
12261
4243
      }
12262
4244
    }
12263
4245
    else
12264
4246
    {
12265
4247
      if (end_of_records)
12266
 
        return(NESTED_LOOP_OK);
 
4248
        return NESTED_LOOP_OK;
12267
4249
      join->first_record=1;
12268
4250
      test_if_item_cache_changed(join->group_fields);
12269
4251
    }
12272
4254
      copy_fields(&join->tmp_table_param);
12273
4255
      copy_funcs(join->tmp_table_param.items_to_copy);
12274
4256
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
12275
 
        return(NESTED_LOOP_ERROR);
12276
 
      return(NESTED_LOOP_OK);
 
4257
        return NESTED_LOOP_ERROR;
 
4258
      return NESTED_LOOP_OK;
12277
4259
    }
12278
4260
  }
12279
4261
  if (update_sum_func(join->sum_funcs))
12280
 
    return(NESTED_LOOP_ERROR);
12281
 
  return(NESTED_LOOP_OK);
 
4262
    return NESTED_LOOP_ERROR;
 
4263
  return NESTED_LOOP_OK;
12282
4264
}
12283
4265
 
12284
 
 
12285
4266
/*****************************************************************************
12286
4267
  Remove calculation with tables that aren't yet read. Remove also tests
12287
4268
  against fields that are read through key where the table is not a
12294
4275
  @return
12295
4276
    1 if right_item is used removable reference key on left_item
12296
4277
*/
12297
 
 
12298
 
static bool test_if_ref(Item_field *left_item,Item *right_item)
 
4278
bool test_if_ref(Item_field *left_item,Item *right_item)
12299
4279
{
12300
4280
  Field *field=left_item->field;
12301
4281
  // No need to change const test. We also have to keep tests on LEFT JOIN
12306
4286
    {
12307
4287
      right_item= right_item->real_item();
12308
4288
      if (right_item->type() == Item::FIELD_ITEM)
12309
 
        return (field->eq_def(((Item_field *) right_item)->field));
 
4289
        return (field->eq_def(((Item_field *) right_item)->field));
12310
4290
      /* remove equalities injected by IN->EXISTS transformation */
12311
4291
      else if (right_item->type() == Item::CACHE_ITEM)
12312
4292
        return ((Item_cache *)right_item)->eq_def (field);
12313
4293
      if (right_item->const_item() && !(right_item->is_null()))
12314
4294
      {
12315
 
        /*
12316
 
          We can remove binary fields and numerical fields except float,
12317
 
          as float comparison isn't 100 % secure
12318
 
          We have to keep normal strings to be able to check for end spaces
 
4295
        /*
 
4296
          We can remove binary fields and numerical fields except float,
 
4297
          as float comparison isn't 100 % secure
 
4298
          We have to keep normal strings to be able to check for end spaces
12319
4299
 
12320
 
          sergefp: the above seems to be too restrictive. Counterexample:
12321
 
            create table t100 (v varchar(10), key(v)) default charset=latin1;
12322
 
            insert into t100 values ('a'),('a ');
12323
 
            explain select * from t100 where v='a';
12324
 
          The EXPLAIN shows 'using Where'. Running the query returns both
12325
 
          rows, so it seems there are no problems with endspace in the most
12326
 
          frequent case?
12327
 
        */
12328
 
        if (field->binary() &&
12329
 
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
12330
 
            field->decimals() == 0)
12331
 
        {
12332
 
          return !store_val_in_field(field, right_item, CHECK_FIELD_WARN);
12333
 
        }
 
4300
                sergefp: the above seems to be too restrictive. Counterexample:
 
4301
                  create table t100 (v varchar(10), key(v)) default charset=latin1;
 
4302
                  insert into t100 values ('a'),('a ');
 
4303
                  explain select * from t100 where v='a';
 
4304
                The EXPLAIN shows 'using Where'. Running the query returns both
 
4305
                rows, so it seems there are no problems with endspace in the most
 
4306
                frequent case?
 
4307
        */
 
4308
        if (field->binary() &&
 
4309
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
 
4310
            field->decimals() == 0)
 
4311
        {
 
4312
          return ! store_val_in_field(field, right_item, CHECK_FIELD_WARN);
 
4313
        }
12334
4314
      }
12335
4315
    }
12336
4316
  }
12337
 
  return 0;                                     // keep test
12338
 
}
12339
 
 
12340
 
/**
12341
 
   @brief Replaces an expression destructively inside the expression tree of
12342
 
   the WHERE clase.
12343
 
 
12344
 
   @note Because of current requirements for semijoin flattening, we do not
12345
 
   need to recurse here, hence this function will only examine the top-level
12346
 
   AND conditions. (see JOIN::prepare, comment above the line 
12347
 
   'if (do_materialize)'
12348
 
   
12349
 
   @param join The top-level query.
12350
 
   @param old_cond The expression to be replaced.
12351
 
   @param new_cond The expression to be substituted.
12352
 
   @param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for
12353
 
   the new expression.
12354
 
   @return <code>true</code> if there was an error, <code>false</code> if
12355
 
   successful.
12356
 
*/
12357
 
static bool replace_where_subcondition(JOIN *join, Item *old_cond, 
12358
 
                                       Item *new_cond, bool do_fix_fields)
12359
 
{
12360
 
  if (join->conds == old_cond) {
12361
 
    join->conds= new_cond;
12362
 
    if (do_fix_fields)
12363
 
      new_cond->fix_fields(join->thd, &join->conds);
12364
 
    return false;
12365
 
  }
12366
 
  
12367
 
  if (join->conds->type() == Item::COND_ITEM) {
12368
 
    List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
12369
 
    Item *item;
12370
 
    while ((item= li++))
12371
 
      if (item == old_cond) 
12372
 
      {
12373
 
        li.replace(new_cond);
12374
 
        if (do_fix_fields)
12375
 
          new_cond->fix_fields(join->thd, li.ref());
12376
 
        return false;
12377
 
      }
12378
 
  }
12379
 
 
12380
 
  return true;
 
4317
  return 0;
12381
4318
}
12382
4319
 
12383
4320
/*
12384
4321
  Extract a condition that can be checked after reading given table
12385
 
  
 
4322
 
12386
4323
  SYNOPSIS
12387
4324
    make_cond_for_table()
12388
4325
      cond         Condition to analyze
12389
4326
      tables       Tables for which "current field values" are available
12390
 
      used_table   Table that we're extracting the condition for (may 
 
4327
      used_table   Table that we're extracting the condition for (may
12391
4328
                   also include PSEUDO_TABLE_BITS
12392
4329
 
12393
4330
  DESCRIPTION
12397
4334
 
12398
4335
    The function assumes that
12399
4336
      - Constant parts of the condition has already been checked.
12400
 
      - Condition that could be checked for tables in 'tables' has already 
 
4337
      - Condition that could be checked for tables in 'tables' has already
12401
4338
        been checked.
12402
 
        
 
4339
 
12403
4340
    The function takes into account that some parts of the condition are
12404
4341
    guaranteed to be true by employed 'ref' access methods (the code that
12405
4342
    does this is located at the end, search down for "EQ_FUNC").
12406
4343
 
12407
4344
 
12408
 
  SEE ALSO 
 
4345
  SEE ALSO
12409
4346
    make_cond_for_info_schema uses similar algorithm
12410
4347
 
12411
4348
  RETURN
12412
4349
    Extracted condition
12413
4350
*/
12414
 
 
12415
 
static COND *
12416
 
make_cond_for_table(COND *cond, table_map tables, table_map used_table,
12417
 
                    bool exclude_expensive_cond)
 
4351
COND *make_cond_for_table(COND *cond, table_map tables, table_map used_table, bool exclude_expensive_cond)
12418
4352
{
12419
4353
  if (used_table && !(cond->used_tables() & used_table) &&
12420
 
      /*
12421
 
        Exclude constant conditions not checked at optimization time if
12422
 
        the table we are pushing conditions to is the first one.
12423
 
        As a result, such conditions are not considered as already checked
12424
 
        and will be checked at execution time, attached to the first table.
12425
 
      */
12426
 
      !((used_table & 1) && cond->is_expensive()))
 
4354
    /*
 
4355
      Exclude constant conditions not checked at optimization time if
 
4356
      the table we are pushing conditions to is the first one.
 
4357
      As a result, such conditions are not considered as already checked
 
4358
      and will be checked at execution time, attached to the first table.
 
4359
    */
 
4360
    !((used_table & 1) && cond->is_expensive()))
12427
4361
    return (COND*) 0;                           // Already checked
12428
4362
  if (cond->type() == Item::COND_ITEM)
12429
4363
  {
12432
4366
      /* Create new top level AND item */
12433
4367
      Item_cond_and *new_cond=new Item_cond_and;
12434
4368
      if (!new_cond)
12435
 
        return (COND*) 0;                       // OOM /* purecov: inspected */
 
4369
        return (COND*) 0;
12436
4370
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
12437
4371
      Item *item;
12438
4372
      while ((item=li++))
12439
4373
      {
12440
 
        Item *fix=make_cond_for_table(item,tables,used_table,
12441
 
                                      exclude_expensive_cond);
12442
 
        if (fix)
12443
 
          new_cond->argument_list()->push_back(fix);
 
4374
        Item *fix= make_cond_for_table(item,tables,used_table,
 
4375
                                            exclude_expensive_cond);
 
4376
        if (fix)
 
4377
          new_cond->argument_list()->push_back(fix);
12444
4378
      }
12445
 
      switch (new_cond->argument_list()->elements) {
12446
 
      case 0:
12447
 
        return (COND*) 0;                       // Always true
12448
 
      case 1:
12449
 
        return new_cond->argument_list()->head();
12450
 
      default:
12451
 
        /*
12452
 
          Item_cond_and do not need fix_fields for execution, its parameters
12453
 
          are fixed or do not need fix_fields, too
12454
 
        */
12455
 
        new_cond->quick_fix_field();
12456
 
        new_cond->used_tables_cache=
12457
 
          ((Item_cond_and*) cond)->used_tables_cache &
12458
 
          tables;
12459
 
        return new_cond;
 
4379
      switch (new_cond->argument_list()->elements) 
 
4380
      {
 
4381
        case 0:
 
4382
          return (COND*) 0;                     // Always true
 
4383
        case 1:
 
4384
          return new_cond->argument_list()->head();
 
4385
        default:
 
4386
          /*
 
4387
            Item_cond_and do not need fix_fields for execution, its parameters
 
4388
            are fixed or do not need fix_fields, too
 
4389
          */
 
4390
          new_cond->quick_fix_field();
 
4391
          new_cond->used_tables_cache= ((Item_cond_and*) cond)->used_tables_cache & tables;
 
4392
          return new_cond;
12460
4393
      }
12461
4394
    }
12462
4395
    else
12463
4396
    {                                           // Or list
12464
4397
      Item_cond_or *new_cond=new Item_cond_or;
12465
4398
      if (!new_cond)
12466
 
        return (COND*) 0;                       // OOM /* purecov: inspected */
 
4399
        return (COND*) 0;
12467
4400
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
12468
4401
      Item *item;
12469
4402
      while ((item=li++))
12470
4403
      {
12471
 
        Item *fix=make_cond_for_table(item,tables,0L, exclude_expensive_cond);
12472
 
        if (!fix)
12473
 
          return (COND*) 0;                     // Always true
12474
 
        new_cond->argument_list()->push_back(fix);
 
4404
        Item *fix= make_cond_for_table(item,tables,0L, exclude_expensive_cond);
 
4405
        if (!fix)
 
4406
          return (COND*) 0;                     // Always true
 
4407
        new_cond->argument_list()->push_back(fix);
12475
4408
      }
12476
4409
      /*
12477
 
        Item_cond_and do not need fix_fields for execution, its parameters
12478
 
        are fixed or do not need fix_fields, too
 
4410
        Item_cond_and do not need fix_fields for execution, its parameters
 
4411
        are fixed or do not need fix_fields, too
12479
4412
      */
12480
4413
      new_cond->quick_fix_field();
12481
4414
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
12500
4433
  if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK)
12501
4434
    return cond;                                // Not boolean op
12502
4435
 
12503
 
  /* 
 
4436
  /*
12504
4437
    Remove equalities that are guaranteed to be true by use of 'ref' access
12505
4438
    method
12506
4439
  */
12508
4441
  {
12509
4442
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
12510
4443
    Item *right_item= ((Item_func*) cond)->arguments()[1];
12511
 
    if (left_item->type() == Item::FIELD_ITEM &&
12512
 
        test_if_ref((Item_field*) left_item,right_item))
 
4444
    if (left_item->type() == Item::FIELD_ITEM && test_if_ref((Item_field*) left_item,right_item))
12513
4445
    {
12514
4446
      cond->marker=3;                   // Checked when read
12515
4447
      return (COND*) 0;
12516
4448
    }
12517
 
    if (right_item->type() == Item::FIELD_ITEM &&
12518
 
        test_if_ref((Item_field*) right_item,left_item))
 
4449
    if (right_item->type() == Item::FIELD_ITEM &&       test_if_ref((Item_field*) right_item,left_item))
12519
4450
    {
12520
4451
      cond->marker=3;                   // Checked when read
12521
4452
      return (COND*) 0;
12525
4456
  return cond;
12526
4457
}
12527
4458
 
12528
 
 
12529
 
static Item *
12530
 
part_of_refkey(Table *table,Field *field)
 
4459
static Item *part_of_refkey(Table *table,Field *field)
12531
4460
{
12532
4461
  if (!table->reginfo.join_tab)
12533
4462
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
12553
4482
  return (Item*) 0;
12554
4483
}
12555
4484
 
12556
 
 
12557
4485
/**
12558
4486
  Test if one can use the key to resolve order_st BY.
12559
4487
 
12574
4502
  @retval
12575
4503
    -1   Reverse key can be used
12576
4504
*/
12577
 
 
12578
 
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx,
12579
 
                                uint32_t *used_key_parts)
 
4505
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
12580
4506
{
12581
 
  KEY_PART_INFO *key_part,*key_part_end;
12582
 
  key_part=table->key_info[idx].key_part;
12583
 
  key_part_end=key_part+table->key_info[idx].key_parts;
 
4507
  KEY_PART_INFO *key_part= NULL;
 
4508
  KEY_PART_INFO *key_part_end= NULL;
 
4509
  key_part= table->key_info[idx].key_part;
 
4510
  key_part_end= key_part + table->key_info[idx].key_parts;
12584
4511
  key_part_map const_key_parts=table->const_key_parts[idx];
12585
 
  int reverse=0;
 
4512
  int reverse= 0;
12586
4513
  bool on_primary_key= false;
12587
4514
 
12588
4515
  for (; order ; order=order->next, const_key_parts>>=1)
12595
4522
      These are already skipped in the order_st BY by const_expression_in_where()
12596
4523
    */
12597
4524
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
12598
 
      key_part++; 
 
4525
      key_part++;
12599
4526
 
12600
4527
    if (key_part == key_part_end)
12601
4528
    {
12602
 
      /* 
 
4529
      /*
12603
4530
        We are at the end of the key. Check if the engine has the primary
12604
4531
        key as a suffix to the secondary keys. If it has continue to check
12605
4532
        the primary key as a suffix.
12614
4541
        const_key_parts=table->const_key_parts[table->s->primary_key];
12615
4542
 
12616
4543
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
12617
 
          key_part++; 
 
4544
          key_part++;
12618
4545
        /*
12619
4546
         The primary and secondary key parts were all const (i.e. there's
12620
4547
         one row).  The sorting doesn't matter.
12638
4565
    key_part++;
12639
4566
  }
12640
4567
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
12641
 
    (uint) (key_part - table->key_info[idx].key_part);
 
4568
    (uint32_t) (key_part - table->key_info[idx].key_part);
12642
4569
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
12643
4570
                         HA_READ_PREV))
12644
4571
    reverse= 0;                                 // Index can't be used
12645
4572
  return(reverse);
12646
4573
}
12647
4574
 
12648
 
 
12649
4575
/**
12650
4576
  Test if a second key is the subkey of the first one.
12651
4577
 
12661
4587
  @retval
12662
4588
    0   no sub key
12663
4589
*/
12664
 
 
12665
 
inline bool 
12666
 
is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
12667
 
          KEY_PART_INFO *ref_key_part_end)
 
4590
inline bool is_subkey(KEY_PART_INFO *key_part,
 
4591
                      KEY_PART_INFO *ref_key_part,
 
4592
                      KEY_PART_INFO *ref_key_part_end)
12668
4593
{
12669
4594
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
12670
 
    if (!key_part->field->eq(ref_key_part->field))
 
4595
    if (! key_part->field->eq(ref_key_part->field))
12671
4596
      return 0;
12672
4597
  return 1;
12673
4598
}
12683
4608
    - MAX_KEY                   If we can't use other key
12684
4609
    - the number of found key   Otherwise
12685
4610
*/
12686
 
 
12687
 
static uint
12688
 
test_if_subkey(order_st *order, Table *table, uint32_t ref, uint32_t ref_key_parts,
12689
 
               const key_map *usable_keys)
 
4611
static uint32_t test_if_subkey(order_st *order,
 
4612
                               Table *table,
 
4613
                               uint32_t ref,
 
4614
                               uint32_t ref_key_parts,
 
4615
                               const key_map *usable_keys)
12690
4616
{
12691
4617
  uint32_t nr;
12692
4618
  uint32_t min_length= UINT32_MAX;
12697
4623
 
12698
4624
  for (nr= 0 ; nr < table->s->keys ; nr++)
12699
4625
  {
12700
 
    if (usable_keys->is_set(nr) &&
 
4626
    if (usable_keys->test(nr) &&
12701
4627
        table->key_info[nr].key_length < min_length &&
12702
4628
        table->key_info[nr].key_parts >= ref_key_parts &&
12703
4629
        is_subkey(table->key_info[nr].key_part, ref_key_part,
12711
4637
  return best;
12712
4638
}
12713
4639
 
12714
 
 
12715
4640
/**
12716
4641
  Check if GROUP BY/DISTINCT can be optimized away because the set is
12717
4642
  already known to be distinct.
12730
4655
    of the table are referenced by a list : either the select list
12731
4656
    through find_field_in_item_list or GROUP BY list through
12732
4657
    find_field_in_order_list.
12733
 
    If the above holds and the key parts cannot contain NULLs then we 
 
4658
    If the above holds and the key parts cannot contain NULLs then we
12734
4659
    can safely remove the GROUP BY/DISTINCT,
12735
4660
    as no result set can be more distinct than an unique key.
12736
4661
 
12743
4668
  @retval
12744
4669
    0                    not found.
12745
4670
*/
12746
 
 
12747
 
static bool
12748
 
list_contains_unique_index(Table *table,
12749
 
                          bool (*find_func) (Field *, void *), void *data)
 
4671
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
12750
4672
{
12751
4673
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
12752
4674
  {
12754
4676
         (table->key_info[keynr].flags & HA_NOSAME))
12755
4677
    {
12756
4678
      KEY *keyinfo= table->key_info + keynr;
12757
 
      KEY_PART_INFO *key_part, *key_part_end;
 
4679
      KEY_PART_INFO *key_part= NULL;
 
4680
      KEY_PART_INFO *key_part_end= NULL;
12758
4681
 
12759
4682
      for (key_part=keyinfo->key_part,
12760
4683
           key_part_end=key_part+ keyinfo->key_parts;
12761
4684
           key_part < key_part_end;
12762
4685
           key_part++)
12763
4686
      {
12764
 
        if (key_part->field->maybe_null() || 
12765
 
            !find_func(key_part->field, data))
 
4687
        if (key_part->field->maybe_null() ||
 
4688
            ! find_func(key_part->field, data))
12766
4689
          break;
12767
4690
      }
12768
4691
      if (key_part == key_part_end)
12772
4695
  return 0;
12773
4696
}
12774
4697
 
12775
 
 
12776
4698
/**
12777
4699
  Helper function for list_contains_unique_index.
12778
4700
  Find a field reference in a list of order_st structures.
12786
4708
  @retval
12787
4709
    0                    not found.
12788
4710
*/
12789
 
 
12790
 
static bool
12791
 
find_field_in_order_list (Field *field, void *data)
 
4711
bool find_field_in_order_list (Field *field, void *data)
12792
4712
{
12793
4713
  order_st *group= (order_st *) data;
12794
4714
  bool part_found= 0;
12805
4725
  return part_found;
12806
4726
}
12807
4727
 
12808
 
 
12809
4728
/**
12810
4729
  Helper function for list_contains_unique_index.
12811
4730
  Find a field reference in a dynamic list of Items.
12819
4738
  @retval
12820
4739
    0                    not found.
12821
4740
*/
12822
 
 
12823
 
static bool
12824
 
find_field_in_item_list (Field *field, void *data)
 
4741
bool find_field_in_item_list (Field *field, void *data)
12825
4742
{
12826
4743
  List<Item> *fields= (List<Item> *) data;
12827
4744
  bool part_found= 0;
12840
4757
  return part_found;
12841
4758
}
12842
4759
 
12843
 
 
12844
4760
/**
12845
4761
  Test if we can skip the order_st BY by using an index.
12846
4762
 
12852
4768
      no_changes
12853
4769
      map
12854
4770
 
12855
 
  If we can use an index, the JOIN_TAB / tab->select struct
 
4771
  If we can use an index, the JoinTable / tab->select struct
12856
4772
  is changed to use the index.
12857
4773
 
12858
4774
  The index must cover all fields in <order>, or it will not be considered.
12859
4775
 
12860
4776
  @todo
12861
 
    - sergeyp: Results of all index merge selects actually are ordered 
 
4777
    - sergeyp: Results of all index merge selects actually are ordered
12862
4778
    by clustered PK values.
12863
4779
 
12864
4780
  @retval
12866
4782
  @retval
12867
4783
    1    We can use an index.
12868
4784
*/
12869
 
 
12870
 
static bool
12871
 
test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,ha_rows select_limit,
12872
 
                        bool no_changes, const key_map *map)
 
4785
bool test_if_skip_sort_order(JoinTable *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
12873
4786
{
12874
4787
  int32_t ref_key;
12875
4788
  uint32_t ref_key_parts;
12891
4804
    Item *item= (*tmp_order->item)->real_item();
12892
4805
    if (item->type() != Item::FIELD_ITEM)
12893
4806
    {
12894
 
      usable_keys.clear_all();
 
4807
      usable_keys.reset();
12895
4808
      return(0);
12896
4809
    }
12897
 
    usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey);
12898
 
    if (usable_keys.is_clear_all())
 
4810
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
 
4811
    if (usable_keys.none())
12899
4812
      return(0);                                        // No usable keys
12900
4813
  }
12901
4814
 
12905
4818
  {
12906
4819
    ref_key=       tab->ref.key;
12907
4820
    ref_key_parts= tab->ref.key_parts;
12908
 
    if (tab->type == JT_REF_OR_NULL)
 
4821
    if (tab->type == AM_REF_OR_NULL)
12909
4822
      return(0);
12910
4823
  }
12911
4824
  else if (select && select->quick)             // Range found by opt_range
12912
4825
  {
12913
4826
    int quick_type= select->quick->get_type();
12914
4827
    save_quick= select->quick;
12915
 
    /* 
12916
 
      assume results are not ordered when index merge is used 
12917
 
      TODO: sergeyp: Results of all index merge selects actually are ordered 
 
4828
    /*
 
4829
      assume results are not ordered when index merge is used
 
4830
      TODO: sergeyp: Results of all index merge selects actually are ordered
12918
4831
      by clustered PK values.
12919
4832
    */
12920
 
  
12921
 
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE || 
12922
 
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || 
 
4833
 
 
4834
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
4835
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
12923
4836
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
12924
4837
      return(0);
12925
4838
    ref_key=       select->quick->index;
12931
4844
    /*
12932
4845
      We come here when there is a REF key.
12933
4846
    */
12934
 
    if (!usable_keys.is_set(ref_key))
 
4847
    if (! usable_keys.test(ref_key))
12935
4848
    {
12936
4849
      /*
12937
 
        We come here when ref_key is not among usable_keys
 
4850
        We come here when ref_key is not among usable_keys
12938
4851
      */
12939
4852
      uint32_t new_ref_key;
12940
4853
      /*
12941
 
        If using index only read, only consider other possible index only
12942
 
        keys
 
4854
        If using index only read, only consider other possible index only
 
4855
        keys
12943
4856
      */
12944
 
      if (table->covering_keys.is_set(ref_key))
12945
 
        usable_keys.intersect(table->covering_keys);
 
4857
      if (table->covering_keys.test(ref_key))
 
4858
        usable_keys&= table->covering_keys;
12946
4859
      if (tab->pre_idx_push_select_cond)
12947
4860
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
12948
4861
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
12949
4862
                                       &usable_keys)) < MAX_KEY)
12950
4863
      {
12951
 
        /* Found key that can be used to retrieve data in sorted order */
12952
 
        if (tab->ref.key >= 0)
12953
 
        {
 
4864
        /* Found key that can be used to retrieve data in sorted order */
 
4865
        if (tab->ref.key >= 0)
 
4866
        {
12954
4867
          /*
12955
 
            We'll use ref access method on key new_ref_key. In general case 
 
4868
            We'll use ref access method on key new_ref_key. In general case
12956
4869
            the index search tuple for new_ref_key will be different (e.g.
12957
4870
            when one index is defined as (part1, part2, ...) and another as
12958
 
            (part1, part2(N), ...) and the WHERE clause contains 
12959
 
            "part1 = const1 AND part2=const2". 
 
4871
            (part1, part2(N), ...) and the WHERE clause contains
 
4872
            "part1 = const1 AND part2=const2".
12960
4873
            So we build tab->ref from scratch here.
12961
4874
          */
12962
 
          KEYUSE *keyuse= tab->keyuse;
12963
 
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
 
4875
          optimizer::KeyUse *keyuse= tab->keyuse;
 
4876
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
12964
4877
            keyuse++;
12965
4878
 
12966
 
          if (create_ref_for_key(tab->join, tab, keyuse, 
 
4879
          if (create_ref_for_key(tab->join, tab, keyuse,
12967
4880
                                 tab->join->const_table_map))
12968
4881
            return(0);
12969
 
        }
12970
 
        else
12971
 
        {
 
4882
        }
 
4883
        else
 
4884
        {
12972
4885
          /*
12973
4886
            The range optimizer constructed QUICK_RANGE for ref_key, and
12974
4887
            we want to use instead new_ref_key as the index. We can't
12978
4891
            parameres are set correctly by the range optimizer.
12979
4892
           */
12980
4893
          key_map new_ref_key_map;
12981
 
          new_ref_key_map.clear_all();  // Force the creation of quick select
12982
 
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
 
4894
          new_ref_key_map.reset();  // Force the creation of quick select
 
4895
          new_ref_key_map.set(new_ref_key); // only for new_ref_key.
12983
4896
 
12984
 
          if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0,
 
4897
          if (select->test_quick_select(tab->join->session, new_ref_key_map, 0,
12985
4898
                                        (tab->join->select_options &
12986
4899
                                         OPTION_FOUND_ROWS) ?
12987
4900
                                        HA_POS_ERROR :
12989
4902
                                        true) <=
12990
4903
              0)
12991
4904
            return(0);
12992
 
        }
 
4905
        }
12993
4906
        ref_key= new_ref_key;
12994
4907
      }
12995
4908
    }
12996
4909
    /* Check if we get the rows in requested sorted order by using the key */
12997
 
    if (usable_keys.is_set(ref_key) &&
 
4910
    if (usable_keys.test(ref_key) &&
12998
4911
        (order_direction= test_if_order_by_key(order,table,ref_key,
12999
4912
                                               &used_key_parts)))
13000
4913
      goto check_reverse_order;
13019
4932
    uint32_t tablenr= tab - join->join_tab;
13020
4933
    ha_rows table_records= table->file->stats.records;
13021
4934
    bool group= join->group && order == join->group_list;
 
4935
    optimizer::Position cur_pos;
13022
4936
 
13023
4937
    /*
13024
4938
      If not used with LIMIT, only use keys if the whole query can be
13027
4941
    */
13028
4942
    if (select_limit >= table_records)
13029
4943
    {
13030
 
      /* 
13031
 
        filesort() and join cache are usually faster than reading in 
 
4944
      /*
 
4945
        filesort() and join cache are usually faster than reading in
13032
4946
        index order and not using join cache
13033
4947
        */
13034
 
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
 
4948
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
13035
4949
        return(0);
13036
4950
      keys= *table->file->keys_to_use_for_scanning();
13037
 
      keys.merge(table->covering_keys);
 
4951
      keys|= table->covering_keys;
13038
4952
 
13039
4953
      /*
13040
 
        We are adding here also the index specified in FORCE INDEX clause, 
13041
 
        if any.
 
4954
        We are adding here also the index specified in FORCE INDEX clause,
 
4955
        if any.
13042
4956
        This is to allow users to use index in order_st BY.
13043
4957
      */
13044
 
      if (table->force_index) 
13045
 
        keys.merge(group ? table->keys_in_use_for_group_by :
13046
 
                           table->keys_in_use_for_order_by);
13047
 
      keys.intersect(usable_keys);
 
4958
      if (table->force_index)
 
4959
        keys|= (group ? table->keys_in_use_for_group_by :
 
4960
                                table->keys_in_use_for_order_by);
 
4961
      keys&= usable_keys;
13048
4962
    }
13049
4963
    else
13050
4964
      keys= usable_keys;
13051
4965
 
13052
 
    read_time= join->best_positions[tablenr].read_time;
 
4966
    cur_pos= join->getPosFromOptimalPlan(tablenr);
 
4967
    read_time= cur_pos.getCost();
13053
4968
    for (uint32_t i= tablenr+1; i < join->tables; i++)
13054
 
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
 
4969
    {
 
4970
      cur_pos= join->getPosFromOptimalPlan(i);
 
4971
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
 
4972
    }
13055
4973
 
13056
4974
    for (nr=0; nr < table->s->keys ; nr++)
13057
4975
    {
13058
4976
      int direction;
13059
 
      if (keys.is_set(nr) &&
 
4977
      if (keys.test(nr) &&
13060
4978
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
13061
4979
      {
13062
 
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13063
 
        
13064
 
        /* 
 
4980
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
 
4981
 
 
4982
        /*
13065
4983
          Don't use an index scan with order_st BY without limit.
13066
4984
          For GROUP BY without limit always use index scan
13067
 
          if there is a suitable index. 
 
4985
          if there is a suitable index.
13068
4986
          Why we hold to this asymmetry hardly can be explained
13069
4987
          rationally. It's easy to demonstrate that using
13070
4988
          temporary table + filesort could be cheaper for grouping
13071
4989
          queries too.
13072
 
        */ 
 
4990
        */
13073
4991
        if (is_covering ||
13074
 
            select_limit != HA_POS_ERROR || 
 
4992
            select_limit != HA_POS_ERROR ||
13075
4993
            (ref_key < 0 && (group || table->force_index)))
13076
 
        { 
 
4994
        {
13077
4995
          double rec_per_key;
13078
4996
          double index_scan_time;
13079
4997
          KEY *keyinfo= tab->table->key_info+nr;
13082
5000
          if (group)
13083
5001
          {
13084
5002
            rec_per_key= keyinfo->rec_per_key[used_key_parts-1];
13085
 
            set_if_bigger(rec_per_key, 1);
 
5003
            set_if_bigger(rec_per_key, 1.0);
13086
5004
            /*
13087
5005
              With a grouping query each group containing on average
13088
5006
              rec_per_key records produces only one row that will
13089
5007
              be included into the result set.
13090
 
            */  
 
5008
            */
13091
5009
            if (select_limit > table_records/rec_per_key)
13092
5010
                select_limit= table_records;
13093
5011
            else
13094
5012
              select_limit= (ha_rows) (select_limit*rec_per_key);
13095
5013
          }
13096
 
          /* 
 
5014
          /*
13097
5015
            If tab=tk is not the last joined table tn then to get first
13098
5016
            L records from the result set we can expect to retrieve
13099
5017
            only L/fanout(tk,tn) where fanout(tk,tn) says how many
13102
5020
            So the estimate for L/fanout(tk,tn) will be too optimistic
13103
5021
            and as result we'll choose an index scan when using ref/range
13104
5022
            access + filesort will be cheaper.
13105
 
          */
 
5023
          */
13106
5024
          select_limit= (ha_rows) (select_limit < fanout ?
13107
5025
                                   1 : select_limit/fanout);
13108
5026
          /*
13109
5027
            We assume that each of the tested indexes is not correlated
13110
5028
            with ref_key. Thus, to select first N records we have to scan
13111
 
            N/selectivity(ref_key) index entries. 
 
5029
            N/selectivity(ref_key) index entries.
13112
5030
            selectivity(ref_key) = #scanned_records/#table_records =
13113
5031
            table->quick_condition_rows/table_records.
13114
5032
            In any case we can't select more than #table_records.
13115
 
            N/(table->quick_condition_rows/table_records) > table_records 
 
5033
            N/(table->quick_condition_rows/table_records) > table_records
13116
5034
            <=> N > table->quick_condition_rows.
13117
 
          */ 
 
5035
          */
13118
5036
          if (select_limit > table->quick_condition_rows)
13119
5037
            select_limit= table_records;
13120
5038
          else
13122
5040
                                     (double) table_records /
13123
5041
                                      table->quick_condition_rows);
13124
5042
          rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1];
13125
 
          set_if_bigger(rec_per_key, 1);
 
5043
          set_if_bigger(rec_per_key, 1.0);
13126
5044
          /*
13127
5045
            Here we take into account the fact that rows are
13128
5046
            accessed in sequences rec_per_key records in each.
13131
5049
            in a sequence we'll touch not more pages than the
13132
5050
            table file contains.
13133
5051
            TODO. Use the formula for a disk sweep sequential access
13134
 
            to calculate the cost of accessing data rows for one 
 
5052
            to calculate the cost of accessing data rows for one
13135
5053
            index entry.
13136
 
          */
 
5054
          */
13137
5055
          index_scan_time= select_limit/rec_per_key *
13138
 
                           cmin(rec_per_key, table->file->scan_time());
 
5056
                           min(rec_per_key, table->file->scan_time());
13139
5057
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
13140
5058
              index_scan_time < read_time)
13141
5059
          {
13142
5060
            ha_rows quick_records= table_records;
13143
5061
            if (is_best_covering && !is_covering)
13144
5062
              continue;
13145
 
            if (table->quick_keys.is_set(nr))
 
5063
            if (table->quick_keys.test(nr))
13146
5064
              quick_records= table->quick_rows[nr];
13147
5065
            if (best_key < 0 ||
13148
 
                (select_limit <= cmin(quick_records,best_records) ?
 
5066
                (select_limit <= min(quick_records,best_records) ?
13149
5067
                 keyinfo->key_parts < best_key_parts :
13150
5068
                 quick_records < best_records))
13151
5069
            {
13153
5071
              best_key_parts= keyinfo->key_parts;
13154
5072
              best_records= quick_records;
13155
5073
              is_best_covering= is_covering;
13156
 
              best_key_direction= direction; 
 
5074
              best_key_direction= direction;
13157
5075
            }
13158
 
          }   
13159
 
        }      
 
5076
          }
 
5077
        }
13160
5078
      }
13161
5079
    }
13162
5080
    if (best_key >= 0)
13163
5081
    {
13164
5082
      bool quick_created= false;
13165
 
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
 
5083
      if (table->quick_keys.test(best_key) && best_key != ref_key)
13166
5084
      {
13167
 
        key_map map;
13168
 
        map.clear_all();       // Force the creation of quick select
13169
 
        map.set_bit(best_key); // only best_key.
13170
 
        quick_created=         
13171
 
          select->test_quick_select(join->thd, map, 0,
 
5085
        key_map test_map;
 
5086
        test_map.reset();       // Force the creation of quick select
 
5087
        test_map.set(best_key); // only best_key.
 
5088
        quick_created=
 
5089
          select->test_quick_select(join->session, test_map, 0,
13172
5090
                                    join->select_options & OPTION_FOUND_ROWS ?
13173
5091
                                    HA_POS_ERROR :
13174
5092
                                    join->unit->select_limit_cnt,
13177
5095
      if (!no_changes)
13178
5096
      {
13179
5097
        if (!quick_created)
13180
 
        {
 
5098
        {
13181
5099
          tab->index= best_key;
13182
5100
          tab->read_first_record= best_key_direction > 0 ?
13183
5101
                                  join_read_first:join_read_last;
13184
 
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
 
5102
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
13185
5103
          if (select && select->quick)
13186
5104
          {
13187
5105
            delete select->quick;
13188
5106
            select->quick= 0;
13189
5107
          }
13190
 
          if (table->covering_keys.is_set(best_key))
 
5108
          if (table->covering_keys.test(best_key))
13191
5109
          {
13192
5110
            table->key_read=1;
13193
5111
            table->file->extra(HA_EXTRA_KEYREAD);
13197
5115
          {
13198
5116
            tab->ref.key= -1;
13199
5117
            tab->ref.key_parts= 0;
13200
 
            if (select_limit < table_records) 
 
5118
            if (select_limit < table_records)
13201
5119
              tab->limit= select_limit;
13202
5120
          }
13203
5121
        }
13204
 
        else if (tab->type != JT_ALL)
 
5122
        else if (tab->type != AM_ALL)
13205
5123
        {
13206
5124
          /*
13207
5125
            We're about to use a quick access to the table.
13209
5127
            method is actually used.
13210
5128
          */
13211
5129
          assert(tab->select->quick);
13212
 
          tab->type=JT_ALL;
 
5130
          tab->type= AM_ALL;
13213
5131
          tab->use_quick=1;
13214
5132
          tab->ref.key= -1;
13215
5133
          tab->ref.key_parts=0;         // Don't use ref key.
13216
5134
          tab->read_first_record= join_init_read_record;
13217
 
          /*
13218
 
            TODO: update the number of records in join->best_positions[tablenr]
13219
 
          */
13220
5135
        }
13221
5136
      }
13222
5137
      used_key_parts= best_key_parts;
13223
5138
      order_direction= best_key_direction;
13224
5139
    }
13225
5140
    else
13226
 
      return(0); 
13227
 
  } 
 
5141
      return(0);
 
5142
  }
13228
5143
 
13229
 
check_reverse_order:                  
 
5144
check_reverse_order:
13230
5145
  if (order_direction == -1)            // If order_st BY ... DESC
13231
5146
  {
13232
5147
    if (select && select->quick)
13233
5148
    {
13234
5149
      /*
13235
 
        Don't reverse the sort order, if it's already done.
 
5150
        Don't reverse the sort order, if it's already done.
13236
5151
        (In some cases test_if_order_by_key() can be called multiple times
13237
5152
      */
13238
5153
      if (!select->quick->reverse_sorted())
13249
5164
          select->quick= save_quick;
13250
5165
          return(0);                   // Use filesort
13251
5166
        }
13252
 
            
 
5167
 
13253
5168
        /* order_st BY range_key DESC */
13254
 
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
13255
 
                                    used_key_parts, &error);
13256
 
        if (!tmp || error)
13257
 
        {
13258
 
          delete tmp;
13259
 
          select->quick= save_quick;
13260
 
          tab->limit= 0;
13261
 
          return(0);            // Reverse sort not supported
13262
 
        }
13263
 
        select->quick=tmp;
 
5169
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
5170
                                          used_key_parts, &error);
 
5171
        if (!tmp || error)
 
5172
        {
 
5173
          delete tmp;
 
5174
                select->quick= save_quick;
 
5175
                tab->limit= 0;
 
5176
          return(0);            // Reverse sort not supported
 
5177
        }
 
5178
        select->quick=tmp;
13264
5179
      }
13265
5180
    }
13266
 
    else if (tab->type != JT_NEXT && 
 
5181
    else if (tab->type != AM_NEXT &&
13267
5182
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
13268
5183
    {
13269
5184
      /*
13270
 
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
 
5185
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
13271
5186
 
13272
 
        Use a traversal function that starts by reading the last row
13273
 
        with key part (A) and then traverse the index backwards.
 
5187
        Use a traversal function that starts by reading the last row
 
5188
        with key part (A) and then traverse the index backwards.
13274
5189
      */
13275
5190
      tab->read_first_record= join_read_last_key;
13276
5191
      tab->read_record.read_record= join_read_prev_same;
13281
5196
  return(1);
13282
5197
}
13283
5198
 
13284
 
 
13285
5199
/*
13286
5200
  If not selecting by given key, create an index how records should be read
13287
5201
 
13288
5202
  SYNOPSIS
13289
5203
   create_sort_index()
13290
 
     thd                Thread handler
 
5204
     session            Thread handler
13291
5205
     tab                Table to sort (in join structure)
13292
5206
     order              How table should be sorted
13293
5207
     filesort_limit     Max number of rows that needs to be sorted
13294
5208
     select_limit       Max number of rows in final output
13295
5209
                        Used to decide if we should use index or not
13296
5210
     is_order_by        true if we are sorting on order_st BY, false if GROUP BY
13297
 
                        Used to decide if we should use index or not     
 
5211
                        Used to decide if we should use index or not
13298
5212
 
13299
5213
 
13300
5214
  IMPLEMENTATION
13303
5217
   - If no index, create with filesort() an index file that can be used to
13304
5218
     retrieve rows in order (should be done with 'read_record').
13305
5219
     The sorted data is stored in tab->table and will be freed when calling
13306
 
     free_io_cache(tab->table).
 
5220
     tab->table->free_io_cache().
13307
5221
 
13308
5222
  RETURN VALUES
13309
5223
    0           ok
13310
5224
    -1          Some fatal error
13311
5225
    1           No records
13312
5226
*/
13313
 
 
13314
 
static int
13315
 
create_sort_index(THD *thd, JOIN *join, order_st *order,
13316
 
                  ha_rows filesort_limit, ha_rows select_limit,
13317
 
                  bool is_order_by)
 
5227
int create_sort_index(Session *session, JOIN *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
13318
5228
{
13319
5229
  uint32_t length= 0;
13320
5230
  ha_rows examined_rows;
13321
5231
  Table *table;
13322
5232
  SQL_SELECT *select;
13323
 
  JOIN_TAB *tab;
 
5233
  JoinTable *tab;
13324
5234
 
13325
5235
  if (join->tables == join->const_tables)
13326
5236
    return(0);                          // One row, no need to sort
13334
5244
    is going to be used as it is applied now only for one table queries
13335
5245
    with covering indexes.
13336
5246
  */
13337
 
  if ((order != join->group_list || 
 
5247
  if ((order != join->group_list ||
13338
5248
       !(join->select_options & SELECT_BIG_RESULT) ||
13339
5249
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
13340
 
      test_if_skip_sort_order(tab,order,select_limit,0, 
 
5250
      test_if_skip_sort_order(tab,order,select_limit,0,
13341
5251
                              is_order_by ?  &table->keys_in_use_for_order_by :
13342
5252
                              &table->keys_in_use_for_group_by))
13343
5253
    return(0);
13344
5254
  for (order_st *ord= join->order; ord; ord= ord->next)
13345
5255
    length++;
13346
 
  if (!(join->sortorder= 
 
5256
  if (!(join->sortorder=
13347
5257
        make_unireg_sortorder(order, &length, join->sortorder)))
13348
 
    goto err;                           /* purecov: inspected */
 
5258
    goto err;
13349
5259
 
13350
 
  table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE),
13351
 
                                             MYF(MY_WME | MY_ZEROFILL));
 
5260
  table->sort.io_cache= new IO_CACHE;
 
5261
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
13352
5262
  table->status=0;                              // May be wrong if quick_select
13353
5263
 
13354
5264
  // If table has a range, move it to select
13358
5268
    {
13359
5269
      select->quick=tab->quick;
13360
5270
      tab->quick=0;
13361
 
      /* 
 
5271
      /*
13362
5272
        We can only use 'Only index' if quick key is same as ref_key
13363
5273
        and in index_merge 'Only index' cannot be used
13364
5274
      */
13365
 
      if (table->key_read && ((uint) tab->ref.key != select->quick->index))
 
5275
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
13366
5276
      {
13367
 
        table->key_read=0;
13368
 
        table->file->extra(HA_EXTRA_NO_KEYREAD);
 
5277
        table->key_read=0;
 
5278
        table->file->extra(HA_EXTRA_NO_KEYREAD);
13369
5279
      }
13370
5280
    }
13371
5281
    else
13372
5282
    {
13373
5283
      /*
13374
 
        We have a ref on a const;  Change this to a range that filesort
13375
 
        can use.
13376
 
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
13377
 
        field, quick will contain an empty record set.
 
5284
        We have a ref on a const;  Change this to a range that filesort
 
5285
        can use.
 
5286
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
 
5287
        field, quick will contain an empty record set.
13378
5288
      */
13379
 
      if (!(select->quick= (get_quick_select_for_ref(thd, table, &tab->ref, 
 
5289
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
13380
5290
                                                     tab->found_records))))
13381
 
        goto err;
 
5291
        goto err;
13382
5292
    }
13383
5293
  }
13384
5294
 
13389
5299
 
13390
5300
  if (table->s->tmp_table)
13391
5301
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
13392
 
  table->sort.found_records=filesort(thd, table,join->sortorder, length,
 
5302
  table->sort.found_records=filesort(session, table,join->sortorder, length,
13393
5303
                                     select, filesort_limit, 0,
13394
5304
                                     &examined_rows);
13395
5305
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
13401
5311
  tab->select_cond=0;
13402
5312
  tab->last_inner= 0;
13403
5313
  tab->first_unmatched= 0;
13404
 
  tab->type=JT_ALL;                             // Read with normal read_record
 
5314
  tab->type= AM_ALL;                            // Read with normal read_record
13405
5315
  tab->read_first_record= join_init_read_record;
13406
5316
  tab->join->examined_rows+=examined_rows;
13407
5317
  if (table->key_read)                          // Restore if we used indexes
13414
5324
  return(-1);
13415
5325
}
13416
5326
 
13417
 
static bool copy_blobs(Field **ptr)
13418
 
{
13419
 
  for (; *ptr ; ptr++)
13420
 
  {
13421
 
    if ((*ptr)->flags & BLOB_FLAG)
13422
 
      if (((Field_blob *) (*ptr))->copy())
13423
 
        return 1;                               // Error
13424
 
  }
13425
 
  return 0;
13426
 
}
13427
 
 
13428
 
static void free_blobs(Field **ptr)
13429
 
{
13430
 
  for (; *ptr ; ptr++)
13431
 
  {
13432
 
    if ((*ptr)->flags & BLOB_FLAG)
13433
 
      ((Field_blob *) (*ptr))->free();
13434
 
  }
13435
 
}
13436
 
 
13437
 
 
13438
 
static int
13439
 
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
13440
 
{
13441
 
  int error;
13442
 
  ulong reclength,offset;
13443
 
  uint32_t field_count;
13444
 
  THD *thd= join->thd;
13445
 
 
13446
 
  entry->reginfo.lock_type=TL_WRITE;
13447
 
 
13448
 
  /* Calculate how many saved fields there is in list */
13449
 
  field_count=0;
13450
 
  List_iterator<Item> it(fields);
13451
 
  Item *item;
13452
 
  while ((item=it++))
13453
 
  {
13454
 
    if (item->get_tmp_table_field() && ! item->const_item())
13455
 
      field_count++;
13456
 
  }
13457
 
 
13458
 
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having) 
13459
 
  {                    // only const items with no OPTION_FOUND_ROWS
13460
 
    join->unit->select_limit_cnt= 1;            // Only send first row
13461
 
    return(0);
13462
 
  }
13463
 
  Field **first_field=entry->field+entry->s->fields - field_count;
13464
 
  offset= (field_count ? 
13465
 
           entry->field[entry->s->fields - field_count]->
13466
 
           offset(entry->record[0]) : 0);
13467
 
  reclength=entry->s->reclength-offset;
13468
 
 
13469
 
  free_io_cache(entry);                         // Safety
13470
 
  entry->file->info(HA_STATUS_VARIABLE);
13471
 
  if (entry->s->db_type() == heap_hton ||
13472
 
      (!entry->s->blob_fields &&
13473
 
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
13474
 
        thd->variables.sortbuff_size)))
13475
 
    error=remove_dup_with_hash_index(join->thd, entry,
13476
 
                                     field_count, first_field,
13477
 
                                     reclength, having);
13478
 
  else
13479
 
    error=remove_dup_with_compare(join->thd, entry, first_field, offset,
13480
 
                                  having);
13481
 
 
13482
 
  free_blobs(first_field);
13483
 
  return(error);
13484
 
}
13485
 
 
13486
 
 
13487
 
static int remove_dup_with_compare(THD *thd, Table *table, Field **first_field,
13488
 
                                   ulong offset, Item *having)
 
5327
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
13489
5328
{
13490
5329
  handler *file=table->file;
13491
5330
  char *org_record,*new_record;
13492
5331
  unsigned char *record;
13493
5332
  int error;
13494
 
  ulong reclength= table->s->reclength-offset;
 
5333
  uint32_t reclength= table->s->reclength-offset;
13495
5334
 
13496
5335
  org_record=(char*) (record=table->record[0])+offset;
13497
5336
  new_record=(char*) table->record[1]+offset;
13500
5339
  error=file->rnd_next(record);
13501
5340
  for (;;)
13502
5341
  {
13503
 
    if (thd->killed)
 
5342
    if (session->killed)
13504
5343
    {
13505
 
      thd->send_kill_message();
 
5344
      session->send_kill_message();
13506
5345
      error=0;
13507
5346
      goto err;
13508
5347
    }
13509
5348
    if (error)
13510
5349
    {
13511
5350
      if (error == HA_ERR_RECORD_DELETED)
13512
 
        continue;
 
5351
        continue;
13513
5352
      if (error == HA_ERR_END_OF_FILE)
13514
 
        break;
 
5353
        break;
13515
5354
      goto err;
13516
5355
    }
13517
5356
    if (having && !having->val_int())
13518
5357
    {
13519
5358
      if ((error=file->ha_delete_row(record)))
13520
 
        goto err;
 
5359
        goto err;
13521
5360
      error=file->rnd_next(record);
13522
5361
      continue;
13523
5362
    }
13535
5374
    {
13536
5375
      if ((error=file->rnd_next(record)))
13537
5376
      {
13538
 
        if (error == HA_ERR_RECORD_DELETED)
13539
 
          continue;
13540
 
        if (error == HA_ERR_END_OF_FILE)
13541
 
          break;
13542
 
        goto err;
 
5377
        if (error == HA_ERR_RECORD_DELETED)
 
5378
          continue;
 
5379
        if (error == HA_ERR_END_OF_FILE)
 
5380
          break;
 
5381
        goto err;
13543
5382
      }
13544
5383
      if (table->compare_record(first_field) == 0)
13545
5384
      {
13546
 
        if ((error=file->ha_delete_row(record)))
13547
 
          goto err;
 
5385
        if ((error=file->ha_delete_row(record)))
 
5386
          goto err;
13548
5387
      }
13549
5388
      else if (!found)
13550
5389
      {
13551
 
        found=1;
13552
 
        file->position(record); // Remember position
 
5390
        found= 1;
 
5391
        file->position(record); // Remember position
13553
5392
      }
13554
5393
    }
13555
5394
    if (!found)
13567
5406
  return(1);
13568
5407
}
13569
5408
 
13570
 
 
13571
5409
/**
13572
5410
  Generate a hash index for each row to quickly find duplicate rows.
13573
5411
 
13574
5412
  @note
13575
5413
    Note that this will not work on tables with blobs!
13576
5414
*/
13577
 
 
13578
 
static int remove_dup_with_hash_index(THD *thd, Table *table,
13579
 
                                      uint32_t field_count,
13580
 
                                      Field **first_field,
13581
 
                                      ulong key_length,
13582
 
                                      Item *having)
 
5415
int remove_dup_with_hash_index(Session *session, 
 
5416
                               Table *table,
 
5417
                               uint32_t field_count,
 
5418
                               Field **first_field,
 
5419
                               uint32_t key_length,
 
5420
                               Item *having)
13583
5421
{
13584
5422
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
13585
5423
  int error;
13586
5424
  handler *file= table->file;
13587
 
  ulong extra_length= ALIGN_SIZE(key_length)-key_length;
 
5425
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
13588
5426
  uint32_t *field_lengths,*field_length;
13589
5427
  HASH hash;
13590
5428
 
13591
5429
  if (!my_multi_malloc(MYF(MY_WME),
13592
5430
                       &key_buffer,
13593
 
                       (uint) ((key_length + extra_length) *
 
5431
                       (uint32_t) ((key_length + extra_length) *
13594
5432
                               (long) file->stats.records),
13595
5433
                       &field_lengths,
13596
 
                       (uint) (field_count*sizeof(*field_lengths)),
 
5434
                       (uint32_t) (field_count*sizeof(*field_lengths)),
13597
5435
                       NULL))
13598
5436
    return(1);
13599
5437
 
13600
5438
  {
13601
5439
    Field **ptr;
13602
 
    ulong total_length= 0;
 
5440
    uint32_t total_length= 0;
13603
5441
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
13604
5442
    {
13605
5443
      uint32_t length= (*ptr)->sort_length();
13611
5449
    extra_length= ALIGN_SIZE(key_length)-key_length;
13612
5450
  }
13613
5451
 
13614
 
  if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, 
 
5452
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
13615
5453
                key_length, (hash_get_key) 0, 0, 0))
13616
5454
  {
13617
5455
    free((char*) key_buffer);
13623
5461
  for (;;)
13624
5462
  {
13625
5463
    unsigned char *org_key_pos;
13626
 
    if (thd->killed)
 
5464
    if (session->killed)
13627
5465
    {
13628
 
      thd->send_kill_message();
 
5466
      session->send_kill_message();
13629
5467
      error=0;
13630
5468
      goto err;
13631
5469
    }
13632
5470
    if ((error=file->rnd_next(record)))
13633
5471
    {
13634
5472
      if (error == HA_ERR_RECORD_DELETED)
13635
 
        continue;
 
5473
        continue;
13636
5474
      if (error == HA_ERR_END_OF_FILE)
13637
 
        break;
 
5475
        break;
13638
5476
      goto err;
13639
5477
    }
13640
5478
    if (having && !having->val_int())
13641
5479
    {
13642
5480
      if ((error=file->ha_delete_row(record)))
13643
 
        goto err;
 
5481
        goto err;
13644
5482
      continue;
13645
5483
    }
13646
5484
 
13657
5495
    {
13658
5496
      /* Duplicated found ; Remove the row */
13659
5497
      if ((error=file->ha_delete_row(record)))
13660
 
        goto err;
 
5498
        goto err;
13661
5499
    }
13662
5500
    else
13663
5501
      (void) my_hash_insert(&hash, org_key_pos);
13679
5517
  return(1);
13680
5518
}
13681
5519
 
13682
 
 
13683
 
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length,
13684
 
                                  SORT_FIELD *sortorder)
 
5520
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length, SORT_FIELD *sortorder)
13685
5521
{
13686
5522
  uint32_t count;
13687
5523
  SORT_FIELD *sort,*pos;
13691
5527
    count++;
13692
5528
  if (!sortorder)
13693
5529
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
13694
 
                                       (cmax(count, *length) + 1));
 
5530
                                       (max(count, *length) + 1));
13695
5531
  pos= sort= sortorder;
13696
5532
 
13697
5533
  if (!pos)
13717
5553
  return(sort);
13718
5554
}
13719
5555
 
13720
 
 
13721
 
/*****************************************************************************
13722
 
  Fill join cache with packed records
13723
 
  Records are stored in tab->cache.buffer and last record in
13724
 
  last record is stored with pointers to blobs to support very big
13725
 
  records
13726
 
******************************************************************************/
13727
 
 
13728
 
static int
13729
 
join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count)
13730
 
{
13731
 
  register unsigned int i;
13732
 
  unsigned int length, blobs;
13733
 
  size_t size;
13734
 
  CACHE_FIELD *copy,**blob_ptr;
13735
 
  JOIN_CACHE  *cache;
13736
 
  JOIN_TAB *join_tab;
13737
 
 
13738
 
  cache= &tables[table_count].cache;
13739
 
  cache->fields=blobs=0;
13740
 
 
13741
 
  join_tab=tables;
13742
 
  for (i=0 ; i < table_count ; i++,join_tab++)
13743
 
  {
13744
 
    if (!join_tab->used_fieldlength)            /* Not calced yet */
13745
 
      calc_used_field_length(thd, join_tab);
13746
 
    cache->fields+=join_tab->used_fields;
13747
 
    blobs+=join_tab->used_blobs;
13748
 
 
13749
 
    /* SemiJoinDuplicateElimination: reserve space for rowid */
13750
 
    if (join_tab->rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
13751
 
    {
13752
 
      cache->fields++;
13753
 
      join_tab->used_fieldlength += join_tab->table->file->ref_length;
13754
 
    }
13755
 
  }
13756
 
  if (!(cache->field=(CACHE_FIELD*)
13757
 
        sql_alloc(sizeof(CACHE_FIELD)*(cache->fields+table_count*2)+(blobs+1)*
13758
 
 
13759
 
                  sizeof(CACHE_FIELD*))))
13760
 
  {
13761
 
    free((unsigned char*) cache->buff);         /* purecov: inspected */
13762
 
    cache->buff=0;                              /* purecov: inspected */
13763
 
    return(1);                          /* purecov: inspected */
13764
 
  }
13765
 
  copy=cache->field;
13766
 
  blob_ptr=cache->blob_ptr=(CACHE_FIELD**)
13767
 
    (cache->field+cache->fields+table_count*2);
13768
 
 
13769
 
  length=0;
13770
 
  for (i=0 ; i < table_count ; i++)
13771
 
  {
13772
 
    uint32_t null_fields=0, used_fields;
13773
 
    Field **f_ptr,*field;
13774
 
    MY_BITMAP *read_set= tables[i].table->read_set;
13775
 
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
13776
 
         used_fields ;
13777
 
         f_ptr++)
13778
 
    {
13779
 
      field= *f_ptr;
13780
 
      if (bitmap_is_set(read_set, field->field_index))
13781
 
      {
13782
 
        used_fields--;
13783
 
        length+=field->fill_cache_field(copy);
13784
 
        if (copy->blob_field)
13785
 
          (*blob_ptr++)=copy;
13786
 
        if (field->maybe_null())
13787
 
          null_fields++;
13788
 
        copy->get_rowid= NULL;
13789
 
        copy++;
13790
 
      }
13791
 
    }
13792
 
    /* Copy null bits from table */
13793
 
    if (null_fields && tables[i].table->getNullFields())
13794
 
    {                                           /* must copy null bits */
13795
 
      copy->str= tables[i].table->null_flags;
13796
 
      copy->length= tables[i].table->s->null_bytes;
13797
 
      copy->strip=0;
13798
 
      copy->blob_field=0;
13799
 
      copy->get_rowid= NULL;
13800
 
      length+=copy->length;
13801
 
      copy++;
13802
 
      cache->fields++;
13803
 
    }
13804
 
    /* If outer join table, copy null_row flag */
13805
 
    if (tables[i].table->maybe_null)
13806
 
    {
13807
 
      copy->str= (unsigned char*) &tables[i].table->null_row;
13808
 
      copy->length=sizeof(tables[i].table->null_row);
13809
 
      copy->strip=0;
13810
 
      copy->blob_field=0;
13811
 
      copy->get_rowid= NULL;
13812
 
      length+=copy->length;
13813
 
      copy++;
13814
 
      cache->fields++;
13815
 
    }
13816
 
    /* SemiJoinDuplicateElimination: Allocate space for rowid if needed */
13817
 
    if (tables[i].rowid_keep_flags & JOIN_TAB::KEEP_ROWID)
13818
 
    {
13819
 
      copy->str= tables[i].table->file->ref;
13820
 
      copy->length= tables[i].table->file->ref_length;
13821
 
      copy->strip=0;
13822
 
      copy->blob_field=0;
13823
 
      copy->get_rowid= NULL;
13824
 
      if (tables[i].rowid_keep_flags & JOIN_TAB::CALL_POSITION)
13825
 
      {
13826
 
        /* We will need to call h->position(): */
13827
 
        copy->get_rowid= tables[i].table;
13828
 
        /* And those after us won't have to: */
13829
 
        tables[i].rowid_keep_flags &=  ~((int)JOIN_TAB::CALL_POSITION);
13830
 
      }
13831
 
      copy++;
13832
 
    }
13833
 
  }
13834
 
 
13835
 
  cache->length=length+blobs*sizeof(char*);
13836
 
  cache->blobs=blobs;
13837
 
  *blob_ptr=0;                                  /* End sequentel */
13838
 
  size=cmax(thd->variables.join_buff_size, (ulong)cache->length);
13839
 
  if (!(cache->buff=(unsigned char*) my_malloc(size,MYF(0))))
13840
 
    return(1);                          /* Don't use cache */ /* purecov: inspected */
13841
 
  cache->end=cache->buff+size;
13842
 
  reset_cache_write(cache);
13843
 
  return(0);
13844
 
}
13845
 
 
13846
 
 
13847
 
static ulong
13848
 
used_blob_length(CACHE_FIELD **ptr)
13849
 
{
13850
 
  uint32_t length,blob_length;
13851
 
  for (length=0 ; *ptr ; ptr++)
13852
 
  {
13853
 
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
13854
 
    length+=blob_length;
13855
 
    (*ptr)->blob_field->get_ptr(&(*ptr)->str);
13856
 
  }
13857
 
  return length;
13858
 
}
13859
 
 
13860
 
 
13861
 
static bool
13862
 
store_record_in_cache(JOIN_CACHE *cache)
13863
 
{
13864
 
  uint32_t length;
13865
 
  unsigned char *pos;
13866
 
  CACHE_FIELD *copy,*end_field;
13867
 
  bool last_record;
13868
 
 
13869
 
  pos=cache->pos;
13870
 
  end_field=cache->field+cache->fields;
13871
 
 
13872
 
  length=cache->length;
13873
 
  if (cache->blobs)
13874
 
    length+=used_blob_length(cache->blob_ptr);
13875
 
  if ((last_record= (length + cache->length > (size_t) (cache->end - pos))))
13876
 
    cache->ptr_record=cache->records;
13877
 
  /*
13878
 
    There is room in cache. Put record there
13879
 
  */
13880
 
  cache->records++;
13881
 
  for (copy=cache->field ; copy < end_field; copy++)
13882
 
  {
13883
 
    if (copy->blob_field)
13884
 
    {
13885
 
      if (last_record)
13886
 
      {
13887
 
        copy->blob_field->get_image(pos, copy->length+sizeof(char*), 
13888
 
                                    copy->blob_field->charset());
13889
 
        pos+=copy->length+sizeof(char*);
13890
 
      }
13891
 
      else
13892
 
      {
13893
 
        copy->blob_field->get_image(pos, copy->length, // blob length
13894
 
                                    copy->blob_field->charset());
13895
 
        memcpy(pos+copy->length,copy->str,copy->blob_length);  // Blob data
13896
 
        pos+=copy->length+copy->blob_length;
13897
 
      }
13898
 
    }
13899
 
    else
13900
 
    {
13901
 
      // SemiJoinDuplicateElimination: Get the rowid into table->ref:
13902
 
      if (copy->get_rowid)
13903
 
        copy->get_rowid->file->position(copy->get_rowid->record[0]);
13904
 
 
13905
 
      if (copy->strip)
13906
 
      {
13907
 
        unsigned char *str,*end;
13908
 
        for (str=copy->str,end= str+copy->length;
13909
 
             end > str && end[-1] == ' ' ;
13910
 
             end--) ;
13911
 
        length=(uint) (end-str);
13912
 
        memcpy(pos+2, str, length);
13913
 
        int2store(pos, length);
13914
 
        pos+= length+2;
13915
 
      }
13916
 
      else
13917
 
      {
13918
 
        memcpy(pos,copy->str,copy->length);
13919
 
        pos+=copy->length;
13920
 
      }
13921
 
    }
13922
 
  }
13923
 
  cache->pos=pos;
13924
 
  return last_record || (size_t) (cache->end - pos) < cache->length;
13925
 
}
13926
 
 
13927
 
 
13928
 
static void
13929
 
reset_cache_read(JOIN_CACHE *cache)
13930
 
{
13931
 
  cache->record_nr=0;
13932
 
  cache->pos=cache->buff;
13933
 
}
13934
 
 
13935
 
 
13936
 
static void reset_cache_write(JOIN_CACHE *cache)
13937
 
{
13938
 
  reset_cache_read(cache);
13939
 
  cache->records= 0;
13940
 
  cache->ptr_record= UINT32_MAX;
13941
 
}
13942
 
 
13943
 
 
13944
 
static void
13945
 
read_cached_record(JOIN_TAB *tab)
13946
 
{
13947
 
  unsigned char *pos;
13948
 
  uint32_t length;
13949
 
  bool last_record;
13950
 
  CACHE_FIELD *copy,*end_field;
13951
 
 
13952
 
  last_record=tab->cache.record_nr++ == tab->cache.ptr_record;
13953
 
  pos=tab->cache.pos;
13954
 
  for (copy=tab->cache.field,end_field=copy+tab->cache.fields ;
13955
 
       copy < end_field;
13956
 
       copy++)
13957
 
  {
13958
 
    if (copy->blob_field)
13959
 
    {
13960
 
      if (last_record)
13961
 
      {
13962
 
        copy->blob_field->set_image(pos, copy->length+sizeof(char*),
13963
 
                                    copy->blob_field->charset());
13964
 
        pos+=copy->length+sizeof(char*);
13965
 
      }
13966
 
      else
13967
 
      {
13968
 
        copy->blob_field->set_ptr(pos, pos+copy->length);
13969
 
        pos+=copy->length+copy->blob_field->get_length();
13970
 
      }
13971
 
    }
13972
 
    else
13973
 
    {
13974
 
      if (copy->strip)
13975
 
      {
13976
 
        length= uint2korr(pos);
13977
 
        memcpy(copy->str, pos+2, length);
13978
 
        memset(copy->str+length, ' ', copy->length-length);
13979
 
        pos+= 2 + length;
13980
 
      }
13981
 
      else
13982
 
      {
13983
 
        memcpy(copy->str,pos,copy->length);
13984
 
        pos+=copy->length;
13985
 
      }
13986
 
    }
13987
 
  }
13988
 
  tab->cache.pos=pos;
13989
 
  return;
13990
 
}
13991
 
 
13992
 
 
13993
5556
/*
13994
5557
  eq_ref: Create the lookup key and check if it is the same as saved key
13995
5558
 
13996
5559
  SYNOPSIS
13997
5560
    cmp_buffer_with_ref()
13998
5561
      tab  Join tab of the accessed table
13999
 
 
14000
 
  DESCRIPTION 
14001
 
    Used by eq_ref access method: create the index lookup key and check if 
 
5562
 
 
5563
  DESCRIPTION
 
5564
    Used by eq_ref access method: create the index lookup key and check if
14002
5565
    we've used this key at previous lookup (If yes, we don't need to repeat
14003
5566
    the lookup - the record has been already fetched)
14004
5567
 
14005
 
  RETURN 
 
5568
  RETURN
14006
5569
    true   No cached record for the key, or failed to create the key (due to
14007
5570
           out-of-domain error)
14008
 
    false  The created key is the same as the previous one (and the record 
 
5571
    false  The created key is the same as the previous one (and the record
14009
5572
           is already in table->record)
14010
5573
*/
14011
 
 
14012
 
static bool
14013
 
cmp_buffer_with_ref(JOIN_TAB *tab)
 
5574
static bool cmp_buffer_with_ref(JoinTable *tab)
14014
5575
{
14015
5576
  bool no_prev_key;
14016
5577
  if (!tab->ref.disable_cache)
14021
5582
      memcpy(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length);
14022
5583
    }
14023
5584
  }
14024
 
  else 
 
5585
  else
14025
5586
    no_prev_key= true;
14026
 
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, &tab->ref)) ||
 
5587
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->session, &tab->ref)) ||
14027
5588
      no_prev_key)
14028
5589
    return 1;
14029
5590
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
14030
5591
    != 0;
14031
5592
}
14032
5593
 
14033
 
 
14034
 
bool
14035
 
cp_buffer_from_ref(THD *thd, TABLE_REF *ref)
 
5594
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
14036
5595
{
14037
 
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
14038
 
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
5596
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
 
5597
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
14039
5598
  bool result= 0;
14040
5599
 
14041
 
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
 
5600
  for (StoredKey **copy=ref->key_copy ; *copy ; copy++)
14042
5601
  {
14043
5602
    if ((*copy)->copy() & 1)
14044
5603
    {
14046
5605
      break;
14047
5606
    }
14048
5607
  }
14049
 
  thd->count_cuted_fields= save_count_cuted_fields;
 
5608
  session->count_cuted_fields= save_count_cuted_fields;
14050
5609
  return result;
14051
5610
}
14052
5611
 
14053
 
 
14054
5612
/*****************************************************************************
14055
5613
  Group and order functions
14056
5614
*****************************************************************************/
14071
5629
 
14072
5630
  ref_pointer_array and all_fields are updated.
14073
5631
 
14074
 
  @param[in] thd                     Pointer to current thread structure
 
5632
  @param[in] session                 Pointer to current thread structure
14075
5633
  @param[in,out] ref_pointer_array  All select, group and order by fields
14076
5634
  @param[in] tables                 List of tables to search in (usually
14077
5635
    FROM clause)
14087
5645
  @retval
14088
5646
    true  if error occurred
14089
5647
*/
14090
 
 
14091
 
static bool
14092
 
find_order_in_list(THD *thd, Item **ref_pointer_array, TableList *tables,
14093
 
                   order_st *order, List<Item> &fields, List<Item> &all_fields,
14094
 
                   bool is_group_field)
 
5648
static bool find_order_in_list(Session *session, 
 
5649
                               Item **ref_pointer_array, 
 
5650
                               TableList *tables,
 
5651
                               order_st *order,
 
5652
                               List<Item> &fields,
 
5653
                               List<Item> &all_fields,
 
5654
                               bool is_group_field)
14095
5655
{
14096
5656
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
14097
5657
  Item::Type order_item_type;
14106
5666
  */
14107
5667
  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
14108
5668
  {                                             /* Order by position */
14109
 
    uint32_t count= (uint) order_item->val_int();
 
5669
    uint32_t count= (uint32_t) order_item->val_int();
14110
5670
    if (!count || count > fields.elements)
14111
5671
    {
14112
5672
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
14113
 
               order_item->full_name(), thd->where);
 
5673
               order_item->full_name(), session->where);
14114
5674
      return true;
14115
5675
    }
14116
5676
    order->item= ref_pointer_array + count - 1;
14136
5696
      for this name (in case if we would perform lookup in all tables).
14137
5697
    */
14138
5698
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
14139
 
        order_item->fix_fields(thd, order->item))
 
5699
        order_item->fix_fields(session, order->item))
14140
5700
      return true;
14141
5701
 
14142
5702
    /* Lookup the current GROUP field in the FROM clause. */
14145
5705
    if ((is_group_field && order_item_type == Item::FIELD_ITEM) ||
14146
5706
        order_item_type == Item::REF_ITEM)
14147
5707
    {
14148
 
      from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables,
14149
 
                                       NULL, &view_ref, IGNORE_ERRORS, true,
14150
 
                                       false);
 
5708
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
 
5709
                                       NULL, &view_ref, IGNORE_ERRORS, false);
14151
5710
      if (!from_field)
14152
5711
        from_field= (Field*) not_found_field;
14153
5712
    }
14185
5744
        warning so the user knows that the field from the FROM clause
14186
5745
        overshadows the column reference from the SELECT list.
14187
5746
      */
14188
 
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
5747
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
14189
5748
                          ER(ER_NON_UNIQ_ERROR),
14190
5749
                          ((Item_ident*) order_item)->field_name,
14191
 
                          current_thd->where);
 
5750
                          current_session->where);
14192
5751
    }
14193
5752
  }
14194
5753
 
14205
5764
    arguments for which fix_fields already was called.
14206
5765
  */
14207
5766
  if (!order_item->fixed &&
14208
 
      (order_item->fix_fields(thd, order->item) ||
 
5767
      (order_item->fix_fields(session, order->item) ||
14209
5768
       (order_item= *order->item)->check_cols(1) ||
14210
 
       thd->is_fatal_error))
 
5769
       session->is_fatal_error))
14211
5770
    return true; /* Wrong field. */
14212
5771
 
14213
5772
  uint32_t el= all_fields.elements;
14217
5776
  return false;
14218
5777
}
14219
5778
 
14220
 
 
14221
5779
/**
14222
5780
  Change order to point at item in select list.
14223
5781
 
14224
5782
  If item isn't a number and doesn't exits in the select list, add it the
14225
5783
  the field list.
14226
5784
*/
14227
 
 
14228
 
int setup_order(THD *thd, Item **ref_pointer_array, TableList *tables,
14229
 
                List<Item> &fields, List<Item> &all_fields, order_st *order)
 
5785
int setup_order(Session *session,
 
5786
                Item **ref_pointer_array,
 
5787
                TableList *tables,
 
5788
                            List<Item> &fields,
 
5789
                List<Item> &all_fields,
 
5790
                order_st *order)
14230
5791
{
14231
 
  thd->where="order clause";
 
5792
  session->where="order clause";
14232
5793
  for (; order; order=order->next)
14233
5794
  {
14234
 
    if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
 
5795
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
14235
5796
                           all_fields, false))
14236
5797
      return 1;
14237
5798
  }
14238
5799
  return 0;
14239
5800
}
14240
5801
 
14241
 
 
14242
5802
/**
14243
5803
  Intitialize the GROUP BY list.
14244
5804
 
14245
 
  @param thd                    Thread handler
 
5805
  @param session                        Thread handler
14246
5806
  @param ref_pointer_array      We store references to all fields that was
14247
5807
                               not in 'fields' here.
14248
5808
  @param fields         All fields in the select part. Any item in
14264
5824
  @retval
14265
5825
    1  error (probably out of memory)
14266
5826
*/
14267
 
 
14268
 
int
14269
 
setup_group(THD *thd, Item **ref_pointer_array, TableList *tables,
14270
 
            List<Item> &fields, List<Item> &all_fields, order_st *order,
14271
 
            bool *hidden_group_fields)
 
5827
int setup_group(Session *session,
 
5828
                Item **ref_pointer_array,
 
5829
                TableList *tables,
 
5830
                      List<Item> &fields,
 
5831
                List<Item> &all_fields,
 
5832
                order_st *order,
 
5833
                      bool *hidden_group_fields)
14272
5834
{
14273
5835
  *hidden_group_fields=0;
14274
5836
  order_st *ord;
14278
5840
 
14279
5841
  uint32_t org_fields=all_fields.elements;
14280
5842
 
14281
 
  thd->where="group statement";
 
5843
  session->where="group statement";
14282
5844
  for (ord= order; ord; ord= ord->next)
14283
5845
  {
14284
 
    if (find_order_in_list(thd, ref_pointer_array, tables, ord, fields,
 
5846
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
14285
5847
                           all_fields, true))
14286
5848
      return 1;
14287
5849
    (*ord->item)->marker= UNDEF_POS;            /* Mark found */
14312
5874
    Item_field *field;
14313
5875
    int cur_pos_in_select_list= 0;
14314
5876
    List_iterator<Item> li(fields);
14315
 
    List_iterator<Item_field> naf_it(thd->lex->current_select->non_agg_fields);
 
5877
    List_iterator<Item_field> naf_it(session->lex->current_select->non_agg_fields);
14316
5878
 
14317
5879
    field= naf_it++;
14318
5880
    while (field && (item=li++))
14361
5923
  Try to use the fields in the order given by 'order' to allow one to
14362
5924
  optimize away 'order by'.
14363
5925
*/
14364
 
 
14365
 
static order_st *
14366
 
create_distinct_group(THD *thd, Item **ref_pointer_array,
14367
 
                      order_st *order_list, List<Item> &fields,
14368
 
                      List<Item> &all_fields __attribute__((unused)),
14369
 
                      bool *all_order_by_fields_used)
 
5926
order_st *create_distinct_group(Session *session,
 
5927
                                Item **ref_pointer_array,
 
5928
                                order_st *order_list,
 
5929
                                List<Item> &fields,
 
5930
                                List<Item> &,
 
5931
                                bool *all_order_by_fields_used)
14370
5932
{
14371
5933
  List_iterator<Item> li(fields);
14372
5934
  Item *item;
14381
5943
  {
14382
5944
    if (order->in_field_list)
14383
5945
    {
14384
 
      order_st *ord=(order_st*) thd->memdup((char*) order,sizeof(order_st));
 
5946
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
14385
5947
      if (!ord)
14386
 
        return 0;
 
5948
        return 0;
14387
5949
      *prev=ord;
14388
5950
      prev= &ord->next;
14389
5951
      (*ord->item)->marker=1;
14397
5959
  {
14398
5960
    if (!item->const_item() && !item->with_sum_func && !item->marker)
14399
5961
    {
14400
 
      /* 
14401
 
        Don't put duplicate columns from the SELECT list into the 
 
5962
      /*
 
5963
        Don't put duplicate columns from the SELECT list into the
14402
5964
        GROUP BY list.
14403
5965
      */
14404
5966
      order_st *ord_iter;
14405
5967
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
14406
5968
        if ((*ord_iter->item)->eq(item, 1))
14407
5969
          goto next_item;
14408
 
      
14409
 
      order_st *ord=(order_st*) thd->calloc(sizeof(order_st));
 
5970
 
 
5971
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
14410
5972
      if (!ord)
14411
 
        return 0;
 
5973
        return 0;
14412
5974
 
14413
5975
      /*
14414
5976
        We have here only field_list (not all_field_list), so we can use
14427
5989
  return group;
14428
5990
}
14429
5991
 
14430
 
 
14431
5992
/**
14432
5993
  Update join with count of the different type of fields.
14433
5994
*/
14434
 
 
14435
 
void
14436
 
count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, 
14437
 
                  List<Item> &fields, bool reset_with_sum_func)
 
5995
void count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param, List<Item> &fields, bool reset_with_sum_func)
14438
5996
{
14439
5997
  List_iterator<Item> li(fields);
14440
5998
  Item *field;
14451
6009
    {
14452
6010
      if (! field->const_item())
14453
6011
      {
14454
 
        Item_sum *sum_item=(Item_sum*) field->real_item();
 
6012
        Item_sum *sum_item=(Item_sum*) field->real_item();
14455
6013
        if (!sum_item->depended_from() ||
14456
6014
            sum_item->depended_from() == select_lex)
14457
6015
        {
14474
6032
    {
14475
6033
      param->func_count++;
14476
6034
      if (reset_with_sum_func)
14477
 
        field->with_sum_func=0;
14478
 
    }
14479
 
  }
14480
 
}
14481
 
 
14482
 
 
14483
 
/**
14484
 
  Return 1 if second is a subpart of first argument.
14485
 
 
14486
 
  If first parts has different direction, change it to second part
14487
 
  (group is sorted like order)
14488
 
*/
14489
 
 
14490
 
static bool
14491
 
test_if_subpart(order_st *a,order_st *b)
14492
 
{
14493
 
  for (; a && b; a=a->next,b=b->next)
14494
 
  {
14495
 
    if ((*a->item)->eq(*b->item,1))
14496
 
      a->asc=b->asc;
14497
 
    else
14498
 
      return 0;
14499
 
  }
14500
 
  return test(!b);
14501
 
}
14502
 
 
14503
 
/**
14504
 
  Return table number if there is only one table in sort order
14505
 
  and group and order is compatible, else return 0.
14506
 
*/
14507
 
 
14508
 
static Table *
14509
 
get_sort_by_table(order_st *a,order_st *b,TableList *tables)
14510
 
{
14511
 
  table_map map= (table_map) 0;
14512
 
 
14513
 
  if (!a)
14514
 
    a=b;                                        // Only one need to be given
14515
 
  else if (!b)
14516
 
    b=a;
14517
 
 
14518
 
  for (; a && b; a=a->next,b=b->next)
14519
 
  {
14520
 
    if (!(*a->item)->eq(*b->item,1))
14521
 
      return(0);
14522
 
    map|=a->item[0]->used_tables();
14523
 
  }
14524
 
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
14525
 
    return(0);
14526
 
 
14527
 
  for (; !(map & tables->table->map); tables= tables->next_leaf) {};
14528
 
  if (map != tables->table->map)
14529
 
    return(0);                          // More than one table
14530
 
  return(tables->table);
14531
 
}
14532
 
 
14533
 
 
14534
 
/**
14535
 
  calc how big buffer we need for comparing group entries.
14536
 
*/
14537
 
 
14538
 
static void
14539
 
calc_group_buffer(JOIN *join,order_st *group)
14540
 
{
14541
 
  uint32_t key_length=0, parts=0, null_parts=0;
14542
 
 
14543
 
  if (group)
14544
 
    join->group= 1;
14545
 
  for (; group ; group=group->next)
14546
 
  {
14547
 
    Item *group_item= *group->item;
14548
 
    Field *field= group_item->get_tmp_table_field();
14549
 
    if (field)
14550
 
    {
14551
 
      enum_field_types type;
14552
 
      if ((type= field->type()) == DRIZZLE_TYPE_BLOB)
14553
 
        key_length+=MAX_BLOB_WIDTH;             // Can't be used as a key
14554
 
      else if (type == DRIZZLE_TYPE_VARCHAR)
14555
 
        key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
14556
 
      else
14557
 
        key_length+= field->pack_length();
14558
 
    }
14559
 
    else
14560
 
    { 
14561
 
      switch (group_item->result_type()) {
14562
 
      case REAL_RESULT:
14563
 
        key_length+= sizeof(double);
14564
 
        break;
14565
 
      case INT_RESULT:
14566
 
        key_length+= sizeof(int64_t);
14567
 
        break;
14568
 
      case DECIMAL_RESULT:
14569
 
        key_length+= my_decimal_get_binary_size(group_item->max_length - 
14570
 
                                                (group_item->decimals ? 1 : 0),
14571
 
                                                group_item->decimals);
14572
 
        break;
14573
 
      case STRING_RESULT:
14574
 
      {
14575
 
        enum enum_field_types type= group_item->field_type();
14576
 
        /*
14577
 
          As items represented as DATE/TIME fields in the group buffer
14578
 
          have STRING_RESULT result type, we increase the length 
14579
 
          by 8 as maximum pack length of such fields.
14580
 
        */
14581
 
        if (type == DRIZZLE_TYPE_TIME ||
14582
 
            type == DRIZZLE_TYPE_NEWDATE ||
14583
 
            type == DRIZZLE_TYPE_DATETIME ||
14584
 
            type == DRIZZLE_TYPE_TIMESTAMP)
14585
 
        {
14586
 
          key_length+= 8;
14587
 
        }
14588
 
        else
14589
 
        {
14590
 
          /*
14591
 
            Group strings are taken as varstrings and require an length field.
14592
 
            A field is not yet created by create_tmp_field()
14593
 
            and the sizes should match up.
14594
 
          */
14595
 
          key_length+= group_item->max_length + HA_KEY_BLOB_LENGTH;
14596
 
        }
14597
 
        break;
14598
 
      }
14599
 
      default:
14600
 
        /* This case should never be choosen */
14601
 
        assert(0);
14602
 
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
14603
 
      }
14604
 
    }
14605
 
    parts++;
14606
 
    if (group_item->maybe_null)
14607
 
      null_parts++;
14608
 
  }
14609
 
  join->tmp_table_param.group_length=key_length+null_parts;
14610
 
  join->tmp_table_param.group_parts=parts;
14611
 
  join->tmp_table_param.group_null_parts=null_parts;
14612
 
}
14613
 
 
14614
 
 
14615
 
/**
14616
 
  allocate group fields or take prepared (cached).
14617
 
 
14618
 
  @param main_join   join of current select
14619
 
  @param curr_join   current join (join of current select or temporary copy
14620
 
                     of it)
14621
 
 
14622
 
  @retval
14623
 
    0   ok
14624
 
  @retval
14625
 
    1   failed
14626
 
*/
14627
 
 
14628
 
static bool
14629
 
make_group_fields(JOIN *main_join, JOIN *curr_join)
14630
 
{
14631
 
  if (main_join->group_fields_cache.elements)
14632
 
  {
14633
 
    curr_join->group_fields= main_join->group_fields_cache;
14634
 
    curr_join->sort_and_group= 1;
14635
 
  }
14636
 
  else
14637
 
  {
14638
 
    if (alloc_group_fields(curr_join, curr_join->group_list))
14639
 
      return (1);
14640
 
    main_join->group_fields_cache= curr_join->group_fields;
14641
 
  }
14642
 
  return (0);
14643
 
}
14644
 
 
14645
 
 
14646
 
/**
14647
 
  Get a list of buffers for saveing last group.
14648
 
 
14649
 
  Groups are saved in reverse order for easyer check loop.
14650
 
*/
14651
 
 
14652
 
static bool
14653
 
alloc_group_fields(JOIN *join,order_st *group)
14654
 
{
14655
 
  if (group)
14656
 
  {
14657
 
    for (; group ; group=group->next)
14658
 
    {
14659
 
      Cached_item *tmp=new_Cached_item(join->thd, *group->item, false);
14660
 
      if (!tmp || join->group_fields.push_front(tmp))
14661
 
        return true;
14662
 
    }
14663
 
  }
14664
 
  join->sort_and_group=1;                       /* Mark for do_select */
14665
 
  return false;
14666
 
}
14667
 
 
 
6035
        field->with_sum_func=0;
 
6036
    }
 
6037
  }
 
6038
}
14668
6039
 
14669
6040
/*
14670
6041
  Test if a single-row cache of items changed, and update the cache.
14672
6043
  @details Test if a list of items that typically represents a result
14673
6044
  row has changed. If the value of some item changed, update the cached
14674
6045
  value for this item.
14675
 
  
 
6046
 
14676
6047
  @param list list of <item, cached_value> pairs stored as Cached_item.
14677
6048
 
14678
6049
  @return -1 if no item changed
14679
6050
  @return index of the first item that changed
14680
6051
*/
14681
 
 
14682
6052
int test_if_item_cache_changed(List<Cached_item> &list)
14683
6053
{
14684
6054
  List_iterator<Cached_item> li(list);
14693
6063
  return(idx);
14694
6064
}
14695
6065
 
14696
 
 
14697
6066
/**
14698
6067
  Setup copy_fields to save fields at start of new group.
14699
6068
 
14703
6072
  Change old item_field to use a new field with points at saved fieldvalue
14704
6073
  This function is only called before use of send_fields.
14705
6074
 
14706
 
  @param thd                   THD pointer
 
6075
  @param session                   Session pointer
14707
6076
  @param param                 temporary table parameters
14708
6077
  @param ref_pointer_array     array of pointers to top elements of filed list
14709
6078
  @param res_selected_fields   new list of items of select item list
14722
6091
  @retval
14723
6092
    !=0   error
14724
6093
*/
14725
 
 
14726
 
bool
14727
 
setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
14728
 
                  Item **ref_pointer_array,
14729
 
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
14730
 
                  uint32_t elements, List<Item> &all_fields)
 
6094
bool setup_copy_fields(Session *session,
 
6095
                       Tmp_Table_Param *param,
 
6096
                       Item **ref_pointer_array,
 
6097
                       List<Item> &res_selected_fields,
 
6098
                       List<Item> &res_all_fields,
 
6099
                       uint32_t elements,
 
6100
                       List<Item> &all_fields)
14731
6101
{
14732
6102
  Item *pos;
14733
6103
  List_iterator_fast<Item> li(all_fields);
14734
 
  Copy_field *copy= NULL;
 
6104
  CopyField *copy= NULL;
14735
6105
  res_selected_fields.empty();
14736
6106
  res_all_fields.empty();
14737
6107
  List_iterator_fast<Item> itr(res_all_fields);
14738
6108
  List<Item> extra_funcs;
14739
6109
  uint32_t i, border= all_fields.elements - elements;
14740
6110
 
14741
 
  if (param->field_count && 
14742
 
      !(copy=param->copy_field= new Copy_field[param->field_count]))
 
6111
  if (param->field_count &&
 
6112
      !(copy=param->copy_field= new CopyField[param->field_count]))
14743
6113
    goto err2;
14744
6114
 
14745
6115
  param->copy_funcs.empty();
14751
6121
    if (real_pos->type() == Item::FIELD_ITEM)
14752
6122
    {
14753
6123
      Item_field *item;
14754
 
      if (!(item= new Item_field(thd, ((Item_field*) real_pos))))
14755
 
        goto err;
 
6124
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
 
6125
        goto err;
14756
6126
      if (pos->type() == Item::REF_ITEM)
14757
6127
      {
14758
6128
        /* preserve the names of the ref when dereferncing */
14764
6134
      pos= item;
14765
6135
      if (item->field->flags & BLOB_FLAG)
14766
6136
      {
14767
 
        if (!(pos= new Item_copy_string(pos)))
14768
 
          goto err;
14769
 
       /*
14770
 
         Item_copy_string::copy for function can call 
14771
 
         Item_copy_string::val_int for blob via Item_ref.
14772
 
         But if Item_copy_string::copy for blob isn't called before,
14773
 
         it's value will be wrong
14774
 
         so let's insert Item_copy_string for blobs in the beginning of 
14775
 
         copy_funcs
14776
 
         (to see full test case look at having.test, BUG #4358) 
14777
 
       */
14778
 
        if (param->copy_funcs.push_front(pos))
14779
 
          goto err;
 
6137
        if (!(pos= new Item_copy_string(pos)))
 
6138
          goto err;
 
6139
            /*
 
6140
              Item_copy_string::copy for function can call
 
6141
              Item_copy_string::val_int for blob via Item_ref.
 
6142
              But if Item_copy_string::copy for blob isn't called before,
 
6143
              it's value will be wrong
 
6144
              so let's insert Item_copy_string for blobs in the beginning of
 
6145
              copy_funcs
 
6146
              (to see full test case look at having.test, BUG #4358)
 
6147
            */
 
6148
        if (param->copy_funcs.push_front(pos))
 
6149
          goto err;
14780
6150
      }
14781
6151
      else
14782
6152
      {
14783
 
        /* 
14784
 
           set up save buffer and change result_field to point at 
14785
 
           saved value
14786
 
        */
14787
 
        field= item->field;
14788
 
        item->result_field=field->new_field(thd->mem_root,field->table, 1);
14789
6153
        /*
14790
 
          We need to allocate one extra byte for null handling and
14791
 
          another extra byte to not get warnings from purify in
14792
 
          Field_varstring::val_int
 
6154
          set up save buffer and change result_field to point at
 
6155
          saved value
14793
6156
        */
14794
 
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
14795
 
          goto err;
 
6157
        field= item->field;
 
6158
        item->result_field=field->new_field(session->mem_root,field->table, 1);
 
6159
              /*
 
6160
                We need to allocate one extra byte for null handling and
 
6161
                another extra byte to not get warnings from purify in
 
6162
                Field_varstring::val_int
 
6163
              */
 
6164
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
 
6165
          goto err;
14796
6166
        if (copy)
14797
6167
        {
14798
6168
          copy->set(tmp, item->result_field);
14812
6182
    {                                           // Save for send fields
14813
6183
      pos= real_pos;
14814
6184
      /* TODO:
14815
 
         In most cases this result will be sent to the user.
14816
 
         This should be changed to use copy_int or copy_real depending
14817
 
         on how the value is to be used: In some cases this may be an
14818
 
         argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
 
6185
        In most cases this result will be sent to the user.
 
6186
        This should be changed to use copy_int or copy_real depending
 
6187
        on how the value is to be used: In some cases this may be an
 
6188
        argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
14819
6189
      */
14820
6190
      if (!(pos=new Item_copy_string(pos)))
14821
 
        goto err;
 
6191
        goto err;
14822
6192
      if (i < border)                           // HAVING, order_st and GROUP BY
14823
6193
      {
14824
6194
        if (extra_funcs.push_back(pos))
14825
6195
          goto err;
14826
6196
      }
14827
6197
      else if (param->copy_funcs.push_back(pos))
14828
 
        goto err;
 
6198
        goto err;
14829
6199
    }
14830
6200
    res_all_fields.push_back(pos);
14831
6201
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
14844
6214
 
14845
6215
  return(0);
14846
6216
 
14847
 
 err:
 
6217
err:
14848
6218
  if (copy)
14849
6219
    delete [] param->copy_field;                        // This is never 0
14850
6220
  param->copy_field=0;
14852
6222
  return(true);
14853
6223
}
14854
6224
 
14855
 
 
14856
6225
/**
14857
6226
  Make a copy of all simple SELECT'ed items.
14858
6227
 
14859
6228
  This is done at the start of a new group so that we can retrieve
14860
6229
  these later when the group changes.
14861
6230
*/
14862
 
 
14863
 
void
14864
 
copy_fields(TMP_TABLE_PARAM *param)
 
6231
void copy_fields(Tmp_Table_Param *param)
14865
6232
{
14866
 
  Copy_field *ptr=param->copy_field;
14867
 
  Copy_field *end=param->copy_field_end;
 
6233
  CopyField *ptr= param->copy_field;
 
6234
  CopyField *end= param->copy_field_end;
14868
6235
 
14869
6236
  for (; ptr != end; ptr++)
14870
6237
    (*ptr->do_copy)(ptr);
14875
6242
    item->copy();
14876
6243
}
14877
6244
 
14878
 
 
14879
 
/**
14880
 
  Make an array of pointers to sum_functions to speed up
14881
 
  sum_func calculation.
14882
 
 
14883
 
  @retval
14884
 
    0   ok
14885
 
  @retval
14886
 
    1   Error
14887
 
*/
14888
 
 
14889
 
bool JOIN::alloc_func_list()
14890
 
{
14891
 
  uint32_t func_count, group_parts;
14892
 
 
14893
 
  func_count= tmp_table_param.sum_func_count;
14894
 
  /*
14895
 
    If we are using rollup, we need a copy of the summary functions for
14896
 
    each level
14897
 
  */
14898
 
  if (rollup.state != ROLLUP::STATE_NONE)
14899
 
    func_count*= (send_group_parts+1);
14900
 
 
14901
 
  group_parts= send_group_parts;
14902
 
  /*
14903
 
    If distinct, reserve memory for possible
14904
 
    disctinct->group_by optimization
14905
 
  */
14906
 
  if (select_distinct)
14907
 
  {
14908
 
    group_parts+= fields_list.elements;
14909
 
    /*
14910
 
      If the order_st clause is specified then it's possible that
14911
 
      it also will be optimized, so reserve space for it too
14912
 
    */
14913
 
    if (order)
14914
 
    {
14915
 
      order_st *ord;
14916
 
      for (ord= order; ord; ord= ord->next)
14917
 
        group_parts++;
14918
 
    }
14919
 
  }
14920
 
 
14921
 
  /* This must use calloc() as rollup_make_fields depends on this */
14922
 
  sum_funcs= (Item_sum**) thd->calloc(sizeof(Item_sum**) * (func_count+1) +
14923
 
                                      sizeof(Item_sum***) * (group_parts+1));
14924
 
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
14925
 
  return(sum_funcs == 0);
14926
 
}
14927
 
 
14928
 
 
14929
 
/**
14930
 
  Initialize 'sum_funcs' array with all Item_sum objects.
14931
 
 
14932
 
  @param field_list        All items
14933
 
  @param send_fields       Items in select list
14934
 
  @param before_group_by   Set to 1 if this is called before GROUP BY handling
14935
 
  @param recompute         Set to true if sum_funcs must be recomputed
14936
 
 
14937
 
  @retval
14938
 
    0  ok
14939
 
  @retval
14940
 
    1  error
14941
 
*/
14942
 
 
14943
 
bool JOIN::make_sum_func_list(List<Item> &field_list, List<Item> &send_fields,
14944
 
                              bool before_group_by, bool recompute)
14945
 
{
14946
 
  List_iterator_fast<Item> it(field_list);
14947
 
  Item_sum **func;
14948
 
  Item *item;
14949
 
 
14950
 
  if (*sum_funcs && !recompute)
14951
 
    return(false); /* We have already initialized sum_funcs. */
14952
 
 
14953
 
  func= sum_funcs;
14954
 
  while ((item=it++))
14955
 
  {
14956
 
    if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
14957
 
        (!((Item_sum*) item)->depended_from() ||
14958
 
         ((Item_sum *)item)->depended_from() == select_lex))
14959
 
      *func++= (Item_sum*) item;
14960
 
  }
14961
 
  if (before_group_by && rollup.state == ROLLUP::STATE_INITED)
14962
 
  {
14963
 
    rollup.state= ROLLUP::STATE_READY;
14964
 
    if (rollup_make_fields(field_list, send_fields, &func))
14965
 
      return(true);                     // Should never happen
14966
 
  }
14967
 
  else if (rollup.state == ROLLUP::STATE_NONE)
14968
 
  {
14969
 
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
14970
 
      sum_funcs_end[i]= func;
14971
 
  }
14972
 
  else if (rollup.state == ROLLUP::STATE_READY)
14973
 
    return(false);                         // Don't put end marker
14974
 
  *func=0;                                      // End marker
14975
 
  return(false);
14976
 
}
14977
 
 
14978
 
 
14979
6245
/**
14980
6246
  Change all funcs and sum_funcs to fields in tmp table, and create
14981
6247
  new list of all items.
14982
6248
 
14983
 
  @param thd                   THD pointer
 
6249
  @param session                   Session pointer
14984
6250
  @param ref_pointer_array     array of pointers to top elements of filed list
14985
6251
  @param res_selected_fields   new list of items of select item list
14986
6252
  @param res_all_fields        new list of all items
14992
6258
  @retval
14993
6259
    !=0   error
14994
6260
*/
14995
 
 
14996
 
static bool
14997
 
change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
14998
 
                         List<Item> &res_selected_fields,
14999
 
                         List<Item> &res_all_fields,
15000
 
                         uint32_t elements, List<Item> &all_fields)
 
6261
bool change_to_use_tmp_fields(Session *session,
 
6262
                              Item **ref_pointer_array,
 
6263
                                                List<Item> &res_selected_fields,
 
6264
                                                List<Item> &res_all_fields,
 
6265
                                                uint32_t elements,
 
6266
                              List<Item> &all_fields)
15001
6267
{
15002
6268
  List_iterator_fast<Item> it(all_fields);
15003
6269
  Item *item_field,*item;
15018
6284
    {
15019
6285
      if (item->type() == Item::FIELD_ITEM)
15020
6286
      {
15021
 
        item_field= item->get_tmp_table_item(thd);
 
6287
        item_field= item->get_tmp_table_item(session);
15022
6288
      }
15023
6289
      else if ((field= item->get_tmp_table_field()))
15024
6290
      {
15025
 
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
15026
 
          item_field= ((Item_sum*) item)->result_item(field);
15027
 
        else
15028
 
          item_field= (Item*) new Item_field(field);
15029
 
        if (!item_field)
15030
 
          return(true);                    // Fatal error
 
6291
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
 
6292
          item_field= ((Item_sum*) item)->result_item(field);
 
6293
        else
 
6294
          item_field= (Item*) new Item_field(field);
 
6295
        if (!item_field)
 
6296
          return(true);                    // Fatal error
15031
6297
 
15032
6298
        if (item->real_item()->type() != Item::FIELD_ITEM)
15033
6299
          field->orig_table= 0;
15034
 
        item_field->name= item->name;
 
6300
        item_field->name= item->name;
15035
6301
        if (item->type() == Item::REF_ITEM)
15036
6302
        {
15037
6303
          Item_field *ifield= (Item_field *) item_field;
15041
6307
        }
15042
6308
      }
15043
6309
      else
15044
 
        item_field= item;
 
6310
        item_field= item;
15045
6311
    }
15046
6312
    res_all_fields.push_back(item_field);
15047
6313
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
15055
6321
  return(false);
15056
6322
}
15057
6323
 
15058
 
 
15059
6324
/**
15060
6325
  Change all sum_func refs to fields to point at fields in tmp table.
15061
6326
  Change all funcs to be fields in tmp table.
15062
6327
 
15063
 
  @param thd                   THD pointer
 
6328
  @param session                   Session pointer
15064
6329
  @param ref_pointer_array     array of pointers to top elements of filed list
15065
6330
  @param res_selected_fields   new list of items of select item list
15066
6331
  @param res_all_fields        new list of all items
15072
6337
  @retval
15073
6338
    1   error
15074
6339
*/
15075
 
 
15076
 
static bool
15077
 
change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
15078
 
                          List<Item> &res_selected_fields,
15079
 
                          List<Item> &res_all_fields, uint32_t elements,
15080
 
                          List<Item> &all_fields)
 
6340
bool change_refs_to_tmp_fields(Session *session,
 
6341
                               Item **ref_pointer_array,
 
6342
                               List<Item> &res_selected_fields,
 
6343
                               List<Item> &res_all_fields,
 
6344
                               uint32_t elements,
 
6345
                                                 List<Item> &all_fields)
15081
6346
{
15082
6347
  List_iterator_fast<Item> it(all_fields);
15083
6348
  Item *item, *new_item;
15087
6352
  uint32_t i, border= all_fields.elements - elements;
15088
6353
  for (i= 0; (item= it++); i++)
15089
6354
  {
15090
 
    res_all_fields.push_back(new_item= item->get_tmp_table_item(thd));
 
6355
    res_all_fields.push_back(new_item= item->get_tmp_table_item(session));
15091
6356
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
15092
6357
      new_item;
15093
6358
  }
15097
6362
    itr++;
15098
6363
  itr.sublist(res_selected_fields, elements);
15099
6364
 
15100
 
  return thd->is_fatal_error;
 
6365
  return session->is_fatal_error;
15101
6366
}
15102
6367
 
15103
 
 
15104
 
 
15105
6368
/******************************************************************************
15106
6369
  Code for calculating functions
15107
6370
******************************************************************************/
15108
6371
 
15109
 
 
15110
6372
/**
15111
6373
  Call ::setup for all sum functions.
15112
6374
 
15113
 
  @param thd           thread handler
 
6375
  @param session           thread handler
15114
6376
  @param func_ptr      sum function list
15115
6377
 
15116
6378
  @retval
15118
6380
  @retval
15119
6381
    true   error
15120
6382
*/
15121
 
 
15122
 
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr)
 
6383
bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
15123
6384
{
15124
6385
  Item_sum *func;
15125
6386
  while ((func= *(func_ptr++)))
15126
6387
  {
15127
 
    if (func->setup(thd))
 
6388
    if (func->setup(session))
15128
6389
      return(true);
15129
6390
  }
15130
6391
  return(false);
15131
6392
}
15132
6393
 
15133
 
 
15134
 
static void
15135
 
init_tmptable_sum_functions(Item_sum **func_ptr)
 
6394
void init_tmptable_sum_functions(Item_sum **func_ptr)
15136
6395
{
15137
6396
  Item_sum *func;
15138
6397
  while ((func= *(func_ptr++)))
15139
6398
    func->reset_field();
15140
6399
}
15141
6400
 
15142
 
 
15143
6401
/** Update record 0 in tmp_table from record 1. */
15144
 
 
15145
 
static void
15146
 
update_tmptable_sum_func(Item_sum **func_ptr,
15147
 
                         Table *tmp_table __attribute__((unused)))
 
6402
void update_tmptable_sum_func(Item_sum **func_ptr, Table *)
15148
6403
{
15149
6404
  Item_sum *func;
15150
6405
  while ((func= *(func_ptr++)))
15151
6406
    func->update_field();
15152
6407
}
15153
6408
 
15154
 
 
15155
6409
/** Copy result of sum functions to record in tmp_table. */
15156
 
 
15157
 
static void
15158
 
copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
 
6410
void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
15159
6411
{
15160
6412
  for (; func_ptr != end_ptr ; func_ptr++)
15161
6413
    (void) (*func_ptr)->save_in_result_field(1);
15162
6414
  return;
15163
6415
}
15164
6416
 
15165
 
 
15166
 
static bool
15167
 
init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
 
6417
bool init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
15168
6418
{
15169
6419
  for (; func_ptr != end_ptr ;func_ptr++)
15170
6420
  {
15180
6430
  return 0;
15181
6431
}
15182
6432
 
15183
 
 
15184
 
static bool
15185
 
update_sum_func(Item_sum **func_ptr)
 
6433
bool update_sum_func(Item_sum **func_ptr)
15186
6434
{
15187
6435
  Item_sum *func;
15188
6436
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
15192
6440
}
15193
6441
 
15194
6442
/** Copy result of functions to record in tmp_table. */
15195
 
 
15196
 
void
15197
 
copy_funcs(Item **func_ptr)
 
6443
void copy_funcs(Item **func_ptr)
15198
6444
{
15199
6445
  Item *func;
15200
6446
  for (; (func = *func_ptr) ; func_ptr++)
15201
6447
    func->save_in_result_field(1);
15202
6448
}
15203
6449
 
15204
 
 
15205
 
/**
15206
 
  Create a condition for a const reference and add this to the
15207
 
  currenct select for the table.
15208
 
*/
15209
 
 
15210
 
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab)
15211
 
{
15212
 
  if (!join_tab->ref.key_parts)
15213
 
    return(false);
15214
 
 
15215
 
  Item_cond_and *cond=new Item_cond_and();
15216
 
  Table *table=join_tab->table;
15217
 
  int error;
15218
 
  if (!cond)
15219
 
    return(true);
15220
 
 
15221
 
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
15222
 
  {
15223
 
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
15224
 
                              fieldnr-1];
15225
 
    Item *value=join_tab->ref.items[i];
15226
 
    cond->add(new Item_func_equal(new Item_field(field), value));
15227
 
  }
15228
 
  if (thd->is_fatal_error)
15229
 
    return(true);
15230
 
 
15231
 
  if (!cond->fixed)
15232
 
    cond->fix_fields(thd, (Item**)&cond);
15233
 
  if (join_tab->select)
15234
 
  {
15235
 
    error=(int) cond->add(join_tab->select->cond);
15236
 
    join_tab->select_cond=join_tab->select->cond=cond;
15237
 
  }
15238
 
  else if ((join_tab->select= make_select(join_tab->table, 0, 0, cond, 0,
15239
 
                                          &error)))
15240
 
    join_tab->select_cond=cond;
15241
 
 
15242
 
  return(error ? true : false);
15243
 
}
15244
 
 
15245
 
 
15246
6450
/**
15247
6451
  Free joins of subselect of this select.
15248
6452
 
15249
 
  @param thd      THD pointer
15250
 
  @param select   pointer to st_select_lex which subselects joins we will free
 
6453
  @param session      Session pointer
 
6454
  @param select   pointer to Select_Lex which subselects joins we will free
15251
6455
*/
15252
 
 
15253
 
void free_underlaid_joins(THD *thd __attribute__((unused)),
15254
 
                          SELECT_LEX *select)
 
6456
void free_underlaid_joins(Session *, Select_Lex *select)
15255
6457
{
15256
 
  for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
 
6458
  for (Select_Lex_Unit *unit= select->first_inner_unit();
15257
6459
       unit;
15258
6460
       unit= unit->next_unit())
15259
6461
    unit->cleanup();
15275
6477
  @b EXAMPLES
15276
6478
    @code
15277
6479
      SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP
15278
 
      SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP 
 
6480
      SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP
15279
6481
  @endcode
15280
6482
 
15281
6483
  @b IMPLEMENTATION
15288
6490
    This substitution is needed GROUP BY queries with ROLLUP if
15289
6491
    SELECT list contains expressions over group by attributes.
15290
6492
 
15291
 
  @param thd                  reference to the context
 
6493
  @param session                  reference to the context
15292
6494
  @param expr                 expression to make replacement
15293
6495
  @param group_list           list of references to group by items
15294
6496
  @param changed        out:  returns 1 if item contains a replaced field item
15295
6497
 
15296
6498
  @todo
15297
6499
    - TODO: Some functions are not null-preserving. For those functions
15298
 
    updating of the maybe_null attribute is an overkill. 
 
6500
    updating of the maybe_null attribute is an overkill.
15299
6501
 
15300
6502
  @retval
15301
6503
    0   if ok
15302
6504
  @retval
15303
6505
    1   on error
15304
6506
*/
15305
 
 
15306
 
static bool change_group_ref(THD *thd, Item_func *expr, order_st *group_list,
15307
 
                             bool *changed)
 
6507
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
15308
6508
{
15309
6509
  if (expr->arg_count)
15310
6510
  {
15311
 
    Name_resolution_context *context= &thd->lex->current_select->context;
 
6511
    Name_resolution_context *context= &session->lex->current_select->context;
15312
6512
    Item **arg,**arg_end;
15313
6513
    bool arg_changed= false;
15314
6514
    for (arg= expr->arguments(),
15327
6527
            if (!(new_item= new Item_ref(context, group_tmp->item, 0,
15328
6528
                                        item->name)))
15329
6529
              return 1;                                 // fatal_error is set
15330
 
            thd->change_item_tree(arg, new_item);
 
6530
            session->change_item_tree(arg, new_item);
15331
6531
            arg_changed= true;
15332
6532
          }
15333
6533
        }
15334
6534
      }
15335
6535
      else if (item->type() == Item::FUNC_ITEM)
15336
6536
      {
15337
 
        if (change_group_ref(thd, (Item_func *) item, group_list, &arg_changed))
 
6537
        if (change_group_ref(session, (Item_func *) item, group_list, &arg_changed))
15338
6538
          return 1;
15339
6539
      }
15340
6540
    }
15347
6547
  return 0;
15348
6548
}
15349
6549
 
15350
 
 
15351
 
/** Allocate memory needed for other rollup functions. */
15352
 
 
15353
 
bool JOIN::rollup_init()
15354
 
{
15355
 
  uint32_t i,j;
15356
 
  Item **ref_array;
15357
 
 
15358
 
  tmp_table_param.quick_group= 0;       // Can't create groups in tmp table
15359
 
  rollup.state= ROLLUP::STATE_INITED;
15360
 
 
15361
 
  /*
15362
 
    Create pointers to the different sum function groups
15363
 
    These are updated by rollup_make_fields()
15364
 
  */
15365
 
  tmp_table_param.group_parts= send_group_parts;
15366
 
 
15367
 
  if (!(rollup.null_items= (Item_null_result**) thd->alloc((sizeof(Item*) +
15368
 
                                                sizeof(Item**) +
15369
 
                                                sizeof(List<Item>) +
15370
 
                                                ref_pointer_array_size)
15371
 
                                                * send_group_parts )))
15372
 
    return 1;
15373
 
  
15374
 
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
15375
 
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
15376
 
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
15377
 
 
15378
 
  /*
15379
 
    Prepare space for field list for the different levels
15380
 
    These will be filled up in rollup_make_fields()
15381
 
  */
15382
 
  for (i= 0 ; i < send_group_parts ; i++)
15383
 
  {
15384
 
    rollup.null_items[i]= new (thd->mem_root) Item_null_result();
15385
 
    List<Item> *rollup_fields= &rollup.fields[i];
15386
 
    rollup_fields->empty();
15387
 
    rollup.ref_pointer_arrays[i]= ref_array;
15388
 
    ref_array+= all_fields.elements;
15389
 
  }
15390
 
  for (i= 0 ; i < send_group_parts; i++)
15391
 
  {
15392
 
    for (j=0 ; j < fields_list.elements ; j++)
15393
 
      rollup.fields[i].push_back(rollup.null_items[i]);
15394
 
  }
15395
 
  List_iterator<Item> it(all_fields);
15396
 
  Item *item;
15397
 
  while ((item= it++))
15398
 
  {
15399
 
    order_st *group_tmp;
15400
 
    bool found_in_group= 0;
15401
 
 
15402
 
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
15403
 
    {
15404
 
      if (*group_tmp->item == item)
15405
 
      {
15406
 
        item->maybe_null= 1;
15407
 
        found_in_group= 1;
15408
 
        if (item->const_item())
15409
 
        {
15410
 
          /*
15411
 
            For ROLLUP queries each constant item referenced in GROUP BY list
15412
 
            is wrapped up into an Item_func object yielding the same value
15413
 
            as the constant item. The objects of the wrapper class are never
15414
 
            considered as constant items and besides they inherit all
15415
 
            properties of the Item_result_field class.
15416
 
            This wrapping allows us to ensure writing constant items
15417
 
            into temporary tables whenever the result of the ROLLUP
15418
 
            operation has to be written into a temporary table, e.g. when
15419
 
            ROLLUP is used together with DISTINCT in the SELECT list.
15420
 
            Usually when creating temporary tables for a intermidiate
15421
 
            result we do not include fields for constant expressions.
15422
 
          */           
15423
 
          Item* new_item= new Item_func_rollup_const(item);
15424
 
          if (!new_item)
15425
 
            return 1;
15426
 
          new_item->fix_fields(thd, (Item **) 0);
15427
 
          thd->change_item_tree(it.ref(), new_item);
15428
 
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
15429
 
          { 
15430
 
            if (*tmp->item == item)
15431
 
              thd->change_item_tree(tmp->item, new_item);
15432
 
          }
15433
 
        }
15434
 
      }
15435
 
    }
15436
 
    if (item->type() == Item::FUNC_ITEM && !found_in_group)
15437
 
    {
15438
 
      bool changed= false;
15439
 
      if (change_group_ref(thd, (Item_func *) item, group_list, &changed))
15440
 
        return 1;
15441
 
      /*
15442
 
        We have to prevent creation of a field in a temporary table for
15443
 
        an expression that contains GROUP BY attributes.
15444
 
        Marking the expression item as 'with_sum_func' will ensure this.
15445
 
      */ 
15446
 
      if (changed)
15447
 
        item->with_sum_func= 1;
15448
 
    }
15449
 
  }
15450
 
  return 0;
15451
 
}
15452
 
  
15453
 
 
15454
 
/**
15455
 
  Fill up rollup structures with pointers to fields to use.
15456
 
 
15457
 
  Creates copies of item_sum items for each sum level.
15458
 
 
15459
 
  @param fields_arg             List of all fields (hidden and real ones)
15460
 
  @param sel_fields             Pointer to selected fields
15461
 
  @param func                   Store here a pointer to all fields
15462
 
 
15463
 
  @retval
15464
 
    0   if ok;
15465
 
    In this case func is pointing to next not used element.
15466
 
  @retval
15467
 
    1    on error
15468
 
*/
15469
 
 
15470
 
bool JOIN::rollup_make_fields(List<Item> &fields_arg, List<Item> &sel_fields,
15471
 
                              Item_sum ***func)
15472
 
{
15473
 
  List_iterator_fast<Item> it(fields_arg);
15474
 
  Item *first_field= sel_fields.head();
15475
 
  uint32_t level;
15476
 
 
15477
 
  /*
15478
 
    Create field lists for the different levels
15479
 
 
15480
 
    The idea here is to have a separate field list for each rollup level to
15481
 
    avoid all runtime checks of which columns should be NULL.
15482
 
 
15483
 
    The list is stored in reverse order to get sum function in such an order
15484
 
    in func that it makes it easy to reset them with init_sum_functions()
15485
 
 
15486
 
    Assuming:  SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
15487
 
 
15488
 
    rollup.fields[0] will contain list where a,b,c is NULL
15489
 
    rollup.fields[1] will contain list where b,c is NULL
15490
 
    ...
15491
 
    rollup.ref_pointer_array[#] points to fields for rollup.fields[#]
15492
 
    ...
15493
 
    sum_funcs_end[0] points to all sum functions
15494
 
    sum_funcs_end[1] points to all sum functions, except grand totals
15495
 
    ...
15496
 
  */
15497
 
 
15498
 
  for (level=0 ; level < send_group_parts ; level++)
15499
 
  {
15500
 
    uint32_t i;
15501
 
    uint32_t pos= send_group_parts - level -1;
15502
 
    bool real_fields= 0;
15503
 
    Item *item;
15504
 
    List_iterator<Item> new_it(rollup.fields[pos]);
15505
 
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
15506
 
    order_st *start_group;
15507
 
 
15508
 
    /* Point to first hidden field */
15509
 
    Item **ref_array= ref_array_start + fields_arg.elements-1;
15510
 
 
15511
 
    /* Remember where the sum functions ends for the previous level */
15512
 
    sum_funcs_end[pos+1]= *func;
15513
 
 
15514
 
    /* Find the start of the group for this level */
15515
 
    for (i= 0, start_group= group_list ;
15516
 
         i++ < pos ;
15517
 
         start_group= start_group->next)
15518
 
      ;
15519
 
 
15520
 
    it.rewind();
15521
 
    while ((item= it++))
15522
 
    {
15523
 
      if (item == first_field)
15524
 
      {
15525
 
        real_fields= 1;                         // End of hidden fields
15526
 
        ref_array= ref_array_start;
15527
 
      }
15528
 
 
15529
 
      if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
15530
 
          (!((Item_sum*) item)->depended_from() ||
15531
 
           ((Item_sum *)item)->depended_from() == select_lex))
15532
 
          
15533
 
      {
15534
 
        /*
15535
 
          This is a top level summary function that must be replaced with
15536
 
          a sum function that is reset for this level.
15537
 
 
15538
 
          NOTE: This code creates an object which is not that nice in a
15539
 
          sub select.  Fortunately it's not common to have rollup in
15540
 
          sub selects.
15541
 
        */
15542
 
        item= item->copy_or_same(thd);
15543
 
        ((Item_sum*) item)->make_unique();
15544
 
        *(*func)= (Item_sum*) item;
15545
 
        (*func)++;
15546
 
      }
15547
 
      else 
15548
 
      {
15549
 
        /* Check if this is something that is part of this group by */
15550
 
        order_st *group_tmp;
15551
 
        for (group_tmp= start_group, i= pos ;
15552
 
             group_tmp ; group_tmp= group_tmp->next, i++)
15553
 
        {
15554
 
          if (*group_tmp->item == item)
15555
 
          {
15556
 
            /*
15557
 
              This is an element that is used by the GROUP BY and should be
15558
 
              set to NULL in this level
15559
 
            */
15560
 
            Item_null_result *null_item= new (thd->mem_root) Item_null_result();
15561
 
            if (!null_item)
15562
 
              return 1;
15563
 
            item->maybe_null= 1;                // Value will be null sometimes
15564
 
            null_item->result_field= item->get_tmp_table_field();
15565
 
            item= null_item;
15566
 
            break;
15567
 
          }
15568
 
        }
15569
 
      }
15570
 
      *ref_array= item;
15571
 
      if (real_fields)
15572
 
      {
15573
 
        (void) new_it++;                        // Point to next item
15574
 
        new_it.replace(item);                   // Replace previous
15575
 
        ref_array++;
15576
 
      }
15577
 
      else
15578
 
        ref_array--;
15579
 
    }
15580
 
  }
15581
 
  sum_funcs_end[0]= *func;                      // Point to last function
15582
 
  return 0;
15583
 
}
15584
 
 
15585
 
/**
15586
 
  Send all rollup levels higher than the current one to the client.
15587
 
 
15588
 
  @b SAMPLE
15589
 
    @code
15590
 
      SELECT a, b, c SUM(b) FROM t1 GROUP BY a,b WITH ROLLUP
15591
 
  @endcode
15592
 
 
15593
 
  @param idx            Level we are on:
15594
 
                        - 0 = Total sum level
15595
 
                        - 1 = First group changed  (a)
15596
 
                        - 2 = Second group changed (a,b)
15597
 
 
15598
 
  @retval
15599
 
    0   ok
15600
 
  @retval
15601
 
    1   If send_data_failed()
15602
 
*/
15603
 
 
15604
 
int JOIN::rollup_send_data(uint32_t idx)
15605
 
{
15606
 
  uint32_t i;
15607
 
  for (i= send_group_parts ; i-- > idx ; )
15608
 
  {
15609
 
    /* Get reference pointers to sum functions in place */
15610
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
15611
 
           ref_pointer_array_size);
15612
 
    if ((!having || having->val_int()))
15613
 
    {
15614
 
      if (send_records < unit->select_limit_cnt && do_send_rows &&
15615
 
          result->send_data(rollup.fields[i]))
15616
 
        return 1;
15617
 
      send_records++;
15618
 
    }
15619
 
  }
15620
 
  /* Restore ref_pointer_array */
15621
 
  set_items_ref_array(current_ref_pointer_array);
15622
 
  return 0;
15623
 
}
15624
 
 
15625
 
/**
15626
 
  Write all rollup levels higher than the current one to a temp table.
15627
 
 
15628
 
  @b SAMPLE
15629
 
    @code
15630
 
      SELECT a, b, SUM(c) FROM t1 GROUP BY a,b WITH ROLLUP
15631
 
  @endcode
15632
 
 
15633
 
  @param idx                 Level we are on:
15634
 
                               - 0 = Total sum level
15635
 
                               - 1 = First group changed  (a)
15636
 
                               - 2 = Second group changed (a,b)
15637
 
  @param table               reference to temp table
15638
 
 
15639
 
  @retval
15640
 
    0   ok
15641
 
  @retval
15642
 
    1   if write_data_failed()
15643
 
*/
15644
 
 
15645
 
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
15646
 
{
15647
 
  uint32_t i;
15648
 
  for (i= send_group_parts ; i-- > idx ; )
15649
 
  {
15650
 
    /* Get reference pointers to sum functions in place */
15651
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
15652
 
           ref_pointer_array_size);
15653
 
    if ((!having || having->val_int()))
15654
 
    {
15655
 
      int write_error;
15656
 
      Item *item;
15657
 
      List_iterator_fast<Item> it(rollup.fields[i]);
15658
 
      while ((item= it++))
15659
 
      {
15660
 
        if (item->type() == Item::NULL_ITEM && item->is_result_field())
15661
 
          item->save_in_result_field(1);
15662
 
      }
15663
 
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
15664
 
      if ((write_error= table_arg->file->ha_write_row(table_arg->record[0])))
15665
 
      {
15666
 
        if (create_myisam_from_heap(thd, table_arg, 
15667
 
                                    tmp_table_param.start_recinfo,
15668
 
                                    &tmp_table_param.recinfo,
15669
 
                                    write_error, 0))
15670
 
          return 1;                  
15671
 
      }
15672
 
    }
15673
 
  }
15674
 
  /* Restore ref_pointer_array */
15675
 
  set_items_ref_array(current_ref_pointer_array);
15676
 
  return 0;
15677
 
}
15678
 
 
15679
 
/**
15680
 
  clear results if there are not rows found for group
15681
 
  (end_send_group/end_write_group)
15682
 
*/
15683
 
 
15684
 
void JOIN::clear()
15685
 
{
15686
 
  clear_tables(this);
15687
 
  copy_fields(&tmp_table_param);
15688
 
 
15689
 
  if (sum_funcs)
15690
 
  {
15691
 
    Item_sum *func, **func_ptr= sum_funcs;
15692
 
    while ((func= *(func_ptr++)))
15693
 
      func->clear();
15694
 
  }
15695
 
}
15696
 
 
15697
6550
/**
15698
6551
  EXPLAIN handling.
15699
6552
 
15700
6553
  Send a description about what how the select will be done to stdout.
15701
6554
*/
15702
 
 
15703
6555
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
15704
6556
                     bool distinct,const char *message)
15705
6557
{
15706
6558
  List<Item> field_list;
15707
6559
  List<Item> item_list;
15708
 
  THD *thd=join->thd;
 
6560
  Session *session=join->session;
15709
6561
  select_result *result=join->result;
15710
6562
  Item *item_null= new Item_null();
15711
6563
  const CHARSET_INFO * const cs= system_charset_info;
15712
6564
  int quick_type;
15713
6565
  /* Don't log this into the slow query log */
15714
 
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
6566
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
15715
6567
  join->unit->offset_limit_cnt= 0;
15716
6568
 
15717
 
  /* 
 
6569
  /*
15718
6570
    NOTE: the number/types of items pushed into item_list must be in sync with
15719
 
    EXPLAIN column types as they're "defined" in THD::send_explain_fields()
 
6571
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
15720
6572
  */
15721
6573
  if (message)
15722
6574
  {
15726
6578
                                        strlen(join->select_lex->type), cs));
15727
6579
    for (uint32_t i=0 ; i < 7; i++)
15728
6580
      item_list.push_back(item_null);
15729
 
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
6581
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
15730
6582
      item_list.push_back(item_null);
15731
 
  
 
6583
 
15732
6584
    item_list.push_back(new Item_string(message,strlen(message),cs));
15733
6585
    if (result->send_data(item_list))
15734
6586
      join->error= 1;
15735
6587
  }
15736
6588
  else if (join->select_lex == join->unit->fake_select_lex)
15737
6589
  {
15738
 
    /* 
 
6590
    /*
15739
6591
      here we assume that the query will return at least two rows, so we
15740
6592
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
15741
6593
      and no filesort will be actually done, but executing all selects in
15752
6604
                                        cs));
15753
6605
    /* table */
15754
6606
    {
15755
 
      SELECT_LEX *sl= join->unit->first_select();
 
6607
      Select_Lex *sl= join->unit->first_select();
15756
6608
      uint32_t len= 6, lastop= 0;
15757
6609
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
15758
6610
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
15774
6626
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
15775
6627
    }
15776
6628
    /* type */
15777
 
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
15778
 
                                          strlen(join_type_str[JT_ALL]),
15779
 
                                          cs));
 
6629
    item_list.push_back(new Item_string(access_method_str[AM_ALL].c_str(),
 
6630
                                        access_method_str[AM_ALL].length(),
 
6631
                                        cs));
15780
6632
    /* possible_keys */
15781
6633
    item_list.push_back(item_null);
15782
6634
    /* key*/
15786
6638
    /* ref */
15787
6639
    item_list.push_back(item_null);
15788
6640
    /* in_rows */
15789
 
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
6641
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
15790
6642
      item_list.push_back(item_null);
15791
6643
    /* rows */
15792
6644
    item_list.push_back(item_null);
15805
6657
    table_map used_tables=0;
15806
6658
    for (uint32_t i=0 ; i < join->tables ; i++)
15807
6659
    {
15808
 
      JOIN_TAB *tab=join->join_tab+i;
 
6660
      JoinTable *tab=join->join_tab+i;
15809
6661
      Table *table=tab->table;
15810
6662
      TableList *table_list= tab->table->pos_in_table_list;
15811
 
      char buff[512]; 
 
6663
      char buff[512];
15812
6664
      char buff1[512], buff2[512], buff3[512];
15813
6665
      char keylen_str_buf[64];
15814
6666
      String extra(buff, sizeof(buff),cs);
15830
6682
      item_list.push_back(new Item_string(join->select_lex->type,
15831
6683
                                          strlen(join->select_lex->type),
15832
6684
                                          cs));
15833
 
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
 
6685
      if (tab->type == AM_ALL && tab->select && tab->select->quick)
15834
6686
      {
15835
6687
        quick_type= tab->select->quick->get_type();
15836
6688
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
15837
6689
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
15838
6690
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
15839
 
          tab->type = JT_INDEX_MERGE;
 
6691
          tab->type = AM_INDEX_MERGE;
15840
6692
        else
15841
 
          tab->type = JT_RANGE;
 
6693
          tab->type = AM_RANGE;
15842
6694
      }
15843
6695
      /* table */
15844
6696
      if (table->derived_select_number)
15851
6703
      }
15852
6704
      else
15853
6705
      {
15854
 
        TableList *real_table= table->pos_in_table_list; 
 
6706
        TableList *real_table= table->pos_in_table_list;
15855
6707
        item_list.push_back(new Item_string(real_table->alias,
15856
6708
                                            strlen(real_table->alias),
15857
6709
                                            cs));
15858
6710
      }
15859
6711
      /* "type" column */
15860
 
      item_list.push_back(new Item_string(join_type_str[tab->type],
15861
 
                                          strlen(join_type_str[tab->type]),
 
6712
      item_list.push_back(new Item_string(access_method_str[tab->type].c_str(),
 
6713
                                          access_method_str[tab->type].length(),
15862
6714
                                          cs));
15863
6715
      /* Build "possible_keys" value and add it to item_list */
15864
 
      if (!tab->keys.is_clear_all())
 
6716
      if (tab->keys.any())
15865
6717
      {
15866
6718
        uint32_t j;
15867
6719
        for (j=0 ; j < table->s->keys ; j++)
15868
6720
        {
15869
 
          if (tab->keys.is_set(j))
 
6721
          if (tab->keys.test(j))
15870
6722
          {
15871
6723
            if (tmp1.length())
15872
6724
              tmp1.append(',');
15873
 
            tmp1.append(table->key_info[j].name, 
 
6725
            tmp1.append(table->key_info[j].name,
15874
6726
                        strlen(table->key_info[j].name),
15875
6727
                        system_charset_info);
15876
6728
          }
15889
6741
        item_list.push_back(new Item_string(key_info->name,
15890
6742
                                            strlen(key_info->name),
15891
6743
                                            system_charset_info));
15892
 
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) - 
 
6744
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
15893
6745
                keylen_str_buf;
15894
6746
        item_list.push_back(new Item_string(keylen_str_buf, length,
15895
6747
                                            system_charset_info));
15896
 
        for (store_key **ref=tab->ref.key_copy ; *ref ; ref++)
 
6748
        for (StoredKey **ref=tab->ref.key_copy ; *ref ; ref++)
15897
6749
        {
15898
6750
          if (tmp2.length())
15899
6751
            tmp2.append(',');
15902
6754
        }
15903
6755
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
15904
6756
      }
15905
 
      else if (tab->type == JT_NEXT)
 
6757
      else if (tab->type == AM_NEXT)
15906
6758
      {
15907
6759
        KEY *key_info=table->key_info+ tab->index;
15908
6760
        register uint32_t length;
15909
6761
        item_list.push_back(new Item_string(key_info->name,
15910
6762
                                            strlen(key_info->name),cs));
15911
 
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) - 
 
6763
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
15912
6764
                keylen_str_buf;
15913
 
        item_list.push_back(new Item_string(keylen_str_buf, 
 
6765
        item_list.push_back(new Item_string(keylen_str_buf,
15914
6766
                                            length,
15915
6767
                                            system_charset_info));
15916
6768
        item_list.push_back(item_null);
15924
6776
      }
15925
6777
      else
15926
6778
      {
15927
 
        if (table_list->schema_table && table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
6779
        if (table_list->schema_table && 
 
6780
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
15928
6781
        {
15929
 
          const char *tmp_buff;
15930
 
          int f_idx;
15931
6782
          if (table_list->has_db_lookup_value)
15932
6783
          {
15933
 
            f_idx= table_list->schema_table->idx_field1;
15934
 
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
15935
 
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
15936
 
          }          
 
6784
            int f_idx= table_list->schema_table->getFirstColumnIndex();
 
6785
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
6786
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
6787
          }
15937
6788
          if (table_list->has_table_lookup_value)
15938
6789
          {
15939
6790
            if (table_list->has_db_lookup_value)
15940
6791
              tmp2.append(',');
15941
 
            f_idx= table_list->schema_table->idx_field2;
15942
 
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
15943
 
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
 
6792
            int f_idx= table_list->schema_table->getSecondColumnIndex();
 
6793
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
6794
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
15944
6795
          }
15945
6796
          if (tmp2.length())
15946
6797
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
15952
6803
        item_list.push_back(item_null);
15953
6804
        item_list.push_back(item_null);
15954
6805
      }
15955
 
      
 
6806
 
15956
6807
      /* Add "rows" field to item_list. */
15957
6808
      if (table_list->schema_table)
15958
6809
      {
15959
6810
        /* in_rows */
15960
 
        if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
6811
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
15961
6812
          item_list.push_back(item_null);
15962
6813
        /* rows */
15963
6814
        item_list.push_back(item_null);
15967
6818
        double examined_rows;
15968
6819
        if (tab->select && tab->select->quick)
15969
6820
          examined_rows= rows2double(tab->select->quick->records);
15970
 
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
15971
 
          examined_rows= rows2double(tab->limit ? tab->limit : 
 
6821
        else if (tab->type == AM_NEXT || tab->type == AM_ALL)
 
6822
          examined_rows= rows2double(tab->limit ? tab->limit :
15972
6823
                                     tab->table->file->records());
15973
6824
        else
15974
 
          examined_rows= join->best_positions[i].records_read; 
15975
 
 
15976
 
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows, 
 
6825
        {
 
6826
          optimizer::Position cur_pos= join->getPosFromOptimalPlan(i);
 
6827
          examined_rows= cur_pos.getFanout();
 
6828
        }
 
6829
 
 
6830
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
15977
6831
                                         MY_INT64_NUM_DECIMAL_DIGITS));
15978
6832
 
15979
6833
        /* Add "filtered" field to item_list. */
15980
 
        if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
6834
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
15981
6835
        {
15982
 
          float f= 0.0; 
 
6836
          float f= 0.0;
15983
6837
          if (examined_rows)
15984
 
            f= (float) (100.0 * join->best_positions[i].records_read /
 
6838
          {
 
6839
            optimizer::Position cur_pos= join->getPosFromOptimalPlan(i);
 
6840
            f= (float) (100.0 * cur_pos.getFanout() /
15985
6841
                        examined_rows);
 
6842
          }
15986
6843
          item_list.push_back(new Item_float(f, 2));
15987
6844
        }
15988
6845
      }
15989
6846
 
15990
6847
      /* Build "Extra" field and add it to item_list. */
15991
6848
      bool key_read=table->key_read;
15992
 
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
15993
 
          table->covering_keys.is_set(tab->index))
 
6849
      if ((tab->type == AM_NEXT || tab->type == AM_CONST) &&
 
6850
          table->covering_keys.test(tab->index))
15994
6851
        key_read=1;
15995
6852
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
15996
6853
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
15997
6854
        key_read=1;
15998
 
        
 
6855
 
15999
6856
      if (tab->info)
16000
6857
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
16001
6858
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
16024
6881
        else if (tab->select && tab->select->quick)
16025
6882
          keyno = tab->select->quick->index;
16026
6883
 
16027
 
        if (keyno != MAX_KEY && keyno == table->file->pushed_idx_cond_keyno &&
16028
 
            table->file->pushed_idx_cond)
16029
 
          extra.append(STRING_WITH_LEN("; Using index condition"));
16030
 
 
16031
 
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || 
 
6884
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
16032
6885
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
16033
6886
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
16034
6887
        {
16039
6892
        {
16040
6893
          if (tab->use_quick == 2)
16041
6894
          {
16042
 
            /* 4 bits per 1 hex digit + terminating '\0' */
16043
 
            char buf[MAX_KEY / 4 + 1];
 
6895
            /*
 
6896
             * To print out the bitset in tab->keys, we go through
 
6897
             * it 32 bits at a time. We need to do this to ensure
 
6898
             * that the to_ulong() method will not throw an
 
6899
             * out_of_range exception at runtime which would happen
 
6900
             * if the bitset we were working with was larger than 64
 
6901
             * bits on a 64-bit platform (for example).
 
6902
             */
 
6903
            stringstream s, w;
 
6904
            string str;
 
6905
            w << tab->keys;
 
6906
            w >> str;
 
6907
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
 
6908
            {
 
6909
              bitset<32> tmp(str, pos, 32);
 
6910
              if (tmp.any())
 
6911
                s << uppercase << hex << tmp.to_ulong();
 
6912
            }
16044
6913
            extra.append(STRING_WITH_LEN("; Range checked for each "
16045
6914
                                         "record (index map: 0x"));
16046
 
            extra.append(tab->keys.print(buf));
 
6915
            extra.append(s.str().c_str());
16047
6916
            extra.append(')');
16048
6917
          }
16049
6918
          else if (tab->select->cond)
16050
6919
          {
16051
 
            const COND *pushed_cond= tab->table->file->pushed_cond;
16052
 
 
16053
 
            if (thd->variables.engine_condition_pushdown && pushed_cond)
16054
 
            {
16055
 
              extra.append(STRING_WITH_LEN("; Using where with pushed "
16056
 
                                           "condition"));
16057
 
              if (thd->lex->describe & DESCRIBE_EXTENDED)
16058
 
              {
16059
 
                extra.append(STRING_WITH_LEN(": "));
16060
 
                ((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
16061
 
              }
16062
 
            }
16063
 
            else
16064
 
              extra.append(STRING_WITH_LEN("; Using where"));
 
6920
            extra.append(STRING_WITH_LEN("; Using where"));
16065
6921
          }
16066
6922
        }
16067
6923
        if (key_read)
16073
6929
        }
16074
6930
        if (table->reginfo.not_exists_optimize)
16075
6931
          extra.append(STRING_WITH_LEN("; Not exists"));
16076
 
          
16077
 
        if (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE &&
16078
 
            !(((QUICK_RANGE_SELECT*)(tab->select->quick))->mrr_flags &
16079
 
             HA_MRR_USE_DEFAULT_IMPL))
16080
 
        {
16081
 
          extra.append(STRING_WITH_LEN("; Using MRR"));
16082
 
        }
16083
6932
 
16084
6933
        if (table_list->schema_table &&
16085
 
            table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
6934
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
16086
6935
        {
16087
6936
          if (!table_list->table_open_method)
16088
6937
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
16109
6958
          need_order=0;
16110
6959
          extra.append(STRING_WITH_LEN("; Using filesort"));
16111
6960
        }
16112
 
        if (distinct & test_all_bits(used_tables,thd->used_tables))
 
6961
        if (distinct & test_all_bits(used_tables,session->used_tables))
16113
6962
          extra.append(STRING_WITH_LEN("; Distinct"));
16114
6963
 
16115
6964
        if (tab->insideout_match_tab)
16117
6966
          extra.append(STRING_WITH_LEN("; LooseScan"));
16118
6967
        }
16119
6968
 
16120
 
        if (tab->flush_weedout_table)
16121
 
          extra.append(STRING_WITH_LEN("; Start temporary"));
16122
 
        else if (tab->check_weed_out_table)
16123
 
          extra.append(STRING_WITH_LEN("; End temporary"));
16124
 
        else if (tab->do_firstmatch)
16125
 
        {
16126
 
          extra.append(STRING_WITH_LEN("; FirstMatch("));
16127
 
          Table *prev_table=tab->do_firstmatch->table;
16128
 
          if (prev_table->derived_select_number)
16129
 
          {
16130
 
            char namebuf[NAME_LEN];
16131
 
            /* Derived table name generation */
16132
 
            int len= snprintf(namebuf, sizeof(namebuf)-1,
16133
 
                              "<derived%u>",
16134
 
                              prev_table->derived_select_number);
16135
 
            extra.append(namebuf, len);
16136
 
          }
16137
 
          else
16138
 
            extra.append(prev_table->pos_in_table_list->alias);
16139
 
          extra.append(STRING_WITH_LEN(")"));
16140
 
        }
16141
 
 
16142
6969
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
16143
6970
        {
16144
6971
          if (tab->ref.cond_guards[part])
16167
6994
        join->error= 1;
16168
6995
    }
16169
6996
  }
16170
 
  for (SELECT_LEX_UNIT *unit= join->select_lex->first_inner_unit();
 
6997
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
16171
6998
       unit;
16172
6999
       unit= unit->next_unit())
16173
7000
  {
16174
 
    if (mysql_explain_union(thd, unit, result))
 
7001
    if (mysql_explain_union(session, unit, result))
16175
7002
      return;
16176
7003
  }
16177
7004
  return;
16178
7005
}
16179
7006
 
16180
 
 
16181
 
bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result)
 
7007
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
16182
7008
{
16183
 
  bool res= 0;
16184
 
  SELECT_LEX *first= unit->first_select();
 
7009
  bool res= false;
 
7010
  Select_Lex *first= unit->first_select();
16185
7011
 
16186
 
  for (SELECT_LEX *sl= first;
 
7012
  for (Select_Lex *sl= first;
16187
7013
       sl;
16188
7014
       sl= sl->next_select())
16189
7015
  {
16190
7016
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
16191
7017
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
16192
 
    sl->type= (((&thd->lex->select_lex)==sl)?
16193
 
               (sl->first_inner_unit() || sl->next_select() ? 
 
7018
    sl->type= (((&session->lex->select_lex)==sl)?
 
7019
               (sl->first_inner_unit() || sl->next_select() ?
16194
7020
                "PRIMARY" : "SIMPLE"):
16195
7021
               ((sl == first)?
16196
7022
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
16210
7036
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
16211
7037
    unit->fake_select_lex->type= "UNION RESULT";
16212
7038
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
16213
 
    if (!(res= unit->prepare(thd, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
7039
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
16214
7040
      res= unit->exec();
16215
7041
    res|= unit->cleanup();
16216
7042
  }
16217
7043
  else
16218
7044
  {
16219
 
    thd->lex->current_select= first;
 
7045
    session->lex->current_select= first;
16220
7046
    unit->set_limit(unit->global_parameters);
16221
 
    res= mysql_select(thd, &first->ref_pointer_array,
 
7047
    res= mysql_select(session, &first->ref_pointer_array,
16222
7048
                        (TableList*) first->table_list.first,
16223
7049
                        first->with_wild, first->item_list,
16224
7050
                        first->where,
16227
7053
                        (order_st*) first->order_list.first,
16228
7054
                        (order_st*) first->group_list.first,
16229
7055
                        first->having,
16230
 
                        (order_st*) thd->lex->proc_list.first,
16231
 
                        first->options | thd->options | SELECT_DESCRIBE,
 
7056
                        first->options | session->options | SELECT_DESCRIBE,
16232
7057
                        result, unit, first);
16233
7058
  }
16234
 
  return(res || thd->is_error());
 
7059
  return(res || session->is_error());
16235
7060
}
16236
7061
 
16237
 
 
16238
 
static void print_table_array(THD *thd, String *str, TableList **table, 
 
7062
static void print_table_array(Session *session, String *str, TableList **table,
16239
7063
                              TableList **end)
16240
7064
{
16241
 
  (*table)->print(thd, str, QT_ORDINARY);
 
7065
  (*table)->print(session, str, QT_ORDINARY);
16242
7066
 
16243
7067
  for (TableList **tbl= table + 1; tbl < end; tbl++)
16244
7068
  {
16250
7074
    }
16251
7075
    else if (curr->straight)
16252
7076
      str->append(STRING_WITH_LEN(" straight_join "));
16253
 
    else if (curr->sj_inner_tables)
16254
 
      str->append(STRING_WITH_LEN(" semi join "));
16255
7077
    else
16256
7078
      str->append(STRING_WITH_LEN(" join "));
16257
 
    curr->print(thd, str, QT_ORDINARY);
 
7079
    curr->print(session, str, QT_ORDINARY);
16258
7080
    if (curr->on_expr)
16259
7081
    {
16260
7082
      str->append(STRING_WITH_LEN(" on("));
16264
7086
  }
16265
7087
}
16266
7088
 
16267
 
 
16268
7089
/**
16269
7090
  Print joins from the FROM clause.
16270
 
  @param thd     thread handler
 
7091
  @param session     thread handler
16271
7092
  @param str     string where table should be printed
16272
7093
  @param tables  list of tables in join
16273
7094
  @query_type    type of the query is being generated
16274
7095
*/
16275
 
 
16276
 
static void print_join(THD *thd,
16277
 
                       String *str,
16278
 
                       List<TableList> *tables,
16279
 
                       enum_query_type query_type __attribute__((unused)))
 
7096
void print_join(Session *session, String *str,
 
7097
                List<TableList> *tables, enum_query_type)
16280
7098
{
16281
7099
  /* List is reversed => we should reverse it before using */
16282
7100
  List_iterator_fast<TableList> ti(*tables);
16283
 
  TableList **table= (TableList **)thd->alloc(sizeof(TableList*) *
 
7101
  TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
16284
7102
                                                tables->elements);
16285
7103
  if (table == 0)
16286
7104
    return;  // out of memory
16287
7105
 
16288
7106
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
16289
7107
    *t= ti++;
16290
 
  
16291
 
  /* 
16292
 
    If the first table is a semi-join nest, swap it with something that is
16293
 
    not a semi-join nest.
16294
 
  */
16295
 
  if ((*table)->sj_inner_tables)
16296
 
  {
16297
 
    TableList **end= table + tables->elements;
16298
 
    for (TableList **t2= table; t2!=end; t2++)
16299
 
    {
16300
 
      if (!(*t2)->sj_inner_tables)
16301
 
      {
16302
 
        TableList *tmp= *t2;
16303
 
        *t2= *table;
16304
 
        *table= tmp;
16305
 
        break;
16306
 
      }
16307
 
    }
16308
 
  }
16309
7108
  assert(tables->elements >= 1);
16310
 
  print_table_array(thd, str, table, table + tables->elements);
16311
 
}
16312
 
 
16313
 
 
16314
 
/**
16315
 
  @brief Print an index hint
16316
 
 
16317
 
  @details Prints out the USE|FORCE|IGNORE index hint.
16318
 
 
16319
 
  @param      thd         the current thread
16320
 
  @param[out] str         appends the index hint here
16321
 
  @param      hint        what the hint is (as string : "USE INDEX"|
16322
 
                          "FORCE INDEX"|"IGNORE INDEX")
16323
 
  @param      hint_length the length of the string in 'hint'
16324
 
  @param      indexes     a list of index names for the hint
16325
 
*/
16326
 
 
16327
 
void 
16328
 
Index_hint::print(THD *thd, String *str)
16329
 
{
16330
 
  switch (type)
16331
 
  {
16332
 
    case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
16333
 
    case INDEX_HINT_USE:    str->append(STRING_WITH_LEN("USE INDEX")); break;
16334
 
    case INDEX_HINT_FORCE:  str->append(STRING_WITH_LEN("FORCE INDEX")); break;
16335
 
  }
16336
 
  str->append (STRING_WITH_LEN(" ("));
16337
 
  if (key_name.length)
16338
 
  {
16339
 
    if (thd && !my_strnncoll(system_charset_info,
16340
 
                             (const unsigned char *)key_name.str, key_name.length, 
16341
 
                             (const unsigned char *)primary_key_name, 
16342
 
                             strlen(primary_key_name)))
16343
 
      str->append(primary_key_name);
16344
 
    else
16345
 
      append_identifier(thd, str, key_name.str, key_name.length);
16346
 
  }
16347
 
  str->append(')');
16348
 
}
16349
 
 
16350
 
 
16351
 
/**
16352
 
  Print table as it should be in join list.
16353
 
 
16354
 
  @param str   string where table should be printed
16355
 
*/
16356
 
 
16357
 
void TableList::print(THD *thd, String *str, enum_query_type query_type)
16358
 
{
16359
 
  if (nested_join)
16360
 
  {
16361
 
    str->append('(');
16362
 
    print_join(thd, str, &nested_join->join_list, query_type);
16363
 
    str->append(')');
16364
 
  }
16365
 
  else
16366
 
  {
16367
 
    const char *cmp_name;                         // Name to compare with alias
16368
 
    if (derived)
16369
 
    {
16370
 
      // A derived table
16371
 
      str->append('(');
16372
 
      derived->print(str, query_type);
16373
 
      str->append(')');
16374
 
      cmp_name= "";                               // Force printing of alias
16375
 
    }
16376
 
    else
16377
 
    {
16378
 
      // A normal table
16379
 
      {
16380
 
        append_identifier(thd, str, db, db_length);
16381
 
        str->append('.');
16382
 
      }
16383
 
      if (schema_table)
16384
 
      {
16385
 
        append_identifier(thd, str, schema_table_name,
16386
 
                          strlen(schema_table_name));
16387
 
        cmp_name= schema_table_name;
16388
 
      }
16389
 
      else
16390
 
      {
16391
 
        append_identifier(thd, str, table_name, table_name_length);
16392
 
        cmp_name= table_name;
16393
 
      }
16394
 
    }
16395
 
    if (my_strcasecmp(table_alias_charset, cmp_name, alias))
16396
 
    {
16397
 
      char t_alias_buff[MAX_ALIAS_NAME];
16398
 
      const char *t_alias= alias;
16399
 
 
16400
 
      str->append(' ');
16401
 
      if (lower_case_table_names== 1)
16402
 
      {
16403
 
        if (alias && alias[0])
16404
 
        {
16405
 
          my_stpcpy(t_alias_buff, alias);
16406
 
          my_casedn_str(files_charset_info, t_alias_buff);
16407
 
          t_alias= t_alias_buff;
16408
 
        }
16409
 
      }
16410
 
 
16411
 
      append_identifier(thd, str, t_alias, strlen(t_alias));
16412
 
    }
16413
 
 
16414
 
    if (index_hints)
16415
 
    {
16416
 
      List_iterator<Index_hint> it(*index_hints);
16417
 
      Index_hint *hint;
16418
 
 
16419
 
      while ((hint= it++))
16420
 
      {
16421
 
        str->append (STRING_WITH_LEN(" "));
16422
 
        hint->print (thd, str);
16423
 
      }
16424
 
    }
16425
 
  }
16426
 
}
16427
 
 
16428
 
 
16429
 
void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
16430
 
{
16431
 
  /* QQ: thd may not be set for sub queries, but this should be fixed */
16432
 
  if (!thd)
16433
 
    thd= current_thd;
 
7109
  print_table_array(session, str, table, table + tables->elements);
 
7110
}
 
7111
 
 
7112
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
 
7113
{
 
7114
  /* QQ: session may not be set for sub queries, but this should be fixed */
 
7115
  if (!session)
 
7116
    session= current_session;
16434
7117
 
16435
7118
  str->append(STRING_WITH_LEN("select "));
16436
7119
 
16437
7120
  /* First add options */
16438
7121
  if (options & SELECT_STRAIGHT_JOIN)
16439
7122
    str->append(STRING_WITH_LEN("straight_join "));
16440
 
  if ((thd->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
16441
 
      (this == &thd->lex->select_lex))
16442
 
    str->append(STRING_WITH_LEN("high_priority "));
16443
7123
  if (options & SELECT_DISTINCT)
16444
7124
    str->append(STRING_WITH_LEN("distinct "));
16445
7125
  if (options & SELECT_SMALL_RESULT)
16472
7152
  {
16473
7153
    str->append(STRING_WITH_LEN(" from "));
16474
7154
    /* go through join tree */
16475
 
    print_join(thd, str, &top_join_list, query_type);
 
7155
    print_join(session, str, &top_join_list, query_type);
16476
7156
  }
16477
7157
  else if (where)
16478
7158
  {
16479
7159
    /*
16480
 
      "SELECT 1 FROM DUAL WHERE 2" should not be printed as 
 
7160
      "SELECT 1 FROM DUAL WHERE 2" should not be printed as
16481
7161
      "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
16482
7162
    */
16483
7163
    str->append(STRING_WITH_LEN(" from DUAL "));
16535
7215
  }
16536
7216
 
16537
7217
  // limit
16538
 
  print_limit(thd, str, query_type);
 
7218
  print_limit(session, str, query_type);
16539
7219
 
16540
7220
  // PROCEDURE unsupported here
16541
7221
}
16542
7222
 
16543
 
 
16544
 
/**
16545
 
  change select_result object of JOIN.
16546
 
 
16547
 
  @param res            new select_result object
16548
 
 
16549
 
  @retval
16550
 
    false   OK
16551
 
  @retval
16552
 
    true    error
16553
 
*/
16554
 
 
16555
 
bool JOIN::change_result(select_result *res)
16556
 
{
16557
 
  result= res;
16558
 
  if (result->prepare(fields_list, select_lex->master_unit()) ||
16559
 
                     result->prepare2())
16560
 
  {
16561
 
    return(true);
16562
 
  }
16563
 
  return(false);
16564
 
}
16565
 
 
16566
7223
/**
16567
7224
  @} (end of group Query_Optimizer)
16568
7225
*/