~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/sql_select.cc

  • Committer: Patrick Galbraith
  • Date: 2008-07-24 16:57:40 UTC
  • mto: (202.2.4 rename-mysql-to-drizzle)
  • mto: This revision was merged to the branch mainline in revision 212.
  • Revision ID: patg@ishvara-20080724165740-x58yw6zs6d9o17lf
Most everything working with client rename
mysqlslap test still fails... can't connect to the server

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
  @defgroup Query_Optimizer  Query Optimizer
24
24
  @{
25
25
*/
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
 
#include <drizzled/util/test.h>
 
26
 
 
27
#ifdef USE_PRAGMA_IMPLEMENTATION
 
28
#pragma implementation                          // gcc: Class implementation
 
29
#endif
 
30
 
 
31
#include "mysql_priv.h"
 
32
#include "sql_select.h"
 
33
 
 
34
#include <m_ctype.h>
 
35
#include <my_bit.h>
 
36
#include <hash.h>
34
37
 
35
38
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
36
39
                              "MAYBE_REF","ALL","range","index",
41
44
struct st_sargable_param;
42
45
 
43
46
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
44
 
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
 
47
static bool make_join_statistics(JOIN *join, TABLE_LIST *leaves, COND *conds,
45
48
                                 DYNAMIC_ARRAY *keyuse);
46
49
static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
47
50
                                JOIN_TAB *join_tab,
48
 
                                uint32_t tables, COND *conds,
 
51
                                uint tables, COND *conds,
49
52
                                COND_EQUAL *cond_equal,
50
53
                                table_map table_map, SELECT_LEX *select_lex,
51
54
                                st_sargable_param **sargables);
52
55
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
53
 
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
 
56
static void set_position(JOIN *join,uint index,JOIN_TAB *table,KEYUSE *key);
54
57
static bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
55
58
                               table_map used_tables);
56
59
static bool choose_plan(JOIN *join,table_map join_tables);
57
60
 
58
61
static void best_access_path(JOIN *join, JOIN_TAB *s, THD *thd,
59
 
                             table_map remaining_tables, uint32_t idx,
 
62
                             table_map remaining_tables, uint idx,
60
63
                             double record_count, double read_time);
61
64
static void optimize_straight_join(JOIN *join, table_map join_tables);
62
65
static bool greedy_search(JOIN *join, table_map remaining_tables,
63
 
                             uint32_t depth, uint32_t prune_level);
 
66
                             uint depth, uint prune_level);
64
67
static bool best_extension_by_limited_search(JOIN *join,
65
68
                                             table_map remaining_tables,
66
 
                                             uint32_t idx, double record_count,
67
 
                                             double read_time, uint32_t depth,
68
 
                                             uint32_t prune_level);
69
 
static uint32_t determine_search_depth(JOIN* join);
 
69
                                             uint idx, double record_count,
 
70
                                             double read_time, uint depth,
 
71
                                             uint prune_level);
 
72
static uint determine_search_depth(JOIN* join);
70
73
static int join_tab_cmp(const void* ptr1, const void* ptr2);
71
74
static int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
72
75
/*
73
76
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
74
77
  tested and approved.
75
78
*/
76
 
static bool find_best(JOIN *join,table_map rest_tables,uint32_t index,
 
79
static bool find_best(JOIN *join,table_map rest_tables,uint index,
77
80
                      double record_count,double read_time);
78
 
static uint32_t cache_record_length(JOIN *join,uint32_t index);
79
 
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
 
81
static uint cache_record_length(JOIN *join,uint index);
 
82
static double prev_record_reads(JOIN *join, uint idx, table_map found_ref);
80
83
static bool get_best_combination(JOIN *join);
81
84
static store_key *get_store_key(THD *thd,
82
85
                                KEYUSE *keyuse, table_map used_tables,
83
 
                                KEY_PART_INFO *key_part, unsigned char *key_buff,
84
 
                                uint32_t maybe_null);
85
 
static bool make_simple_join(JOIN *join,Table *tmp_table);
 
86
                                KEY_PART_INFO *key_part, uchar *key_buff,
 
87
                                uint maybe_null);
 
88
static bool make_simple_join(JOIN *join,TABLE *tmp_table);
86
89
static void make_outerjoin_info(JOIN *join);
87
90
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
88
 
static bool make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after);
89
 
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
 
91
static bool make_join_readinfo(JOIN *join, uint64_t options, uint no_jbuf_after);
 
92
static bool only_eq_ref_tables(JOIN *join, ORDER *order, table_map tables);
90
93
static void update_depend_map(JOIN *join);
91
 
static void update_depend_map(JOIN *join, order_st *order);
92
 
static order_st *remove_const(JOIN *join,order_st *first_order,COND *cond,
 
94
static void update_depend_map(JOIN *join, ORDER *order);
 
95
static ORDER *remove_const(JOIN *join,ORDER *first_order,COND *cond,
93
96
                           bool change_list, bool *simple_order);
94
 
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
 
97
static int return_zero_rows(JOIN *join, select_result *res,TABLE_LIST *tables,
95
98
                            List<Item> &fields, bool send_row,
96
99
                            uint64_t select_options, const char *info,
97
100
                            Item *having);
98
101
static COND *build_equal_items(THD *thd, COND *cond,
99
102
                               COND_EQUAL *inherited,
100
 
                               List<TableList> *join_list,
 
103
                               List<TABLE_LIST> *join_list,
101
104
                               COND_EQUAL **cond_equal_ref);
102
105
static COND* substitute_for_best_equal_field(COND *cond,
103
106
                                             COND_EQUAL *cond_equal,
104
107
                                             void *table_join_idx);
105
 
static COND *simplify_joins(JOIN *join, List<TableList> *join_list,
 
108
static COND *simplify_joins(JOIN *join, List<TABLE_LIST> *join_list,
106
109
                            COND *conds, bool top, bool in_sj);
107
110
static bool check_interleaving_with_nj(JOIN_TAB *last, JOIN_TAB *next);
108
111
static void restore_prev_nj_state(JOIN_TAB *last);
109
 
static void reset_nj_counters(List<TableList> *join_list);
110
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
111
 
                                          uint32_t first_unused);
 
112
static void reset_nj_counters(List<TABLE_LIST> *join_list);
 
113
static uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list,
 
114
                                          uint first_unused);
112
115
 
113
116
static 
114
117
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab);
116
119
                                  const JOIN_TAB *tab);
117
120
 
118
121
static COND *optimize_cond(JOIN *join, COND *conds,
119
 
                           List<TableList> *join_list,
 
122
                           List<TABLE_LIST> *join_list,
120
123
                           Item::cond_result *cond_value);
121
124
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
122
 
static int do_select(JOIN *join,List<Item> *fields,Table *tmp_table);
 
125
static bool open_tmp_table(TABLE *table);
 
126
static bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo, 
 
127
                                    MI_COLUMNDEF *start_recinfo,
 
128
                                    MI_COLUMNDEF **recinfo,
 
129
                                    uint64_t options);
 
130
static int do_select(JOIN *join,List<Item> *fields,TABLE *tmp_table);
123
131
 
124
132
static enum_nested_loop_state
125
133
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
160
168
static COND *make_cond_for_table(COND *cond,table_map table,
161
169
                                 table_map used_table,
162
170
                                 bool exclude_expensive_cond);
163
 
static Item* part_of_refkey(Table *form,Field *field);
164
 
static bool test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,
 
171
static Item* part_of_refkey(TABLE *form,Field *field);
 
172
static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,
165
173
                                    ha_rows select_limit, bool no_changes,
166
174
                                    const key_map *map);
167
 
static bool list_contains_unique_index(Table *table,
 
175
static bool list_contains_unique_index(TABLE *table,
168
176
                          bool (*find_func) (Field *, void *), void *data);
169
177
static bool find_field_in_item_list (Field *field, void *data);
170
178
static bool find_field_in_order_list (Field *field, void *data);
171
 
static int create_sort_index(THD *thd, JOIN *join, order_st *order,
 
179
static int create_sort_index(THD *thd, JOIN *join, ORDER *order,
172
180
                             ha_rows filesort_limit, ha_rows select_limit,
173
181
                             bool is_order_by);
174
 
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
 
182
static int remove_duplicates(JOIN *join,TABLE *entry,List<Item> &fields,
175
183
                             Item *having);
176
 
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
 
184
static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field,
177
185
                                   ulong offset,Item *having);
178
 
static int remove_dup_with_hash_index(THD *thd,Table *table,
179
 
                                      uint32_t field_count, Field **first_field,
 
186
static int remove_dup_with_hash_index(THD *thd,TABLE *table,
 
187
                                      uint field_count, Field **first_field,
180
188
 
181
189
                                      ulong key_length,Item *having);
182
 
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count);
 
190
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count);
183
191
static ulong used_blob_length(CACHE_FIELD **ptr);
184
192
static bool store_record_in_cache(JOIN_CACHE *cache);
185
193
static void reset_cache_read(JOIN_CACHE *cache);
186
194
static void reset_cache_write(JOIN_CACHE *cache);
187
195
static void read_cached_record(JOIN_TAB *tab);
188
196
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
189
 
static order_st *create_distinct_group(THD *thd, Item **ref_pointer_array,
190
 
                                    order_st *order, List<Item> &fields,
 
197
static ORDER *create_distinct_group(THD *thd, Item **ref_pointer_array,
 
198
                                    ORDER *order, List<Item> &fields,
191
199
                                    List<Item> &all_fields,
192
200
                                    bool *all_order_by_fields_used);
193
 
static bool test_if_subpart(order_st *a,order_st *b);
194
 
static Table *get_sort_by_table(order_st *a,order_st *b,TableList *tables);
195
 
static void calc_group_buffer(JOIN *join,order_st *group);
 
201
static bool test_if_subpart(ORDER *a,ORDER *b);
 
202
static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
 
203
static void calc_group_buffer(JOIN *join,ORDER *group);
196
204
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
197
 
static bool alloc_group_fields(JOIN *join,order_st *group);
 
205
static bool alloc_group_fields(JOIN *join,ORDER *group);
198
206
// Create list for using with tempory table
199
207
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
200
208
                                     List<Item> &new_list1,
201
209
                                     List<Item> &new_list2,
202
 
                                     uint32_t elements, List<Item> &items);
 
210
                                     uint elements, List<Item> &items);
203
211
// Create list for using with tempory table
204
212
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
205
213
                                      List<Item> &new_list1,
206
214
                                      List<Item> &new_list2,
207
 
                                      uint32_t elements, List<Item> &items);
 
215
                                      uint elements, List<Item> &items);
208
216
static void init_tmptable_sum_functions(Item_sum **func);
209
 
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
 
217
static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table);
210
218
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
211
219
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
212
220
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
213
221
static bool init_sum_functions(Item_sum **func, Item_sum **end);
214
222
static bool update_sum_func(Item_sum **func);
215
223
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
216
 
                            bool distinct, const char *message=NULL);
 
224
                            bool distinct, const char *message=NullS);
217
225
static Item *remove_additional_cond(Item* conds);
218
226
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
219
227
static bool test_if_ref(Item_field *left_item,Item *right_item);
242
250
{
243
251
  bool res;
244
252
  register SELECT_LEX *select_lex = &lex->select_lex;
245
 
  DRIZZLE_SELECT_START();
 
253
  MYSQL_SELECT_START();
246
254
 
247
255
  if (select_lex->master_unit()->is_union() || 
248
256
      select_lex->master_unit()->fake_select_lex)
258
266
      setup_tables_done_option changed for next rexecution
259
267
    */
260
268
    res= mysql_select(thd, &select_lex->ref_pointer_array,
261
 
                      (TableList*) select_lex->table_list.first,
 
269
                      (TABLE_LIST*) select_lex->table_list.first,
262
270
                      select_lex->with_wild, select_lex->item_list,
263
271
                      select_lex->where,
264
272
                      select_lex->order_list.elements +
265
273
                      select_lex->group_list.elements,
266
 
                      (order_st*) select_lex->order_list.first,
267
 
                      (order_st*) select_lex->group_list.first,
 
274
                      (ORDER*) select_lex->order_list.first,
 
275
                      (ORDER*) select_lex->group_list.first,
268
276
                      select_lex->having,
269
 
                      (order_st*) lex->proc_list.first,
 
277
                      (ORDER*) lex->proc_list.first,
270
278
                      select_lex->options | thd->options |
271
279
                      setup_tables_done_option,
272
280
                      result, unit, select_lex);
275
283
  if (unlikely(res))
276
284
    result->abort();
277
285
 
278
 
  DRIZZLE_SELECT_END();
 
286
  MYSQL_SELECT_END();
279
287
  return(res);
280
288
}
281
289
 
395
403
  Function to setup clauses without sum functions.
396
404
*/
397
405
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
398
 
                               TableList *tables,
399
 
                               TableList *leaves,
 
406
                               TABLE_LIST *tables,
 
407
                               TABLE_LIST *leaves,
400
408
                               List<Item> &fields,
401
409
                               List<Item> &all_fields,
402
410
                               COND **conds,
403
 
                               order_st *order,
404
 
                               order_st *group, bool *hidden_group_fields)
 
411
                               ORDER *order,
 
412
                               ORDER *group, bool *hidden_group_fields)
405
413
{
406
414
  int res;
407
415
  nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
438
446
*/
439
447
int
440
448
JOIN::prepare(Item ***rref_pointer_array,
441
 
              TableList *tables_init,
442
 
              uint32_t wild_num, COND *conds_init, uint32_t og_num,
443
 
              order_st *order_init, order_st *group_init,
 
449
              TABLE_LIST *tables_init,
 
450
              uint wild_num, COND *conds_init, uint og_num,
 
451
              ORDER *order_init, ORDER *group_init,
444
452
              Item *having_init,
445
 
              order_st *proc_param_init, SELECT_LEX *select_lex_arg,
 
453
              ORDER *proc_param_init, SELECT_LEX *select_lex_arg,
446
454
              SELECT_LEX_UNIT *unit_arg)
447
455
{
448
456
  // to prevent double initialization on EXPLAIN
476
484
                                    false))
477
485
      return(-1);
478
486
 
479
 
  TableList *table_ptr;
 
487
  TABLE_LIST *table_ptr;
480
488
  for (table_ptr= select_lex->leaf_tables;
481
489
       table_ptr;
482
490
       table_ptr= table_ptr->next_leaf)
529
537
        requirements are:
530
538
          1. Subquery predicate is an IN/=ANY subq predicate
531
539
          2. Subquery is a single SELECT (not a UNION)
532
 
          3. Subquery does not have GROUP BY or order_st BY
 
540
          3. Subquery does not have GROUP BY or ORDER BY
533
541
          4. Subquery does not use aggregate functions or HAVING
534
542
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
535
543
          6. No execution method was already chosen (by a prepared statement).
572
580
 
573
581
        /* Register the subquery for further processing */
574
582
        select_lex->outer_select()->join->sj_subselects.append(thd->mem_root, in_subs);
575
 
        in_subs->expr_join_nest= (TableList*)thd->thd_marker;
 
583
        in_subs->expr_join_nest= (TABLE_LIST*)thd->thd_marker;
576
584
      }
577
585
      else
578
586
      {
595
603
             (Subquery is non-correlated ||
596
604
              Subquery is correlated to any query outer to IN predicate ||
597
605
              (Subquery is correlated to the immediate outer query &&
598
 
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
 
606
               Subquery !contains {GROUP BY, ORDER BY [LIMIT],
599
607
               aggregate functions) && subquery predicate is not under "NOT IN"))
600
608
          6. No execution method was already chosen (by a prepared statement).
601
609
 
631
639
 
632
640
  if (order)
633
641
  {
634
 
    order_st *ord;
 
642
    ORDER *ord;
635
643
    for (ord= order; ord; ord= ord->next)
636
644
    {
637
645
      Item *item= *ord->item;
674
682
  {
675
683
    /* Caclulate the number of groups */
676
684
    send_group_parts= 0;
677
 
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
685
    for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
678
686
      send_group_parts++;
679
687
  }
680
688
  
780
788
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
781
789
  if (where)
782
790
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
783
 
  for (uint32_t i = 0; i < join_tab->ref.key_parts; i++)
 
791
  for (uint i = 0; i < join_tab->ref.key_parts; i++)
784
792
  {
785
793
    if (join_tab->ref.cond_guards[i])
786
794
    {
826
834
  /* Check if this table is functionally dependent on the tables that
827
835
     are within the same outer join nest
828
836
  */
829
 
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
 
837
  TABLE_LIST *embedding= join_tab->table->pos_in_table_list->embedding;
830
838
  if (join_tab->type == JT_EQ_REF)
831
839
  {
832
840
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
833
 
    uint32_t idx;
 
841
    uint idx;
834
842
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
835
843
    {
836
844
      JOIN_TAB *ref_tab= join->join_tab + idx;
845
853
}
846
854
 
847
855
 
 
856
TABLE *create_duplicate_weedout_tmp_table(THD *thd, uint uniq_tuple_length_arg,
 
857
                                          SJ_TMP_TABLE *sjtbl);
 
858
 
 
859
 
848
860
/*
849
861
  Setup the strategies to eliminate semi-join duplicates.
850
862
  
942
954
*/
943
955
 
944
956
static
945
 
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
957
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint no_jbuf_after)
946
958
{
947
959
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
948
960
  struct {
952
964
      2 - Temptable (maybe confluent),
953
965
      3 - Temptable with join buffering
954
966
    */
955
 
    uint32_t strategy;
956
 
    uint32_t start_idx; /* Left range bound */
957
 
    uint32_t end_idx;   /* Right range bound */
 
967
    uint strategy;
 
968
    uint start_idx; /* Left range bound */
 
969
    uint end_idx;   /* Right range bound */
958
970
    /* 
959
971
      For Temptable strategy: Bitmap of all outer and correlated tables from 
960
972
      all involved join nests.
962
974
    table_map outer_tables;
963
975
  } dups_ranges [MAX_TABLES];
964
976
 
965
 
  TableList *emb_insideout_nest= NULL;
 
977
  TABLE_LIST *emb_insideout_nest= NULL;
966
978
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
967
979
                               tables) whose ranges we're in */
968
980
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
969
981
  table_map range_start_map= 0; /* table_map at current range start */
970
982
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
971
983
  int cur_range= 0;
972
 
  uint32_t i;
 
984
  uint i;
973
985
 
974
986
  /*
975
987
    First pass: locate the duplicate-generating ranges and pick the strategies.
977
989
  for (i=join->const_tables ; i < join->tables ; i++)
978
990
  {
979
991
    JOIN_TAB *tab=join->join_tab+i;
980
 
    Table *table=tab->table;
 
992
    TABLE *table=tab->table;
981
993
    cur_map |= table->map;
982
994
 
983
995
    if (tab->emb_sj_nest) // Encountered an sj-inner table
1110
1122
    {
1111
1123
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
1112
1124
      table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
1113
 
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
1114
 
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
 
1125
      uint jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
 
1126
      uint jt_null_bits= 0;    // # null bits in tuple bytes
1115
1127
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
1116
 
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
 
1128
      uint rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
1117
1129
      JOIN_TAB *last_outer_tab= tab - 1;
1118
1130
      /*
1119
1131
        Walk through the range and remember
1145
1157
      if (jt_rowid_offset) /* Temptable has at least one rowid */
1146
1158
      {
1147
1159
        SJ_TMP_TABLE *sjtbl;
1148
 
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
 
1160
        uint tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
1149
1161
        if (!(sjtbl= (SJ_TMP_TABLE*)thd->alloc(sizeof(SJ_TMP_TABLE))) ||
1150
1162
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) thd->alloc(tabs_size)))
1151
1163
          return(true);
1192
1204
  {
1193
1205
    if (sj_tbl->tmp_table)
1194
1206
    {
1195
 
      sj_tbl->tmp_table->free_tmp_table(join->thd);
 
1207
      free_tmp_table(join->thd, sj_tbl->tmp_table);
1196
1208
    }
1197
1209
  }
1198
1210
  join->sj_tmp_tables= NULL;
1199
1211
}
1200
1212
 
1201
 
uint32_t make_join_orderinfo(JOIN *join);
 
1213
uint make_join_orderinfo(JOIN *join);
1202
1214
 
1203
1215
/**
1204
1216
  global select optimisation.
1220
1232
    return(0);
1221
1233
  optimized= 1;
1222
1234
 
1223
 
  thd->set_proc_info("optimizing");
 
1235
  thd_proc_info(thd, "optimizing");
1224
1236
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
1225
1237
              unit->select_limit_cnt);
1226
1238
  /* select_limit is used to decide if we are likely to scan the whole table */
1254
1266
    }
1255
1267
  }
1256
1268
#endif
 
1269
  SELECT_LEX *sel= thd->lex->current_select;
 
1270
  if (sel->first_cond_optimization)
 
1271
  {
 
1272
    /*
 
1273
      The following code will allocate the new items in a permanent
 
1274
      MEMROOT for prepared statements and stored procedures.
 
1275
    */
 
1276
    sel->first_cond_optimization= 0;
1257
1277
 
1258
 
  /* Convert all outer joins to inner joins if possible */
1259
 
  conds= simplify_joins(this, join_list, conds, true, false);
1260
 
  build_bitmap_for_nested_joins(join_list, 0);
 
1278
    /* Convert all outer joins to inner joins if possible */
 
1279
    conds= simplify_joins(this, join_list, conds, true, false);
 
1280
    build_bitmap_for_nested_joins(join_list, 0);
 
1281
  }
1261
1282
 
1262
1283
  conds= optimize_cond(this, conds, join_list, &cond_value);   
1263
1284
  if (thd->is_error())
1288
1309
    }
1289
1310
  }
1290
1311
 
1291
 
  /* Optimize count(*), cmin() and cmax() */
 
1312
  /* Optimize count(*), min() and max() */
1292
1313
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
1293
1314
  {
1294
1315
    int res;
1346
1367
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
1347
1368
 
1348
1369
  /* Calculate how to do the join */
1349
 
  thd->set_proc_info("statistics");
 
1370
  thd_proc_info(thd, "statistics");
1350
1371
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
1351
1372
      thd->is_fatal_error)
1352
1373
  {
1355
1376
 
1356
1377
  /* Remove distinct if only const tables */
1357
1378
  select_distinct= select_distinct && (const_tables != tables);
1358
 
  thd->set_proc_info("preparing");
 
1379
  thd_proc_info(thd, "preparing");
1359
1380
  if (result->initialize_tables(this))
1360
1381
  {
1361
1382
    return(1);                          // error == -1
1441
1462
 
1442
1463
  /* Optimize distinct away if possible */
1443
1464
  {
1444
 
    order_st *org_order= order;
 
1465
    ORDER *org_order= order;
1445
1466
    order=remove_const(this, order,conds,1, &simple_order);
1446
1467
    if (thd->is_error())
1447
1468
    {
1450
1471
    }
1451
1472
 
1452
1473
    /*
1453
 
      If we are using order_st BY NULL or order_st BY const_expression,
 
1474
      If we are using ORDER BY NULL or ORDER BY const_expression,
1454
1475
      return result in any order (even if we are using a GROUP BY)
1455
1476
    */
1456
1477
    if (!order && org_order)
1484
1505
        We have found that grouping can be removed since groups correspond to
1485
1506
        only one row anyway, but we still have to guarantee correct result
1486
1507
        order. The line below effectively rewrites the query from GROUP BY
1487
 
        <fields> to order_st BY <fields>. There are two exceptions:
 
1508
        <fields> to ORDER BY <fields>. There are two exceptions:
1488
1509
        - if skip_sort_order is set (see above), then we can simply skip
1489
1510
          GROUP BY;
1490
 
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
 
1511
        - we can only rewrite ORDER BY if the ORDER BY fields are 'compatible'
1491
1512
          with the GROUP BY ones, i.e. either one is a prefix of another.
1492
 
          We only check if the order_st BY is a prefix of GROUP BY. In this case
 
1513
          We only check if the ORDER BY is a prefix of GROUP BY. In this case
1493
1514
          test_if_subpart() copies the ASC/DESC attributes from the original
1494
 
          order_st BY fields.
1495
 
          If GROUP BY is a prefix of order_st BY, then it is safe to leave
 
1515
          ORDER BY fields.
 
1516
          If GROUP BY is a prefix of ORDER BY, then it is safe to leave
1496
1517
          'order' as is.
1497
1518
       */
1498
1519
      if (!order || test_if_subpart(group_list, order))
1499
1520
          order= skip_sort_order ? 0 : group_list;
1500
1521
      /*
1501
1522
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be 
1502
 
        rewritten to IGNORE INDEX FOR order_st BY(fields).
 
1523
        rewritten to IGNORE INDEX FOR ORDER BY(fields).
1503
1524
      */
1504
1525
      join_tab->table->keys_in_use_for_order_by=
1505
1526
        join_tab->table->keys_in_use_for_group_by;
1524
1545
    /*
1525
1546
      We are only using one table. In this case we change DISTINCT to a
1526
1547
      GROUP BY query if:
1527
 
      - The GROUP BY can be done through indexes (no sort) and the order_st
 
1548
      - The GROUP BY can be done through indexes (no sort) and the ORDER
1528
1549
        BY only uses selected fields.
1529
 
        (In this case we can later optimize away GROUP BY and order_st BY)
 
1550
        (In this case we can later optimize away GROUP BY and ORDER BY)
1530
1551
      - We are scanning the whole table without LIMIT
1531
1552
        This can happen if:
1532
1553
        - We are using CALC_FOUND_ROWS
1533
 
        - We are using an order_st BY that can't be optimized away.
 
1554
        - We are using an ORDER BY that can't be optimized away.
1534
1555
 
1535
1556
      We don't want to use this optimization when we are using LIMIT
1536
1557
      because in this case we can just create a temporary table that
1562
1583
          {
1563
1584
            /*
1564
1585
              Force MySQL to read the table in sorted order to get result in
1565
 
              order_st BY order.
 
1586
              ORDER BY order.
1566
1587
            */
1567
1588
            tmp_table_param.quick_group=0;
1568
1589
          }
1578
1599
  }
1579
1600
  simple_group= 0;
1580
1601
  {
1581
 
    order_st *old_group_list;
 
1602
    ORDER *old_group_list;
1582
1603
    group_list= remove_const(this, (old_group_list= group_list), conds,
1583
1604
                             rollup.state == ROLLUP::STATE_NONE,
1584
1605
                             &simple_group);
1619
1640
    This has to be done if all tables are not already read (const tables)
1620
1641
    and one of the following conditions holds:
1621
1642
    - We are using DISTINCT (simple distinct's are already optimized away)
1622
 
    - We are using an order_st BY or GROUP BY on fields not in the first table
1623
 
    - We are using different order_st BY and GROUP BY orders
 
1643
    - We are using an ORDER BY or GROUP BY on fields not in the first table
 
1644
    - We are using different ORDER BY and GROUP BY orders
1624
1645
    - The user wants us to buffer the result.
1625
1646
  */
1626
1647
  need_tmp= (const_tables != tables &&
1628
1649
              (group_list && order) ||
1629
1650
              test(select_options & OPTION_BUFFER_RESULT)));
1630
1651
 
1631
 
  uint32_t no_jbuf_after= make_join_orderinfo(this);
 
1652
  uint no_jbuf_after= make_join_orderinfo(this);
1632
1653
  uint64_t select_opts_for_readinfo= 
1633
1654
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
1634
1655
 
1712
1733
  */
1713
1734
  if (need_tmp || select_distinct || group_list || order)
1714
1735
  {
1715
 
    for (uint32_t i = const_tables; i < tables; i++)
 
1736
    for (uint i = const_tables; i < tables; i++)
1716
1737
      join_tab[i].table->prepare_for_position();
1717
1738
  }
1718
1739
 
1752
1773
        Force using of tmp table if sorting by a SP or UDF function due to
1753
1774
        their expensive and probably non-deterministic nature.
1754
1775
      */
1755
 
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
1776
      for (ORDER *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
1756
1777
      {
1757
1778
        Item *item= *tmp_order->item;
1758
1779
        if (item->is_expensive())
1790
1811
  /* Create a tmp table if distinct or if the sort is too complicated */
1791
1812
  if (need_tmp)
1792
1813
  {
1793
 
    thd->set_proc_info("Creating tmp table");
 
1814
    thd_proc_info(thd, "Creating tmp table");
1794
1815
 
1795
1816
    init_items_ref_array();
1796
1817
 
1797
1818
    tmp_table_param.hidden_field_count= (all_fields.elements -
1798
1819
                                         fields_list.elements);
1799
 
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
1800
 
                                                             (order_st*) 0);
 
1820
    ORDER *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
 
1821
                                                             (ORDER*) 0);
1801
1822
    /*
1802
1823
      Pushing LIMIT to the temporary table creation is not applicable
1803
 
      when there is order_st BY or GROUP BY or there is no GROUP BY, but
 
1824
      when there is ORDER BY or GROUP BY or there is no GROUP BY, but
1804
1825
      there are aggregate functions, because in all these cases we need
1805
1826
      all result rows.
1806
1827
    */
1838
1859
    /* if group or order on first table, sort first */
1839
1860
    if (group_list && simple_group)
1840
1861
    {
1841
 
      thd->set_proc_info("Sorting for group");
 
1862
      thd_proc_info(thd, "Sorting for group");
1842
1863
      if (create_sort_index(thd, this, group_list,
1843
1864
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
1844
1865
          alloc_group_fields(this, group_list) ||
1859
1880
 
1860
1881
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1861
1882
      {
1862
 
        thd->set_proc_info("Sorting for order");
 
1883
        thd_proc_info(thd, "Sorting for order");
1863
1884
        if (create_sort_index(thd, this, order,
1864
1885
                              HA_POS_ERROR, HA_POS_ERROR, true))
1865
1886
        {
1925
1946
{
1926
1947
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1927
1948
                                    select_lex->offset_limit->val_uint() :
1928
 
                                    0UL);
 
1949
                                    0ULL);
1929
1950
 
1930
1951
  first_record= 0;
1931
1952
 
1990
2011
{
1991
2012
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1992
2013
  {
1993
 
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((unsigned char*) join_tab,
 
2014
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((uchar*) join_tab,
1994
2015
                                                sizeof(JOIN_TAB) * tables)))
1995
2016
      return 1;
1996
2017
  }
2015
2036
  List<Item> *columns_list= &fields_list;
2016
2037
  int      tmp_error;
2017
2038
 
2018
 
  thd->set_proc_info("executing");
 
2039
  thd_proc_info(thd, "executing");
2019
2040
  error= 0;
2020
2041
  (void) result->prepare2(); // Currently, this cannot fail.
2021
2042
 
2083
2104
  if (select_options & SELECT_DESCRIBE)
2084
2105
  {
2085
2106
    /*
2086
 
      Check if we managed to optimize order_st BY away and don't use temporary
2087
 
      table to resolve order_st BY: in that case, we only may need to do
 
2107
      Check if we managed to optimize ORDER BY away and don't use temporary
 
2108
      table to resolve ORDER BY: in that case, we only may need to do
2088
2109
      filesort for GROUP BY.
2089
2110
    */
2090
2111
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
2110
2131
    select_describe(this, need_tmp,
2111
2132
                    order != 0 && !skip_sort_order,
2112
2133
                    select_distinct,
2113
 
                    !tables ? "No tables used" : NULL);
 
2134
                    !tables ? "No tables used" : NullS);
2114
2135
    return;
2115
2136
  }
2116
2137
 
2117
2138
  JOIN *curr_join= this;
2118
2139
  List<Item> *curr_all_fields= &all_fields;
2119
2140
  List<Item> *curr_fields_list= &fields_list;
2120
 
  Table *curr_tmp_table= 0;
 
2141
  TABLE *curr_tmp_table= 0;
2121
2142
  /*
2122
2143
    Initialize examined rows here because the values from all join parts
2123
2144
    must be accumulated in examined_row_count. Hence every join
2141
2162
    curr_tmp_table= exec_tmp_table1;
2142
2163
 
2143
2164
    /* Copy data to the temporary table */
2144
 
    thd->set_proc_info("Copying to tmp table");
 
2165
    thd_proc_info(thd, "Copying to tmp table");
2145
2166
    if (!curr_join->sort_and_group &&
2146
2167
        curr_join->const_tables != curr_join->tables)
2147
2168
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
2245
2266
              exec_tmp_table2= create_tmp_table(thd,
2246
2267
                                                &curr_join->tmp_table_param,
2247
2268
                                                *curr_all_fields,
2248
 
                                                (order_st*) 0,
 
2269
                                                (ORDER*) 0,
2249
2270
                                                curr_join->select_distinct && 
2250
2271
                                                !curr_join->group_list,
2251
2272
                                                1, curr_join->select_options,
2256
2277
      }
2257
2278
      if (curr_join->group_list)
2258
2279
      {
2259
 
        thd->set_proc_info("Creating sort index");
 
2280
        thd_proc_info(thd, "Creating sort index");
2260
2281
        if (curr_join->join_tab == join_tab && save_join_tab())
2261
2282
        {
2262
2283
          return;
2270
2291
        sortorder= curr_join->sortorder;
2271
2292
      }
2272
2293
      
2273
 
      thd->set_proc_info("Copying to group table");
 
2294
      thd_proc_info(thd, "Copying to group table");
2274
2295
      tmp_error= -1;
2275
2296
      if (curr_join != this)
2276
2297
      {
2327
2348
    curr_join->join_free();                     /* Free quick selects */
2328
2349
    if (curr_join->select_distinct && ! curr_join->group_list)
2329
2350
    {
2330
 
      thd->set_proc_info("Removing duplicates");
 
2351
      thd_proc_info(thd, "Removing duplicates");
2331
2352
      if (curr_join->tmp_having)
2332
2353
        curr_join->tmp_having->update_used_tables();
2333
2354
      if (remove_duplicates(curr_join, curr_tmp_table,
2385
2406
  }
2386
2407
  if (curr_join->group_list || curr_join->order)
2387
2408
  {
2388
 
    thd->set_proc_info("Sorting result");
 
2409
    thd_proc_info(thd, "Sorting result");
2389
2410
    /* If we have already done the group, add HAVING to sorted table */
2390
2411
    if (curr_join->tmp_having && ! curr_join->group_list && 
2391
2412
        ! curr_join->sort_and_group)
2456
2477
        return;
2457
2478
      }
2458
2479
      /*
2459
 
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
 
2480
        Here we sort rows for ORDER BY/GROUP BY clause, if the optimiser
2460
2481
        chose FILESORT to be faster than INDEX SCAN or there is no 
2461
2482
        suitable index present.
2462
2483
        Note, that create_sort_index calls test_if_skip_sort_order and may
2495
2516
  curr_join->fields= curr_fields_list;
2496
2517
 
2497
2518
  {
2498
 
    thd->set_proc_info("Sending data");
 
2519
    thd_proc_info(thd, "Sending data");
2499
2520
    result->send_fields(*curr_fields_list,
2500
2521
                        Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2501
2522
    error= do_select(curr_join, curr_fields_list, NULL);
2547
2568
 
2548
2569
  cleanup(1);
2549
2570
  if (exec_tmp_table1)
2550
 
    exec_tmp_table1->free_tmp_table(thd);
 
2571
    free_tmp_table(thd, exec_tmp_table1);
2551
2572
  if (exec_tmp_table2)
2552
 
    exec_tmp_table2->free_tmp_table(thd);
 
2573
    free_tmp_table(thd, exec_tmp_table2);
2553
2574
  delete select;
2554
2575
  delete_dynamic(&keyuse);
2555
2576
  return(error);
2576
2597
                              for a, b and c in this list.
2577
2598
  @param conds                top level item of an expression representing
2578
2599
                              WHERE clause of the top level select
2579
 
  @param og_num               total number of order_st BY and GROUP BY clauses
 
2600
  @param og_num               total number of ORDER BY and GROUP BY clauses
2580
2601
                              arguments
2581
 
  @param order                linked list of order_st BY agruments
 
2602
  @param order                linked list of ORDER BY agruments
2582
2603
  @param group                linked list of GROUP BY arguments
2583
2604
  @param having               top level item of HAVING expression
2584
2605
  @param proc_param           list of PROCEDUREs
2603
2624
 
2604
2625
bool
2605
2626
mysql_select(THD *thd, Item ***rref_pointer_array,
2606
 
             TableList *tables, uint32_t wild_num, List<Item> &fields,
2607
 
             COND *conds, uint32_t og_num,  order_st *order, order_st *group,
2608
 
             Item *having, order_st *proc_param, uint64_t select_options,
 
2627
             TABLE_LIST *tables, uint wild_num, List<Item> &fields,
 
2628
             COND *conds, uint og_num,  ORDER *order, ORDER *group,
 
2629
             Item *having, ORDER *proc_param, uint64_t select_options,
2609
2630
             select_result *result, SELECT_LEX_UNIT *unit,
2610
2631
             SELECT_LEX *select_lex)
2611
2632
{
2649
2670
  {
2650
2671
    if (!(join= new JOIN(thd, fields, select_options, result)))
2651
2672
        return(true);
2652
 
    thd->set_proc_info("init");
 
2673
    thd_proc_info(thd, "init");
2653
2674
    thd->used_tables=0;                         // Updated by setup_fields
2654
2675
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2655
2676
                           conds, og_num, order, group, having, proc_param,
2659
2680
    }
2660
2681
  }
2661
2682
 
2662
 
  /* dump_TableList_graph(select_lex, select_lex->leaf_tables); */
 
2683
  /* dump_TABLE_LIST_graph(select_lex, select_lex->leaf_tables); */
2663
2684
  if (join->flatten_subqueries())
2664
2685
  {
2665
2686
    err= 1;
2666
2687
    goto err;
2667
2688
  }
2668
 
  /* dump_TableList_struct(select_lex, select_lex->leaf_tables); */
 
2689
  /* dump_TABLE_LIST_struct(select_lex, select_lex->leaf_tables); */
2669
2690
 
2670
2691
  if ((err= join->optimize()))
2671
2692
  {
2692
2713
err:
2693
2714
  if (free_join)
2694
2715
  {
2695
 
    thd->set_proc_info("end");
 
2716
    thd_proc_info(thd, "end");
2696
2717
    err|= select_lex->cleanup();
2697
2718
    return(err || thd->is_error());
2698
2719
  }
2714
2735
}
2715
2736
 
2716
2737
 
2717
 
static TableList *alloc_join_nest(THD *thd)
 
2738
static TABLE_LIST *alloc_join_nest(THD *thd)
2718
2739
{
2719
 
  TableList *tbl;
2720
 
  if (!(tbl= (TableList*) thd->calloc(ALIGN_SIZE(sizeof(TableList))+
2721
 
                                       sizeof(nested_join_st))))
 
2740
  TABLE_LIST *tbl;
 
2741
  if (!(tbl= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
 
2742
                                       sizeof(NESTED_JOIN))))
2722
2743
    return NULL;
2723
 
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl + 
2724
 
                                    ALIGN_SIZE(sizeof(TableList)));
 
2744
  tbl->nested_join= (NESTED_JOIN*) ((uchar*)tbl + 
 
2745
                                    ALIGN_SIZE(sizeof(TABLE_LIST)));
2725
2746
  return tbl;
2726
2747
}
2727
2748
 
2728
2749
 
2729
 
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TableList> *tlist)
 
2750
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TABLE_LIST> *tlist)
2730
2751
{
2731
 
  List_iterator<TableList> it(*tlist);
2732
 
  TableList *table;
 
2752
  List_iterator<TABLE_LIST> it(*tlist);
 
2753
  TABLE_LIST *table;
2733
2754
  while ((table= it++))
2734
2755
  {
2735
2756
    if (table->on_expr)
2741
2762
 
2742
2763
 
2743
2764
/*
2744
 
  Convert a subquery predicate into a TableList semi-join nest
 
2765
  Convert a subquery predicate into a TABLE_LIST semi-join nest
2745
2766
 
2746
2767
  SYNOPSIS
2747
2768
    convert_subq_to_sj()
2750
2771
       subq_pred    Subquery predicate to be converted
2751
2772
  
2752
2773
  DESCRIPTION
2753
 
    Convert a subquery predicate into a TableList semi-join nest. All the 
 
2774
    Convert a subquery predicate into a TABLE_LIST semi-join nest. All the 
2754
2775
    prerequisites are already checked, so the conversion is always successfull.
2755
2776
 
2756
2777
    Prepared Statements: the transformation is permanent:
2757
 
     - Changes in TableList structures are naturally permanent
 
2778
     - Changes in TABLE_LIST structures are naturally permanent
2758
2779
     - Item tree changes are performed on statement MEM_ROOT:
2759
2780
        = we activate statement MEM_ROOT 
2760
2781
        = this function is called before the first fix_prepare_information
2771
2792
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
2772
2793
{
2773
2794
  SELECT_LEX *parent_lex= parent_join->select_lex;
2774
 
  TableList *emb_tbl_nest= NULL;
2775
 
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
 
2795
  TABLE_LIST *emb_tbl_nest= NULL;
 
2796
  List<TABLE_LIST> *emb_join_list= &parent_lex->top_join_list;
2776
2797
  THD *thd= parent_join->thd;
2777
2798
 
2778
2799
  /*
2809
2830
    }
2810
2831
    else if (!subq_pred->expr_join_nest->nested_join)
2811
2832
    {
2812
 
      TableList *outer_tbl= subq_pred->expr_join_nest;      
2813
 
      TableList *wrap_nest;
 
2833
      TABLE_LIST *outer_tbl= subq_pred->expr_join_nest;      
 
2834
      TABLE_LIST *wrap_nest;
2814
2835
      /*
2815
2836
        We're dealing with
2816
2837
 
2825
2846
        Q:  other subqueries may be pointing to this element. What to do?
2826
2847
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
2827
2848
            But we'll need to fix other pointers.
2828
 
        A2: Another way: have TableList::next_ptr so the following
 
2849
        A2: Another way: have TABLE_LIST::next_ptr so the following
2829
2850
            subqueries know the table has been nested.
2830
 
        A3: changes in the TableList::outer_join will make everything work
 
2851
        A3: changes in the TABLE_LIST::outer_join will make everything work
2831
2852
            automatically.
2832
2853
      */
2833
2854
      if (!(wrap_nest= alloc_join_nest(parent_join->thd)))
2854
2875
      wrap_nest->on_expr= outer_tbl->on_expr;
2855
2876
      outer_tbl->on_expr= NULL;
2856
2877
 
2857
 
      List_iterator<TableList> li(*wrap_nest->join_list);
2858
 
      TableList *tbl;
 
2878
      List_iterator<TABLE_LIST> li(*wrap_nest->join_list);
 
2879
      TABLE_LIST *tbl;
2859
2880
      while ((tbl= li++))
2860
2881
      {
2861
2882
        if (tbl == outer_tbl)
2873
2894
    }
2874
2895
  }
2875
2896
 
2876
 
  TableList *sj_nest;
2877
 
  nested_join_st *nested_join;
 
2897
  TABLE_LIST *sj_nest;
 
2898
  NESTED_JOIN *nested_join;
2878
2899
  if (!(sj_nest= alloc_join_nest(parent_join->thd)))
2879
2900
  {
2880
2901
    return(true);
2899
2920
  */
2900
2921
  st_select_lex *subq_lex= subq_pred->unit->first_select();
2901
2922
  nested_join->join_list.empty();
2902
 
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
2903
 
  TableList *tl, *last_leaf;
 
2923
  List_iterator_fast<TABLE_LIST> li(subq_lex->top_join_list);
 
2924
  TABLE_LIST *tl, *last_leaf;
2904
2925
  while ((tl= li++))
2905
2926
  {
2906
2927
    tl->embedding= sj_nest;
2936
2957
  /*TODO: also reset the 'with_subselect' there. */
2937
2958
 
2938
2959
  /* n. Adjust the parent_join->tables counter */
2939
 
  uint32_t table_no= parent_join->tables;
 
2960
  uint table_no= parent_join->tables;
2940
2961
  /* n. Walk through child's tables and adjust table->map */
2941
2962
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
2942
2963
  {
2944
2965
    tl->table->map= ((table_map)1) << table_no;
2945
2966
    SELECT_LEX *old_sl= tl->select_lex;
2946
2967
    tl->select_lex= parent_join->select_lex; 
2947
 
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
 
2968
    for(TABLE_LIST *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
2948
2969
      emb->select_lex= parent_join->select_lex;
2949
2970
  }
2950
2971
  parent_join->tables += subq_lex->join->tables;
2994
3015
  }
2995
3016
  else
2996
3017
  {
2997
 
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
 
3018
    for (uint i= 0; i < subq_pred->left_expr->cols(); i++)
2998
3019
    {
2999
3020
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
3000
3021
                                                element_index(i));
3072
3093
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
3073
3094
  }
3074
3095
 
3075
 
  //dump_TableList_struct(select_lex, select_lex->leaf_tables);
 
3096
  //dump_TABLE_LIST_struct(select_lex, select_lex->leaf_tables);
3076
3097
  /* 
3077
3098
    2. Pick which subqueries to convert:
3078
3099
      sort the subquery array
3193
3214
    false - Otherwise
3194
3215
*/
3195
3216
 
3196
 
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
 
3217
bool find_eq_ref_candidate(TABLE *table, table_map sj_inner_tables)
3197
3218
{
3198
3219
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
3199
 
  uint32_t key;
 
3220
  uint key;
3200
3221
 
3201
3222
  if (keyuse)
3202
3223
  {
3263
3284
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
3264
3285
       tables)
3265
3286
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
3266
 
     * Semi-join nests TableList::sj_inner_tables
 
3287
     * Semi-join nests TABLE_LIST::sj_inner_tables
3267
3288
 
3268
3289
    This operation is (and should be) performed at each PS execution since
3269
3290
    tables may become/cease to be constant across PS reexecutions.
3275
3296
 
3276
3297
int pull_out_semijoin_tables(JOIN *join)
3277
3298
{
3278
 
  TableList *sj_nest;
3279
 
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
 
3299
  TABLE_LIST *sj_nest;
 
3300
  List_iterator<TABLE_LIST> sj_list_it(join->select_lex->sj_nests);
3280
3301
   
3281
3302
  /* Try pulling out of the each of the semi-joins */
3282
3303
  while ((sj_nest= sj_list_it++))
3284
3305
    /* Action #1: Mark the constant tables to be pulled out */
3285
3306
    table_map pulled_tables= 0;
3286
3307
     
3287
 
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
3288
 
    TableList *tbl;
 
3308
    List_iterator<TABLE_LIST> child_li(sj_nest->nested_join->join_list);
 
3309
    TABLE_LIST *tbl;
3289
3310
    while ((tbl= child_li++))
3290
3311
    {
3291
3312
      if (tbl->table)
3361
3382
 
3362
3383
 
3363
3384
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
3364
 
                                      Table *table,
 
3385
                                      TABLE *table,
3365
3386
                                      const key_map *keys,ha_rows limit)
3366
3387
{
3367
3388
  int error;
3394
3415
{
3395
3416
  Field *field;              /* field against which to check sargability */
3396
3417
  Item **arg_value;          /* values of potential keys for lookups     */
3397
 
  uint32_t num_values;           /* number of values in the above array      */
 
3418
  uint num_values;           /* number of values in the above array      */
3398
3419
} SARGABLE_PARAM;  
3399
3420
 
3400
3421
/**
3407
3428
*/
3408
3429
 
3409
3430
static bool
3410
 
make_join_statistics(JOIN *join, TableList *tables, COND *conds,
 
3431
make_join_statistics(JOIN *join, TABLE_LIST *tables, COND *conds,
3411
3432
                     DYNAMIC_ARRAY *keyuse_array)
3412
3433
{
3413
3434
  int error;
3414
 
  Table *table;
3415
 
  uint32_t i,table_count,const_count,key;
 
3435
  TABLE *table;
 
3436
  uint i,table_count,const_count,key;
3416
3437
  table_map found_const_table_map, all_table_map, found_ref, refs;
3417
3438
  key_map const_ref, eq_part;
3418
 
  Table **table_vector;
 
3439
  TABLE **table_vector;
3419
3440
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
3420
3441
  KEYUSE *keyuse,*start_keyuse;
3421
3442
  table_map outer_join=0;
3425
3446
  table_count=join->tables;
3426
3447
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
3427
3448
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
3428
 
  table_vector=(Table**) join->thd->alloc(sizeof(Table*)*(table_count*2));
 
3449
  table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2));
3429
3450
  if (!stat || !stat_ref || !table_vector)
3430
3451
    return(1);                          // Eom /* purecov: inspected */
3431
3452
 
3439
3460
       tables;
3440
3461
       s++, tables= tables->next_leaf, i++)
3441
3462
  {
3442
 
    TableList *embedding= tables->embedding;
 
3463
    TABLE_LIST *embedding= tables->embedding;
3443
3464
    stat_vector[i]=s;
3444
3465
    s->keys.init();
3445
3466
    s->const_keys.init();
3456
3477
    table->quick_keys.clear_all();
3457
3478
    table->reginfo.join_tab=s;
3458
3479
    table->reginfo.not_exists_optimize=0;
3459
 
    memset(table->const_key_parts, 0,
3460
 
           sizeof(key_part_map)*table->s->keys);
 
3480
    bzero((char*) table->const_key_parts, sizeof(key_part_map)*table->s->keys);
3461
3481
    all_table_map|= table->map;
3462
3482
    s->join=join;
3463
3483
    s->info=0;                                  // For describe
3490
3510
      s->embedding_map= 0;
3491
3511
      do
3492
3512
      {
3493
 
        nested_join_st *nested_join= embedding->nested_join;
 
3513
        NESTED_JOIN *nested_join= embedding->nested_join;
3494
3514
        s->embedding_map|=nested_join->nj_map;
3495
3515
        s->dependent|= embedding->dep_tables;
3496
3516
        embedding= embedding->embedding;
3499
3519
      while (embedding);
3500
3520
      continue;
3501
3521
    }
3502
 
    if ((table->file->stats.records <= 1) &&
 
3522
    if ((table->s->system || table->file->stats.records <= 1) &&
3503
3523
        !s->dependent &&
3504
3524
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
3505
3525
    {
3521
3541
    */
3522
3542
    for (i= 0, s= stat ; i < table_count ; i++, s++)
3523
3543
    {
3524
 
      for (uint32_t j= 0 ; j < table_count ; j++)
 
3544
      for (uint j= 0 ; j < table_count ; j++)
3525
3545
      {
3526
3546
        table= stat[j].table;
3527
3547
        if (s->dependent & table->map)
3718
3738
      key_map possible_keys= field->key_start;
3719
3739
      possible_keys.intersect(field->table->keys_in_use_for_query);
3720
3740
      bool is_const= 1;
3721
 
      for (uint32_t j=0; j < sargables->num_values; j++)
 
3741
      for (uint j=0; j < sargables->num_values; j++)
3722
3742
        is_const&= sargables->arg_value[j]->const_item();
3723
3743
      if (is_const)
3724
3744
        join_tab[0].const_keys.merge(possible_keys);
3747
3767
      This is can't be to high as otherwise we are likely to use
3748
3768
      table scan.
3749
3769
    */
3750
 
    s->worst_seeks= cmin((double) s->found_records / 10,
 
3770
    s->worst_seeks= min((double) s->found_records / 10,
3751
3771
                        (double) s->read_time*3);
3752
3772
    if (s->worst_seeks < 2.0)                   // Fix for small tables
3753
3773
      s->worst_seeks=2.0;
3818
3838
  }
3819
3839
  else
3820
3840
  {
3821
 
    memcpy(join->best_positions, join->positions,
3822
 
           sizeof(POSITION)*join->const_tables);
 
3841
    memcpy((uchar*) join->best_positions,(uchar*) join->positions,
 
3842
           sizeof(POSITION)*join->const_tables);
3823
3843
    join->best_read=1.0;
3824
3844
  }
3825
3845
  /* Generate an execution plan from the found optimal join order. */
3848
3868
  */
3849
3869
  bool          null_rejecting; 
3850
3870
  bool          *cond_guard; /* See KEYUSE::cond_guard */
3851
 
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
 
3871
  uint          sj_pred_no; /* See KEYUSE::sj_pred_no */
3852
3872
} KEY_FIELD;
3853
3873
 
3854
3874
/**
3877
3897
 
3878
3898
static KEY_FIELD *
3879
3899
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
3880
 
                 uint32_t and_level)
 
3900
                 uint and_level)
3881
3901
{
3882
3902
  if (start == new_fields)
3883
3903
    return start;                               // Impossible or
3900
3920
          The cause is as follows: Some of the tables are already known to be
3901
3921
          const tables (the detection code is in make_join_statistics(),
3902
3922
          above the update_ref_and_keys() call), but we didn't propagate 
3903
 
          information about this: Table::const_table is not set to true, and
 
3923
          information about this: TABLE::const_table is not set to true, and
3904
3924
          Item::update_used_tables() hasn't been called for each item.
3905
3925
          The result of this is that we're missing some 'ref' accesses.
3906
3926
          TODO: OptimizerTeam: Fix this
4004
4024
*/
4005
4025
 
4006
4026
static void
4007
 
add_key_field(KEY_FIELD **key_fields,uint32_t and_level, Item_func *cond,
4008
 
              Field *field, bool eq_func, Item **value, uint32_t num_values,
 
4027
add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond,
 
4028
              Field *field, bool eq_func, Item **value, uint num_values,
4009
4029
              table_map usable_tables, SARGABLE_PARAM **sargables)
4010
4030
{
4011
 
  uint32_t exists_optimize= 0;
 
4031
  uint exists_optimize= 0;
4012
4032
  if (!(field->flags & PART_KEY_FLAG))
4013
4033
  {
4014
4034
    // Don't remove column IS NULL on a LEFT JOIN table
4022
4042
  {
4023
4043
    table_map used_tables=0;
4024
4044
    bool optimizable=0;
4025
 
    for (uint32_t i=0; i<num_values; i++)
 
4045
    for (uint i=0; i<num_values; i++)
4026
4046
    {
4027
4047
      used_tables|=(value[i])->used_tables();
4028
4048
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
4058
4078
      stat[0].key_dependent|=used_tables;
4059
4079
 
4060
4080
      bool is_const=1;
4061
 
      for (uint32_t i=0; i<num_values; i++)
 
4081
      for (uint i=0; i<num_values; i++)
4062
4082
      {
4063
4083
        if (!(is_const&= value[i]->const_item()))
4064
4084
          break;
4176
4196
*/
4177
4197
 
4178
4198
static void
4179
 
add_key_equal_fields(KEY_FIELD **key_fields, uint32_t and_level,
 
4199
add_key_equal_fields(KEY_FIELD **key_fields, uint and_level,
4180
4200
                     Item_func *cond, Item_field *field_item,
4181
4201
                     bool eq_func, Item **val,
4182
 
                     uint32_t num_values, table_map usable_tables,
 
4202
                     uint num_values, table_map usable_tables,
4183
4203
                     SARGABLE_PARAM **sargables)
4184
4204
{
4185
4205
  Field *field= field_item->field;
4207
4227
}
4208
4228
 
4209
4229
static void
4210
 
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint32_t *and_level,
 
4230
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level,
4211
4231
               COND *cond, table_map usable_tables,
4212
4232
               SARGABLE_PARAM **sargables)
4213
4233
{
4300
4320
    if (cond_func->functype() == Item_func::BETWEEN)
4301
4321
    {
4302
4322
      values= cond_func->arguments();
4303
 
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
4323
      for (uint i= 1 ; i < cond_func->argument_count() ; i++)
4304
4324
      {
4305
4325
        Item_field *field_item;
4306
4326
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
4411
4431
static uint
4412
4432
max_part_bit(key_part_map bits)
4413
4433
{
4414
 
  uint32_t found;
 
4434
  uint found;
4415
4435
  for (found=0; bits & 1 ; found++,bits>>=1) ;
4416
4436
  return found;
4417
4437
}
4420
4440
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
4421
4441
{
4422
4442
  Field *field=key_field->field;
4423
 
  Table *form= field->table;
 
4443
  TABLE *form= field->table;
4424
4444
  KEYUSE keyuse;
4425
4445
 
4426
4446
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
4427
4447
  {
4428
 
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
4448
    for (uint key=0 ; key < form->s->keys ; key++)
4429
4449
    {
4430
4450
      if (!(form->keys_in_use_for_query.is_set(key)))
4431
4451
        continue;
4432
4452
 
4433
 
      uint32_t key_parts= (uint) form->key_info[key].key_parts;
4434
 
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
4453
      uint key_parts= (uint) form->key_info[key].key_parts;
 
4454
      for (uint part=0 ; part <  key_parts ; part++)
4435
4455
      {
4436
4456
        if (field->eq(form->key_info[key].key_part[part].field))
4437
4457
        {
4445
4465
          keyuse.null_rejecting= key_field->null_rejecting;
4446
4466
          keyuse.cond_guard= key_field->cond_guard;
4447
4467
          keyuse.sj_pred_no= key_field->sj_pred_no;
4448
 
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
4468
          VOID(insert_dynamic(keyuse_array,(uchar*) &keyuse));
4449
4469
        }
4450
4470
      }
4451
4471
    }
4507
4527
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
4508
4528
*/
4509
4529
 
4510
 
static void add_key_fields_for_nj(JOIN *join, TableList *nested_join_table,
4511
 
                                  KEY_FIELD **end, uint32_t *and_level,
 
4530
static void add_key_fields_for_nj(JOIN *join, TABLE_LIST *nested_join_table,
 
4531
                                  KEY_FIELD **end, uint *and_level,
4512
4532
                                  SARGABLE_PARAM **sargables)
4513
4533
{
4514
 
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
4515
 
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
 
4534
  List_iterator<TABLE_LIST> li(nested_join_table->nested_join->join_list);
 
4535
  List_iterator<TABLE_LIST> li2(nested_join_table->nested_join->join_list);
4516
4536
  bool have_another = false;
4517
4537
  table_map tables= 0;
4518
 
  TableList *table;
 
4538
  TABLE_LIST *table;
4519
4539
  assert(nested_join_table->nested_join);
4520
4540
 
4521
4541
  while ((table= li++) || (have_another && (li=li2, have_another=false,
4528
4548
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
4529
4549
        have_another= true;
4530
4550
        li2= li;
4531
 
        li= List_iterator<TableList>(table->nested_join->join_list); 
 
4551
        li= List_iterator<TABLE_LIST>(table->nested_join->join_list); 
4532
4552
      }
4533
4553
      else
4534
4554
        add_key_fields_for_nj(join, table, end, and_level, sargables);
4566
4586
 
4567
4587
static bool
4568
4588
update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
4569
 
                    uint32_t tables, COND *cond,
4570
 
                    COND_EQUAL *cond_equal __attribute__((unused)),
 
4589
                    uint tables, COND *cond,
 
4590
                    COND_EQUAL *cond_equal __attribute__((__unused__)),
4571
4591
                    table_map normal_tables, SELECT_LEX *select_lex,
4572
4592
                    SARGABLE_PARAM **sargables)
4573
4593
{
4574
4594
  uint  and_level,i,found_eq_constant;
4575
4595
  KEY_FIELD *key_fields, *end, *field;
4576
 
  uint32_t sz;
4577
 
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
 
4596
  uint sz;
 
4597
  uint m= max(select_lex->max_equal_elems,1);
4578
4598
  
4579
4599
  /* 
4580
4600
    We use the same piece of memory to store both  KEY_FIELD 
4597
4617
    can be not more than select_lex->max_equal_elems such 
4598
4618
    substitutions.
4599
4619
  */ 
4600
 
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
 
4620
  sz= max(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
4601
4621
      (((thd->lex->current_select->cond_count+1)*2 +
4602
4622
        thd->lex->current_select->between_count)*m+1);
4603
4623
  if (!(key_fields=(KEY_FIELD*) thd->alloc(sz)))
4643
4663
 
4644
4664
  /* Process ON conditions for the nested joins */
4645
4665
  {
4646
 
    List_iterator<TableList> li(*join_tab->join->join_list);
4647
 
    TableList *table;
 
4666
    List_iterator<TABLE_LIST> li(*join_tab->join->join_list);
 
4667
    TABLE_LIST *table;
4648
4668
    while ((table= li++))
4649
4669
    {
4650
4670
      if (table->nested_join)
4673
4693
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
4674
4694
          (qsort_cmp) sort_keyuse);
4675
4695
 
4676
 
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
4677
 
    insert_dynamic(keyuse,(unsigned char*) &key_end);
 
4696
    bzero((char*) &key_end,sizeof(key_end));    /* Add for easy testing */
 
4697
    VOID(insert_dynamic(keyuse,(uchar*) &key_end));
4678
4698
 
4679
4699
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
4680
4700
    prev= &key_end;
4707
4727
      save_pos++;
4708
4728
    }
4709
4729
    i=(uint) (save_pos-(KEYUSE*) keyuse->buffer);
4710
 
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
4730
    VOID(set_dynamic(keyuse,(uchar*) &key_end,i));
4711
4731
    keyuse->elements=i;
4712
4732
  }
4713
4733
  return false;
4737
4757
        (map= (keyuse->used_tables & ~join->const_table_map &
4738
4758
               ~OUTER_REF_TABLE_BIT)))
4739
4759
    {
4740
 
      uint32_t tablenr;
 
4760
      uint tablenr;
4741
4761
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
4742
4762
      if (map == 1)                     // Only one table
4743
4763
      {
4744
 
        Table *tmp_table=join->all_tables[tablenr];
4745
 
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
 
4764
        TABLE *tmp_table=join->all_tables[tablenr];
 
4765
        keyuse->ref_table_rows= max(tmp_table->file->stats.records, 100);
4746
4766
      }
4747
4767
    }
4748
4768
    /*
4778
4798
{
4779
4799
  List<Item_field> indexed_fields;
4780
4800
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
4781
 
  order_st      *cur_group;
 
4801
  ORDER      *cur_group;
4782
4802
  Item_field *cur_item;
4783
4803
  key_map possible_keys(0);
4784
4804
 
4786
4806
  { /* Collect all query fields referenced in the GROUP clause. */
4787
4807
    for (cur_group= join->group_list; cur_group; cur_group= cur_group->next)
4788
4808
      (*cur_group->item)->walk(&Item::collect_item_field_processor, 0,
4789
 
                               (unsigned char*) &indexed_fields);
 
4809
                               (uchar*) &indexed_fields);
4790
4810
  }
4791
4811
  else if (join->select_distinct)
4792
4812
  { /* Collect all query fields referenced in the SELECT clause. */
4795
4815
    Item *item;
4796
4816
    while ((item= select_items_it++))
4797
4817
      item->walk(&Item::collect_item_field_processor, 0,
4798
 
                 (unsigned char*) &indexed_fields);
 
4818
                 (uchar*) &indexed_fields);
4799
4819
  }
4800
4820
  else
4801
4821
    return;
4824
4844
/** Save const tables first as used tables. */
4825
4845
 
4826
4846
static void
4827
 
set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
 
4847
set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key)
4828
4848
{
4829
4849
  join->positions[idx].table= table;
4830
4850
  join->positions[idx].key=key;
4861
4881
    Bitmap of bound IN-equalities.
4862
4882
*/
4863
4883
 
4864
 
uint64_t get_bound_sj_equalities(TableList *sj_nest, 
 
4884
uint64_t get_bound_sj_equalities(TABLE_LIST *sj_nest, 
4865
4885
                                  table_map remaining_tables)
4866
4886
{
4867
4887
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
4868
4888
  Item *item;
4869
 
  uint32_t i= 0;
 
4889
  uint i= 0;
4870
4890
  uint64_t res= 0;
4871
4891
  while ((item= li++))
4872
4892
  {
4878
4898
    */
4879
4899
    if (!(item->used_tables() & remaining_tables))
4880
4900
    {
4881
 
      res |= 1UL < i;
 
4901
      res |= 1ULL < i;
4882
4902
    }
4883
4903
  }
4884
4904
  return res;
4915
4935
                 JOIN_TAB  *s,
4916
4936
                 THD       *thd,
4917
4937
                 table_map remaining_tables,
4918
 
                 uint32_t      idx,
 
4938
                 uint      idx,
4919
4939
                 double    record_count,
4920
 
                 double    read_time __attribute__((unused)))
 
4940
                 double    read_time __attribute__((__unused__)))
4921
4941
{
4922
4942
  KEYUSE *best_key=         0;
4923
 
  uint32_t best_max_key_part=   0;
 
4943
  uint best_max_key_part=   0;
4924
4944
  bool found_constraint= 0;
4925
4945
  double best=              DBL_MAX;
4926
4946
  double best_time=         DBL_MAX;
4928
4948
  table_map best_ref_depends_map= 0;
4929
4949
  double tmp;
4930
4950
  ha_rows rec;
4931
 
  uint32_t best_is_sj_inside_out=    0;
 
4951
  uint best_is_sj_inside_out=    0;
4932
4952
 
4933
4953
  if (s->keyuse)
4934
4954
  {                                            /* Use key if possible */
4935
 
    Table *table= s->table;
 
4955
    TABLE *table= s->table;
4936
4956
    KEYUSE *keyuse,*start_key=0;
4937
4957
    double best_records= DBL_MAX;
4938
 
    uint32_t max_key_part=0;
 
4958
    uint max_key_part=0;
4939
4959
    uint64_t bound_sj_equalities= 0;
4940
4960
    bool try_sj_inside_out= false;
4941
4961
    /*
4966
4986
    {
4967
4987
      key_part_map found_part= 0;
4968
4988
      table_map found_ref= 0;
4969
 
      uint32_t key= keyuse->key;
 
4989
      uint key= keyuse->key;
4970
4990
      KEY *keyinfo= table->key_info+key;
4971
4991
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
4972
4992
      key_part_map const_part= 0;
4980
5000
 
4981
5001
      do /* For each keypart */
4982
5002
      {
4983
 
        uint32_t keypart= keyuse->keypart;
 
5003
        uint keypart= keyuse->keypart;
4984
5004
        table_map best_part_found_ref= 0;
4985
5005
        double best_prev_record_reads= DBL_MAX;
4986
5006
        
5019
5039
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
5020
5040
          {
5021
5041
            if (!(remaining_tables & keyuse->used_tables))
5022
 
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5042
              bound_sj_equalities |= 1ULL << keyuse->sj_pred_no;
5023
5043
            else
5024
5044
            {
5025
 
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5045
              handled_sj_equalities |= 1ULL << keyuse->sj_pred_no;
5026
5046
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
5027
5047
            }
5028
5048
          }
5056
5076
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
5057
5077
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
5058
5078
        {
5059
 
          uint32_t n_fixed_parts= max_part_bit(found_part);
 
5079
          uint n_fixed_parts= max_part_bit(found_part);
5060
5080
          if (n_fixed_parts != keyinfo->key_parts &&
5061
5081
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
5062
5082
               PREV_BITS(uint, keyinfo->key_parts))
5097
5117
        if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
5098
5118
            !ref_or_null_part)
5099
5119
        {                                         /* use eq key */
5100
 
          max_key_part= UINT32_MAX;
 
5120
          max_key_part= (uint) ~0;
5101
5121
          if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)
5102
5122
          {
5103
5123
            tmp = prev_record_reads(join, idx, found_ref);
5171
5191
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5172
5192
            }
5173
5193
            else
5174
 
              tmp= record_count*cmin(tmp,s->worst_seeks);
 
5194
              tmp= record_count*min(tmp,s->worst_seeks);
5175
5195
          }
5176
5196
        }
5177
5197
        else
5227
5247
            */
5228
5248
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
5229
5249
                table->quick_key_parts[key] == max_key_part &&          //(C2)
5230
 
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
 
5250
                table->quick_n_ranges[key] == 1+test(ref_or_null_part)) //(C3)
5231
5251
            {
5232
5252
              tmp= records= (double) table->quick_rows[key];
5233
5253
            }
5320
5340
              if (table->quick_keys.is_set(key) &&
5321
5341
                  table->quick_key_parts[key] <= max_key_part &&
5322
5342
                  const_part & (1 << table->quick_key_parts[key]) &&
5323
 
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
5324
 
                                                     const_part) ? 1 : 0) &&
 
5343
                  table->quick_n_ranges[key] == 1 + test(ref_or_null_part &
 
5344
                                                         const_part) &&
5325
5345
                  records > (double) table->quick_rows[key])
5326
5346
              {
5327
5347
                tmp= records= (double) table->quick_rows[key];
5336
5356
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5337
5357
            }
5338
5358
            else
5339
 
              tmp= record_count * cmin(tmp,s->worst_seeks);
 
5359
              tmp= record_count * min(tmp,s->worst_seeks);
5340
5360
          }
5341
5361
          else
5342
5362
            tmp= best_time;                    // Do nothing
5474
5494
    /*
5475
5495
      We estimate the cost of evaluating WHERE clause for found records
5476
5496
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
5477
 
      tmp give us total cost of using Table SCAN
 
5497
      tmp give us total cost of using TABLE SCAN
5478
5498
    */
5479
5499
    if (best == DBL_MAX ||
5480
5500
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
5505
5525
      idx == join->const_tables &&
5506
5526
      s->table == join->sort_by_table &&
5507
5527
      join->unit->select_limit_cnt >= records)
5508
 
    join->sort_by_table= (Table*) 1;  // Must use temporary table
 
5528
    join->sort_by_table= (TABLE*) 1;  // Must use temporary table
5509
5529
 
5510
5530
  return;
5511
5531
}
5537
5557
static bool
5538
5558
choose_plan(JOIN *join, table_map join_tables)
5539
5559
{
5540
 
  uint32_t search_depth= join->thd->variables.optimizer_search_depth;
5541
 
  uint32_t prune_level=  join->thd->variables.optimizer_prune_level;
 
5560
  uint search_depth= join->thd->variables.optimizer_search_depth;
 
5561
  uint prune_level=  join->thd->variables.optimizer_prune_level;
5542
5562
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
5543
5563
 
5544
5564
  join->cur_embedding_map= 0;
5672
5692
 
5673
5693
  @todo
5674
5694
    this value should be determined dynamically, based on statistics:
5675
 
    uint32_t max_tables_for_exhaustive_opt= 7;
 
5695
    uint max_tables_for_exhaustive_opt= 7;
5676
5696
 
5677
5697
  @todo
5678
5698
    this value could be determined by some mapping of the form:
5687
5707
static uint
5688
5708
determine_search_depth(JOIN *join)
5689
5709
{
5690
 
  uint32_t table_count=  join->tables - join->const_tables;
5691
 
  uint32_t search_depth;
 
5710
  uint table_count=  join->tables - join->const_tables;
 
5711
  uint search_depth;
5692
5712
  /* TODO: this value should be determined dynamically, based on statistics: */
5693
 
  uint32_t max_tables_for_exhaustive_opt= 7;
 
5713
  uint max_tables_for_exhaustive_opt= 7;
5694
5714
 
5695
5715
  if (table_count <= max_tables_for_exhaustive_opt)
5696
5716
    search_depth= table_count+1; // use exhaustive for small number of tables
5732
5752
optimize_straight_join(JOIN *join, table_map join_tables)
5733
5753
{
5734
5754
  JOIN_TAB *s;
5735
 
  uint32_t idx= join->const_tables;
 
5755
  uint idx= join->const_tables;
5736
5756
  double    record_count= 1.0;
5737
5757
  double    read_time=    0.0;
5738
5758
 
5753
5773
  if (join->sort_by_table &&
5754
5774
      join->sort_by_table != join->positions[join->const_tables].table->table)
5755
5775
    read_time+= record_count;  // We have to make a temp table
5756
 
  memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
5776
  memcpy((uchar*) join->best_positions, (uchar*) join->positions,
 
5777
         sizeof(POSITION)*idx);
5757
5778
  join->best_read= read_time;
5758
5779
}
5759
5780
 
5842
5863
static bool
5843
5864
greedy_search(JOIN      *join,
5844
5865
              table_map remaining_tables,
5845
 
              uint32_t      search_depth,
5846
 
              uint32_t      prune_level)
 
5866
              uint      search_depth,
 
5867
              uint      prune_level)
5847
5868
{
5848
5869
  double    record_count= 1.0;
5849
5870
  double    read_time=    0.0;
5850
 
  uint32_t      idx= join->const_tables; // index into 'join->best_ref'
5851
 
  uint32_t      best_idx;
5852
 
  uint32_t      size_remain;    // cardinality of remaining_tables
 
5871
  uint      idx= join->const_tables; // index into 'join->best_ref'
 
5872
  uint      best_idx;
 
5873
  uint      size_remain;    // cardinality of remaining_tables
5853
5874
  POSITION  best_pos;
5854
5875
  JOIN_TAB  *best_table; // the next plan node to be added to the curr QEP
5855
5876
 
5889
5910
      pos= join->best_ref[++best_idx];
5890
5911
    assert((pos != NULL)); // should always find 'best_table'
5891
5912
    /* move 'best_table' at the first free position in the array of joins */
5892
 
    std::swap(join->best_ref[idx], join->best_ref[best_idx]);
 
5913
    swap_variables(JOIN_TAB*, join->best_ref[idx], join->best_ref[best_idx]);
5893
5914
 
5894
5915
    /* compute the cost of the new plan extended with 'best_table' */
5895
5916
    record_count*= join->positions[idx].records_read;
6022
6043
static bool
6023
6044
best_extension_by_limited_search(JOIN      *join,
6024
6045
                                 table_map remaining_tables,
6025
 
                                 uint32_t      idx,
 
6046
                                 uint      idx,
6026
6047
                                 double    record_count,
6027
6048
                                 double    read_time,
6028
 
                                 uint32_t      search_depth,
6029
 
                                 uint32_t      prune_level)
 
6049
                                 uint      search_depth,
 
6050
                                 uint      prune_level)
6030
6051
{
6031
6052
  THD *thd= join->thd;
6032
6053
  if (thd->killed)  // Abort
6103
6124
 
6104
6125
      if ( (search_depth > 1) && (remaining_tables & ~real_table_bit) )
6105
6126
      { /* Recursively expand the current partial plan */
6106
 
        std::swap(join->best_ref[idx], *pos);
 
6127
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6107
6128
        if (best_extension_by_limited_search(join,
6108
6129
                                             remaining_tables & ~real_table_bit,
6109
6130
                                             idx + 1,
6112
6133
                                             search_depth - 1,
6113
6134
                                             prune_level))
6114
6135
          return(true);
6115
 
        std::swap(join->best_ref[idx], *pos);
 
6136
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6116
6137
      }
6117
6138
      else
6118
6139
      { /*
6127
6148
          current_read_time+= current_record_count;
6128
6149
        if ((search_depth == 1) || (current_read_time < join->best_read))
6129
6150
        {
6130
 
          memcpy(join->best_positions, join->positions,
 
6151
          memcpy((uchar*) join->best_positions, (uchar*) join->positions,
6131
6152
                 sizeof(POSITION) * (idx + 1));
6132
6153
          join->best_read= current_read_time - 0.001;
6133
6154
        }
6150
6171
    true        Fatal error
6151
6172
*/
6152
6173
static bool
6153
 
find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count,
 
6174
find_best(JOIN *join,table_map rest_tables,uint idx,double record_count,
6154
6175
          double read_time)
6155
6176
{
6156
6177
  THD *thd= join->thd;
6165
6186
      read_time+=record_count;                  // We have to make a temp table
6166
6187
    if (read_time < join->best_read)
6167
6188
    {
6168
 
      memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
6189
      memcpy((uchar*) join->best_positions,(uchar*) join->positions,
 
6190
             sizeof(POSITION)*idx);
6169
6191
      join->best_read= read_time - 0.001;
6170
6192
    }
6171
6193
    return(false);
6204
6226
          best_record_count=current_record_count;
6205
6227
          best_read_time=current_read_time;
6206
6228
        }
6207
 
        std::swap(join->best_ref[idx], *pos);
 
6229
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6208
6230
        if (find_best(join,rest_tables & ~real_table_bit,idx+1,
6209
6231
                      current_record_count,current_read_time))
6210
6232
          return(true);
6211
 
        std::swap(join->best_ref[idx], *pos);
 
6233
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6212
6234
      }
6213
6235
      restore_prev_nj_state(s);
6214
6236
      restore_prev_sj_state(rest_tables, s);
6224
6246
  Find how much space the prevous read not const tables takes in cache.
6225
6247
*/
6226
6248
 
6227
 
static void calc_used_field_length(THD *thd __attribute__((unused)),
 
6249
static void calc_used_field_length(THD *thd __attribute__((__unused__)),
6228
6250
                                   JOIN_TAB *join_tab)
6229
6251
{
6230
 
  uint32_t null_fields,blobs,fields,rec_length;
 
6252
  uint null_fields,blobs,fields,rec_length;
6231
6253
  Field **f_ptr,*field;
6232
6254
  MY_BITMAP *read_set= join_tab->table->read_set;;
6233
6255
 
6236
6258
  {
6237
6259
    if (bitmap_is_set(read_set, field->field_index))
6238
6260
    {
6239
 
      uint32_t flags=field->flags;
 
6261
      uint flags=field->flags;
6240
6262
      fields++;
6241
6263
      rec_length+=field->pack_length();
6242
6264
      if (flags & BLOB_FLAG)
6246
6268
    }
6247
6269
  }
6248
6270
  if (null_fields)
6249
 
    rec_length+=(join_tab->table->getNullFields() + 7)/8;
 
6271
    rec_length+=(join_tab->table->s->null_fields+7)/8;
6250
6272
  if (join_tab->table->maybe_null)
6251
6273
    rec_length+=sizeof(bool);
6252
6274
  if (blobs)
6253
6275
  {
6254
 
    uint32_t blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
6255
 
                             (join_tab->table->getRecordLength()- rec_length));
6256
 
    rec_length+=(uint) cmax((uint)4,blob_length);
 
6276
    uint blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
 
6277
                             (join_tab->table->s->reclength- rec_length));
 
6278
    rec_length+=(uint) max(4,blob_length);
6257
6279
  }
6258
6280
  join_tab->used_fields=fields;
6259
6281
  join_tab->used_fieldlength=rec_length;
6262
6284
 
6263
6285
 
6264
6286
static uint
6265
 
cache_record_length(JOIN *join,uint32_t idx)
 
6287
cache_record_length(JOIN *join,uint idx)
6266
6288
{
6267
 
  uint32_t length=0;
 
6289
  uint length=0;
6268
6290
  JOIN_TAB **pos,**end;
6269
6291
  THD *thd=join->thd;
6270
6292
 
6333
6355
*/
6334
6356
 
6335
6357
static double
6336
 
prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
 
6358
prev_record_reads(JOIN *join, uint idx, table_map found_ref)
6337
6359
{
6338
6360
  double found=1.0;
6339
6361
  POSITION *pos_end= join->positions - 1;
6373
6395
static bool
6374
6396
get_best_combination(JOIN *join)
6375
6397
{
6376
 
  uint32_t i,tablenr;
 
6398
  uint i,tablenr;
6377
6399
  table_map used_tables;
6378
6400
  JOIN_TAB *join_tab,*j;
6379
6401
  KEYUSE *keyuse;
6380
 
  uint32_t table_count;
 
6402
  uint table_count;
6381
6403
  THD *thd=join->thd;
6382
6404
 
6383
6405
  table_count=join->tables;
6390
6412
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
6391
6413
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
6392
6414
  {
6393
 
    Table *form;
 
6415
    TABLE *form;
6394
6416
    *j= *join->best_positions[tablenr].table;
6395
6417
    form=join->table[tablenr]=j->table;
6396
6418
    used_tables|= form->map;
6427
6449
{
6428
6450
  KEYUSE *keyuse=org_keyuse;
6429
6451
  THD  *thd= join->thd;
6430
 
  uint32_t keyparts,length,key;
6431
 
  Table *table;
 
6452
  uint keyparts,length,key;
 
6453
  TABLE *table;
6432
6454
  KEY *keyinfo;
6433
6455
 
6434
6456
  /*  Use best key from find_best */
6438
6460
 
6439
6461
  {
6440
6462
    keyparts=length=0;
6441
 
    uint32_t found_part_ref_or_null= 0;
 
6463
    uint found_part_ref_or_null= 0;
6442
6464
    /*
6443
6465
      Calculate length for the used key
6444
6466
      Stop if there is a missing key part or when we find second key_part
6465
6487
  j->ref.key_parts=keyparts;
6466
6488
  j->ref.key_length=length;
6467
6489
  j->ref.key=(int) key;
6468
 
  if (!(j->ref.key_buff= (unsigned char*) thd->calloc(ALIGN_SIZE(length)*2)) ||
 
6490
  if (!(j->ref.key_buff= (uchar*) thd->calloc(ALIGN_SIZE(length)*2)) ||
6469
6491
      !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) *
6470
6492
                                                   (keyparts+1)))) ||
6471
6493
      !(j->ref.items=    (Item**) thd->alloc(sizeof(Item*)*keyparts)) ||
6480
6502
  keyuse=org_keyuse;
6481
6503
 
6482
6504
  store_key **ref_key= j->ref.key_copy;
6483
 
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
 
6505
  uchar *key_buff=j->ref.key_buff, *null_ref_key= 0;
6484
6506
  bool keyuse_uses_no_tables= true;
6485
6507
  {
6486
 
    uint32_t i;
 
6508
    uint i;
6487
6509
    for (i=0 ; i < keyparts ; keyuse++,i++)
6488
6510
    {
6489
6511
      while (keyuse->keypart != i ||
6490
6512
             ((~used_tables) & keyuse->used_tables))
6491
6513
        keyuse++;                               /* Skip other parts */
6492
6514
 
6493
 
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
 
6515
      uint maybe_null= test(keyinfo->key_part[i].null_bit);
6494
6516
      j->ref.items[i]=keyuse->val;              // Save for cond removal
6495
6517
      j->ref.cond_guards[i]= keyuse->cond_guard;
6496
6518
      if (keyuse->null_rejecting) 
6552
6574
 
6553
6575
static store_key *
6554
6576
get_store_key(THD *thd, KEYUSE *keyuse, table_map used_tables,
6555
 
              KEY_PART_INFO *key_part, unsigned char *key_buff, uint32_t maybe_null)
 
6577
              KEY_PART_INFO *key_part, uchar *key_buff, uint maybe_null)
6556
6578
{
6557
6579
  if (!((~used_tables) & keyuse->used_tables))          // if const item
6558
6580
  {
6595
6617
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
6596
6618
{
6597
6619
  bool error;
6598
 
  Table *table= field->table;
 
6620
  TABLE *table= field->table;
6599
6621
  THD *thd= table->in_use;
6600
6622
  ha_rows cuted_fields=thd->cuted_fields;
 
6623
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
 
6624
                                                   table->write_set);
6601
6625
 
6602
6626
  /*
6603
6627
    we should restore old value of count_cuted_fields because
6608
6632
  thd->count_cuted_fields= check_flag;
6609
6633
  error= item->save_in_field(field, 1);
6610
6634
  thd->count_cuted_fields= old_count_cuted_fields;
 
6635
  dbug_tmp_restore_column_map(table->write_set, old_map);
6611
6636
  return error || cuted_fields != thd->cuted_fields;
6612
6637
}
6613
6638
 
6614
6639
 
6615
6640
static bool
6616
 
make_simple_join(JOIN *join,Table *tmp_table)
 
6641
make_simple_join(JOIN *join,TABLE *tmp_table)
6617
6642
{
6618
 
  Table **tableptr;
 
6643
  TABLE **tableptr;
6619
6644
  JOIN_TAB *join_tab;
6620
6645
 
6621
6646
  /*
6622
 
    Reuse Table * and JOIN_TAB if already allocated by a previous call
 
6647
    Reuse TABLE * and JOIN_TAB if already allocated by a previous call
6623
6648
    to this function through JOIN::exec (may happen for sub-queries).
6624
6649
  */
6625
6650
  if (!join->table_reexec)
6626
6651
  {
6627
 
    if (!(join->table_reexec= (Table**) join->thd->alloc(sizeof(Table*))))
 
6652
    if (!(join->table_reexec= (TABLE**) join->thd->alloc(sizeof(TABLE*))))
6628
6653
      return(true);                        /* purecov: inspected */
6629
6654
    if (join->tmp_join)
6630
6655
      join->tmp_join->table_reexec= join->table_reexec;
6673
6698
  join_tab->ref.key_parts= 0;
6674
6699
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
6675
6700
  join_tab->do_firstmatch= NULL;
6676
 
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
 
6701
  bzero((char*) &join_tab->read_record,sizeof(join_tab->read_record));
6677
6702
  tmp_table->status=0;
6678
6703
  tmp_table->null_row=0;
6679
6704
  return(false);
6749
6774
 
6750
6775
static void add_not_null_conds(JOIN *join)
6751
6776
{
6752
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6777
  for (uint i=join->const_tables ; i < join->tables ; i++)
6753
6778
  {
6754
6779
    JOIN_TAB *tab=join->join_tab+i;
6755
6780
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF || 
6756
6781
         tab->type == JT_REF_OR_NULL) &&
6757
6782
        !tab->table->maybe_null)
6758
6783
    {
6759
 
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
 
6784
      for (uint keypart= 0; keypart < tab->ref.key_parts; keypart++)
6760
6785
      {
6761
6786
        if (tab->ref.null_rejecting & (1 << keypart))
6762
6787
        {
6869
6894
static void
6870
6895
make_outerjoin_info(JOIN *join)
6871
6896
{
6872
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6897
  for (uint i=join->const_tables ; i < join->tables ; i++)
6873
6898
  {
6874
6899
    JOIN_TAB *tab=join->join_tab+i;
6875
 
    Table *table=tab->table;
6876
 
    TableList *tbl= table->pos_in_table_list;
6877
 
    TableList *embedding= tbl->embedding;
 
6900
    TABLE *table=tab->table;
 
6901
    TABLE_LIST *tbl= table->pos_in_table_list;
 
6902
    TABLE_LIST *embedding= tbl->embedding;
6878
6903
 
6879
6904
    if (tbl->outer_join)
6880
6905
    {
6894
6919
      /* Ignore sj-nests: */
6895
6920
      if (!embedding->on_expr)
6896
6921
        continue;
6897
 
      nested_join_st *nested_join= embedding->nested_join;
 
6922
      NESTED_JOIN *nested_join= embedding->nested_join;
6898
6923
      if (!nested_join->counter_)
6899
6924
      {
6900
6925
        /* 
6971
6996
    }
6972
6997
    used_tables=((select->const_tables=join->const_table_map) |
6973
6998
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
6974
 
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6999
    for (uint i=join->const_tables ; i < join->tables ; i++)
6975
7000
    {
6976
7001
      JOIN_TAB *tab=join->join_tab+i;
6977
7002
      /*
7040
7065
          tab->type == JT_EQ_REF)
7041
7066
      {
7042
7067
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
7043
 
                                       thd->memdup((unsigned char*) select,
 
7068
                                       thd->memdup((uchar*) select,
7044
7069
                                                   sizeof(*select)));
7045
7070
        if (!sel)
7046
7071
          return(1);                    // End of memory
7095
7120
          }
7096
7121
          tab->quick=0;
7097
7122
        }
7098
 
        uint32_t ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
 
7123
        uint ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
7099
7124
        if (i == join->const_tables && ref_key)
7100
7125
        {
7101
7126
          if (!tab->const_keys.is_clear_all() &&
7187
7212
                                         current_map, 0)))
7188
7213
            {
7189
7214
              tab->cache.select=(SQL_SELECT*)
7190
 
                thd->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
7215
                thd->memdup((uchar*) sel, sizeof(SQL_SELECT));
7191
7216
              tab->cache.select->cond=tmp;
7192
7217
              tab->cache.select->read_tables=join->const_table_map;
7193
7218
            }
7305
7330
    false  No
7306
7331
*/
7307
7332
 
7308
 
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, 
 
7333
bool uses_index_fields_only(Item *item, TABLE *tbl, uint keyno, 
7309
7334
                            bool other_tbls_ok)
7310
7335
{
7311
7336
  if (item->const_item())
7400
7425
    Index condition, or NULL if no condition could be inferred.
7401
7426
*/
7402
7427
 
7403
 
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno,
 
7428
Item *make_cond_for_index(Item *cond, TABLE *table, uint keyno,
7404
7429
                          bool other_tbls_ok)
7405
7430
{
7406
7431
  if (!cond)
7407
7432
    return NULL;
7408
7433
  if (cond->type() == Item::COND_ITEM)
7409
7434
  {
7410
 
    uint32_t n_marked= 0;
 
7435
    uint n_marked= 0;
7411
7436
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
7412
7437
    {
7413
7438
      Item_cond_and *new_cond=new Item_cond_and;
7539
7564
    Try to extract and push the index condition down to table handler
7540
7565
*/
7541
7566
 
7542
 
static void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
 
7567
static void push_index_cond(JOIN_TAB *tab, uint keyno, bool other_tbls_ok)
7543
7568
{
7544
7569
  Item *idx_cond;
7545
7570
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
7593
7618
 
7594
7619
 
7595
7620
    /*
7596
 
      Determine if the set is already ordered for order_st BY, so it can 
 
7621
      Determine if the set is already ordered for ORDER BY, so it can 
7597
7622
      disable join cache because it will change the ordering of the results.
7598
7623
      Code handles sort table that is at any location (not only first after 
7599
7624
      the const tables) despite the fact that it's currently prohibited.
7601
7626
      ordered. If there is a temp table the ordering is done as a last
7602
7627
      operation and doesn't prevent join cache usage.
7603
7628
    */
7604
 
uint32_t make_join_orderinfo(JOIN *join)
 
7629
uint make_join_orderinfo(JOIN *join)
7605
7630
{
7606
 
  uint32_t i;
 
7631
  uint i;
7607
7632
  if (join->need_tmp)
7608
7633
    return join->tables;
7609
7634
 
7610
7635
  for (i=join->const_tables ; i < join->tables ; i++)
7611
7636
  {
7612
7637
    JOIN_TAB *tab=join->join_tab+i;
7613
 
    Table *table=tab->table;
 
7638
    TABLE *table=tab->table;
7614
7639
    if ((table == join->sort_by_table && 
7615
7640
         (!join->order || join->skip_sort_order)) ||
7616
 
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
 
7641
        (join->sort_by_table == (TABLE *) 1 && i != join->const_tables))
7617
7642
    {
7618
7643
      break;
7619
7644
    }
7645
7670
*/
7646
7671
 
7647
7672
static bool
7648
 
make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
7673
make_join_readinfo(JOIN *join, uint64_t options, uint no_jbuf_after)
7649
7674
{
7650
 
  uint32_t i;
 
7675
  uint i;
7651
7676
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
7652
7677
  bool sorted= 1;
7653
7678
 
7654
7679
  for (i=join->const_tables ; i < join->tables ; i++)
7655
7680
  {
7656
7681
    JOIN_TAB *tab=join->join_tab+i;
7657
 
    Table *table=tab->table;
 
7682
    TABLE *table=tab->table;
7658
7683
    bool using_join_cache;
7659
7684
    tab->read_record.table= table;
7660
7685
    tab->read_record.file=table->file;
7667
7692
    sorted= 0;                                  // only first must be sorted
7668
7693
    if (tab->insideout_match_tab)
7669
7694
    {
7670
 
      if (!(tab->insideout_buf= (unsigned char*)join->thd->alloc(tab->table->key_info
 
7695
      if (!(tab->insideout_buf= (uchar*)join->thd->alloc(tab->table->key_info
7671
7696
                                                         [tab->index].
7672
7697
                                                         key_length)))
7673
7698
        return true;
7819
7844
                  table->file->primary_key_is_clustered())
7820
7845
                tab->index= table->s->primary_key;
7821
7846
              else
7822
 
                tab->index= table->find_shortest_key(&table->covering_keys);
 
7847
                tab->index=find_shortest_key(table, & table->covering_keys);
7823
7848
            }
7824
7849
            tab->read_first_record= join_read_first;
7825
7850
            tab->type=JT_NEXT;          // Read with index_first / index_next
7883
7908
  select= 0;
7884
7909
  delete quick;
7885
7910
  quick= 0;
7886
 
  if (cache.buff)
7887
 
    free(cache.buff);
 
7911
  x_free(cache.buff);
7888
7912
  cache.buff= 0;
7889
7913
  limit= 0;
7890
7914
  if (table)
7938
7962
    a correlated subquery itself, but has subqueries, we can free it
7939
7963
    fully and also free JOINs of all its subqueries. The exception
7940
7964
    is a subquery in SELECT list, e.g: @n
7941
 
    SELECT a, (select cmax(b) from t1) group by c @n
 
7965
    SELECT a, (select max(b) from t1) group by c @n
7942
7966
    This subquery will not be evaluated at first sweep and its value will
7943
7967
    not be inserted into the temporary table. Instead, it's evaluated
7944
7968
    when selecting from the temporary table. Therefore, it can't be freed
8082
8106
 
8083
8107
 
8084
8108
/**
8085
 
  Remove the following expressions from order_st BY and GROUP BY:
 
8109
  Remove the following expressions from ORDER BY and GROUP BY:
8086
8110
  Constant expressions @n
8087
8111
  Expression that only uses tables that are of type EQ_REF and the reference
8088
 
  is in the order_st list or if all refereed tables are of the above type.
 
8112
  is in the ORDER list or if all refereed tables are of the above type.
8089
8113
 
8090
8114
  In the following, the X field can be removed:
8091
8115
  @code
8092
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
8093
 
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
 
8116
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
 
8117
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
8094
8118
  @endcode
8095
8119
 
8096
8120
  These can't be optimized:
8097
8121
  @code
8098
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
8099
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
8100
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
 
8122
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
 
8123
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
 
8124
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
8101
8125
  @endcode
8102
8126
*/
8103
8127
 
8104
8128
static bool
8105
 
eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
 
8129
eq_ref_table(JOIN *join, ORDER *start_order, JOIN_TAB *tab)
8106
8130
{
8107
8131
  if (tab->cached_eq_ref_table)                 // If cached
8108
8132
    return tab->eq_ref_table;
8114
8138
    return (tab->eq_ref_table=0);               // We must use this
8115
8139
  Item **ref_item=tab->ref.items;
8116
8140
  Item **end=ref_item+tab->ref.key_parts;
8117
 
  uint32_t found=0;
 
8141
  uint found=0;
8118
8142
  table_map map=tab->table->map;
8119
8143
 
8120
8144
  for (; ref_item != end ; ref_item++)
8121
8145
  {
8122
8146
    if (! (*ref_item)->const_item())
8123
8147
    {                                           // Not a const ref
8124
 
      order_st *order;
 
8148
      ORDER *order;
8125
8149
      for (order=start_order ; order ; order=order->next)
8126
8150
      {
8127
8151
        if ((*ref_item)->eq(order->item[0],0))
8132
8156
        found++;
8133
8157
        assert(!(order->used & map));
8134
8158
        order->used|=map;
8135
 
        continue;                               // Used in order_st BY
 
8159
        continue;                               // Used in ORDER BY
8136
8160
      }
8137
8161
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
8138
8162
        return (tab->eq_ref_table=0);
8154
8178
 
8155
8179
 
8156
8180
static bool
8157
 
only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
 
8181
only_eq_ref_tables(JOIN *join,ORDER *order,table_map tables)
8158
8182
{
 
8183
  if (specialflag &  SPECIAL_SAFE_MODE)
 
8184
    return 0;                   // skip this optimize /* purecov: inspected */
8159
8185
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
8160
8186
  {
8161
8187
    if (tables & 1 && !eq_ref_table(join, order, *tab))
8176
8202
    TABLE_REF *ref= &join_tab->ref;
8177
8203
    table_map depend_map=0;
8178
8204
    Item **item=ref->items;
8179
 
    uint32_t i;
 
8205
    uint i;
8180
8206
    for (i=0 ; i < ref->key_parts ; i++,item++)
8181
8207
      depend_map|=(*item)->used_tables();
8182
8208
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
8194
8220
 
8195
8221
/** Update the dependency map for the sort order. */
8196
8222
 
8197
 
static void update_depend_map(JOIN *join, order_st *order)
 
8223
static void update_depend_map(JOIN *join, ORDER *order)
8198
8224
{
8199
8225
  for (; order ; order=order->next)
8200
8226
  {
8218
8244
 
8219
8245
 
8220
8246
/**
8221
 
  Remove all constants and check if order_st only contains simple
 
8247
  Remove all constants and check if ORDER only contains simple
8222
8248
  expressions.
8223
8249
 
8224
8250
  simple_order is set to 1 if sort_order only uses fields from head table
8236
8262
    Returns new sort order
8237
8263
*/
8238
8264
 
8239
 
static order_st *
8240
 
remove_const(JOIN *join,order_st *first_order, COND *cond,
 
8265
static ORDER *
 
8266
remove_const(JOIN *join,ORDER *first_order, COND *cond,
8241
8267
             bool change_list, bool *simple_order)
8242
8268
{
8243
8269
  if (join->tables == join->const_tables)
8244
8270
    return change_list ? 0 : first_order;               // No need to sort
8245
8271
 
8246
 
  order_st *order,**prev_ptr;
 
8272
  ORDER *order,**prev_ptr;
8247
8273
  table_map first_table= join->join_tab[join->const_tables].table->map;
8248
8274
  table_map not_const_tables= ~join->const_table_map;
8249
8275
  table_map ref;
8300
8326
 
8301
8327
 
8302
8328
static int
8303
 
return_zero_rows(JOIN *join, select_result *result,TableList *tables,
 
8329
return_zero_rows(JOIN *join, select_result *result,TABLE_LIST *tables,
8304
8330
                 List<Item> &fields, bool send_row, uint64_t select_options,
8305
8331
                 const char *info, Item *having)
8306
8332
{
8314
8340
 
8315
8341
  if (send_row)
8316
8342
  {
8317
 
    for (TableList *table= tables; table; table= table->next_leaf)
 
8343
    for (TABLE_LIST *table= tables; table; table= table->next_leaf)
8318
8344
      mark_as_null_row(table->table);           // All fields are NULL
8319
8345
    if (having && having->val_int() == 0)
8320
8346
      send_row=0;
8346
8372
    must clear only the non-const tables, as const tables
8347
8373
    are not re-calculated.
8348
8374
  */
8349
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
8375
  for (uint i=join->const_tables ; i < join->tables ; i++)
8350
8376
    mark_as_null_row(join->table[i]);           // All fields are NULL
8351
8377
}
8352
8378
 
8638
8664
 
8639
8665
      if (field_item->result_type() == STRING_RESULT)
8640
8666
      {
8641
 
        const CHARSET_INFO * const cs= ((Field_str*) field_item->field)->charset();
 
8667
        CHARSET_INFO *cs= ((Field_str*) field_item->field)->charset();
8642
8668
        if (!item)
8643
8669
        {
8644
8670
          Item_func_eq *eq_item;
8710
8736
static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row,
8711
8737
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
8712
8738
8713
 
  uint32_t n= left_row->cols();
8714
 
  for (uint32_t i= 0 ; i < n; i++)
 
8739
  uint n= left_row->cols();
 
8740
  for (uint i= 0 ; i < n; i++)
8715
8741
  {
8716
8742
    bool is_converted;
8717
8743
    Item *left_item= left_row->element_index(i);
8998
9024
      as soon the field is not of a string type or the field reference is
8999
9025
      an argument of a comparison predicate. 
9000
9026
    */ 
9001
 
    unsigned char *is_subst_valid= (unsigned char *) 1;
 
9027
    uchar *is_subst_valid= (uchar *) 1;
9002
9028
    cond= cond->compile(&Item::subst_argument_checker,
9003
9029
                        &is_subst_valid, 
9004
9030
                        &Item::equal_fields_propagator,
9005
 
                        (unsigned char *) inherited);
 
9031
                        (uchar *) inherited);
9006
9032
    cond->update_used_tables();
9007
9033
  }
9008
9034
  return cond;
9077
9103
   
9078
9104
static COND *build_equal_items(THD *thd, COND *cond,
9079
9105
                               COND_EQUAL *inherited,
9080
 
                               List<TableList> *join_list,
 
9106
                               List<TABLE_LIST> *join_list,
9081
9107
                               COND_EQUAL **cond_equal_ref)
9082
9108
{
9083
9109
  COND_EQUAL *cond_equal= 0;
9105
9131
 
9106
9132
  if (join_list)
9107
9133
  {
9108
 
    TableList *table;
9109
 
    List_iterator<TableList> li(*join_list);
 
9134
    TABLE_LIST *table;
 
9135
    List_iterator<TABLE_LIST> li(*join_list);
9110
9136
 
9111
9137
    while ((table= li++))
9112
9138
    {
9113
9139
      if (table->on_expr)
9114
9140
      {
9115
 
        List<TableList> *nested_join_list= table->nested_join ?
 
9141
        List<TABLE_LIST> *nested_join_list= table->nested_join ?
9116
9142
          &table->nested_join->join_list : NULL;
9117
9143
        /*
9118
9144
          We can modify table->on_expr because its old value will
9436
9462
        */  
9437
9463
        if (!possible_keys.is_clear_all())
9438
9464
        {
9439
 
          Table *tab= field->table;
 
9465
          TABLE *tab= field->table;
9440
9466
          KEYUSE *use;
9441
9467
          for (use= stat->keyuse; use && use->table == tab; use++)
9442
9468
            if (possible_keys.is_set(use->key) && 
9748
9774
*/
9749
9775
 
9750
9776
static COND *
9751
 
simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top,
 
9777
simplify_joins(JOIN *join, List<TABLE_LIST> *join_list, COND *conds, bool top,
9752
9778
               bool in_sj)
9753
9779
{
9754
 
  TableList *table;
9755
 
  nested_join_st *nested_join;
9756
 
  TableList *prev_table= 0;
9757
 
  List_iterator<TableList> li(*join_list);
 
9780
  TABLE_LIST *table;
 
9781
  NESTED_JOIN *nested_join;
 
9782
  TABLE_LIST *prev_table= 0;
 
9783
  List_iterator<TABLE_LIST> li(*join_list);
9758
9784
 
9759
9785
  /* 
9760
9786
    Try to simplify join operations from join_list.
9904
9930
    }
9905
9931
    else if (nested_join && !table->on_expr)
9906
9932
    {
9907
 
      TableList *tbl;
9908
 
      List_iterator<TableList> it(nested_join->join_list);
 
9933
      TABLE_LIST *tbl;
 
9934
      List_iterator<TABLE_LIST> it(nested_join->join_list);
9909
9935
      while ((tbl= it++))
9910
9936
      {
9911
9937
        tbl->embedding= table->embedding;
9938
9964
    First unused bit in nested_join_map after the call.
9939
9965
*/
9940
9966
 
9941
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, 
9942
 
                                          uint32_t first_unused)
 
9967
static uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list, 
 
9968
                                          uint first_unused)
9943
9969
{
9944
 
  List_iterator<TableList> li(*join_list);
9945
 
  TableList *table;
 
9970
  List_iterator<TABLE_LIST> li(*join_list);
 
9971
  TABLE_LIST *table;
9946
9972
  while ((table= li++))
9947
9973
  {
9948
 
    nested_join_st *nested_join;
 
9974
    NESTED_JOIN *nested_join;
9949
9975
    if ((nested_join= table->nested_join))
9950
9976
    {
9951
9977
      /*
9974
10000
 
9975
10001
 
9976
10002
/**
9977
 
  Set nested_join_st::counter=0 in all nested joins in passed list.
 
10003
  Set NESTED_JOIN::counter=0 in all nested joins in passed list.
9978
10004
 
9979
 
    Recursively set nested_join_st::counter=0 for all nested joins contained in
 
10005
    Recursively set NESTED_JOIN::counter=0 for all nested joins contained in
9980
10006
    the passed join_list.
9981
10007
 
9982
10008
  @param join_list  List of nested joins to process. It may also contain base
9983
10009
                    tables which will be ignored.
9984
10010
*/
9985
10011
 
9986
 
static void reset_nj_counters(List<TableList> *join_list)
 
10012
static void reset_nj_counters(List<TABLE_LIST> *join_list)
9987
10013
{
9988
 
  List_iterator<TableList> li(*join_list);
9989
 
  TableList *table;
 
10014
  List_iterator<TABLE_LIST> li(*join_list);
 
10015
  TABLE_LIST *table;
9990
10016
  while ((table= li++))
9991
10017
  {
9992
 
    nested_join_st *nested_join;
 
10018
    NESTED_JOIN *nested_join;
9993
10019
    if ((nested_join= table->nested_join))
9994
10020
    {
9995
10021
      nested_join->counter_= 0;
10012
10038
 
10013
10039
  @verbatim
10014
10040
     IMPLEMENTATION 
10015
 
       LIMITATIONS ON JOIN order_st
 
10041
       LIMITATIONS ON JOIN ORDER
10016
10042
         The nested [outer] joins executioner algorithm imposes these limitations
10017
10043
         on join order:
10018
10044
         1. "Outer tables first" -  any "outer" table must be before any 
10076
10102
         position:
10077
10103
          1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested
10078
10104
             joins) we've opened but didn't close.
10079
 
          2. {each nested_join_st structure not simplified away}->counter - number
 
10105
          2. {each NESTED_JOIN structure not simplified away}->counter - number
10080
10106
             of this nested join's children that have already been added to to
10081
10107
             the partial join order.
10082
10108
  @endverbatim
10095
10121
 
10096
10122
static bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
10097
10123
{
10098
 
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
 
10124
  TABLE_LIST *next_emb= next_tab->table->pos_in_table_list->embedding;
10099
10125
  JOIN *join= last_tab->join;
10100
10126
 
10101
10127
  if (join->cur_embedding_map & ~next_tab->embedding_map)
10152
10178
 
10153
10179
static void restore_prev_nj_state(JOIN_TAB *last)
10154
10180
{
10155
 
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
10181
  TABLE_LIST *last_emb= last->table->pos_in_table_list->embedding;
10156
10182
  JOIN *join= last->join;
10157
10183
  while (last_emb)
10158
10184
  {
10175
10201
static 
10176
10202
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
10177
10203
{
10178
 
  TableList *emb_sj_nest;
 
10204
  TABLE_LIST *emb_sj_nest;
10179
10205
  if ((emb_sj_nest= tab->emb_sj_nest))
10180
10206
  {
10181
10207
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
10193
10219
static void restore_prev_sj_state(const table_map remaining_tables, 
10194
10220
                                  const JOIN_TAB *tab)
10195
10221
{
10196
 
  TableList *emb_sj_nest;
 
10222
  TABLE_LIST *emb_sj_nest;
10197
10223
  if ((emb_sj_nest= tab->emb_sj_nest))
10198
10224
  {
10199
10225
    /* If we're removing the last SJ-inner table, remove the sj-nest */
10207
10233
 
10208
10234
 
10209
10235
static COND *
10210
 
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
 
10236
optimize_cond(JOIN *join, COND *conds, List<TABLE_LIST> *join_list,
10211
10237
              Item::cond_result *cond_value)
10212
10238
{
10213
10239
  THD *thd= join->thd;
10270
10296
        li.remove();
10271
10297
      else if (item != new_item)
10272
10298
      {
10273
 
        li.replace(new_item);
 
10299
        VOID(li.replace(new_item));
10274
10300
        should_fix_fields=1;
10275
10301
      }
10276
10302
      if (*cond_value == Item::COND_UNDEF)
10355
10381
        thd->substitute_null_with_insert_id= false;
10356
10382
      }
10357
10383
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
10358
 
      else if (((field->type() == DRIZZLE_TYPE_NEWDATE) ||
10359
 
                (field->type() == DRIZZLE_TYPE_DATETIME)) &&
 
10384
      else if (((field->type() == MYSQL_TYPE_NEWDATE) ||
 
10385
                (field->type() == MYSQL_TYPE_DATETIME)) &&
10360
10386
                (field->flags & NOT_NULL_FLAG) &&
10361
10387
               !field->table->maybe_null)
10362
10388
      {
10503
10529
  return 0;
10504
10530
}
10505
10531
 
 
10532
/****************************************************************************
 
10533
  Create internal temporary table
 
10534
****************************************************************************/
 
10535
 
 
10536
/**
 
10537
  Create field for temporary table from given field.
 
10538
 
 
10539
  @param thd           Thread handler
 
10540
  @param org_field    field from which new field will be created
 
10541
  @param name         New field name
 
10542
  @param table         Temporary table
 
10543
  @param item          !=NULL if item->result_field should point to new field.
 
10544
                      This is relevant for how fill_record() is going to work:
 
10545
                      If item != NULL then fill_record() will update
 
10546
                      the record in the original table.
 
10547
                      If item == NULL then fill_record() will update
 
10548
                      the temporary table
 
10549
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
10550
                               field instead of blob.
 
10551
 
 
10552
  @retval
 
10553
    NULL                on error
 
10554
  @retval
 
10555
    new_created field
 
10556
*/
 
10557
 
 
10558
Field *create_tmp_field_from_field(THD *thd, Field *org_field,
 
10559
                                   const char *name, TABLE *table,
 
10560
                                   Item_field *item, uint convert_blob_length)
 
10561
{
 
10562
  Field *new_field;
 
10563
 
 
10564
  /* 
 
10565
    Make sure that the blob fits into a Field_varstring which has 
 
10566
    2-byte lenght. 
 
10567
  */
 
10568
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
 
10569
      (org_field->flags & BLOB_FLAG))
 
10570
    new_field= new Field_varstring(convert_blob_length,
 
10571
                                   org_field->maybe_null(),
 
10572
                                   org_field->field_name, table->s,
 
10573
                                   org_field->charset());
 
10574
  else
 
10575
    new_field= org_field->new_field(thd->mem_root, table,
 
10576
                                    table == org_field->table);
 
10577
  if (new_field)
 
10578
  {
 
10579
    new_field->init(table);
 
10580
    new_field->orig_table= org_field->orig_table;
 
10581
    if (item)
 
10582
      item->result_field= new_field;
 
10583
    else
 
10584
      new_field->field_name= name;
 
10585
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
 
10586
    if (org_field->maybe_null() || (item && item->maybe_null))
 
10587
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
 
10588
    if (org_field->type() == MYSQL_TYPE_VAR_STRING ||
 
10589
        org_field->type() == MYSQL_TYPE_VARCHAR)
 
10590
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
 
10591
    else if (org_field->type() == FIELD_TYPE_DOUBLE)
 
10592
      ((Field_double *) new_field)->not_fixed= true;
 
10593
  }
 
10594
  return new_field;
 
10595
}
 
10596
 
 
10597
/**
 
10598
  Create field for temporary table using type of given item.
 
10599
 
 
10600
  @param thd                   Thread handler
 
10601
  @param item                  Item to create a field for
 
10602
  @param table                 Temporary table
 
10603
  @param copy_func             If set and item is a function, store copy of
 
10604
                               item in this array
 
10605
  @param modify_item           1 if item->result_field should point to new
 
10606
                               item. This is relevent for how fill_record()
 
10607
                               is going to work:
 
10608
                               If modify_item is 1 then fill_record() will
 
10609
                               update the record in the original table.
 
10610
                               If modify_item is 0 then fill_record() will
 
10611
                               update the temporary table
 
10612
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
10613
                               field instead of blob.
 
10614
 
 
10615
  @retval
 
10616
    0  on error
 
10617
  @retval
 
10618
    new_created field
 
10619
*/
 
10620
 
 
10621
static Field *create_tmp_field_from_item(THD *thd __attribute__((__unused__)),
 
10622
                                         Item *item, TABLE *table,
 
10623
                                         Item ***copy_func, bool modify_item,
 
10624
                                         uint convert_blob_length)
 
10625
{
 
10626
  bool maybe_null= item->maybe_null;
 
10627
  Field *new_field;
 
10628
 
 
10629
  switch (item->result_type()) {
 
10630
  case REAL_RESULT:
 
10631
    new_field= new Field_double(item->max_length, maybe_null,
 
10632
                                item->name, item->decimals, true);
 
10633
    break;
 
10634
  case INT_RESULT:
 
10635
    /* 
 
10636
      Select an integer type with the minimal fit precision.
 
10637
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
 
10638
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into 
 
10639
      Field_long : make them Field_int64_t.  
 
10640
    */
 
10641
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
 
10642
      new_field=new Field_int64_t(item->max_length, maybe_null,
 
10643
                                   item->name, item->unsigned_flag);
 
10644
    else
 
10645
      new_field=new Field_long(item->max_length, maybe_null,
 
10646
                               item->name, item->unsigned_flag);
 
10647
    break;
 
10648
  case STRING_RESULT:
 
10649
    assert(item->collation.collation);
 
10650
  
 
10651
    enum enum_field_types type;
 
10652
    /*
 
10653
      DATE/TIME fields have STRING_RESULT result type. 
 
10654
      To preserve type they needed to be handled separately.
 
10655
    */
 
10656
    if ((type= item->field_type()) == MYSQL_TYPE_DATETIME ||
 
10657
        type == MYSQL_TYPE_TIME || type == MYSQL_TYPE_NEWDATE ||
 
10658
        type == MYSQL_TYPE_TIMESTAMP)
 
10659
      new_field= item->tmp_table_field_from_field_type(table, 1);
 
10660
    /* 
 
10661
      Make sure that the blob fits into a Field_varstring which has 
 
10662
      2-byte lenght. 
 
10663
    */
 
10664
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
 
10665
             convert_blob_length <= Field_varstring::MAX_SIZE && 
 
10666
             convert_blob_length)
 
10667
      new_field= new Field_varstring(convert_blob_length, maybe_null,
 
10668
                                     item->name, table->s,
 
10669
                                     item->collation.collation);
 
10670
    else
 
10671
      new_field= item->make_string_field(table);
 
10672
    new_field->set_derivation(item->collation.derivation);
 
10673
    break;
 
10674
  case DECIMAL_RESULT:
 
10675
  {
 
10676
    uint8_t dec= item->decimals;
 
10677
    uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
 
10678
    uint32_t len= item->max_length;
 
10679
 
 
10680
    /*
 
10681
      Trying to put too many digits overall in a DECIMAL(prec,dec)
 
10682
      will always throw a warning. We must limit dec to
 
10683
      DECIMAL_MAX_SCALE however to prevent an assert() later.
 
10684
    */
 
10685
 
 
10686
    if (dec > 0)
 
10687
    {
 
10688
      signed int overflow;
 
10689
 
 
10690
      dec= min(dec, DECIMAL_MAX_SCALE);
 
10691
 
 
10692
      /*
 
10693
        If the value still overflows the field with the corrected dec,
 
10694
        we'll throw out decimals rather than integers. This is still
 
10695
        bad and of course throws a truncation warning.
 
10696
        +1: for decimal point
 
10697
      */
 
10698
 
 
10699
      overflow= my_decimal_precision_to_length(intg + dec, dec,
 
10700
                                               item->unsigned_flag) - len;
 
10701
 
 
10702
      if (overflow > 0)
 
10703
        dec= max(0, dec - overflow);            // too long, discard fract
 
10704
      else
 
10705
        len -= item->decimals - dec;            // corrected value fits
 
10706
    }
 
10707
 
 
10708
    new_field= new Field_new_decimal(len, maybe_null, item->name,
 
10709
                                     dec, item->unsigned_flag);
 
10710
    break;
 
10711
  }
 
10712
  case ROW_RESULT:
 
10713
  default:
 
10714
    // This case should never be choosen
 
10715
    assert(0);
 
10716
    new_field= 0;
 
10717
    break;
 
10718
  }
 
10719
  if (new_field)
 
10720
    new_field->init(table);
 
10721
    
 
10722
  if (copy_func && item->is_result_field())
 
10723
    *((*copy_func)++) = item;                   // Save for copy_funcs
 
10724
  if (modify_item)
 
10725
    item->set_result_field(new_field);
 
10726
  if (item->type() == Item::NULL_ITEM)
 
10727
    new_field->is_created_from_null_item= true;
 
10728
  return new_field;
 
10729
}
 
10730
 
 
10731
 
 
10732
/**
 
10733
  Create field for information schema table.
 
10734
 
 
10735
  @param thd            Thread handler
 
10736
  @param table          Temporary table
 
10737
  @param item           Item to create a field for
 
10738
 
 
10739
  @retval
 
10740
    0                   on error
 
10741
  @retval
 
10742
    new_created field
 
10743
*/
 
10744
 
 
10745
Field *create_tmp_field_for_schema(THD *thd __attribute__((__unused__)),
 
10746
                                   Item *item, TABLE *table)
 
10747
{
 
10748
  if (item->field_type() == MYSQL_TYPE_VARCHAR)
 
10749
  {
 
10750
    Field *field;
 
10751
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
 
10752
      field= new Field_blob(item->max_length, item->maybe_null,
 
10753
                            item->name, item->collation.collation);
 
10754
    else
 
10755
      field= new Field_varstring(item->max_length, item->maybe_null,
 
10756
                                 item->name,
 
10757
                                 table->s, item->collation.collation);
 
10758
    if (field)
 
10759
      field->init(table);
 
10760
    return field;
 
10761
  }
 
10762
  return item->tmp_table_field_from_field_type(table, 0);
 
10763
}
 
10764
 
 
10765
 
 
10766
/**
 
10767
  Create field for temporary table.
 
10768
 
 
10769
  @param thd            Thread handler
 
10770
  @param table          Temporary table
 
10771
  @param item           Item to create a field for
 
10772
  @param type           Type of item (normally item->type)
 
10773
  @param copy_func      If set and item is a function, store copy of item
 
10774
                       in this array
 
10775
  @param from_field    if field will be created using other field as example,
 
10776
                       pointer example field will be written here
 
10777
  @param default_field  If field has a default value field, store it here
 
10778
  @param group          1 if we are going to do a relative group by on result
 
10779
  @param modify_item    1 if item->result_field should point to new item.
 
10780
                       This is relevent for how fill_record() is going to
 
10781
                       work:
 
10782
                       If modify_item is 1 then fill_record() will update
 
10783
                       the record in the original table.
 
10784
                       If modify_item is 0 then fill_record() will update
 
10785
                       the temporary table
 
10786
  @param convert_blob_length If >0 create a varstring(convert_blob_length)
 
10787
                             field instead of blob.
 
10788
 
 
10789
  @retval
 
10790
    0                   on error
 
10791
  @retval
 
10792
    new_created field
 
10793
*/
 
10794
 
 
10795
Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
 
10796
                        Item ***copy_func, Field **from_field,
 
10797
                        Field **default_field,
 
10798
                        bool group, bool modify_item,
 
10799
                        bool table_cant_handle_bit_fields __attribute__((__unused__)),
 
10800
                        bool make_copy_field,
 
10801
                        uint convert_blob_length)
 
10802
{
 
10803
  Field *result;
 
10804
  Item::Type orig_type= type;
 
10805
  Item *orig_item= 0;
 
10806
 
 
10807
  if (type != Item::FIELD_ITEM &&
 
10808
      item->real_item()->type() == Item::FIELD_ITEM)
 
10809
  {
 
10810
    orig_item= item;
 
10811
    item= item->real_item();
 
10812
    type= Item::FIELD_ITEM;
 
10813
  }
 
10814
 
 
10815
  switch (type) {
 
10816
  case Item::SUM_FUNC_ITEM:
 
10817
  {
 
10818
    Item_sum *item_sum=(Item_sum*) item;
 
10819
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
 
10820
    if (!result)
 
10821
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
10822
    return result;
 
10823
  }
 
10824
  case Item::FIELD_ITEM:
 
10825
  case Item::DEFAULT_VALUE_ITEM:
 
10826
  {
 
10827
    Item_field *field= (Item_field*) item;
 
10828
    bool orig_modify= modify_item;
 
10829
    if (orig_type == Item::REF_ITEM)
 
10830
      modify_item= 0;
 
10831
    /*
 
10832
      If item have to be able to store NULLs but underlaid field can't do it,
 
10833
      create_tmp_field_from_field() can't be used for tmp field creation.
 
10834
    */
 
10835
    if (field->maybe_null && !field->field->maybe_null())
 
10836
    {
 
10837
      result= create_tmp_field_from_item(thd, item, table, NULL,
 
10838
                                         modify_item, convert_blob_length);
 
10839
      *from_field= field->field;
 
10840
      if (result && modify_item)
 
10841
        field->result_field= result;
 
10842
    } 
 
10843
    else
 
10844
      result= create_tmp_field_from_field(thd, (*from_field= field->field),
 
10845
                                          orig_item ? orig_item->name :
 
10846
                                          item->name,
 
10847
                                          table,
 
10848
                                          modify_item ? field :
 
10849
                                          NULL,
 
10850
                                          convert_blob_length);
 
10851
    if (orig_type == Item::REF_ITEM && orig_modify)
 
10852
      ((Item_ref*)orig_item)->set_result_field(result);
 
10853
    if (field->field->eq_def(result))
 
10854
      *default_field= field->field;
 
10855
    return result;
 
10856
  }
 
10857
  /* Fall through */
 
10858
  case Item::FUNC_ITEM:
 
10859
    /* Fall through */
 
10860
  case Item::COND_ITEM:
 
10861
  case Item::FIELD_AVG_ITEM:
 
10862
  case Item::FIELD_STD_ITEM:
 
10863
  case Item::SUBSELECT_ITEM:
 
10864
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
 
10865
  case Item::PROC_ITEM:
 
10866
  case Item::INT_ITEM:
 
10867
  case Item::REAL_ITEM:
 
10868
  case Item::DECIMAL_ITEM:
 
10869
  case Item::STRING_ITEM:
 
10870
  case Item::REF_ITEM:
 
10871
  case Item::NULL_ITEM:
 
10872
  case Item::VARBIN_ITEM:
 
10873
    if (make_copy_field)
 
10874
    {
 
10875
      assert(((Item_result_field*)item)->result_field);
 
10876
      *from_field= ((Item_result_field*)item)->result_field;
 
10877
    }
 
10878
    return create_tmp_field_from_item(thd, item, table,
 
10879
                                      (make_copy_field ? 0 : copy_func),
 
10880
                                       modify_item, convert_blob_length);
 
10881
  case Item::TYPE_HOLDER:  
 
10882
    result= ((Item_type_holder *)item)->make_field_by_type(table);
 
10883
    result->set_derivation(item->collation.derivation);
 
10884
    return result;
 
10885
  default:                                      // Dosen't have to be stored
 
10886
    return 0;
 
10887
  }
 
10888
}
 
10889
 
 
10890
/*
 
10891
  Set up column usage bitmaps for a temporary table
 
10892
 
 
10893
  IMPLEMENTATION
 
10894
    For temporary tables, we need one bitmap with all columns set and
 
10895
    a tmp_set bitmap to be used by things like filesort.
 
10896
*/
 
10897
 
 
10898
void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps)
 
10899
{
 
10900
  uint field_count= table->s->fields;
 
10901
  bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count,
 
10902
              false);
 
10903
  bitmap_init(&table->tmp_set,
 
10904
              (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)),
 
10905
              field_count, false);
 
10906
  /* write_set and all_set are copies of read_set */
 
10907
  table->def_write_set= table->def_read_set;
 
10908
  table->s->all_set= table->def_read_set;
 
10909
  bitmap_set_all(&table->s->all_set);
 
10910
  table->default_column_bitmaps();
 
10911
}
 
10912
 
 
10913
 
 
10914
/**
 
10915
  Create a temp table according to a field list.
 
10916
 
 
10917
  Given field pointers are changed to point at tmp_table for
 
10918
  send_fields. The table object is self contained: it's
 
10919
  allocated in its own memory root, as well as Field objects
 
10920
  created for table columns.
 
10921
  This function will replace Item_sum items in 'fields' list with
 
10922
  corresponding Item_field items, pointing at the fields in the
 
10923
  temporary table, unless this was prohibited by true
 
10924
  value of argument save_sum_fields. The Item_field objects
 
10925
  are created in THD memory root.
 
10926
 
 
10927
  @param thd                  thread handle
 
10928
  @param param                a description used as input to create the table
 
10929
  @param fields               list of items that will be used to define
 
10930
                              column types of the table (also see NOTES)
 
10931
  @param group                TODO document
 
10932
  @param distinct             should table rows be distinct
 
10933
  @param save_sum_fields      see NOTES
 
10934
  @param select_options
 
10935
  @param rows_limit
 
10936
  @param table_alias          possible name of the temporary table that can
 
10937
                              be used for name resolving; can be "".
 
10938
*/
 
10939
 
 
10940
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
 
10941
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
 
10942
#define RATIO_TO_PACK_ROWS             2
 
10943
#define MIN_STRING_LENGTH_TO_PACK_ROWS   10
 
10944
 
 
10945
TABLE *
 
10946
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
 
10947
                 ORDER *group, bool distinct, bool save_sum_fields,
 
10948
                 uint64_t select_options, ha_rows rows_limit,
 
10949
                 char *table_alias)
 
10950
{
 
10951
  MEM_ROOT *mem_root_save, own_root;
 
10952
  TABLE *table;
 
10953
  TABLE_SHARE *share;
 
10954
  uint  i,field_count,null_count,null_pack_length;
 
10955
  uint  copy_func_count= param->func_count;
 
10956
  uint  hidden_null_count, hidden_null_pack_length, hidden_field_count;
 
10957
  uint  blob_count,group_null_items, string_count;
 
10958
  uint  temp_pool_slot=MY_BIT_NONE;
 
10959
  uint fieldnr= 0;
 
10960
  ulong reclength, string_total_length;
 
10961
  bool  using_unique_constraint= 0;
 
10962
  bool  use_packed_rows= 0;
 
10963
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
 
10964
  char  *tmpname,path[FN_REFLEN];
 
10965
  uchar *pos, *group_buff, *bitmaps;
 
10966
  uchar *null_flags;
 
10967
  Field **reg_field, **from_field, **default_field;
 
10968
  uint *blob_field;
 
10969
  Copy_field *copy=0;
 
10970
  KEY *keyinfo;
 
10971
  KEY_PART_INFO *key_part_info;
 
10972
  Item **copy_func;
 
10973
  MI_COLUMNDEF *recinfo;
 
10974
  uint total_uneven_bit_length= 0;
 
10975
  bool force_copy_fields= param->force_copy_fields;
 
10976
 
 
10977
  status_var_increment(thd->status_var.created_tmp_tables);
 
10978
 
 
10979
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
10980
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
10981
 
 
10982
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
10983
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
 
10984
            current_pid, temp_pool_slot);
 
10985
  else
 
10986
  {
 
10987
    /* if we run out of slots or we are not using tempool */
 
10988
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
 
10989
            thd->thread_id, thd->tmp_table++);
 
10990
  }
 
10991
 
 
10992
  /*
 
10993
    No need to change table name to lower case as we are only creating
 
10994
    MyISAM or HEAP tables here
 
10995
  */
 
10996
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
10997
 
 
10998
 
 
10999
  if (group)
 
11000
  {
 
11001
    if (!param->quick_group)
 
11002
      group=0;                                  // Can't use group key
 
11003
    else for (ORDER *tmp=group ; tmp ; tmp=tmp->next)
 
11004
    {
 
11005
      /*
 
11006
        marker == 4 means two things:
 
11007
        - store NULLs in the key, and
 
11008
        - convert BIT fields to 64-bit long, needed because MEMORY tables
 
11009
          can't index BIT fields.
 
11010
      */
 
11011
      (*tmp->item)->marker= 4;
 
11012
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
 
11013
        using_unique_constraint=1;
 
11014
    }
 
11015
    if (param->group_length >= MAX_BLOB_WIDTH)
 
11016
      using_unique_constraint=1;
 
11017
    if (group)
 
11018
      distinct=0;                               // Can't use distinct
 
11019
  }
 
11020
 
 
11021
  field_count=param->field_count+param->func_count+param->sum_func_count;
 
11022
  hidden_field_count=param->hidden_field_count;
 
11023
 
 
11024
  /*
 
11025
    When loose index scan is employed as access method, it already
 
11026
    computes all groups and the result of all aggregate functions. We
 
11027
    make space for the items of the aggregate function in the list of
 
11028
    functions TMP_TABLE_PARAM::items_to_copy, so that the values of
 
11029
    these items are stored in the temporary table.
 
11030
  */
 
11031
  if (param->precomputed_group_by)
 
11032
    copy_func_count+= param->sum_func_count;
 
11033
  
 
11034
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
11035
 
 
11036
  if (!multi_alloc_root(&own_root,
 
11037
                        &table, sizeof(*table),
 
11038
                        &share, sizeof(*share),
 
11039
                        &reg_field, sizeof(Field*) * (field_count+1),
 
11040
                        &default_field, sizeof(Field*) * (field_count),
 
11041
                        &blob_field, sizeof(uint)*(field_count+1),
 
11042
                        &from_field, sizeof(Field*)*field_count,
 
11043
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
 
11044
                        &param->keyinfo, sizeof(*param->keyinfo),
 
11045
                        &key_part_info,
 
11046
                        sizeof(*key_part_info)*(param->group_parts+1),
 
11047
                        &param->start_recinfo,
 
11048
                        sizeof(*param->recinfo)*(field_count*2+4),
 
11049
                        &tmpname, (uint) strlen(path)+1,
 
11050
                        &group_buff, (group && ! using_unique_constraint ?
 
11051
                                      param->group_length : 0),
 
11052
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
11053
                        NullS))
 
11054
  {
 
11055
    if (temp_pool_slot != MY_BIT_NONE)
 
11056
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11057
    return(NULL);                               /* purecov: inspected */
 
11058
  }
 
11059
  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
 
11060
  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
 
11061
  {
 
11062
    if (temp_pool_slot != MY_BIT_NONE)
 
11063
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11064
    free_root(&own_root, MYF(0));               /* purecov: inspected */
 
11065
    return(NULL);                               /* purecov: inspected */
 
11066
  }
 
11067
  param->items_to_copy= copy_func;
 
11068
  strmov(tmpname,path);
 
11069
  /* make table according to fields */
 
11070
 
 
11071
  bzero((char*) table,sizeof(*table));
 
11072
  bzero((char*) reg_field,sizeof(Field*)*(field_count+1));
 
11073
  bzero((char*) default_field, sizeof(Field*) * (field_count));
 
11074
  bzero((char*) from_field,sizeof(Field*)*field_count);
 
11075
 
 
11076
  table->mem_root= own_root;
 
11077
  mem_root_save= thd->mem_root;
 
11078
  thd->mem_root= &table->mem_root;
 
11079
 
 
11080
  table->field=reg_field;
 
11081
  table->alias= table_alias;
 
11082
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
 
11083
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
 
11084
  table->map=1;
 
11085
  table->temp_pool_slot = temp_pool_slot;
 
11086
  table->copy_blobs= 1;
 
11087
  table->in_use= thd;
 
11088
  table->quick_keys.init();
 
11089
  table->covering_keys.init();
 
11090
  table->keys_in_use_for_query.init();
 
11091
 
 
11092
  table->s= share;
 
11093
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
 
11094
  share->blob_field= blob_field;
 
11095
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
11096
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
11097
  share->table_charset= param->table_charset;
 
11098
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
11099
  share->keys_for_keyread.init();
 
11100
  share->keys_in_use.init();
 
11101
 
 
11102
  /* Calculate which type of fields we will store in the temporary table */
 
11103
 
 
11104
  reclength= string_total_length= 0;
 
11105
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
 
11106
  param->using_indirect_summary_function=0;
 
11107
 
 
11108
  List_iterator_fast<Item> li(fields);
 
11109
  Item *item;
 
11110
  Field **tmp_from_field=from_field;
 
11111
  while ((item=li++))
 
11112
  {
 
11113
    Item::Type type=item->type();
 
11114
    if (not_all_columns)
 
11115
    {
 
11116
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
 
11117
      {
 
11118
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
 
11119
          item->update_used_tables();
 
11120
        if (type == Item::SUBSELECT_ITEM ||
 
11121
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
 
11122
        {
 
11123
          /*
 
11124
            Mark that the we have ignored an item that refers to a summary
 
11125
            function. We need to know this if someone is going to use
 
11126
            DISTINCT on the result.
 
11127
          */
 
11128
          param->using_indirect_summary_function=1;
 
11129
          continue;
 
11130
        }
 
11131
      }
 
11132
      if (item->const_item() && (int) hidden_field_count <= 0)
 
11133
        continue; // We don't have to store this
 
11134
    }
 
11135
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
 
11136
    {                                           /* Can't calc group yet */
 
11137
      ((Item_sum*) item)->result_field=0;
 
11138
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
 
11139
      {
 
11140
        Item **argp= ((Item_sum*) item)->args + i;
 
11141
        Item *arg= *argp;
 
11142
        if (!arg->const_item())
 
11143
        {
 
11144
          Field *new_field=
 
11145
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
 
11146
                             tmp_from_field, &default_field[fieldnr],
 
11147
                             group != 0,not_all_columns,
 
11148
                             distinct, 0,
 
11149
                             param->convert_blob_length);
 
11150
          if (!new_field)
 
11151
            goto err;                                   // Should be OOM
 
11152
          tmp_from_field++;
 
11153
          reclength+=new_field->pack_length();
 
11154
          if (new_field->flags & BLOB_FLAG)
 
11155
          {
 
11156
            *blob_field++= fieldnr;
 
11157
            blob_count++;
 
11158
          }
 
11159
          *(reg_field++)= new_field;
 
11160
          if (new_field->real_type() == MYSQL_TYPE_STRING ||
 
11161
              new_field->real_type() == MYSQL_TYPE_VARCHAR)
 
11162
          {
 
11163
            string_count++;
 
11164
            string_total_length+= new_field->pack_length();
 
11165
          }
 
11166
          thd->mem_root= mem_root_save;
 
11167
          thd->change_item_tree(argp, new Item_field(new_field));
 
11168
          thd->mem_root= &table->mem_root;
 
11169
          if (!(new_field->flags & NOT_NULL_FLAG))
 
11170
          {
 
11171
            null_count++;
 
11172
            /*
 
11173
              new_field->maybe_null() is still false, it will be
 
11174
              changed below. But we have to setup Item_field correctly
 
11175
            */
 
11176
            (*argp)->maybe_null=1;
 
11177
          }
 
11178
          new_field->field_index= fieldnr++;
 
11179
        }
 
11180
      }
 
11181
    }
 
11182
    else
 
11183
    {
 
11184
      /*
 
11185
        The last parameter to create_tmp_field() is a bit tricky:
 
11186
 
 
11187
        We need to set it to 0 in union, to get fill_record() to modify the
 
11188
        temporary table.
 
11189
        We need to set it to 1 on multi-table-update and in select to
 
11190
        write rows to the temporary table.
 
11191
        We here distinguish between UNION and multi-table-updates by the fact
 
11192
        that in the later case group is set to the row pointer.
 
11193
      */
 
11194
      Field *new_field= (param->schema_table) ?
 
11195
        create_tmp_field_for_schema(thd, item, table) :
 
11196
        create_tmp_field(thd, table, item, type, &copy_func,
 
11197
                         tmp_from_field, &default_field[fieldnr],
 
11198
                         group != 0,
 
11199
                         !force_copy_fields &&
 
11200
                           (not_all_columns || group !=0),
 
11201
                         /*
 
11202
                           If item->marker == 4 then we force create_tmp_field
 
11203
                           to create a 64-bit longs for BIT fields because HEAP
 
11204
                           tables can't index BIT fields directly. We do the same
 
11205
                           for distinct, as we want the distinct index to be
 
11206
                           usable in this case too.
 
11207
                         */
 
11208
                         item->marker == 4 || param->bit_fields_as_long,
 
11209
                         force_copy_fields,
 
11210
                         param->convert_blob_length);
 
11211
 
 
11212
      if (!new_field)
 
11213
      {
 
11214
        if (thd->is_fatal_error)
 
11215
          goto err;                             // Got OOM
 
11216
        continue;                               // Some kindf of const item
 
11217
      }
 
11218
      if (type == Item::SUM_FUNC_ITEM)
 
11219
        ((Item_sum *) item)->result_field= new_field;
 
11220
      tmp_from_field++;
 
11221
      reclength+=new_field->pack_length();
 
11222
      if (!(new_field->flags & NOT_NULL_FLAG))
 
11223
        null_count++;
 
11224
      if (new_field->flags & BLOB_FLAG)
 
11225
      {
 
11226
        *blob_field++= fieldnr;
 
11227
        blob_count++;
 
11228
      }
 
11229
      if (item->marker == 4 && item->maybe_null)
 
11230
      {
 
11231
        group_null_items++;
 
11232
        new_field->flags|= GROUP_FLAG;
 
11233
      }
 
11234
      new_field->field_index= fieldnr++;
 
11235
      *(reg_field++)= new_field;
 
11236
    }
 
11237
    if (!--hidden_field_count)
 
11238
    {
 
11239
      /*
 
11240
        This was the last hidden field; Remember how many hidden fields could
 
11241
        have null
 
11242
      */
 
11243
      hidden_null_count=null_count;
 
11244
      /*
 
11245
        We need to update hidden_field_count as we may have stored group
 
11246
        functions with constant arguments
 
11247
      */
 
11248
      param->hidden_field_count= fieldnr;
 
11249
      null_count= 0;
 
11250
    }
 
11251
  }
 
11252
  assert(fieldnr == (uint) (reg_field - table->field));
 
11253
  assert(field_count >= (uint) (reg_field - table->field));
 
11254
  field_count= fieldnr;
 
11255
  *reg_field= 0;
 
11256
  *blob_field= 0;                               // End marker
 
11257
  share->fields= field_count;
 
11258
 
 
11259
  /* If result table is small; use a heap */
 
11260
  /* future: storage engine selection can be made dynamic? */
 
11261
  if (blob_count || using_unique_constraint ||
 
11262
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
11263
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
 
11264
  {
 
11265
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
11266
    table->file= get_new_handler(share, &table->mem_root,
 
11267
                                 share->db_type());
 
11268
    if (group &&
 
11269
        (param->group_parts > table->file->max_key_parts() ||
 
11270
         param->group_length > table->file->max_key_length()))
 
11271
      using_unique_constraint=1;
 
11272
  }
 
11273
  else
 
11274
  {
 
11275
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
11276
    table->file= get_new_handler(share, &table->mem_root,
 
11277
                                 share->db_type());
 
11278
  }
 
11279
  if (!table->file)
 
11280
    goto err;
 
11281
 
 
11282
 
 
11283
  if (!using_unique_constraint)
 
11284
    reclength+= group_null_items;       // null flag is stored separately
 
11285
 
 
11286
  share->blob_fields= blob_count;
 
11287
  if (blob_count == 0)
 
11288
  {
 
11289
    /* We need to ensure that first byte is not 0 for the delete link */
 
11290
    if (param->hidden_field_count)
 
11291
      hidden_null_count++;
 
11292
    else
 
11293
      null_count++;
 
11294
  }
 
11295
  hidden_null_pack_length=(hidden_null_count+7)/8;
 
11296
  null_pack_length= (hidden_null_pack_length +
 
11297
                     (null_count + total_uneven_bit_length + 7) / 8);
 
11298
  reclength+=null_pack_length;
 
11299
  if (!reclength)
 
11300
    reclength=1;                                // Dummy select
 
11301
  /* Use packed rows if there is blobs or a lot of space to gain */
 
11302
  if (blob_count || ((string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS) && (reclength / string_total_length <= RATIO_TO_PACK_ROWS || (string_total_length / string_count) >= AVG_STRING_LENGTH_TO_PACK_ROWS)))
 
11303
    use_packed_rows= 1;
 
11304
 
 
11305
  share->reclength= reclength;
 
11306
  {
 
11307
    uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
 
11308
    share->rec_buff_length= alloc_length;
 
11309
    if (!(table->record[0]= (uchar*)
 
11310
                            alloc_root(&table->mem_root, alloc_length*3)))
 
11311
      goto err;
 
11312
    table->record[1]= table->record[0]+alloc_length;
 
11313
    share->default_values= table->record[1]+alloc_length;
 
11314
  }
 
11315
  copy_func[0]=0;                               // End marker
 
11316
  param->func_count= copy_func - param->items_to_copy; 
 
11317
 
 
11318
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
11319
 
 
11320
  recinfo=param->start_recinfo;
 
11321
  null_flags=(uchar*) table->record[0];
 
11322
  pos=table->record[0]+ null_pack_length;
 
11323
  if (null_pack_length)
 
11324
  {
 
11325
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11326
    recinfo->type=FIELD_NORMAL;
 
11327
    recinfo->length=null_pack_length;
 
11328
    recinfo++;
 
11329
    bfill(null_flags,null_pack_length,255);     // Set null fields
 
11330
 
 
11331
    table->null_flags= (uchar*) table->record[0];
 
11332
    share->null_fields= null_count+ hidden_null_count;
 
11333
    share->null_bytes= null_pack_length;
 
11334
  }
 
11335
  null_count= (blob_count == 0) ? 1 : 0;
 
11336
  hidden_field_count=param->hidden_field_count;
 
11337
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
 
11338
  {
 
11339
    Field *field= *reg_field;
 
11340
    uint length;
 
11341
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11342
 
 
11343
    if (!(field->flags & NOT_NULL_FLAG))
 
11344
    {
 
11345
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
 
11346
      {
 
11347
        /*
 
11348
          We have to reserve one byte here for NULL bits,
 
11349
          as this is updated by 'end_update()'
 
11350
        */
 
11351
        *pos++=0;                               // Null is stored here
 
11352
        recinfo->length=1;
 
11353
        recinfo->type=FIELD_NORMAL;
 
11354
        recinfo++;
 
11355
        bzero((uchar*) recinfo,sizeof(*recinfo));
 
11356
      }
 
11357
      else
 
11358
      {
 
11359
        recinfo->null_bit= 1 << (null_count & 7);
 
11360
        recinfo->null_pos= null_count/8;
 
11361
      }
 
11362
      field->move_field(pos,null_flags+null_count/8,
 
11363
                        1 << (null_count & 7));
 
11364
      null_count++;
 
11365
    }
 
11366
    else
 
11367
      field->move_field(pos,(uchar*) 0,0);
 
11368
    field->reset();
 
11369
 
 
11370
    /*
 
11371
      Test if there is a default field value. The test for ->ptr is to skip
 
11372
      'offset' fields generated by initalize_tables
 
11373
    */
 
11374
    if (default_field[i] && default_field[i]->ptr)
 
11375
    {
 
11376
      /* 
 
11377
         default_field[i] is set only in the cases  when 'field' can
 
11378
         inherit the default value that is defined for the field referred
 
11379
         by the Item_field object from which 'field' has been created.
 
11380
      */
 
11381
      my_ptrdiff_t diff;
 
11382
      Field *orig_field= default_field[i];
 
11383
      /* Get the value from default_values */
 
11384
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
 
11385
                            orig_field->table->record[0]);
 
11386
      orig_field->move_field_offset(diff);      // Points now at default_values
 
11387
      if (orig_field->is_real_null())
 
11388
        field->set_null();
 
11389
      else
 
11390
      {
 
11391
        field->set_notnull();
 
11392
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
 
11393
      }
 
11394
      orig_field->move_field_offset(-diff);     // Back to record[0]
 
11395
    } 
 
11396
 
 
11397
    if (from_field[i])
 
11398
    {                                           /* Not a table Item */
 
11399
      copy->set(field,from_field[i],save_sum_fields);
 
11400
      copy++;
 
11401
    }
 
11402
    length=field->pack_length();
 
11403
    pos+= length;
 
11404
 
 
11405
    /* Make entry for create table */
 
11406
    recinfo->length=length;
 
11407
    if (field->flags & BLOB_FLAG)
 
11408
      recinfo->type= (int) FIELD_BLOB;
 
11409
    else if (use_packed_rows &&
 
11410
             field->real_type() == MYSQL_TYPE_STRING &&
 
11411
             length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
 
11412
      recinfo->type=FIELD_SKIP_ENDSPACE;
 
11413
    else
 
11414
      recinfo->type=FIELD_NORMAL;
 
11415
    if (!--hidden_field_count)
 
11416
      null_count=(null_count+7) & ~7;           // move to next byte
 
11417
 
 
11418
    // fix table name in field entry
 
11419
    field->table_name= &table->alias;
 
11420
  }
 
11421
 
 
11422
  param->copy_field_end=copy;
 
11423
  param->recinfo=recinfo;
 
11424
  store_record(table,s->default_values);        // Make empty default record
 
11425
 
 
11426
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
 
11427
    share->max_rows= ~(ha_rows) 0;
 
11428
  else
 
11429
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
11430
                                 min(thd->variables.tmp_table_size,
 
11431
                                     thd->variables.max_heap_table_size) :
 
11432
                                 thd->variables.tmp_table_size) /
 
11433
                                 share->reclength);
 
11434
  set_if_bigger(share->max_rows,1);             // For dummy start options
 
11435
  /*
 
11436
    Push the LIMIT clause to the temporary table creation, so that we
 
11437
    materialize only up to 'rows_limit' records instead of all result records.
 
11438
  */
 
11439
  set_if_smaller(share->max_rows, rows_limit);
 
11440
  param->end_write_records= rows_limit;
 
11441
 
 
11442
  keyinfo= param->keyinfo;
 
11443
 
 
11444
  if (group)
 
11445
  {
 
11446
    table->group=group;                         /* Table is grouped by key */
 
11447
    param->group_buff=group_buff;
 
11448
    share->keys=1;
 
11449
    share->uniques= test(using_unique_constraint);
 
11450
    table->key_info=keyinfo;
 
11451
    keyinfo->key_part=key_part_info;
 
11452
    keyinfo->flags=HA_NOSAME;
 
11453
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
 
11454
    keyinfo->key_length=0;
 
11455
    keyinfo->rec_per_key=0;
 
11456
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
11457
    keyinfo->name= (char*) "group_key";
 
11458
    ORDER *cur_group= group;
 
11459
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
 
11460
    {
 
11461
      Field *field=(*cur_group->item)->get_tmp_table_field();
 
11462
      bool maybe_null=(*cur_group->item)->maybe_null;
 
11463
      key_part_info->null_bit=0;
 
11464
      key_part_info->field=  field;
 
11465
      key_part_info->offset= field->offset(table->record[0]);
 
11466
      key_part_info->length= (uint16_t) field->key_length();
 
11467
      key_part_info->type=   (uint8_t) field->key_type();
 
11468
      key_part_info->key_type =
 
11469
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
 
11470
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
 
11471
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
 
11472
        0 : FIELDFLAG_BINARY;
 
11473
      if (!using_unique_constraint)
 
11474
      {
 
11475
        cur_group->buff=(char*) group_buff;
 
11476
        if (!(cur_group->field= field->new_key_field(thd->mem_root,table,
 
11477
                                                     group_buff +
 
11478
                                                     test(maybe_null),
 
11479
                                                     field->null_ptr,
 
11480
                                                     field->null_bit)))
 
11481
          goto err; /* purecov: inspected */
 
11482
        if (maybe_null)
 
11483
        {
 
11484
          /*
 
11485
            To be able to group on NULL, we reserved place in group_buff
 
11486
            for the NULL flag just before the column. (see above).
 
11487
            The field data is after this flag.
 
11488
            The NULL flag is updated in 'end_update()' and 'end_write()'
 
11489
          */
 
11490
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
 
11491
          key_part_info->null_bit=field->null_bit;
 
11492
          key_part_info->null_offset= (uint) (field->null_ptr -
 
11493
                                              (uchar*) table->record[0]);
 
11494
          cur_group->buff++;                        // Pointer to field data
 
11495
          group_buff++;                         // Skipp null flag
 
11496
        }
 
11497
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
 
11498
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
 
11499
        group_buff+= cur_group->field->pack_length();
 
11500
      }
 
11501
      keyinfo->key_length+=  key_part_info->length;
 
11502
    }
 
11503
  }
 
11504
 
 
11505
  if (distinct && field_count != param->hidden_field_count)
 
11506
  {
 
11507
    /*
 
11508
      Create an unique key or an unique constraint over all columns
 
11509
      that should be in the result.  In the temporary table, there are
 
11510
      'param->hidden_field_count' extra columns, whose null bits are stored
 
11511
      in the first 'hidden_null_pack_length' bytes of the row.
 
11512
    */
 
11513
    if (blob_count)
 
11514
    {
 
11515
      /*
 
11516
        Special mode for index creation in MyISAM used to support unique
 
11517
        indexes on blobs with arbitrary length. Such indexes cannot be
 
11518
        used for lookups.
 
11519
      */
 
11520
      share->uniques= 1;
 
11521
    }
 
11522
    null_pack_length-=hidden_null_pack_length;
 
11523
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
 
11524
                         (share->uniques ? test(null_pack_length) : 0));
 
11525
    table->distinct= 1;
 
11526
    share->keys= 1;
 
11527
    if (!(key_part_info= (KEY_PART_INFO*)
 
11528
          alloc_root(&table->mem_root,
 
11529
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
 
11530
      goto err;
 
11531
    bzero((void*) key_part_info, keyinfo->key_parts * sizeof(KEY_PART_INFO));
 
11532
    table->key_info=keyinfo;
 
11533
    keyinfo->key_part=key_part_info;
 
11534
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
 
11535
    keyinfo->key_length=(uint16_t) reclength;
 
11536
    keyinfo->name= (char*) "distinct_key";
 
11537
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
11538
    keyinfo->rec_per_key=0;
 
11539
 
 
11540
    /*
 
11541
      Create an extra field to hold NULL bits so that unique indexes on
 
11542
      blobs can distinguish NULL from 0. This extra field is not needed
 
11543
      when we do not use UNIQUE indexes for blobs.
 
11544
    */
 
11545
    if (null_pack_length && share->uniques)
 
11546
    {
 
11547
      key_part_info->null_bit=0;
 
11548
      key_part_info->offset=hidden_null_pack_length;
 
11549
      key_part_info->length=null_pack_length;
 
11550
      key_part_info->field= new Field_string(table->record[0],
 
11551
                                             (uint32_t) key_part_info->length,
 
11552
                                             (uchar*) 0,
 
11553
                                             (uint) 0,
 
11554
                                             Field::NONE,
 
11555
                                             NullS, &my_charset_bin);
 
11556
      if (!key_part_info->field)
 
11557
        goto err;
 
11558
      key_part_info->field->init(table);
 
11559
      key_part_info->key_type=FIELDFLAG_BINARY;
 
11560
      key_part_info->type=    HA_KEYTYPE_BINARY;
 
11561
      key_part_info++;
 
11562
    }
 
11563
    /* Create a distinct key over the columns we are going to return */
 
11564
    for (i=param->hidden_field_count, reg_field=table->field + i ;
 
11565
         i < field_count;
 
11566
         i++, reg_field++, key_part_info++)
 
11567
    {
 
11568
      key_part_info->null_bit=0;
 
11569
      key_part_info->field=    *reg_field;
 
11570
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
 
11571
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
 
11572
      /* TODO:
 
11573
        The below method of computing the key format length of the
 
11574
        key part is a copy/paste from opt_range.cc, and table.cc.
 
11575
        This should be factored out, e.g. as a method of Field.
 
11576
        In addition it is not clear if any of the Field::*_length
 
11577
        methods is supposed to compute the same length. If so, it
 
11578
        might be reused.
 
11579
      */
 
11580
      key_part_info->store_length= key_part_info->length;
 
11581
 
 
11582
      if ((*reg_field)->real_maybe_null())
 
11583
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
 
11584
      if ((*reg_field)->type() == MYSQL_TYPE_BLOB || 
 
11585
          (*reg_field)->real_type() == MYSQL_TYPE_VARCHAR)
 
11586
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
 
11587
 
 
11588
      key_part_info->type=     (uint8_t) (*reg_field)->key_type();
 
11589
      key_part_info->key_type =
 
11590
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
 
11591
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
 
11592
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
 
11593
        0 : FIELDFLAG_BINARY;
 
11594
    }
 
11595
  }
 
11596
 
 
11597
  if (thd->is_fatal_error)                              // If end of memory
 
11598
    goto err;                                    /* purecov: inspected */
 
11599
  share->db_record_offset= 1;
 
11600
  if (share->db_type() == myisam_hton)
 
11601
  {
 
11602
    if (create_myisam_tmp_table(table, param->keyinfo, param->start_recinfo,
 
11603
                                &param->recinfo, select_options))
 
11604
      goto err;
 
11605
  }
 
11606
  if (open_tmp_table(table))
 
11607
    goto err;
 
11608
 
 
11609
  thd->mem_root= mem_root_save;
 
11610
 
 
11611
  return(table);
 
11612
 
 
11613
err:
 
11614
  thd->mem_root= mem_root_save;
 
11615
  free_tmp_table(thd,table);                    /* purecov: inspected */
 
11616
  if (temp_pool_slot != MY_BIT_NONE)
 
11617
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11618
  return(NULL);                         /* purecov: inspected */
 
11619
}
 
11620
 
 
11621
 
 
11622
 
 
11623
 
 
11624
/*
 
11625
  Create a temporary table to weed out duplicate rowid combinations
 
11626
 
 
11627
  SYNOPSIS
 
11628
 
 
11629
    create_duplicate_weedout_tmp_table()
 
11630
      thd
 
11631
      uniq_tuple_length_arg
 
11632
      SJ_TMP_TABLE 
 
11633
 
 
11634
  DESCRIPTION
 
11635
    Create a temporary table to weed out duplicate rowid combinations. The
 
11636
    table has a single column that is a concatenation of all rowids in the
 
11637
    combination. 
 
11638
 
 
11639
    Depending on the needed length, there are two cases:
 
11640
 
 
11641
    1. When the length of the column < max_key_length:
 
11642
 
 
11643
      CREATE TABLE tmp (col VARBINARY(n) NOT NULL, UNIQUE KEY(col));
 
11644
 
 
11645
    2. Otherwise (not a valid SQL syntax but internally supported):
 
11646
 
 
11647
      CREATE TABLE tmp (col VARBINARY NOT NULL, UNIQUE CONSTRAINT(col));
 
11648
 
 
11649
    The code in this function was produced by extraction of relevant parts
 
11650
    from create_tmp_table().
 
11651
 
 
11652
  RETURN
 
11653
    created table
 
11654
    NULL on error
 
11655
*/
 
11656
 
 
11657
TABLE *create_duplicate_weedout_tmp_table(THD *thd, 
 
11658
                                          uint uniq_tuple_length_arg,
 
11659
                                          SJ_TMP_TABLE *sjtbl)
 
11660
{
 
11661
  MEM_ROOT *mem_root_save, own_root;
 
11662
  TABLE *table;
 
11663
  TABLE_SHARE *share;
 
11664
  uint  temp_pool_slot=MY_BIT_NONE;
 
11665
  char  *tmpname,path[FN_REFLEN];
 
11666
  Field **reg_field;
 
11667
  KEY_PART_INFO *key_part_info;
 
11668
  KEY *keyinfo;
 
11669
  uchar *group_buff;
 
11670
  uchar *bitmaps;
 
11671
  uint *blob_field;
 
11672
  MI_COLUMNDEF *recinfo, *start_recinfo;
 
11673
  bool using_unique_constraint=false;
 
11674
  bool use_packed_rows= false;
 
11675
  Field *field, *key_field;
 
11676
  uint blob_count, null_pack_length, null_count;
 
11677
  uchar *null_flags;
 
11678
  uchar *pos;
 
11679
  
 
11680
  /*
 
11681
    STEP 1: Get temporary table name
 
11682
  */
 
11683
  statistic_increment(thd->status_var.created_tmp_tables, &LOCK_status);
 
11684
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
11685
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
11686
 
 
11687
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
11688
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
 
11689
            current_pid, temp_pool_slot);
 
11690
  else
 
11691
  {
 
11692
    /* if we run out of slots or we are not using tempool */
 
11693
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
 
11694
            thd->thread_id, thd->tmp_table++);
 
11695
  }
 
11696
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
11697
 
 
11698
  /* STEP 2: Figure if we'll be using a key or blob+constraint */
 
11699
  if (uniq_tuple_length_arg >= CONVERT_IF_BIGGER_TO_BLOB)
 
11700
    using_unique_constraint= true;
 
11701
 
 
11702
  /* STEP 3: Allocate memory for temptable description */
 
11703
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
11704
  if (!multi_alloc_root(&own_root,
 
11705
                        &table, sizeof(*table),
 
11706
                        &share, sizeof(*share),
 
11707
                        &reg_field, sizeof(Field*) * (1+1),
 
11708
                        &blob_field, sizeof(uint)*2,
 
11709
                        &keyinfo, sizeof(*keyinfo),
 
11710
                        &key_part_info, sizeof(*key_part_info) * 2,
 
11711
                        &start_recinfo,
 
11712
                        sizeof(*recinfo)*(1*2+4),
 
11713
                        &tmpname, (uint) strlen(path)+1,
 
11714
                        &group_buff, (!using_unique_constraint ?
 
11715
                                      uniq_tuple_length_arg : 0),
 
11716
                        &bitmaps, bitmap_buffer_size(1)*2,
 
11717
                        NullS))
 
11718
  {
 
11719
    if (temp_pool_slot != MY_BIT_NONE)
 
11720
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11721
    return(NULL);
 
11722
  }
 
11723
  strmov(tmpname,path);
 
11724
  
 
11725
 
 
11726
  /* STEP 4: Create TABLE description */
 
11727
  bzero((char*) table,sizeof(*table));
 
11728
  bzero((char*) reg_field,sizeof(Field*)*2);
 
11729
 
 
11730
  table->mem_root= own_root;
 
11731
  mem_root_save= thd->mem_root;
 
11732
  thd->mem_root= &table->mem_root;
 
11733
 
 
11734
  table->field=reg_field;
 
11735
  table->alias= "weedout-tmp";
 
11736
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
 
11737
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
 
11738
  table->map=1;
 
11739
  table->temp_pool_slot = temp_pool_slot;
 
11740
  table->copy_blobs= 1;
 
11741
  table->in_use= thd;
 
11742
  table->quick_keys.init();
 
11743
  table->covering_keys.init();
 
11744
  table->keys_in_use_for_query.init();
 
11745
 
 
11746
  table->s= share;
 
11747
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
 
11748
  share->blob_field= blob_field;
 
11749
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
11750
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
11751
  share->table_charset= NULL;
 
11752
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
11753
  share->keys_for_keyread.init();
 
11754
  share->keys_in_use.init();
 
11755
 
 
11756
  blob_count= 0;
 
11757
 
 
11758
  /* Create the field */
 
11759
  {
 
11760
    /*
 
11761
      For the sake of uniformity, always use Field_varstring (altough we could
 
11762
      use Field_string for shorter keys)
 
11763
    */
 
11764
    field= new Field_varstring(uniq_tuple_length_arg, false, "rowids", share,
 
11765
                               &my_charset_bin);
 
11766
    if (!field)
 
11767
      return(0);
 
11768
    field->table= table;
 
11769
    field->key_start.init(0);
 
11770
    field->part_of_key.init(0);
 
11771
    field->part_of_sortkey.init(0);
 
11772
    field->unireg_check= Field::NONE;
 
11773
    field->flags= (NOT_NULL_FLAG | BINARY_FLAG | NO_DEFAULT_VALUE_FLAG);
 
11774
    field->reset_fields();
 
11775
    field->init(table);
 
11776
    field->orig_table= NULL;
 
11777
     
 
11778
    field->field_index= 0;
 
11779
    
 
11780
    *(reg_field++)= field;
 
11781
    *blob_field= 0;
 
11782
    *reg_field= 0;
 
11783
 
 
11784
    share->fields= 1;
 
11785
    share->blob_fields= 0;
 
11786
  }
 
11787
 
 
11788
  uint reclength= field->pack_length();
 
11789
  if (using_unique_constraint)
 
11790
  { 
 
11791
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
11792
    table->file= get_new_handler(share, &table->mem_root,
 
11793
                                 share->db_type());
 
11794
    assert(uniq_tuple_length_arg <= table->file->max_key_length());
 
11795
  }
 
11796
  else
 
11797
  {
 
11798
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
11799
    table->file= get_new_handler(share, &table->mem_root,
 
11800
                                 share->db_type());
 
11801
  }
 
11802
  if (!table->file)
 
11803
    goto err;
 
11804
 
 
11805
  null_count=1;
 
11806
  
 
11807
  null_pack_length= 1;
 
11808
  reclength += null_pack_length;
 
11809
 
 
11810
  share->reclength= reclength;
 
11811
  {
 
11812
    uint alloc_length=ALIGN_SIZE(share->reclength + MI_UNIQUE_HASH_LENGTH+1);
 
11813
    share->rec_buff_length= alloc_length;
 
11814
    if (!(table->record[0]= (uchar*)
 
11815
                            alloc_root(&table->mem_root, alloc_length*3)))
 
11816
      goto err;
 
11817
    table->record[1]= table->record[0]+alloc_length;
 
11818
    share->default_values= table->record[1]+alloc_length;
 
11819
  }
 
11820
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
11821
 
 
11822
  recinfo= start_recinfo;
 
11823
  null_flags=(uchar*) table->record[0];
 
11824
  pos=table->record[0]+ null_pack_length;
 
11825
  if (null_pack_length)
 
11826
  {
 
11827
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11828
    recinfo->type=FIELD_NORMAL;
 
11829
    recinfo->length=null_pack_length;
 
11830
    recinfo++;
 
11831
    bfill(null_flags,null_pack_length,255);     // Set null fields
 
11832
 
 
11833
    table->null_flags= (uchar*) table->record[0];
 
11834
    share->null_fields= null_count;
 
11835
    share->null_bytes= null_pack_length;
 
11836
  }
 
11837
  null_count=1;
 
11838
 
 
11839
  {
 
11840
    //Field *field= *reg_field;
 
11841
    uint length;
 
11842
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11843
    field->move_field(pos,(uchar*) 0,0);
 
11844
 
 
11845
    field->reset();
 
11846
    /*
 
11847
      Test if there is a default field value. The test for ->ptr is to skip
 
11848
      'offset' fields generated by initalize_tables
 
11849
    */
 
11850
    // Initialize the table field:
 
11851
    bzero(field->ptr, field->pack_length());
 
11852
 
 
11853
    length=field->pack_length();
 
11854
    pos+= length;
 
11855
 
 
11856
    /* Make entry for create table */
 
11857
    recinfo->length=length;
 
11858
    if (field->flags & BLOB_FLAG)
 
11859
      recinfo->type= (int) FIELD_BLOB;
 
11860
    else if (use_packed_rows &&
 
11861
             field->real_type() == MYSQL_TYPE_STRING &&
 
11862
             length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
 
11863
      recinfo->type=FIELD_SKIP_ENDSPACE;
 
11864
    else
 
11865
      recinfo->type=FIELD_NORMAL;
 
11866
 
 
11867
    field->table_name= &table->alias;
 
11868
  }
 
11869
 
 
11870
  //param->recinfo=recinfo;
 
11871
  //store_record(table,s->default_values);        // Make empty default record
 
11872
 
 
11873
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
 
11874
    share->max_rows= ~(ha_rows) 0;
 
11875
  else
 
11876
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
11877
                                 min(thd->variables.tmp_table_size,
 
11878
                                     thd->variables.max_heap_table_size) :
 
11879
                                 thd->variables.tmp_table_size) /
 
11880
                                 share->reclength);
 
11881
  set_if_bigger(share->max_rows,1);             // For dummy start options
 
11882
 
 
11883
 
 
11884
  //// keyinfo= param->keyinfo;
 
11885
  if (true)
 
11886
  {
 
11887
    share->keys=1;
 
11888
    share->uniques= test(using_unique_constraint);
 
11889
    table->key_info=keyinfo;
 
11890
    keyinfo->key_part=key_part_info;
 
11891
    keyinfo->flags=HA_NOSAME;
 
11892
    keyinfo->usable_key_parts= keyinfo->key_parts= 1;
 
11893
    keyinfo->key_length=0;
 
11894
    keyinfo->rec_per_key=0;
 
11895
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
11896
    keyinfo->name= (char*) "weedout_key";
 
11897
    {
 
11898
      key_part_info->null_bit=0;
 
11899
      key_part_info->field=  field;
 
11900
      key_part_info->offset= field->offset(table->record[0]);
 
11901
      key_part_info->length= (uint16_t) field->key_length();
 
11902
      key_part_info->type=   (uint8_t) field->key_type();
 
11903
      key_part_info->key_type = FIELDFLAG_BINARY;
 
11904
      if (!using_unique_constraint)
 
11905
      {
 
11906
        if (!(key_field= field->new_key_field(thd->mem_root, table,
 
11907
                                              group_buff,
 
11908
                                              field->null_ptr,
 
11909
                                              field->null_bit)))
 
11910
          goto err;
 
11911
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL; //todo need this?
 
11912
      }
 
11913
      keyinfo->key_length+=  key_part_info->length;
 
11914
    }
 
11915
  }
 
11916
 
 
11917
  if (thd->is_fatal_error)                              // If end of memory
 
11918
    goto err;
 
11919
  share->db_record_offset= 1;
 
11920
  if (share->db_type() == myisam_hton)
 
11921
  {
 
11922
    recinfo++;
 
11923
    if (create_myisam_tmp_table(table, keyinfo, start_recinfo, &recinfo, 0))
 
11924
      goto err;
 
11925
  }
 
11926
  sjtbl->start_recinfo= start_recinfo;
 
11927
  sjtbl->recinfo=       recinfo;
 
11928
  if (open_tmp_table(table))
 
11929
    goto err;
 
11930
 
 
11931
  thd->mem_root= mem_root_save;
 
11932
  return(table);
 
11933
 
 
11934
err:
 
11935
  thd->mem_root= mem_root_save;
 
11936
  free_tmp_table(thd,table);                    /* purecov: inspected */
 
11937
  if (temp_pool_slot != MY_BIT_NONE)
 
11938
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11939
  return(NULL);                         /* purecov: inspected */
 
11940
}
 
11941
 
 
11942
/****************************************************************************/
 
11943
 
 
11944
/**
 
11945
  Create a reduced TABLE object with properly set up Field list from a
 
11946
  list of field definitions.
 
11947
 
 
11948
    The created table doesn't have a table handler associated with
 
11949
    it, has no keys, no group/distinct, no copy_funcs array.
 
11950
    The sole purpose of this TABLE object is to use the power of Field
 
11951
    class to read/write data to/from table->record[0]. Then one can store
 
11952
    the record in any container (RB tree, hash, etc).
 
11953
    The table is created in THD mem_root, so are the table's fields.
 
11954
    Consequently, if you don't BLOB fields, you don't need to free it.
 
11955
 
 
11956
  @param thd         connection handle
 
11957
  @param field_list  list of column definitions
 
11958
 
 
11959
  @return
 
11960
    0 if out of memory, TABLE object in case of success
 
11961
*/
 
11962
 
 
11963
TABLE *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
 
11964
{
 
11965
  uint field_count= field_list.elements;
 
11966
  uint blob_count= 0;
 
11967
  Field **field;
 
11968
  Create_field *cdef;                           /* column definition */
 
11969
  uint record_length= 0;
 
11970
  uint null_count= 0;                 /* number of columns which may be null */
 
11971
  uint null_pack_length;              /* NULL representation array length */
 
11972
  uint *blob_field;
 
11973
  uchar *bitmaps;
 
11974
  TABLE *table;
 
11975
  TABLE_SHARE *share;
 
11976
 
 
11977
  if (!multi_alloc_root(thd->mem_root,
 
11978
                        &table, sizeof(*table),
 
11979
                        &share, sizeof(*share),
 
11980
                        &field, (field_count + 1) * sizeof(Field*),
 
11981
                        &blob_field, (field_count+1) *sizeof(uint),
 
11982
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
11983
                        NullS))
 
11984
    return 0;
 
11985
 
 
11986
  bzero(table, sizeof(*table));
 
11987
  bzero(share, sizeof(*share));
 
11988
  table->field= field;
 
11989
  table->s= share;
 
11990
  share->blob_field= blob_field;
 
11991
  share->fields= field_count;
 
11992
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
11993
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
11994
 
 
11995
  /* Create all fields and calculate the total length of record */
 
11996
  List_iterator_fast<Create_field> it(field_list);
 
11997
  while ((cdef= it++))
 
11998
  {
 
11999
    *field= make_field(share, 0, cdef->length,
 
12000
                       (uchar*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
 
12001
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
 
12002
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
 
12003
                       cdef->unireg_check,
 
12004
                       cdef->interval, cdef->field_name);
 
12005
    if (!*field)
 
12006
      goto error;
 
12007
    (*field)->init(table);
 
12008
    record_length+= (*field)->pack_length();
 
12009
    if (! ((*field)->flags & NOT_NULL_FLAG))
 
12010
      null_count++;
 
12011
 
 
12012
    if ((*field)->flags & BLOB_FLAG)
 
12013
      share->blob_field[blob_count++]= (uint) (field - table->field);
 
12014
 
 
12015
    field++;
 
12016
  }
 
12017
  *field= NULL;                             /* mark the end of the list */
 
12018
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
 
12019
  share->blob_fields= blob_count;
 
12020
 
 
12021
  null_pack_length= (null_count + 7)/8;
 
12022
  share->reclength= record_length + null_pack_length;
 
12023
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
12024
  table->record[0]= (uchar*) thd->alloc(share->rec_buff_length);
 
12025
  if (!table->record[0])
 
12026
    goto error;
 
12027
 
 
12028
  if (null_pack_length)
 
12029
  {
 
12030
    table->null_flags= (uchar*) table->record[0];
 
12031
    share->null_fields= null_count;
 
12032
    share->null_bytes= null_pack_length;
 
12033
  }
 
12034
 
 
12035
  table->in_use= thd;           /* field->reset() may access table->in_use */
 
12036
  {
 
12037
    /* Set up field pointers */
 
12038
    uchar *null_pos= table->record[0];
 
12039
    uchar *field_pos= null_pos + share->null_bytes;
 
12040
    uint null_bit= 1;
 
12041
 
 
12042
    for (field= table->field; *field; ++field)
 
12043
    {
 
12044
      Field *cur_field= *field;
 
12045
      if ((cur_field->flags & NOT_NULL_FLAG))
 
12046
        cur_field->move_field(field_pos);
 
12047
      else
 
12048
      {
 
12049
        cur_field->move_field(field_pos, (uchar*) null_pos, null_bit);
 
12050
        null_bit<<= 1;
 
12051
        if (null_bit == (1 << 8))
 
12052
        {
 
12053
          ++null_pos;
 
12054
          null_bit= 1;
 
12055
        }
 
12056
      }
 
12057
      cur_field->reset();
 
12058
 
 
12059
      field_pos+= cur_field->pack_length();
 
12060
    }
 
12061
  }
 
12062
  return table;
 
12063
error:
 
12064
  for (field= table->field; *field; ++field)
 
12065
    delete *field;                         /* just invokes field destructor */
 
12066
  return 0;
 
12067
}
 
12068
 
 
12069
 
 
12070
static bool open_tmp_table(TABLE *table)
 
12071
{
 
12072
  int error;
 
12073
  if ((error=table->file->ha_open(table, table->s->table_name.str,O_RDWR,
 
12074
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
 
12075
  {
 
12076
    table->file->print_error(error,MYF(0)); /* purecov: inspected */
 
12077
    table->db_stat=0;
 
12078
    return(1);
 
12079
  }
 
12080
  (void) table->file->extra(HA_EXTRA_QUICK);            /* Faster */
 
12081
  return(0);
 
12082
}
 
12083
 
 
12084
 
 
12085
/*
 
12086
  Create MyISAM temporary table
 
12087
 
 
12088
  SYNOPSIS
 
12089
    create_myisam_tmp_table()
 
12090
      table           Table object that descrimes the table to be created
 
12091
      keyinfo         Description of the index (there is always one index)
 
12092
      start_recinfo   MyISAM's column descriptions
 
12093
      recinfo INOUT   End of MyISAM's column descriptions
 
12094
      options         Option bits
 
12095
   
 
12096
  DESCRIPTION
 
12097
    Create a MyISAM temporary table according to passed description. The is
 
12098
    assumed to have one unique index or constraint.
 
12099
 
 
12100
    The passed array or MI_COLUMNDEF structures must have this form:
 
12101
 
 
12102
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
 
12103
         when there are many nullable columns)
 
12104
      2. Table columns
 
12105
      3. One free MI_COLUMNDEF element (*recinfo points here)
 
12106
   
 
12107
    This function may use the free element to create hash column for unique
 
12108
    constraint.
 
12109
 
 
12110
   RETURN
 
12111
     false - OK
 
12112
     true  - Error
 
12113
*/
 
12114
 
 
12115
static bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo, 
 
12116
                                    MI_COLUMNDEF *start_recinfo,
 
12117
                                    MI_COLUMNDEF **recinfo, 
 
12118
                                    uint64_t options)
 
12119
{
 
12120
  int error;
 
12121
  MI_KEYDEF keydef;
 
12122
  MI_UNIQUEDEF uniquedef;
 
12123
  TABLE_SHARE *share= table->s;
 
12124
 
 
12125
  if (share->keys)
 
12126
  {                                             // Get keys for ni_create
 
12127
    bool using_unique_constraint=0;
 
12128
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&table->mem_root,
 
12129
                                            sizeof(*seg) * keyinfo->key_parts);
 
12130
    if (!seg)
 
12131
      goto err;
 
12132
 
 
12133
    bzero(seg, sizeof(*seg) * keyinfo->key_parts);
 
12134
    if (keyinfo->key_length >= table->file->max_key_length() ||
 
12135
        keyinfo->key_parts > table->file->max_key_parts() ||
 
12136
        share->uniques)
 
12137
    {
 
12138
      /* Can't create a key; Make a unique constraint instead of a key */
 
12139
      share->keys=    0;
 
12140
      share->uniques= 1;
 
12141
      using_unique_constraint=1;
 
12142
      bzero((char*) &uniquedef,sizeof(uniquedef));
 
12143
      uniquedef.keysegs=keyinfo->key_parts;
 
12144
      uniquedef.seg=seg;
 
12145
      uniquedef.null_are_equal=1;
 
12146
 
 
12147
      /* Create extra column for hash value */
 
12148
      bzero((uchar*) *recinfo,sizeof(**recinfo));
 
12149
      (*recinfo)->type= FIELD_CHECK;
 
12150
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
 
12151
      (*recinfo)++;
 
12152
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
 
12153
    }
 
12154
    else
 
12155
    {
 
12156
      /* Create an unique key */
 
12157
      bzero((char*) &keydef,sizeof(keydef));
 
12158
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
 
12159
      keydef.keysegs=  keyinfo->key_parts;
 
12160
      keydef.seg= seg;
 
12161
    }
 
12162
    for (uint i=0; i < keyinfo->key_parts ; i++,seg++)
 
12163
    {
 
12164
      Field *field=keyinfo->key_part[i].field;
 
12165
      seg->flag=     0;
 
12166
      seg->language= field->charset()->number;
 
12167
      seg->length=   keyinfo->key_part[i].length;
 
12168
      seg->start=    keyinfo->key_part[i].offset;
 
12169
      if (field->flags & BLOB_FLAG)
 
12170
      {
 
12171
        seg->type=
 
12172
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
 
12173
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
 
12174
        seg->bit_start= (uint8_t)(field->pack_length() - share->blob_ptr_size);
 
12175
        seg->flag= HA_BLOB_PART;
 
12176
        seg->length=0;                  // Whole blob in unique constraint
 
12177
      }
 
12178
      else
 
12179
      {
 
12180
        seg->type= keyinfo->key_part[i].type;
 
12181
        /* Tell handler if it can do suffic space compression */
 
12182
        if (field->real_type() == MYSQL_TYPE_STRING &&
 
12183
            keyinfo->key_part[i].length > 4)
 
12184
          seg->flag|= HA_SPACE_PACK;
 
12185
      }
 
12186
      if (!(field->flags & NOT_NULL_FLAG))
 
12187
      {
 
12188
        seg->null_bit= field->null_bit;
 
12189
        seg->null_pos= (uint) (field->null_ptr - (uchar*) table->record[0]);
 
12190
        /*
 
12191
          We are using a GROUP BY on something that contains NULL
 
12192
          In this case we have to tell MyISAM that two NULL should
 
12193
          on INSERT be regarded at the same value
 
12194
        */
 
12195
        if (!using_unique_constraint)
 
12196
          keydef.flag|= HA_NULL_ARE_EQUAL;
 
12197
      }
 
12198
    }
 
12199
  }
 
12200
  MI_CREATE_INFO create_info;
 
12201
  bzero((char*) &create_info,sizeof(create_info));
 
12202
 
 
12203
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
12204
      OPTION_BIG_TABLES)
 
12205
    create_info.data_file_length= ~(uint64_t) 0;
 
12206
 
 
12207
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
 
12208
                       (uint) (*recinfo-start_recinfo),
 
12209
                       start_recinfo,
 
12210
                       share->uniques, &uniquedef,
 
12211
                       &create_info,
 
12212
                       HA_CREATE_TMP_TABLE)))
 
12213
  {
 
12214
    table->file->print_error(error,MYF(0));     /* purecov: inspected */
 
12215
    table->db_stat=0;
 
12216
    goto err;
 
12217
  }
 
12218
  status_var_increment(table->in_use->status_var.created_tmp_disk_tables);
 
12219
  share->db_record_offset= 1;
 
12220
  return(0);
 
12221
 err:
 
12222
  return(1);
 
12223
}
 
12224
 
 
12225
 
 
12226
void
 
12227
free_tmp_table(THD *thd, TABLE *entry)
 
12228
{
 
12229
  MEM_ROOT own_root= entry->mem_root;
 
12230
  const char *save_proc_info;
 
12231
 
 
12232
  save_proc_info=thd->proc_info;
 
12233
  thd_proc_info(thd, "removing tmp table");
 
12234
 
 
12235
  if (entry->file)
 
12236
  {
 
12237
    if (entry->db_stat)
 
12238
      entry->file->ha_drop_table(entry->s->table_name.str);
 
12239
    else
 
12240
      entry->file->ha_delete_table(entry->s->table_name.str);
 
12241
    delete entry->file;
 
12242
  }
 
12243
 
 
12244
  /* free blobs */
 
12245
  for (Field **ptr=entry->field ; *ptr ; ptr++)
 
12246
    (*ptr)->free();
 
12247
  free_io_cache(entry);
 
12248
 
 
12249
  if (entry->temp_pool_slot != MY_BIT_NONE)
 
12250
    bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot);
 
12251
 
 
12252
  plugin_unlock(0, entry->s->db_plugin);
 
12253
 
 
12254
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
 
12255
  thd_proc_info(thd, save_proc_info);
 
12256
 
 
12257
  return;
 
12258
}
 
12259
 
 
12260
/**
 
12261
  If a HEAP table gets full, create a MyISAM table and copy all rows
 
12262
  to this.
 
12263
*/
 
12264
 
 
12265
bool create_myisam_from_heap(THD *thd, TABLE *table,
 
12266
                             MI_COLUMNDEF *start_recinfo,
 
12267
                             MI_COLUMNDEF **recinfo, 
 
12268
                             int error, bool ignore_last_dupp_key_error)
 
12269
{
 
12270
  TABLE new_table;
 
12271
  TABLE_SHARE share;
 
12272
  const char *save_proc_info;
 
12273
  int write_err;
 
12274
 
 
12275
  if (table->s->db_type() != heap_hton || 
 
12276
      error != HA_ERR_RECORD_FILE_FULL)
 
12277
  {
 
12278
    table->file->print_error(error,MYF(0));
 
12279
    return(1);
 
12280
  }
 
12281
  new_table= *table;
 
12282
  share= *table->s;
 
12283
  new_table.s= &share;
 
12284
  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
 
12285
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
 
12286
                                        new_table.s->db_type())))
 
12287
    return(1);                          // End of memory
 
12288
 
 
12289
  save_proc_info=thd->proc_info;
 
12290
  thd_proc_info(thd, "converting HEAP to MyISAM");
 
12291
 
 
12292
  if (create_myisam_tmp_table(&new_table, table->key_info, start_recinfo,
 
12293
                              recinfo, thd->lex->select_lex.options | 
 
12294
                                               thd->options))
 
12295
    goto err2;
 
12296
  if (open_tmp_table(&new_table))
 
12297
    goto err1;
 
12298
  if (table->file->indexes_are_disabled())
 
12299
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
 
12300
  table->file->ha_index_or_rnd_end();
 
12301
  table->file->ha_rnd_init(1);
 
12302
  if (table->no_rows)
 
12303
  {
 
12304
    new_table.file->extra(HA_EXTRA_NO_ROWS);
 
12305
    new_table.no_rows=1;
 
12306
  }
 
12307
 
 
12308
#ifdef TO_BE_DONE_LATER_IN_4_1
 
12309
  /*
 
12310
    To use start_bulk_insert() (which is new in 4.1) we need to find
 
12311
    all places where a corresponding end_bulk_insert() should be put.
 
12312
  */
 
12313
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
 
12314
  new_table.file->ha_start_bulk_insert(table->file->stats.records);
 
12315
#else
 
12316
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
 
12317
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
 
12318
#endif
 
12319
 
 
12320
  /*
 
12321
    copy all old rows from heap table to MyISAM table
 
12322
    This is the only code that uses record[1] to read/write but this
 
12323
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
 
12324
  */
 
12325
  while (!table->file->rnd_next(new_table.record[1]))
 
12326
  {
 
12327
    write_err= new_table.file->ha_write_row(new_table.record[1]);
 
12328
    if (write_err)
 
12329
      goto err;
 
12330
  }
 
12331
  /* copy row that filled HEAP table */
 
12332
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
 
12333
  {
 
12334
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
 
12335
        !ignore_last_dupp_key_error)
 
12336
      goto err;
 
12337
  }
 
12338
 
 
12339
  /* remove heap table and change to use myisam table */
 
12340
  (void) table->file->ha_rnd_end();
 
12341
  (void) table->file->close();                  // This deletes the table !
 
12342
  delete table->file;
 
12343
  table->file=0;
 
12344
  plugin_unlock(0, table->s->db_plugin);
 
12345
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
 
12346
  new_table.s= table->s;                       // Keep old share
 
12347
  *table= new_table;
 
12348
  *table->s= share;
 
12349
  
 
12350
  table->file->change_table_ptr(table, table->s);
 
12351
  table->use_all_columns();
 
12352
  if (save_proc_info)
 
12353
  {
 
12354
    const char *new_proc_info=
 
12355
      (!strcmp(save_proc_info,"Copying to tmp table") ?
 
12356
      "Copying to tmp table on disk" : save_proc_info);
 
12357
    thd_proc_info(thd, new_proc_info);
 
12358
  }
 
12359
  return(0);
 
12360
 
 
12361
 err:
 
12362
  table->file->print_error(write_err, MYF(0));
 
12363
  (void) table->file->ha_rnd_end();
 
12364
  (void) new_table.file->close();
 
12365
 err1:
 
12366
  new_table.file->ha_delete_table(new_table.s->table_name.str);
 
12367
 err2:
 
12368
  delete new_table.file;
 
12369
  thd_proc_info(thd, save_proc_info);
 
12370
  table->mem_root= new_table.mem_root;
 
12371
  return(1);
 
12372
}
 
12373
 
10506
12374
 
10507
12375
/**
10508
12376
  @details
10518
12386
 
10519
12387
Next_select_func setup_end_select_func(JOIN *join)
10520
12388
{
10521
 
  Table *table= join->tmp_table;
 
12389
  TABLE *table= join->tmp_table;
10522
12390
  TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param;
10523
12391
  Next_select_func end_select;
10524
12392
 
10584
12452
*/
10585
12453
 
10586
12454
static int
10587
 
do_select(JOIN *join,List<Item> *fields,Table *table)
 
12455
do_select(JOIN *join,List<Item> *fields,TABLE *table)
10588
12456
{
10589
12457
  int rc= 0;
10590
12458
  enum_nested_loop_state error= NESTED_LOOP_OK;
10595
12463
 
10596
12464
  if (table)
10597
12465
  {
10598
 
    table->file->extra(HA_EXTRA_WRITE_CACHE);
 
12466
    VOID(table->file->extra(HA_EXTRA_WRITE_CACHE));
10599
12467
    empty_record(table);
10600
12468
    if (table->group && join->tmp_table_param.sum_func_count &&
10601
12469
        table->s->keys && !table->file->inited)
10923
12791
  int error;
10924
12792
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
10925
12793
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
10926
 
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
10927
 
  unsigned char *nulls_ptr= ptr;
 
12794
  uchar *ptr= sjtbl->tmp_table->record[0] + 1;
 
12795
  uchar *nulls_ptr= ptr;
10928
12796
  
10929
12797
  /* Put the the rowids tuple into table->record[0]: */
10930
12798
 
10931
12799
  // 1. Store the length 
10932
12800
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
10933
12801
  {
10934
 
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
 
12802
    *ptr= (uchar)(sjtbl->rowid_len + sjtbl->null_bytes);
10935
12803
    ptr++;
10936
12804
  }
10937
12805
  else
10943
12811
  // 2. Zero the null bytes 
10944
12812
  if (sjtbl->null_bytes)
10945
12813
  {
10946
 
    memset(ptr, 0, sjtbl->null_bytes);
 
12814
    bzero(ptr, sjtbl->null_bytes);
10947
12815
    ptr += sjtbl->null_bytes; 
10948
12816
  }
10949
12817
 
10950
12818
  // 3. Put the rowids
10951
 
  for (uint32_t i=0; tab != tab_end; tab++, i++)
 
12819
  for (uint i=0; tab != tab_end; tab++, i++)
10952
12820
  {
10953
12821
    handler *h= tab->join_tab->table->file;
10954
12822
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
10955
12823
    {
10956
12824
      /* It's a NULL-complemented row */
10957
12825
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
10958
 
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
 
12826
      bzero(ptr + tab->rowid_offset, h->ref_length);
10959
12827
    }
10960
12828
    else
10961
12829
    {
11249
13117
    if (rc == NESTED_LOOP_OK &&
11250
13118
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
11251
13119
    {
11252
 
      uint32_t i;
 
13120
      uint i;
11253
13121
      reset_cache_read(&join_tab->cache);
11254
13122
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
11255
13123
      {
11284
13152
  return NESTED_LOOP_OK;
11285
13153
}
11286
13154
 
 
13155
 
 
13156
/*****************************************************************************
 
13157
  The different ways to read a record
 
13158
  Returns -1 if row was not found, 0 if row was found and 1 on errors
 
13159
*****************************************************************************/
 
13160
 
 
13161
/** Help function when we get some an error from the table handler. */
 
13162
 
 
13163
int report_error(TABLE *table, int error)
 
13164
{
 
13165
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
 
13166
  {
 
13167
    table->status= STATUS_GARBAGE;
 
13168
    return -1;                                  // key not found; ok
 
13169
  }
 
13170
  /*
 
13171
    Locking reads can legally return also these errors, do not
 
13172
    print them to the .err log
 
13173
  */
 
13174
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
 
13175
    sql_print_error("Got error %d when reading table '%s'",
 
13176
                    error, table->s->path.str);
 
13177
  table->file->print_error(error,MYF(0));
 
13178
  return 1;
 
13179
}
 
13180
 
 
13181
 
11287
13182
int safe_index_read(JOIN_TAB *tab)
11288
13183
{
11289
13184
  int error;
11290
 
  Table *table= tab->table;
 
13185
  TABLE *table= tab->table;
11291
13186
  if ((error=table->file->index_read_map(table->record[0],
11292
13187
                                         tab->ref.key_buff,
11293
13188
                                         make_prev_keypart_map(tab->ref.key_parts),
11294
13189
                                         HA_READ_KEY_EXACT)))
11295
 
    return table->report_error(error);
 
13190
    return report_error(table, error);
11296
13191
  return 0;
11297
13192
}
11298
13193
 
11301
13196
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
11302
13197
{
11303
13198
  int error;
11304
 
  Table *table=tab->table;
 
13199
  TABLE *table=tab->table;
11305
13200
  table->const_table=1;
11306
13201
  table->null_row=0;
11307
13202
  table->status=STATUS_NO_RECORD;
11356
13251
  JOIN *join= tab->join;
11357
13252
  if (join->conds)
11358
13253
    update_const_equal_items(join->conds, tab);
11359
 
  TableList *tbl;
 
13254
  TABLE_LIST *tbl;
11360
13255
  for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
11361
13256
  {
11362
 
    TableList *embedded;
11363
 
    TableList *embedding= tbl;
 
13257
    TABLE_LIST *embedded;
 
13258
    TABLE_LIST *embedding= tbl;
11364
13259
    do
11365
13260
    {
11366
13261
      embedded= embedding;
11379
13274
static int
11380
13275
join_read_system(JOIN_TAB *tab)
11381
13276
{
11382
 
  Table *table= tab->table;
 
13277
  TABLE *table= tab->table;
11383
13278
  int error;
11384
13279
  if (table->status & STATUS_GARBAGE)           // If first read
11385
13280
  {
11387
13282
                                           table->s->primary_key)))
11388
13283
    {
11389
13284
      if (error != HA_ERR_END_OF_FILE)
11390
 
        return table->report_error(error);
 
13285
        return report_error(table, error);
11391
13286
      mark_as_null_row(tab->table);
11392
13287
      empty_record(table);                      // Make empty record
11393
13288
      return -1;
11394
13289
    }
11395
 
    update_virtual_fields_marked_for_write(table);
11396
13290
    store_record(table,record[1]);
11397
13291
  }
11398
13292
  else if (!table->status)                      // Only happens with left join
11419
13313
join_read_const(JOIN_TAB *tab)
11420
13314
{
11421
13315
  int error;
11422
 
  Table *table= tab->table;
 
13316
  TABLE *table= tab->table;
11423
13317
  if (table->status & STATUS_GARBAGE)           // If first read
11424
13318
  {
11425
13319
    table->status= 0;
11426
 
    if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13320
    if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11427
13321
      error=HA_ERR_KEY_NOT_FOUND;
11428
13322
    else
11429
13323
    {
11430
13324
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
11431
 
                                            (unsigned char*) tab->ref.key_buff,
 
13325
                                            (uchar*) tab->ref.key_buff,
11432
13326
                                            make_prev_keypart_map(tab->ref.key_parts),
11433
13327
                                            HA_READ_KEY_EXACT);
11434
13328
    }
11438
13332
      mark_as_null_row(tab->table);
11439
13333
      empty_record(table);
11440
13334
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11441
 
        return table->report_error(error);
 
13335
        return report_error(table, error);
11442
13336
      return -1;
11443
13337
    }
11444
 
    update_virtual_fields_marked_for_write(table);
11445
13338
    store_record(table,record[1]);
11446
13339
  }
11447
13340
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
11475
13368
join_read_key(JOIN_TAB *tab)
11476
13369
{
11477
13370
  int error;
11478
 
  Table *table= tab->table;
 
13371
  TABLE *table= tab->table;
11479
13372
 
11480
13373
  if (!table->file->inited)
11481
13374
  {
11496
13389
                                      make_prev_keypart_map(tab->ref.key_parts),
11497
13390
                                      HA_READ_KEY_EXACT);
11498
13391
    if (error && error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11499
 
      return table->report_error(error);
 
13392
      return report_error(table, error);
11500
13393
  }
11501
13394
  table->null_row=0;
11502
13395
  return table->status ? -1 : 0;
11526
13419
join_read_always_key(JOIN_TAB *tab)
11527
13420
{
11528
13421
  int error;
11529
 
  Table *table= tab->table;
 
13422
  TABLE *table= tab->table;
11530
13423
 
11531
13424
  /* Initialize the index first */
11532
13425
  if (!table->file->inited)
11533
13426
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11534
13427
 
11535
13428
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
11536
 
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
 
13429
  for (uint i= 0 ; i < tab->ref.key_parts ; i++)
11537
13430
  {
11538
13431
    if ((tab->ref.null_rejecting & 1 << i) && tab->ref.items[i]->is_null())
11539
13432
        return -1;
11540
13433
  }
11541
13434
 
11542
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13435
  if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11543
13436
    return -1;
11544
13437
  if ((error=table->file->index_read_map(table->record[0],
11545
13438
                                         tab->ref.key_buff,
11547
13440
                                         HA_READ_KEY_EXACT)))
11548
13441
  {
11549
13442
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11550
 
      return table->report_error(error);
 
13443
      return report_error(table, error);
11551
13444
    return -1; /* purecov: inspected */
11552
13445
  }
11553
 
  update_virtual_fields_marked_for_write(table);
11554
13446
  return 0;
11555
13447
}
11556
13448
 
11557
13449
 
11558
13450
/**
11559
 
  This function is used when optimizing away order_st BY in 
11560
 
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
 
13451
  This function is used when optimizing away ORDER BY in 
 
13452
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
11561
13453
*/
11562
13454
  
11563
13455
static int
11564
13456
join_read_last_key(JOIN_TAB *tab)
11565
13457
{
11566
13458
  int error;
11567
 
  Table *table= tab->table;
 
13459
  TABLE *table= tab->table;
11568
13460
 
11569
13461
  if (!table->file->inited)
11570
13462
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11571
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13463
  if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11572
13464
    return -1;
11573
13465
  if ((error=table->file->index_read_last_map(table->record[0],
11574
13466
                                              tab->ref.key_buff,
11575
13467
                                              make_prev_keypart_map(tab->ref.key_parts))))
11576
13468
  {
11577
13469
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11578
 
      return table->report_error(error);
 
13470
      return report_error(table, error);
11579
13471
    return -1; /* purecov: inspected */
11580
13472
  }
11581
13473
  return 0;
11592
13484
static int
11593
13485
join_read_next_same_diff(READ_RECORD *info)
11594
13486
{
11595
 
  Table *table= info->table;
 
13487
  TABLE *table= info->table;
11596
13488
  JOIN_TAB *tab=table->reginfo.join_tab;
11597
13489
  if (tab->insideout_match_tab->found_match)
11598
13490
  {
11608
13500
                                              tab->ref.key_length)))
11609
13501
      {
11610
13502
        if (error != HA_ERR_END_OF_FILE)
11611
 
          return table->report_error(error);
 
13503
          return report_error(table, error);
11612
13504
        table->status= STATUS_GARBAGE;
11613
13505
        return -1;
11614
13506
      }
11625
13517
join_read_next_same(READ_RECORD *info)
11626
13518
{
11627
13519
  int error;
11628
 
  Table *table= info->table;
 
13520
  TABLE *table= info->table;
11629
13521
  JOIN_TAB *tab=table->reginfo.join_tab;
11630
13522
 
11631
13523
  if ((error=table->file->index_next_same(table->record[0],
11633
13525
                                          tab->ref.key_length)))
11634
13526
  {
11635
13527
    if (error != HA_ERR_END_OF_FILE)
11636
 
      return table->report_error(error);
 
13528
      return report_error(table, error);
11637
13529
    table->status= STATUS_GARBAGE;
11638
13530
    return -1;
11639
13531
  }
11640
 
  update_virtual_fields_marked_for_write(table);
11641
13532
  return 0;
11642
13533
}
11643
13534
 
11646
13537
join_read_prev_same(READ_RECORD *info)
11647
13538
{
11648
13539
  int error;
11649
 
  Table *table= info->table;
 
13540
  TABLE *table= info->table;
11650
13541
  JOIN_TAB *tab=table->reginfo.join_tab;
11651
13542
 
11652
13543
  if ((error=table->file->index_prev(table->record[0])))
11653
 
    return table->report_error(error);
 
13544
    return report_error(table, error);
11654
13545
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
11655
13546
                      tab->ref.key_length))
11656
13547
  {
11657
13548
    table->status=STATUS_NOT_FOUND;
11658
13549
    error= -1;
11659
13550
  }
11660
 
  update_virtual_fields_marked_for_write(table);
11661
13551
  return error;
11662
13552
}
11663
13553
 
11706
13596
join_read_first(JOIN_TAB *tab)
11707
13597
{
11708
13598
  int error;
11709
 
  Table *table=tab->table;
 
13599
  TABLE *table=tab->table;
11710
13600
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
11711
13601
      !table->no_keyread)
11712
13602
  {
11735
13625
  if ((error=tab->table->file->index_first(tab->table->record[0])))
11736
13626
  {
11737
13627
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11738
 
      table->report_error(error);
 
13628
      report_error(table, error);
11739
13629
    return -1;
11740
13630
  }
11741
 
  if (not error)
11742
 
    update_virtual_fields_marked_for_write(tab->table);
11743
13631
  return 0;
11744
13632
}
11745
13633
 
11758
13646
      key_copy(tab->insideout_buf, info->record, key, 0);
11759
13647
 
11760
13648
      if ((error=info->file->index_next(info->record)))
11761
 
        return info->table->report_error(error);
11762
 
      if (not error)
11763
 
        update_virtual_fields_marked_for_write(tab->table);
 
13649
        return report_error(info->table, error);
 
13650
      
11764
13651
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
11765
13652
                      tab->insideout_buf, key->key_length));
11766
13653
    tab->insideout_match_tab->found_match= 0;
11776
13663
{
11777
13664
  int error;
11778
13665
  if ((error=info->file->index_next(info->record)))
11779
 
    return info->table->report_error(error);
11780
 
  if (not error)
11781
 
    update_virtual_fields_marked_for_write(info->table);
 
13666
    return report_error(info->table, error);
11782
13667
  return 0;
11783
13668
}
11784
13669
 
11786
13671
static int
11787
13672
join_read_last(JOIN_TAB *tab)
11788
13673
{
11789
 
  Table *table=tab->table;
 
13674
  TABLE *table=tab->table;
11790
13675
  int error;
11791
13676
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
11792
13677
      !table->no_keyread)
11803
13688
  if (!table->file->inited)
11804
13689
    table->file->ha_index_init(tab->index, 1);
11805
13690
  if ((error= tab->table->file->index_last(tab->table->record[0])))
11806
 
    return table->report_error(error);
11807
 
  if (not error)
11808
 
    update_virtual_fields_marked_for_write(tab->table);
 
13691
    return report_error(table, error);
11809
13692
  return 0;
11810
13693
}
11811
13694
 
11815
13698
{
11816
13699
  int error;
11817
13700
  if ((error= info->file->index_prev(info->record)))
11818
 
    return info->table->report_error(error);
11819
 
  if (not error)
11820
 
    update_virtual_fields_marked_for_write(info->table);
 
13701
    return report_error(info->table, error);
11821
13702
  return 0;
11822
13703
}
11823
13704
 
11910
13791
            (jt->ref.key < 0))
11911
13792
        {
11912
13793
          /* Join over all rows in table;  Return number of found rows */
11913
 
          Table *table=jt->table;
 
13794
          TABLE *table=jt->table;
11914
13795
 
11915
13796
          join->select_options ^= OPTION_FOUND_ROWS;
11916
13797
          if (table->sort.record_pointers ||
12022
13903
      if (end_of_records)
12023
13904
        return(NESTED_LOOP_OK);
12024
13905
      join->first_record=1;
12025
 
      test_if_item_cache_changed(join->group_fields);
 
13906
      VOID(test_if_item_cache_changed(join->group_fields));
12026
13907
    }
12027
13908
    if (idx < (int) join->send_group_parts)
12028
13909
    {
12047
13928
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12048
13929
          bool end_of_records)
12049
13930
{
12050
 
  Table *table=join->tmp_table;
 
13931
  TABLE *table=join->tmp_table;
12051
13932
 
12052
13933
  if (join->thd->killed)                        // Aborted by user
12053
13934
  {
12062
13943
    if (!table->uniques)                        // If not unique handling
12063
13944
    {
12064
13945
      /* Copy null values from group to row */
12065
 
      order_st   *group;
 
13946
      ORDER   *group;
12066
13947
      for (group=table->group ; group ; group=group->next)
12067
13948
      {
12068
13949
        Item *item= *group->item;
12069
13950
        if (item->maybe_null)
12070
13951
        {
12071
13952
          Field *field=item->get_tmp_table_field();
12072
 
          field->ptr[-1]= (unsigned char) (field->is_null() ? 1 : 0);
 
13953
          field->ptr[-1]= (uchar) (field->is_null() ? 1 : 0);
12073
13954
        }
12074
13955
      }
12075
13956
    }
12111
13992
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12112
13993
           bool end_of_records)
12113
13994
{
12114
 
  Table *table=join->tmp_table;
12115
 
  order_st   *group;
 
13995
  TABLE *table=join->tmp_table;
 
13996
  ORDER   *group;
12116
13997
  int     error;
12117
13998
 
12118
13999
  if (end_of_records)
12187
14068
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12188
14069
                  bool end_of_records)
12189
14070
{
12190
 
  Table *table=join->tmp_table;
 
14071
  TABLE *table=join->tmp_table;
12191
14072
  int     error;
12192
14073
 
12193
14074
  if (end_of_records)
12234
14115
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12235
14116
                bool end_of_records)
12236
14117
{
12237
 
  Table *table=join->tmp_table;
 
14118
  TABLE *table=join->tmp_table;
12238
14119
  int     idx= -1;
12239
14120
 
12240
14121
  if (join->thd->killed)
12280
14161
      if (end_of_records)
12281
14162
        return(NESTED_LOOP_OK);
12282
14163
      join->first_record=1;
12283
 
      test_if_item_cache_changed(join->group_fields);
 
14164
      VOID(test_if_item_cache_changed(join->group_fields));
12284
14165
    }
12285
14166
    if (idx < (int) join->send_group_parts)
12286
14167
    {
12341
14222
          frequent case?
12342
14223
        */
12343
14224
        if (field->binary() &&
12344
 
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
 
14225
            field->real_type() != MYSQL_TYPE_STRING &&
 
14226
            field->real_type() != MYSQL_TYPE_VARCHAR &&
12345
14227
            field->decimals() == 0)
12346
14228
        {
12347
14229
          return !store_val_in_field(field, right_item, CHECK_FIELD_WARN);
12542
14424
 
12543
14425
 
12544
14426
static Item *
12545
 
part_of_refkey(Table *table,Field *field)
 
14427
part_of_refkey(TABLE *table,Field *field)
12546
14428
{
12547
14429
  if (!table->reginfo.join_tab)
12548
14430
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
12549
14431
 
12550
 
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
 
14432
  uint ref_parts=table->reginfo.join_tab->ref.key_parts;
12551
14433
  if (ref_parts)
12552
14434
  {
12553
14435
    KEY_PART_INFO *key_part=
12554
14436
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
12555
 
    uint32_t part;
 
14437
    uint part;
12556
14438
 
12557
14439
    for (part=0 ; part < ref_parts ; part++)
12558
14440
    {
12570
14452
 
12571
14453
 
12572
14454
/**
12573
 
  Test if one can use the key to resolve order_st BY.
 
14455
  Test if one can use the key to resolve ORDER BY.
12574
14456
 
12575
14457
  @param order                 Sort order
12576
14458
  @param table                 Table to sort
12590
14472
    -1   Reverse key can be used
12591
14473
*/
12592
14474
 
12593
 
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx,
12594
 
                                uint32_t *used_key_parts)
 
14475
static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
 
14476
                                uint *used_key_parts)
12595
14477
{
12596
14478
  KEY_PART_INFO *key_part,*key_part_end;
12597
14479
  key_part=table->key_info[idx].key_part;
12607
14489
 
12608
14490
    /*
12609
14491
      Skip key parts that are constants in the WHERE clause.
12610
 
      These are already skipped in the order_st BY by const_expression_in_where()
 
14492
      These are already skipped in the ORDER BY by const_expression_in_where()
12611
14493
    */
12612
14494
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
12613
14495
      key_part++; 
12661
14543
}
12662
14544
 
12663
14545
 
 
14546
uint find_shortest_key(TABLE *table, const key_map *usable_keys)
 
14547
{
 
14548
  uint min_length= (uint) ~0;
 
14549
  uint best= MAX_KEY;
 
14550
  if (!usable_keys->is_clear_all())
 
14551
  {
 
14552
    for (uint nr=0; nr < table->s->keys ; nr++)
 
14553
    {
 
14554
      if (usable_keys->is_set(nr))
 
14555
      {
 
14556
        if (table->key_info[nr].key_length < min_length)
 
14557
        {
 
14558
          min_length=table->key_info[nr].key_length;
 
14559
          best=nr;
 
14560
        }
 
14561
      }
 
14562
    }
 
14563
  }
 
14564
  return best;
 
14565
}
 
14566
 
12664
14567
/**
12665
14568
  Test if a second key is the subkey of the first one.
12666
14569
 
12700
14603
*/
12701
14604
 
12702
14605
static uint
12703
 
test_if_subkey(order_st *order, Table *table, uint32_t ref, uint32_t ref_key_parts,
 
14606
test_if_subkey(ORDER *order, TABLE *table, uint ref, uint ref_key_parts,
12704
14607
               const key_map *usable_keys)
12705
14608
{
12706
 
  uint32_t nr;
12707
 
  uint32_t min_length= UINT32_MAX;
12708
 
  uint32_t best= MAX_KEY;
12709
 
  uint32_t not_used;
 
14609
  uint nr;
 
14610
  uint min_length= (uint) ~0;
 
14611
  uint best= MAX_KEY;
 
14612
  uint not_used;
12710
14613
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
12711
14614
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
12712
14615
 
12760
14663
*/
12761
14664
 
12762
14665
static bool
12763
 
list_contains_unique_index(Table *table,
 
14666
list_contains_unique_index(TABLE *table,
12764
14667
                          bool (*find_func) (Field *, void *), void *data)
12765
14668
{
12766
 
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
 
14669
  for (uint keynr= 0; keynr < table->s->keys; keynr++)
12767
14670
  {
12768
14671
    if (keynr == table->s->primary_key ||
12769
14672
         (table->key_info[keynr].flags & HA_NOSAME))
12790
14693
 
12791
14694
/**
12792
14695
  Helper function for list_contains_unique_index.
12793
 
  Find a field reference in a list of order_st structures.
 
14696
  Find a field reference in a list of ORDER structures.
12794
14697
  Finds a direct reference of the Field in the list.
12795
14698
 
12796
14699
  @param field                The field to search for.
12797
 
  @param data                 order_st *.The list to search in
 
14700
  @param data                 ORDER *.The list to search in
12798
14701
 
12799
14702
  @retval
12800
14703
    1                    found
12805
14708
static bool
12806
14709
find_field_in_order_list (Field *field, void *data)
12807
14710
{
12808
 
  order_st *group= (order_st *) data;
 
14711
  ORDER *group= (ORDER *) data;
12809
14712
  bool part_found= 0;
12810
 
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
14713
  for (ORDER *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
12811
14714
  {
12812
14715
    Item *item= (*tmp_group->item)->real_item();
12813
14716
    if (item->type() == Item::FIELD_ITEM &&
12857
14760
 
12858
14761
 
12859
14762
/**
12860
 
  Test if we can skip the order_st BY by using an index.
 
14763
  Test if we can skip the ORDER BY by using an index.
12861
14764
 
12862
14765
  SYNOPSIS
12863
14766
    test_if_skip_sort_order()
12883
14786
*/
12884
14787
 
12885
14788
static bool
12886
 
test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,ha_rows select_limit,
 
14789
test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
12887
14790
                        bool no_changes, const key_map *map)
12888
14791
{
12889
 
  int32_t ref_key;
12890
 
  uint32_t ref_key_parts;
 
14792
  int ref_key;
 
14793
  uint ref_key_parts;
12891
14794
  int order_direction;
12892
 
  uint32_t used_key_parts;
12893
 
  Table *table=tab->table;
 
14795
  uint used_key_parts;
 
14796
  TABLE *table=tab->table;
12894
14797
  SQL_SELECT *select=tab->select;
12895
14798
  key_map usable_keys;
12896
14799
  QUICK_SELECT_I *save_quick= 0;
12897
14800
 
12898
14801
  /*
12899
 
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
 
14802
    Keys disabled by ALTER TABLE ... DISABLE KEYS should have already
12900
14803
    been taken into account.
12901
14804
  */
12902
14805
  usable_keys= *map;
12903
14806
 
12904
 
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
14807
  for (ORDER *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
12905
14808
  {
12906
14809
    Item *item= (*tmp_order->item)->real_item();
12907
14810
    if (item->type() != Item::FIELD_ITEM)
12951
14854
      /*
12952
14855
        We come here when ref_key is not among usable_keys
12953
14856
      */
12954
 
      uint32_t new_ref_key;
 
14857
      uint new_ref_key;
12955
14858
      /*
12956
14859
        If using index only read, only consider other possible index only
12957
14860
        keys
13019
14922
      Check whether there is an index compatible with the given order
13020
14923
      usage of which is cheaper than usage of the ref_key index (ref_key>=0)
13021
14924
      or a table scan.
13022
 
      It may be the case if order_st/GROUP BY is used with LIMIT.
 
14925
      It may be the case if ORDER/GROUP BY is used with LIMIT.
13023
14926
    */
13024
 
    uint32_t nr;
 
14927
    uint nr;
13025
14928
    key_map keys;
13026
 
    uint32_t best_key_parts= 0;
 
14929
    uint best_key_parts= 0;
13027
14930
    int best_key_direction= 0;
13028
14931
    ha_rows best_records= 0;
13029
14932
    double read_time;
13031
14934
    bool is_best_covering= false;
13032
14935
    double fanout= 1;
13033
14936
    JOIN *join= tab->join;
13034
 
    uint32_t tablenr= tab - join->join_tab;
 
14937
    uint tablenr= tab - join->join_tab;
13035
14938
    ha_rows table_records= table->file->stats.records;
13036
14939
    bool group= join->group && order == join->group_list;
13037
14940
 
13054
14957
      /*
13055
14958
        We are adding here also the index specified in FORCE INDEX clause, 
13056
14959
        if any.
13057
 
        This is to allow users to use index in order_st BY.
 
14960
        This is to allow users to use index in ORDER BY.
13058
14961
      */
13059
14962
      if (table->force_index) 
13060
14963
        keys.merge(group ? table->keys_in_use_for_group_by :
13065
14968
      keys= usable_keys;
13066
14969
 
13067
14970
    read_time= join->best_positions[tablenr].read_time;
13068
 
    for (uint32_t i= tablenr+1; i < join->tables; i++)
 
14971
    for (uint i= tablenr+1; i < join->tables; i++)
13069
14972
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
13070
14973
 
13071
14974
    for (nr=0; nr < table->s->keys ; nr++)
13077
14980
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13078
14981
        
13079
14982
        /* 
13080
 
          Don't use an index scan with order_st BY without limit.
 
14983
          Don't use an index scan with ORDER BY without limit.
13081
14984
          For GROUP BY without limit always use index scan
13082
14985
          if there is a suitable index. 
13083
14986
          Why we hold to this asymmetry hardly can be explained
13150
15053
            index entry.
13151
15054
          */
13152
15055
          index_scan_time= select_limit/rec_per_key *
13153
 
                           cmin(rec_per_key, table->file->scan_time());
 
15056
                           min(rec_per_key, table->file->scan_time());
13154
15057
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
13155
15058
              index_scan_time < read_time)
13156
15059
          {
13160
15063
            if (table->quick_keys.is_set(nr))
13161
15064
              quick_records= table->quick_rows[nr];
13162
15065
            if (best_key < 0 ||
13163
 
                (select_limit <= cmin(quick_records,best_records) ?
 
15066
                (select_limit <= min(quick_records,best_records) ?
13164
15067
                 keyinfo->key_parts < best_key_parts :
13165
15068
                 quick_records < best_records))
13166
15069
            {
13242
15145
  } 
13243
15146
 
13244
15147
check_reverse_order:                  
13245
 
  if (order_direction == -1)            // If order_st BY ... DESC
 
15148
  if (order_direction == -1)            // If ORDER BY ... DESC
13246
15149
  {
13247
15150
    if (select && select->quick)
13248
15151
    {
13265
15168
          return(0);                   // Use filesort
13266
15169
        }
13267
15170
            
13268
 
        /* order_st BY range_key DESC */
 
15171
        /* ORDER BY range_key DESC */
13269
15172
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
13270
15173
                                    used_key_parts, &error);
13271
15174
        if (!tmp || error)
13282
15185
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
13283
15186
    {
13284
15187
      /*
13285
 
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
 
15188
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
13286
15189
 
13287
15190
        Use a traversal function that starts by reading the last row
13288
15191
        with key part (A) and then traverse the index backwards.
13308
15211
     filesort_limit     Max number of rows that needs to be sorted
13309
15212
     select_limit       Max number of rows in final output
13310
15213
                        Used to decide if we should use index or not
13311
 
     is_order_by        true if we are sorting on order_st BY, false if GROUP BY
 
15214
     is_order_by        true if we are sorting on ORDER BY, false if GROUP BY
13312
15215
                        Used to decide if we should use index or not     
13313
15216
 
13314
15217
 
13327
15230
*/
13328
15231
 
13329
15232
static int
13330
 
create_sort_index(THD *thd, JOIN *join, order_st *order,
 
15233
create_sort_index(THD *thd, JOIN *join, ORDER *order,
13331
15234
                  ha_rows filesort_limit, ha_rows select_limit,
13332
15235
                  bool is_order_by)
13333
15236
{
13334
 
  uint32_t length= 0;
 
15237
  uint length= 0;
13335
15238
  ha_rows examined_rows;
13336
 
  Table *table;
 
15239
  TABLE *table;
13337
15240
  SQL_SELECT *select;
13338
15241
  JOIN_TAB *tab;
13339
15242
 
13356
15259
                              is_order_by ?  &table->keys_in_use_for_order_by :
13357
15260
                              &table->keys_in_use_for_group_by))
13358
15261
    return(0);
13359
 
  for (order_st *ord= join->order; ord; ord= ord->next)
 
15262
  for (ORDER *ord= join->order; ord; ord= ord->next)
13360
15263
    length++;
13361
15264
  if (!(join->sortorder= 
13362
15265
        make_unireg_sortorder(order, &length, join->sortorder)))
13429
15332
  return(-1);
13430
15333
}
13431
15334
 
 
15335
/*****************************************************************************
 
15336
  Remove duplicates from tmp table
 
15337
  This should be recoded to add a unique index to the table and remove
 
15338
  duplicates
 
15339
  Table is a locked single thread table
 
15340
  fields is the number of fields to check (from the end)
 
15341
*****************************************************************************/
 
15342
 
 
15343
static bool compare_record(TABLE *table, Field **ptr)
 
15344
{
 
15345
  for (; *ptr ; ptr++)
 
15346
  {
 
15347
    if ((*ptr)->cmp_offset(table->s->rec_buff_length))
 
15348
      return 1;
 
15349
  }
 
15350
  return 0;
 
15351
}
 
15352
 
13432
15353
static bool copy_blobs(Field **ptr)
13433
15354
{
13434
15355
  for (; *ptr ; ptr++)
13451
15372
 
13452
15373
 
13453
15374
static int
13454
 
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
 
15375
remove_duplicates(JOIN *join, TABLE *entry,List<Item> &fields, Item *having)
13455
15376
{
13456
15377
  int error;
13457
15378
  ulong reclength,offset;
13458
 
  uint32_t field_count;
 
15379
  uint field_count;
13459
15380
  THD *thd= join->thd;
13460
15381
 
13461
15382
  entry->reginfo.lock_type=TL_WRITE;
13499
15420
}
13500
15421
 
13501
15422
 
13502
 
static int remove_dup_with_compare(THD *thd, Table *table, Field **first_field,
 
15423
static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field,
13503
15424
                                   ulong offset, Item *having)
13504
15425
{
13505
15426
  handler *file=table->file;
13506
15427
  char *org_record,*new_record;
13507
 
  unsigned char *record;
 
15428
  uchar *record;
13508
15429
  int error;
13509
15430
  ulong reclength= table->s->reclength-offset;
13510
15431
 
13556
15477
          break;
13557
15478
        goto err;
13558
15479
      }
13559
 
      if (table->compare_record(first_field) == 0)
 
15480
      if (compare_record(table, first_field) == 0)
13560
15481
      {
13561
15482
        if ((error=file->ha_delete_row(record)))
13562
15483
          goto err;
13590
15511
    Note that this will not work on tables with blobs!
13591
15512
*/
13592
15513
 
13593
 
static int remove_dup_with_hash_index(THD *thd, Table *table,
13594
 
                                      uint32_t field_count,
 
15514
static int remove_dup_with_hash_index(THD *thd, TABLE *table,
 
15515
                                      uint field_count,
13595
15516
                                      Field **first_field,
13596
15517
                                      ulong key_length,
13597
15518
                                      Item *having)
13598
15519
{
13599
 
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
 
15520
  uchar *key_buffer, *key_pos, *record=table->record[0];
13600
15521
  int error;
13601
15522
  handler *file= table->file;
13602
15523
  ulong extra_length= ALIGN_SIZE(key_length)-key_length;
13603
 
  uint32_t *field_lengths,*field_length;
 
15524
  uint *field_lengths,*field_length;
13604
15525
  HASH hash;
13605
15526
 
13606
15527
  if (!my_multi_malloc(MYF(MY_WME),
13609
15530
                               (long) file->stats.records),
13610
15531
                       &field_lengths,
13611
15532
                       (uint) (field_count*sizeof(*field_lengths)),
13612
 
                       NULL))
 
15533
                       NullS))
13613
15534
    return(1);
13614
15535
 
13615
15536
  {
13617
15538
    ulong total_length= 0;
13618
15539
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
13619
15540
    {
13620
 
      uint32_t length= (*ptr)->sort_length();
 
15541
      uint length= (*ptr)->sort_length();
13621
15542
      (*field_length++)= length;
13622
15543
      total_length+= length;
13623
15544
    }
13629
15550
  if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, 
13630
15551
                key_length, (hash_get_key) 0, 0, 0))
13631
15552
  {
13632
 
    free((char*) key_buffer);
 
15553
    my_free((char*) key_buffer,MYF(0));
13633
15554
    return(1);
13634
15555
  }
13635
15556
 
13637
15558
  key_pos=key_buffer;
13638
15559
  for (;;)
13639
15560
  {
13640
 
    unsigned char *org_key_pos;
 
15561
    uchar *org_key_pos;
13641
15562
    if (thd->killed)
13642
15563
    {
13643
15564
      thd->send_kill_message();
13678
15599
      (void) my_hash_insert(&hash, org_key_pos);
13679
15600
    key_pos+=extra_length;
13680
15601
  }
13681
 
  free((char*) key_buffer);
 
15602
  my_free((char*) key_buffer,MYF(0));
13682
15603
  hash_free(&hash);
13683
15604
  file->extra(HA_EXTRA_NO_CACHE);
13684
15605
  (void) file->ha_rnd_end();
13685
15606
  return(0);
13686
15607
 
13687
15608
err:
13688
 
  free((char*) key_buffer);
 
15609
  my_free((char*) key_buffer,MYF(0));
13689
15610
  hash_free(&hash);
13690
15611
  file->extra(HA_EXTRA_NO_CACHE);
13691
15612
  (void) file->ha_rnd_end();
13695
15616
}
13696
15617
 
13697
15618
 
13698
 
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length,
 
15619
SORT_FIELD *make_unireg_sortorder(ORDER *order, uint *length,
13699
15620
                                  SORT_FIELD *sortorder)
13700
15621
{
13701
 
  uint32_t count;
 
15622
  uint count;
13702
15623
  SORT_FIELD *sort,*pos;
13703
15624
 
13704
15625
  count=0;
13705
 
  for (order_st *tmp = order; tmp; tmp=tmp->next)
 
15626
  for (ORDER *tmp = order; tmp; tmp=tmp->next)
13706
15627
    count++;
13707
15628
  if (!sortorder)
13708
15629
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
13709
 
                                       (cmax(count, *length) + 1));
 
15630
                                       (max(count, *length) + 1));
13710
15631
  pos= sort= sortorder;
13711
15632
 
13712
15633
  if (!pos)
13741
15662
******************************************************************************/
13742
15663
 
13743
15664
static int
13744
 
join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count)
 
15665
join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count)
13745
15666
{
13746
15667
  register unsigned int i;
13747
15668
  unsigned int length, blobs;
13773
15694
 
13774
15695
                  sizeof(CACHE_FIELD*))))
13775
15696
  {
13776
 
    free((unsigned char*) cache->buff);         /* purecov: inspected */
 
15697
    my_free((uchar*) cache->buff,MYF(0));               /* purecov: inspected */
13777
15698
    cache->buff=0;                              /* purecov: inspected */
13778
15699
    return(1);                          /* purecov: inspected */
13779
15700
  }
13784
15705
  length=0;
13785
15706
  for (i=0 ; i < table_count ; i++)
13786
15707
  {
13787
 
    uint32_t null_fields=0, used_fields;
 
15708
    uint null_fields=0,used_fields;
13788
15709
    Field **f_ptr,*field;
13789
15710
    MY_BITMAP *read_set= tables[i].table->read_set;
13790
15711
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
13805
15726
      }
13806
15727
    }
13807
15728
    /* Copy null bits from table */
13808
 
    if (null_fields && tables[i].table->getNullFields())
 
15729
    if (null_fields && tables[i].table->s->null_fields)
13809
15730
    {                                           /* must copy null bits */
13810
15731
      copy->str= tables[i].table->null_flags;
13811
15732
      copy->length= tables[i].table->s->null_bytes;
13819
15740
    /* If outer join table, copy null_row flag */
13820
15741
    if (tables[i].table->maybe_null)
13821
15742
    {
13822
 
      copy->str= (unsigned char*) &tables[i].table->null_row;
 
15743
      copy->str= (uchar*) &tables[i].table->null_row;
13823
15744
      copy->length=sizeof(tables[i].table->null_row);
13824
15745
      copy->strip=0;
13825
15746
      copy->blob_field=0;
13850
15771
  cache->length=length+blobs*sizeof(char*);
13851
15772
  cache->blobs=blobs;
13852
15773
  *blob_ptr=0;                                  /* End sequentel */
13853
 
  size=cmax(thd->variables.join_buff_size, (ulong)cache->length);
13854
 
  if (!(cache->buff=(unsigned char*) my_malloc(size,MYF(0))))
 
15774
  size=max(thd->variables.join_buff_size, cache->length);
 
15775
  if (!(cache->buff=(uchar*) my_malloc(size,MYF(0))))
13855
15776
    return(1);                          /* Don't use cache */ /* purecov: inspected */
13856
15777
  cache->end=cache->buff+size;
13857
15778
  reset_cache_write(cache);
13862
15783
static ulong
13863
15784
used_blob_length(CACHE_FIELD **ptr)
13864
15785
{
13865
 
  uint32_t length,blob_length;
 
15786
  uint length,blob_length;
13866
15787
  for (length=0 ; *ptr ; ptr++)
13867
15788
  {
13868
15789
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
13876
15797
static bool
13877
15798
store_record_in_cache(JOIN_CACHE *cache)
13878
15799
{
13879
 
  uint32_t length;
13880
 
  unsigned char *pos;
 
15800
  uint length;
 
15801
  uchar *pos;
13881
15802
  CACHE_FIELD *copy,*end_field;
13882
15803
  bool last_record;
13883
15804
 
13919
15840
 
13920
15841
      if (copy->strip)
13921
15842
      {
13922
 
        unsigned char *str,*end;
 
15843
        uchar *str,*end;
13923
15844
        for (str=copy->str,end= str+copy->length;
13924
15845
             end > str && end[-1] == ' ' ;
13925
15846
             end--) ;
13952
15873
{
13953
15874
  reset_cache_read(cache);
13954
15875
  cache->records= 0;
13955
 
  cache->ptr_record= UINT32_MAX;
 
15876
  cache->ptr_record= (uint) ~0;
13956
15877
}
13957
15878
 
13958
15879
 
13959
15880
static void
13960
15881
read_cached_record(JOIN_TAB *tab)
13961
15882
{
13962
 
  unsigned char *pos;
13963
 
  uint32_t length;
 
15883
  uchar *pos;
 
15884
  uint length;
13964
15885
  bool last_record;
13965
15886
  CACHE_FIELD *copy,*end_field;
13966
15887
 
14038
15959
  }
14039
15960
  else 
14040
15961
    no_prev_key= true;
14041
 
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, &tab->ref)) ||
 
15962
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, tab->table,
 
15963
                                            &tab->ref)) ||
14042
15964
      no_prev_key)
14043
15965
    return 1;
14044
15966
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
14047
15969
 
14048
15970
 
14049
15971
bool
14050
 
cp_buffer_from_ref(THD *thd, TABLE_REF *ref)
 
15972
cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref)
14051
15973
{
14052
15974
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
14053
15975
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
15976
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
14054
15977
  bool result= 0;
14055
15978
 
14056
15979
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
14062
15985
    }
14063
15986
  }
14064
15987
  thd->count_cuted_fields= save_count_cuted_fields;
 
15988
  dbug_tmp_restore_column_map(table->write_set, old_map);
14065
15989
  return result;
14066
15990
}
14067
15991
 
14071
15995
*****************************************************************************/
14072
15996
 
14073
15997
/**
14074
 
  Resolve an order_st BY or GROUP BY column reference.
 
15998
  Resolve an ORDER BY or GROUP BY column reference.
14075
15999
 
14076
 
  Given a column reference (represented by 'order') from a GROUP BY or order_st
 
16000
  Given a column reference (represented by 'order') from a GROUP BY or ORDER
14077
16001
  BY clause, find the actual column it represents. If the column being
14078
16002
  resolved is from the GROUP BY clause, the procedure searches the SELECT
14079
16003
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
14080
 
  the order_st BY clause, only the SELECT list is being searched.
 
16004
  the ORDER BY clause, only the SELECT list is being searched.
14081
16005
 
14082
16006
  If 'order' is resolved to an Item, then order->item is set to the found
14083
16007
  Item. If there is no item for the found column (that is, it was resolved
14095
16019
    SELECT list)
14096
16020
  @param[in,out] all_fields         All select, group and order by fields
14097
16021
  @param[in] is_group_field         True if order is a GROUP field, false if
14098
 
    order_st by field
 
16022
    ORDER by field
14099
16023
 
14100
16024
  @retval
14101
16025
    false if OK
14104
16028
*/
14105
16029
 
14106
16030
static bool
14107
 
find_order_in_list(THD *thd, Item **ref_pointer_array, TableList *tables,
14108
 
                   order_st *order, List<Item> &fields, List<Item> &all_fields,
 
16031
find_order_in_list(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16032
                   ORDER *order, List<Item> &fields, List<Item> &all_fields,
14109
16033
                   bool is_group_field)
14110
16034
{
14111
 
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
 
16035
  Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */
14112
16036
  Item::Type order_item_type;
14113
16037
  Item **select_item; /* The corresponding item from the SELECT clause. */
14114
16038
  Field *from_field;  /* The corresponding field from the FROM clause. */
14115
 
  uint32_t counter;
 
16039
  uint counter;
14116
16040
  enum_resolution_type resolution;
14117
16041
 
14118
16042
  /*
14121
16045
  */
14122
16046
  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
14123
16047
  {                                             /* Order by position */
14124
 
    uint32_t count= (uint) order_item->val_int();
 
16048
    uint count= (uint) order_item->val_int();
14125
16049
    if (!count || count > fields.elements)
14126
16050
    {
14127
16051
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
14134
16058
    order->counter_used= 1;
14135
16059
    return false;
14136
16060
  }
14137
 
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
 
16061
  /* Lookup the current GROUP/ORDER field in the SELECT clause. */
14138
16062
  select_item= find_item_in_list(order_item, fields, &counter,
14139
16063
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
14140
16064
  if (!select_item)
14200
16124
        warning so the user knows that the field from the FROM clause
14201
16125
        overshadows the column reference from the SELECT list.
14202
16126
      */
14203
 
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
16127
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
14204
16128
                          ER(ER_NON_UNIQ_ERROR),
14205
16129
                          ((Item_ident*) order_item)->field_name,
14206
16130
                          current_thd->where);
14225
16149
       thd->is_fatal_error))
14226
16150
    return true; /* Wrong field. */
14227
16151
 
14228
 
  uint32_t el= all_fields.elements;
 
16152
  uint el= all_fields.elements;
14229
16153
  all_fields.push_front(order_item); /* Add new field to field list. */
14230
16154
  ref_pointer_array[el]= order_item;
14231
16155
  order->item= ref_pointer_array + el;
14240
16164
  the field list.
14241
16165
*/
14242
16166
 
14243
 
int setup_order(THD *thd, Item **ref_pointer_array, TableList *tables,
14244
 
                List<Item> &fields, List<Item> &all_fields, order_st *order)
 
16167
int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16168
                List<Item> &fields, List<Item> &all_fields, ORDER *order)
14245
16169
{
14246
16170
  thd->where="order clause";
14247
16171
  for (; order; order=order->next)
14281
16205
*/
14282
16206
 
14283
16207
int
14284
 
setup_group(THD *thd, Item **ref_pointer_array, TableList *tables,
14285
 
            List<Item> &fields, List<Item> &all_fields, order_st *order,
 
16208
setup_group(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16209
            List<Item> &fields, List<Item> &all_fields, ORDER *order,
14286
16210
            bool *hidden_group_fields)
14287
16211
{
14288
16212
  *hidden_group_fields=0;
14289
 
  order_st *ord;
 
16213
  ORDER *ord;
14290
16214
 
14291
16215
  if (!order)
14292
16216
    return 0;                           /* Everything is ok */
14293
16217
 
14294
 
  uint32_t org_fields=all_fields.elements;
 
16218
  uint org_fields=all_fields.elements;
14295
16219
 
14296
16220
  thd->where="group statement";
14297
16221
  for (ord= order; ord; ord= ord->next)
14377
16301
  optimize away 'order by'.
14378
16302
*/
14379
16303
 
14380
 
static order_st *
 
16304
static ORDER *
14381
16305
create_distinct_group(THD *thd, Item **ref_pointer_array,
14382
 
                      order_st *order_list, List<Item> &fields,
14383
 
                      List<Item> &all_fields __attribute__((unused)),
 
16306
                      ORDER *order_list, List<Item> &fields,
 
16307
                      List<Item> &all_fields __attribute__((__unused__)),
14384
16308
                      bool *all_order_by_fields_used)
14385
16309
{
14386
16310
  List_iterator<Item> li(fields);
14387
16311
  Item *item;
14388
 
  order_st *order,*group,**prev;
 
16312
  ORDER *order,*group,**prev;
14389
16313
 
14390
16314
  *all_order_by_fields_used= 1;
14391
16315
  while ((item=li++))
14396
16320
  {
14397
16321
    if (order->in_field_list)
14398
16322
    {
14399
 
      order_st *ord=(order_st*) thd->memdup((char*) order,sizeof(order_st));
 
16323
      ORDER *ord=(ORDER*) thd->memdup((char*) order,sizeof(ORDER));
14400
16324
      if (!ord)
14401
16325
        return 0;
14402
16326
      *prev=ord;
14416
16340
        Don't put duplicate columns from the SELECT list into the 
14417
16341
        GROUP BY list.
14418
16342
      */
14419
 
      order_st *ord_iter;
 
16343
      ORDER *ord_iter;
14420
16344
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
14421
16345
        if ((*ord_iter->item)->eq(item, 1))
14422
16346
          goto next_item;
14423
16347
      
14424
 
      order_st *ord=(order_st*) thd->calloc(sizeof(order_st));
 
16348
      ORDER *ord=(ORDER*) thd->calloc(sizeof(ORDER));
14425
16349
      if (!ord)
14426
16350
        return 0;
14427
16351
 
14474
16398
            param->quick_group=0;                       // UDF SUM function
14475
16399
          param->sum_func_count++;
14476
16400
 
14477
 
          for (uint32_t i=0 ; i < sum_item->arg_count ; i++)
 
16401
          for (uint i=0 ; i < sum_item->arg_count ; i++)
14478
16402
          {
14479
16403
            if (sum_item->args[0]->real_item()->type() == Item::FIELD_ITEM)
14480
16404
              param->field_count++;
14503
16427
*/
14504
16428
 
14505
16429
static bool
14506
 
test_if_subpart(order_st *a,order_st *b)
 
16430
test_if_subpart(ORDER *a,ORDER *b)
14507
16431
{
14508
16432
  for (; a && b; a=a->next,b=b->next)
14509
16433
  {
14520
16444
  and group and order is compatible, else return 0.
14521
16445
*/
14522
16446
 
14523
 
static Table *
14524
 
get_sort_by_table(order_st *a,order_st *b,TableList *tables)
 
16447
static TABLE *
 
16448
get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables)
14525
16449
{
14526
16450
  table_map map= (table_map) 0;
14527
16451
 
14551
16475
*/
14552
16476
 
14553
16477
static void
14554
 
calc_group_buffer(JOIN *join,order_st *group)
 
16478
calc_group_buffer(JOIN *join,ORDER *group)
14555
16479
{
14556
 
  uint32_t key_length=0, parts=0, null_parts=0;
 
16480
  uint key_length=0, parts=0, null_parts=0;
14557
16481
 
14558
16482
  if (group)
14559
16483
    join->group= 1;
14564
16488
    if (field)
14565
16489
    {
14566
16490
      enum_field_types type;
14567
 
      if ((type= field->type()) == DRIZZLE_TYPE_BLOB)
 
16491
      if ((type= field->type()) == MYSQL_TYPE_BLOB)
14568
16492
        key_length+=MAX_BLOB_WIDTH;             // Can't be used as a key
14569
 
      else if (type == DRIZZLE_TYPE_VARCHAR)
 
16493
      else if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_VAR_STRING)
14570
16494
        key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
14571
16495
      else
14572
16496
        key_length+= field->pack_length();
14593
16517
          have STRING_RESULT result type, we increase the length 
14594
16518
          by 8 as maximum pack length of such fields.
14595
16519
        */
14596
 
        if (type == DRIZZLE_TYPE_TIME ||
14597
 
            type == DRIZZLE_TYPE_NEWDATE ||
14598
 
            type == DRIZZLE_TYPE_DATETIME ||
14599
 
            type == DRIZZLE_TYPE_TIMESTAMP)
 
16520
        if (type == MYSQL_TYPE_TIME ||
 
16521
            type == MYSQL_TYPE_NEWDATE ||
 
16522
            type == MYSQL_TYPE_DATETIME ||
 
16523
            type == MYSQL_TYPE_TIMESTAMP)
14600
16524
        {
14601
16525
          key_length+= 8;
14602
16526
        }
14665
16589
*/
14666
16590
 
14667
16591
static bool
14668
 
alloc_group_fields(JOIN *join,order_st *group)
 
16592
alloc_group_fields(JOIN *join,ORDER *group)
14669
16593
{
14670
16594
  if (group)
14671
16595
  {
14742
16666
setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
14743
16667
                  Item **ref_pointer_array,
14744
16668
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
14745
 
                  uint32_t elements, List<Item> &all_fields)
 
16669
                  uint elements, List<Item> &all_fields)
14746
16670
{
14747
16671
  Item *pos;
14748
16672
  List_iterator_fast<Item> li(all_fields);
14751
16675
  res_all_fields.empty();
14752
16676
  List_iterator_fast<Item> itr(res_all_fields);
14753
16677
  List<Item> extra_funcs;
14754
 
  uint32_t i, border= all_fields.elements - elements;
 
16678
  uint i, border= all_fields.elements - elements;
14755
16679
 
14756
16680
  if (param->field_count && 
14757
16681
      !(copy=param->copy_field= new Copy_field[param->field_count]))
14761
16685
  for (i= 0; (pos= li++); i++)
14762
16686
  {
14763
16687
    Field *field;
14764
 
    unsigned char *tmp;
 
16688
    uchar *tmp;
14765
16689
    Item *real_pos= pos->real_item();
14766
16690
    if (real_pos->type() == Item::FIELD_ITEM)
14767
16691
    {
14804
16728
        /*
14805
16729
          We need to allocate one extra byte for null handling and
14806
16730
          another extra byte to not get warnings from purify in
14807
 
          Field_varstring::val_int
 
16731
          Field_string::val_int
14808
16732
        */
14809
 
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
 
16733
        if (!(tmp= (uchar*) sql_alloc(field->pack_length()+2)))
14810
16734
          goto err;
14811
16735
        if (copy)
14812
16736
        {
14834
16758
      */
14835
16759
      if (!(pos=new Item_copy_string(pos)))
14836
16760
        goto err;
14837
 
      if (i < border)                           // HAVING, order_st and GROUP BY
 
16761
      if (i < border)                           // HAVING, ORDER and GROUP BY
14838
16762
      {
14839
16763
        if (extra_funcs.push_back(pos))
14840
16764
          goto err;
14852
16776
    itr++;
14853
16777
  itr.sublist(res_selected_fields, elements);
14854
16778
  /*
14855
 
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
 
16779
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
14856
16780
    reference used in these will resolve to a item that is already calculated
14857
16781
  */
14858
16782
  param->copy_funcs.concat(&extra_funcs);
14903
16827
 
14904
16828
bool JOIN::alloc_func_list()
14905
16829
{
14906
 
  uint32_t func_count, group_parts;
 
16830
  uint func_count, group_parts;
14907
16831
 
14908
16832
  func_count= tmp_table_param.sum_func_count;
14909
16833
  /*
14922
16846
  {
14923
16847
    group_parts+= fields_list.elements;
14924
16848
    /*
14925
 
      If the order_st clause is specified then it's possible that
 
16849
      If the ORDER clause is specified then it's possible that
14926
16850
      it also will be optimized, so reserve space for it too
14927
16851
    */
14928
16852
    if (order)
14929
16853
    {
14930
 
      order_st *ord;
 
16854
      ORDER *ord;
14931
16855
      for (ord= order; ord; ord= ord->next)
14932
16856
        group_parts++;
14933
16857
    }
14981
16905
  }
14982
16906
  else if (rollup.state == ROLLUP::STATE_NONE)
14983
16907
  {
14984
 
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
 
16908
    for (uint i=0 ; i <= send_group_parts ;i++)
14985
16909
      sum_funcs_end[i]= func;
14986
16910
  }
14987
16911
  else if (rollup.state == ROLLUP::STATE_READY)
15012
16936
change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
15013
16937
                         List<Item> &res_selected_fields,
15014
16938
                         List<Item> &res_all_fields,
15015
 
                         uint32_t elements, List<Item> &all_fields)
 
16939
                         uint elements, List<Item> &all_fields)
15016
16940
{
15017
16941
  List_iterator_fast<Item> it(all_fields);
15018
16942
  Item *item_field,*item;
15020
16944
  res_selected_fields.empty();
15021
16945
  res_all_fields.empty();
15022
16946
 
15023
 
  uint32_t i, border= all_fields.elements - elements;
 
16947
  uint i, border= all_fields.elements - elements;
15024
16948
  for (i= 0; (item= it++); i++)
15025
16949
  {
15026
16950
    Field *field;
15091
17015
static bool
15092
17016
change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
15093
17017
                          List<Item> &res_selected_fields,
15094
 
                          List<Item> &res_all_fields, uint32_t elements,
 
17018
                          List<Item> &res_all_fields, uint elements,
15095
17019
                          List<Item> &all_fields)
15096
17020
{
15097
17021
  List_iterator_fast<Item> it(all_fields);
15099
17023
  res_selected_fields.empty();
15100
17024
  res_all_fields.empty();
15101
17025
 
15102
 
  uint32_t i, border= all_fields.elements - elements;
 
17026
  uint i, border= all_fields.elements - elements;
15103
17027
  for (i= 0; (item= it++); i++)
15104
17028
  {
15105
17029
    res_all_fields.push_back(new_item= item->get_tmp_table_item(thd));
15159
17083
 
15160
17084
static void
15161
17085
update_tmptable_sum_func(Item_sum **func_ptr,
15162
 
                         Table *tmp_table __attribute__((unused)))
 
17086
                         TABLE *tmp_table __attribute__((unused)))
15163
17087
{
15164
17088
  Item_sum *func;
15165
17089
  while ((func= *(func_ptr++)))
15228
17152
    return(false);
15229
17153
 
15230
17154
  Item_cond_and *cond=new Item_cond_and();
15231
 
  Table *table=join_tab->table;
 
17155
  TABLE *table=join_tab->table;
15232
17156
  int error;
15233
17157
  if (!cond)
15234
17158
    return(true);
15235
17159
 
15236
 
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
 
17160
  for (uint i=0 ; i < join_tab->ref.key_parts ; i++)
15237
17161
  {
15238
17162
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
15239
17163
                              fieldnr-1];
15265
17189
  @param select   pointer to st_select_lex which subselects joins we will free
15266
17190
*/
15267
17191
 
15268
 
void free_underlaid_joins(THD *thd __attribute__((unused)),
 
17192
void free_underlaid_joins(THD *thd __attribute__((__unused__)),
15269
17193
                          SELECT_LEX *select)
15270
17194
{
15271
17195
  for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
15318
17242
    1   on error
15319
17243
*/
15320
17244
 
15321
 
static bool change_group_ref(THD *thd, Item_func *expr, order_st *group_list,
 
17245
static bool change_group_ref(THD *thd, Item_func *expr, ORDER *group_list,
15322
17246
                             bool *changed)
15323
17247
{
15324
17248
  if (expr->arg_count)
15333
17257
      Item *item= *arg;
15334
17258
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
15335
17259
      {
15336
 
        order_st *group_tmp;
 
17260
        ORDER *group_tmp;
15337
17261
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
15338
17262
        {
15339
17263
          if (item->eq(*group_tmp->item,0))
15367
17291
 
15368
17292
bool JOIN::rollup_init()
15369
17293
{
15370
 
  uint32_t i,j;
 
17294
  uint i,j;
15371
17295
  Item **ref_array;
15372
17296
 
15373
17297
  tmp_table_param.quick_group= 0;       // Can't create groups in tmp table
15411
17335
  Item *item;
15412
17336
  while ((item= it++))
15413
17337
  {
15414
 
    order_st *group_tmp;
 
17338
    ORDER *group_tmp;
15415
17339
    bool found_in_group= 0;
15416
17340
 
15417
17341
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
15440
17364
            return 1;
15441
17365
          new_item->fix_fields(thd, (Item **) 0);
15442
17366
          thd->change_item_tree(it.ref(), new_item);
15443
 
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
 
17367
          for (ORDER *tmp= group_tmp; tmp; tmp= tmp->next)
15444
17368
          { 
15445
17369
            if (*tmp->item == item)
15446
17370
              thd->change_item_tree(tmp->item, new_item);
15487
17411
{
15488
17412
  List_iterator_fast<Item> it(fields_arg);
15489
17413
  Item *first_field= sel_fields.head();
15490
 
  uint32_t level;
 
17414
  uint level;
15491
17415
 
15492
17416
  /*
15493
17417
    Create field lists for the different levels
15512
17436
 
15513
17437
  for (level=0 ; level < send_group_parts ; level++)
15514
17438
  {
15515
 
    uint32_t i;
15516
 
    uint32_t pos= send_group_parts - level -1;
 
17439
    uint i;
 
17440
    uint pos= send_group_parts - level -1;
15517
17441
    bool real_fields= 0;
15518
17442
    Item *item;
15519
17443
    List_iterator<Item> new_it(rollup.fields[pos]);
15520
17444
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
15521
 
    order_st *start_group;
 
17445
    ORDER *start_group;
15522
17446
 
15523
17447
    /* Point to first hidden field */
15524
17448
    Item **ref_array= ref_array_start + fields_arg.elements-1;
15562
17486
      else 
15563
17487
      {
15564
17488
        /* Check if this is something that is part of this group by */
15565
 
        order_st *group_tmp;
 
17489
        ORDER *group_tmp;
15566
17490
        for (group_tmp= start_group, i= pos ;
15567
17491
             group_tmp ; group_tmp= group_tmp->next, i++)
15568
17492
        {
15616
17540
    1   If send_data_failed()
15617
17541
*/
15618
17542
 
15619
 
int JOIN::rollup_send_data(uint32_t idx)
 
17543
int JOIN::rollup_send_data(uint idx)
15620
17544
{
15621
 
  uint32_t i;
 
17545
  uint i;
15622
17546
  for (i= send_group_parts ; i-- > idx ; )
15623
17547
  {
15624
17548
    /* Get reference pointers to sum functions in place */
15625
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
17549
    memcpy((char*) ref_pointer_array,
 
17550
           (char*) rollup.ref_pointer_arrays[i],
15626
17551
           ref_pointer_array_size);
15627
17552
    if ((!having || having->val_int()))
15628
17553
    {
15657
17582
    1   if write_data_failed()
15658
17583
*/
15659
17584
 
15660
 
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
 
17585
int JOIN::rollup_write_data(uint idx, TABLE *table_arg)
15661
17586
{
15662
 
  uint32_t i;
 
17587
  uint i;
15663
17588
  for (i= send_group_parts ; i-- > idx ; )
15664
17589
  {
15665
17590
    /* Get reference pointers to sum functions in place */
15666
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
17591
    memcpy((char*) ref_pointer_array,
 
17592
           (char*) rollup.ref_pointer_arrays[i],
15667
17593
           ref_pointer_array_size);
15668
17594
    if ((!having || having->val_int()))
15669
17595
    {
15723
17649
  THD *thd=join->thd;
15724
17650
  select_result *result=join->result;
15725
17651
  Item *item_null= new Item_null();
15726
 
  const CHARSET_INFO * const cs= system_charset_info;
 
17652
  CHARSET_INFO *cs= system_charset_info;
15727
17653
  int quick_type;
15728
17654
  /* Don't log this into the slow query log */
15729
17655
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
15739
17665
                                     join->select_lex->select_number));
15740
17666
    item_list.push_back(new Item_string(join->select_lex->type,
15741
17667
                                        strlen(join->select_lex->type), cs));
15742
 
    for (uint32_t i=0 ; i < 7; i++)
 
17668
    for (uint i=0 ; i < 7; i++)
15743
17669
      item_list.push_back(item_null);
15744
17670
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
15745
17671
      item_list.push_back(item_null);
15768
17694
    /* table */
15769
17695
    {
15770
17696
      SELECT_LEX *sl= join->unit->first_select();
15771
 
      uint32_t len= 6, lastop= 0;
 
17697
      uint len= 6, lastop= 0;
15772
17698
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
15773
17699
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
15774
17700
      {
15818
17744
  else
15819
17745
  {
15820
17746
    table_map used_tables=0;
15821
 
    for (uint32_t i=0 ; i < join->tables ; i++)
 
17747
    for (uint i=0 ; i < join->tables ; i++)
15822
17748
    {
15823
17749
      JOIN_TAB *tab=join->join_tab+i;
15824
 
      Table *table=tab->table;
15825
 
      TableList *table_list= tab->table->pos_in_table_list;
 
17750
      TABLE *table=tab->table;
 
17751
      TABLE_LIST *table_list= tab->table->pos_in_table_list;
15826
17752
      char buff[512]; 
15827
17753
      char buff1[512], buff2[512], buff3[512];
15828
17754
      char keylen_str_buf[64];
15866
17792
      }
15867
17793
      else
15868
17794
      {
15869
 
        TableList *real_table= table->pos_in_table_list; 
 
17795
        TABLE_LIST *real_table= table->pos_in_table_list; 
15870
17796
        item_list.push_back(new Item_string(real_table->alias,
15871
17797
                                            strlen(real_table->alias),
15872
17798
                                            cs));
15878
17804
      /* Build "possible_keys" value and add it to item_list */
15879
17805
      if (!tab->keys.is_clear_all())
15880
17806
      {
15881
 
        uint32_t j;
 
17807
        uint j;
15882
17808
        for (j=0 ; j < table->s->keys ; j++)
15883
17809
        {
15884
17810
          if (tab->keys.is_set(j))
15900
17826
      if (tab->ref.key_parts)
15901
17827
      {
15902
17828
        KEY *key_info=table->key_info+ tab->ref.key;
15903
 
        register uint32_t length;
 
17829
        register uint length;
15904
17830
        item_list.push_back(new Item_string(key_info->name,
15905
17831
                                            strlen(key_info->name),
15906
17832
                                            system_charset_info));
15920
17846
      else if (tab->type == JT_NEXT)
15921
17847
      {
15922
17848
        KEY *key_info=table->key_info+ tab->index;
15923
 
        register uint32_t length;
 
17849
        register uint length;
15924
17850
        item_list.push_back(new Item_string(key_info->name,
15925
17851
                                            strlen(key_info->name),cs));
15926
17852
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) - 
15939
17865
      }
15940
17866
      else
15941
17867
      {
15942
 
        if (table_list->schema_table && table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
17868
        if (table_list->schema_table &&
 
17869
            table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
15943
17870
        {
15944
17871
          const char *tmp_buff;
15945
17872
          int f_idx;
16033
17960
      }
16034
17961
      else
16035
17962
      {
16036
 
        uint32_t keyno= MAX_KEY;
 
17963
        uint keyno= MAX_KEY;
16037
17964
        if (tab->ref.key_parts)
16038
17965
          keyno= tab->ref.key;
16039
17966
        else if (tab->select && tab->select->quick)
16139
18066
        else if (tab->do_firstmatch)
16140
18067
        {
16141
18068
          extra.append(STRING_WITH_LEN("; FirstMatch("));
16142
 
          Table *prev_table=tab->do_firstmatch->table;
 
18069
          TABLE *prev_table=tab->do_firstmatch->table;
16143
18070
          if (prev_table->derived_select_number)
16144
18071
          {
16145
18072
            char namebuf[NAME_LEN];
16154
18081
          extra.append(STRING_WITH_LEN(")"));
16155
18082
        }
16156
18083
 
16157
 
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
18084
        for (uint part= 0; part < tab->ref.key_parts; part++)
16158
18085
        {
16159
18086
          if (tab->ref.cond_guards[part])
16160
18087
          {
16234
18161
    thd->lex->current_select= first;
16235
18162
    unit->set_limit(unit->global_parameters);
16236
18163
    res= mysql_select(thd, &first->ref_pointer_array,
16237
 
                        (TableList*) first->table_list.first,
 
18164
                        (TABLE_LIST*) first->table_list.first,
16238
18165
                        first->with_wild, first->item_list,
16239
18166
                        first->where,
16240
18167
                        first->order_list.elements +
16241
18168
                        first->group_list.elements,
16242
 
                        (order_st*) first->order_list.first,
16243
 
                        (order_st*) first->group_list.first,
 
18169
                        (ORDER*) first->order_list.first,
 
18170
                        (ORDER*) first->group_list.first,
16244
18171
                        first->having,
16245
 
                        (order_st*) thd->lex->proc_list.first,
 
18172
                        (ORDER*) thd->lex->proc_list.first,
16246
18173
                        first->options | thd->options | SELECT_DESCRIBE,
16247
18174
                        result, unit, first);
16248
18175
  }
16250
18177
}
16251
18178
 
16252
18179
 
16253
 
static void print_table_array(THD *thd, String *str, TableList **table, 
16254
 
                              TableList **end)
 
18180
static void print_table_array(THD *thd, String *str, TABLE_LIST **table, 
 
18181
                              TABLE_LIST **end)
16255
18182
{
16256
18183
  (*table)->print(thd, str, QT_ORDINARY);
16257
18184
 
16258
 
  for (TableList **tbl= table + 1; tbl < end; tbl++)
 
18185
  for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++)
16259
18186
  {
16260
 
    TableList *curr= *tbl;
 
18187
    TABLE_LIST *curr= *tbl;
16261
18188
    if (curr->outer_join)
16262
18189
    {
16263
18190
      /* MySQL converts right to left joins */
16290
18217
 
16291
18218
static void print_join(THD *thd,
16292
18219
                       String *str,
16293
 
                       List<TableList> *tables,
16294
 
                       enum_query_type query_type __attribute__((unused)))
 
18220
                       List<TABLE_LIST> *tables,
 
18221
                       enum_query_type query_type __attribute__((__unused__)))
16295
18222
{
16296
18223
  /* List is reversed => we should reverse it before using */
16297
 
  List_iterator_fast<TableList> ti(*tables);
16298
 
  TableList **table= (TableList **)thd->alloc(sizeof(TableList*) *
 
18224
  List_iterator_fast<TABLE_LIST> ti(*tables);
 
18225
  TABLE_LIST **table= (TABLE_LIST **)thd->alloc(sizeof(TABLE_LIST*) *
16299
18226
                                                tables->elements);
16300
18227
  if (table == 0)
16301
18228
    return;  // out of memory
16302
18229
 
16303
 
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
 
18230
  for (TABLE_LIST **t= table + (tables->elements - 1); t >= table; t--)
16304
18231
    *t= ti++;
16305
18232
  
16306
18233
  /* 
16309
18236
  */
16310
18237
  if ((*table)->sj_inner_tables)
16311
18238
  {
16312
 
    TableList **end= table + tables->elements;
16313
 
    for (TableList **t2= table; t2!=end; t2++)
 
18239
    TABLE_LIST **end= table + tables->elements;
 
18240
    for (TABLE_LIST **t2= table; t2!=end; t2++)
16314
18241
    {
16315
18242
      if (!(*t2)->sj_inner_tables)
16316
18243
      {
16317
 
        TableList *tmp= *t2;
 
18244
        TABLE_LIST *tmp= *t2;
16318
18245
        *t2= *table;
16319
18246
        *table= tmp;
16320
18247
        break;
16352
18279
  if (key_name.length)
16353
18280
  {
16354
18281
    if (thd && !my_strnncoll(system_charset_info,
16355
 
                             (const unsigned char *)key_name.str, key_name.length, 
16356
 
                             (const unsigned char *)primary_key_name, 
 
18282
                             (const uchar *)key_name.str, key_name.length, 
 
18283
                             (const uchar *)primary_key_name, 
16357
18284
                             strlen(primary_key_name)))
16358
18285
      str->append(primary_key_name);
16359
18286
    else
16369
18296
  @param str   string where table should be printed
16370
18297
*/
16371
18298
 
16372
 
void TableList::print(THD *thd, String *str, enum_query_type query_type)
 
18299
void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type)
16373
18300
{
16374
18301
  if (nested_join)
16375
18302
  {
16417
18344
      {
16418
18345
        if (alias && alias[0])
16419
18346
        {
16420
 
          my_stpcpy(t_alias_buff, alias);
 
18347
          strmov(t_alias_buff, alias);
16421
18348
          my_casedn_str(files_charset_info, t_alias_buff);
16422
18349
          t_alias= t_alias_buff;
16423
18350
        }
16515
18442
  if (group_list.elements)
16516
18443
  {
16517
18444
    str->append(STRING_WITH_LEN(" group by "));
16518
 
    print_order(str, (order_st *) group_list.first, query_type);
 
18445
    print_order(str, (ORDER *) group_list.first, query_type);
16519
18446
    switch (olap)
16520
18447
    {
16521
18448
      case CUBE_TYPE:
16546
18473
  if (order_list.elements)
16547
18474
  {
16548
18475
    str->append(STRING_WITH_LEN(" order by "));
16549
 
    print_order(str, (order_st *) order_list.first, query_type);
 
18476
    print_order(str, (ORDER *) order_list.first, query_type);
16550
18477
  }
16551
18478
 
16552
18479
  // limit