~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/sql_select.cc

Removed SCCS references.

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, ulonglong 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
 
                            uint64_t select_options, const char *info,
 
99
                            ulonglong 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
                                    ulonglong 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
uint find_shortest_key(TABLE *table, const key_map *usable_keys);
 
173
static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,
165
174
                                    ha_rows select_limit, bool no_changes,
166
175
                                    const key_map *map);
167
 
static bool list_contains_unique_index(Table *table,
 
176
static bool list_contains_unique_index(TABLE *table,
168
177
                          bool (*find_func) (Field *, void *), void *data);
169
178
static bool find_field_in_item_list (Field *field, void *data);
170
179
static bool find_field_in_order_list (Field *field, void *data);
171
 
static int create_sort_index(THD *thd, JOIN *join, order_st *order,
 
180
static int create_sort_index(THD *thd, JOIN *join, ORDER *order,
172
181
                             ha_rows filesort_limit, ha_rows select_limit,
173
182
                             bool is_order_by);
174
 
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
 
183
static int remove_duplicates(JOIN *join,TABLE *entry,List<Item> &fields,
175
184
                             Item *having);
176
 
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
 
185
static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field,
177
186
                                   ulong offset,Item *having);
178
 
static int remove_dup_with_hash_index(THD *thd,Table *table,
179
 
                                      uint32_t field_count, Field **first_field,
 
187
static int remove_dup_with_hash_index(THD *thd,TABLE *table,
 
188
                                      uint field_count, Field **first_field,
180
189
 
181
190
                                      ulong key_length,Item *having);
182
 
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count);
 
191
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count);
183
192
static ulong used_blob_length(CACHE_FIELD **ptr);
184
193
static bool store_record_in_cache(JOIN_CACHE *cache);
185
194
static void reset_cache_read(JOIN_CACHE *cache);
186
195
static void reset_cache_write(JOIN_CACHE *cache);
187
196
static void read_cached_record(JOIN_TAB *tab);
188
197
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,
 
198
static ORDER *create_distinct_group(THD *thd, Item **ref_pointer_array,
 
199
                                    ORDER *order, List<Item> &fields,
191
200
                                    List<Item> &all_fields,
192
201
                                    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);
 
202
static bool test_if_subpart(ORDER *a,ORDER *b);
 
203
static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
 
204
static void calc_group_buffer(JOIN *join,ORDER *group);
196
205
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
197
 
static bool alloc_group_fields(JOIN *join,order_st *group);
 
206
static bool alloc_group_fields(JOIN *join,ORDER *group);
198
207
// Create list for using with tempory table
199
208
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
200
209
                                     List<Item> &new_list1,
201
210
                                     List<Item> &new_list2,
202
 
                                     uint32_t elements, List<Item> &items);
 
211
                                     uint elements, List<Item> &items);
203
212
// Create list for using with tempory table
204
213
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
205
214
                                      List<Item> &new_list1,
206
215
                                      List<Item> &new_list2,
207
 
                                      uint32_t elements, List<Item> &items);
 
216
                                      uint elements, List<Item> &items);
208
217
static void init_tmptable_sum_functions(Item_sum **func);
209
 
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
 
218
static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table);
210
219
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
211
220
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
212
221
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
213
222
static bool init_sum_functions(Item_sum **func, Item_sum **end);
214
223
static bool update_sum_func(Item_sum **func);
215
224
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
216
 
                            bool distinct, const char *message=NULL);
 
225
                            bool distinct, const char *message=NullS);
217
226
static Item *remove_additional_cond(Item* conds);
218
227
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
219
228
static bool test_if_ref(Item_field *left_item,Item *right_item);
242
251
{
243
252
  bool res;
244
253
  register SELECT_LEX *select_lex = &lex->select_lex;
245
 
  DRIZZLE_SELECT_START();
 
254
  DBUG_ENTER("handle_select");
 
255
  MYSQL_SELECT_START();
246
256
 
247
257
  if (select_lex->master_unit()->is_union() || 
248
258
      select_lex->master_unit()->fake_select_lex)
258
268
      setup_tables_done_option changed for next rexecution
259
269
    */
260
270
    res= mysql_select(thd, &select_lex->ref_pointer_array,
261
 
                      (TableList*) select_lex->table_list.first,
 
271
                      (TABLE_LIST*) select_lex->table_list.first,
262
272
                      select_lex->with_wild, select_lex->item_list,
263
273
                      select_lex->where,
264
274
                      select_lex->order_list.elements +
265
275
                      select_lex->group_list.elements,
266
 
                      (order_st*) select_lex->order_list.first,
267
 
                      (order_st*) select_lex->group_list.first,
 
276
                      (ORDER*) select_lex->order_list.first,
 
277
                      (ORDER*) select_lex->group_list.first,
268
278
                      select_lex->having,
269
 
                      (order_st*) lex->proc_list.first,
 
279
                      (ORDER*) lex->proc_list.first,
270
280
                      select_lex->options | thd->options |
271
281
                      setup_tables_done_option,
272
282
                      result, unit, select_lex);
273
283
  }
 
284
  DBUG_PRINT("info",("res: %d  report_error: %d", res,
 
285
                     thd->is_error()));
274
286
  res|= thd->is_error();
275
287
  if (unlikely(res))
276
288
    result->abort();
277
289
 
278
 
  DRIZZLE_SELECT_END();
279
 
  return(res);
 
290
  MYSQL_SELECT_END();
 
291
  DBUG_RETURN(res);
280
292
}
281
293
 
282
294
 
317
329
    this field from inner subqueries.
318
330
 
319
331
  RETURN
320
 
    true  an error occured
321
 
    false ok
 
332
    TRUE  an error occured
 
333
    FALSE ok
322
334
*/
323
335
 
324
336
bool
326
338
                 Item **ref_pointer_array)
327
339
{
328
340
  Item_outer_ref *ref;
329
 
  bool res= false;
330
 
  bool direct_ref= false;
 
341
  bool res= FALSE;
 
342
  bool direct_ref= FALSE;
331
343
 
332
344
  List_iterator<Item_outer_ref> ref_it(select->inner_refs_list);
333
345
  while ((ref= ref_it++))
358
370
    {
359
371
      Item_sum *sum_func;
360
372
      if (ref->in_sum_func->nest_level > select->nest_level)
361
 
        direct_ref= true;
 
373
        direct_ref= TRUE;
362
374
      else
363
375
      {
364
376
        for (sum_func= ref->in_sum_func; sum_func &&
367
379
        {
368
380
          if (sum_func->aggr_level == select->nest_level)
369
381
          {
370
 
            direct_ref= true;
 
382
            direct_ref= TRUE;
371
383
            break;
372
384
          }
373
385
        }
379
391
              new Item_ref(ref->context, item_ref, ref->table_name,
380
392
                          ref->field_name, ref->alias_name_used);
381
393
    if (!new_ref)
382
 
      return true;
 
394
      return TRUE;
383
395
    ref->outer_ref= new_ref;
384
396
    ref->ref= &ref->outer_ref;
385
397
 
386
398
    if (!ref->fixed && ref->fix_fields(thd, 0))
387
 
      return true;
 
399
      return TRUE;
388
400
    thd->used_tables|= item->used_tables();
389
401
  }
390
402
  return res;
395
407
  Function to setup clauses without sum functions.
396
408
*/
397
409
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
398
 
                               TableList *tables,
399
 
                               TableList *leaves,
 
410
                               TABLE_LIST *tables,
 
411
                               TABLE_LIST *leaves,
400
412
                               List<Item> &fields,
401
413
                               List<Item> &all_fields,
402
414
                               COND **conds,
403
 
                               order_st *order,
404
 
                               order_st *group, bool *hidden_group_fields)
 
415
                               ORDER *order,
 
416
                               ORDER *group, bool *hidden_group_fields)
405
417
{
406
418
  int res;
407
419
  nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
 
420
  DBUG_ENTER("setup_without_group");
408
421
 
409
422
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
410
423
  res= setup_conds(thd, tables, leaves, conds);
416
429
  res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
417
430
                          group, hidden_group_fields);
418
431
  thd->lex->allow_sum_func= save_allow_sum_func;
419
 
  return(res);
 
432
  DBUG_RETURN(res);
420
433
}
421
434
 
422
435
/*****************************************************************************
438
451
*/
439
452
int
440
453
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,
 
454
              TABLE_LIST *tables_init,
 
455
              uint wild_num, COND *conds_init, uint og_num,
 
456
              ORDER *order_init, ORDER *group_init,
444
457
              Item *having_init,
445
 
              order_st *proc_param_init, SELECT_LEX *select_lex_arg,
 
458
              ORDER *proc_param_init, SELECT_LEX *select_lex_arg,
446
459
              SELECT_LEX_UNIT *unit_arg)
447
460
{
 
461
  DBUG_ENTER("JOIN::prepare");
 
462
 
448
463
  // to prevent double initialization on EXPLAIN
449
464
  if (optimized)
450
 
    return(0);
 
465
    DBUG_RETURN(0);
451
466
 
452
467
  conds= conds_init;
453
468
  order= order_init;
466
481
    its table from update (see unique_table())
467
482
  */
468
483
  if (thd->derived_tables_processing)
469
 
    select_lex->exclude_from_table_unique_test= true;
 
484
    select_lex->exclude_from_table_unique_test= TRUE;
470
485
 
471
486
  /* Check that all tables, fields, conds and order are ok */
472
487
 
473
488
  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
474
489
      setup_tables_and_check_access(thd, &select_lex->context, join_list,
475
490
                                    tables_list, &select_lex->leaf_tables,
476
 
                                    false))
477
 
      return(-1);
 
491
                                    FALSE))
 
492
      DBUG_RETURN(-1);
478
493
 
479
 
  TableList *table_ptr;
 
494
  TABLE_LIST *table_ptr;
480
495
  for (table_ptr= select_lex->leaf_tables;
481
496
       table_ptr;
482
497
       table_ptr= table_ptr->next_leaf)
490
505
                          select_lex->leaf_tables, fields_list,
491
506
                          all_fields, &conds, order, group_list,
492
507
                          &hidden_group_fields))
493
 
    return(-1);                         /* purecov: inspected */
 
508
    DBUG_RETURN(-1);                            /* purecov: inspected */
494
509
 
495
510
  ref_pointer_array= *rref_pointer_array;
496
511
  
505
520
                          having->check_cols(1)));
506
521
    select_lex->having_fix_field= 0;
507
522
    if (having_fix_rc || thd->is_error())
508
 
      return(-1);                               /* purecov: inspected */
 
523
      DBUG_RETURN(-1);                          /* purecov: inspected */
509
524
    thd->lex->allow_sum_func= save_allow_sum_func;
510
525
  }
511
526
 
 
527
  if (!thd->lex->view_prepare_mode)
512
528
  {
513
529
    Item_subselect *subselect;
514
530
    Item_in_subselect *in_subs= NULL;
523
539
      if (subselect->substype() == Item_subselect::IN_SUBS)
524
540
        in_subs= (Item_in_subselect*)subselect;
525
541
 
 
542
      DBUG_PRINT("info", ("Checking if subq can be converted to semi-join"));
526
543
      /*
527
544
        Check if we're in subquery that is a candidate for flattening into a
528
545
        semi-join (which is done done in flatten_subqueries()). The
529
546
        requirements are:
530
547
          1. Subquery predicate is an IN/=ANY subq predicate
531
548
          2. Subquery is a single SELECT (not a UNION)
532
 
          3. Subquery does not have GROUP BY or order_st BY
 
549
          3. Subquery does not have GROUP BY or ORDER BY
533
550
          4. Subquery does not use aggregate functions or HAVING
534
551
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
535
552
          6. No execution method was already chosen (by a prepared statement).
551
568
          do_semijoin &&
552
569
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
553
570
      {
 
571
        DBUG_PRINT("info", ("Subquery is semi-join conversion candidate"));
554
572
        {
555
573
          if (!in_subs->left_expr->fixed &&
556
574
               in_subs->left_expr->fix_fields(thd, &in_subs->left_expr))
557
575
          {
558
 
            return(-1);
 
576
            DBUG_RETURN(-1);
559
577
          }
560
578
          /*
561
579
            Check that the right part of the subselect contains no more than one
566
584
              ((Item_in_subselect*)subselect)->left_expr->cols()))
567
585
          {
568
586
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
569
 
            return(-1);
 
587
            DBUG_RETURN(-1);
570
588
          }
571
589
        }
572
590
 
573
591
        /* Register the subquery for further processing */
574
592
        select_lex->outer_select()->join->sj_subselects.append(thd->mem_root, in_subs);
575
 
        in_subs->expr_join_nest= (TableList*)thd->thd_marker;
 
593
        in_subs->expr_join_nest= (TABLE_LIST*)thd->thd_marker;
576
594
      }
577
595
      else
578
596
      {
 
597
        DBUG_PRINT("info", ("Subquery can't be converted to semi-join"));
579
598
        bool do_materialize= !test(thd->variables.optimizer_switch &
580
599
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
581
600
        /*
595
614
             (Subquery is non-correlated ||
596
615
              Subquery is correlated to any query outer to IN predicate ||
597
616
              (Subquery is correlated to the immediate outer query &&
598
 
               Subquery !contains {GROUP BY, order_st BY [LIMIT],
 
617
               Subquery !contains {GROUP BY, ORDER BY [LIMIT],
599
618
               aggregate functions) && subquery predicate is not under "NOT IN"))
600
619
          6. No execution method was already chosen (by a prepared statement).
601
620
 
623
642
        if ((trans_res= subselect->select_transformer(this)) !=
624
643
            Item_subselect::RES_OK)
625
644
        {
626
 
          return((trans_res == Item_subselect::RES_ERROR));
 
645
          select_lex->fix_prepare_information(thd, &conds, &having);
 
646
          DBUG_RETURN((trans_res == Item_subselect::RES_ERROR));
627
647
        }
628
648
      }
629
649
    }
630
650
  }
631
651
 
 
652
  select_lex->fix_prepare_information(thd, &conds, &having);
 
653
 
632
654
  if (order)
633
655
  {
634
 
    order_st *ord;
 
656
    ORDER *ord;
635
657
    for (ord= order; ord; ord= ord->next)
636
658
    {
637
659
      Item *item= *ord->item;
642
664
 
643
665
  if (having && having->with_sum_func)
644
666
    having->split_sum_func2(thd, ref_pointer_array, all_fields,
645
 
                            &having, true);
 
667
                            &having, TRUE);
646
668
  if (select_lex->inner_sum_func_list)
647
669
  {
648
670
    Item_sum *end=select_lex->inner_sum_func_list;
651
673
    { 
652
674
      item_sum= item_sum->next;
653
675
      item_sum->split_sum_func2(thd, ref_pointer_array,
654
 
                                all_fields, item_sum->ref_by, false);
 
676
                                all_fields, item_sum->ref_by, FALSE);
655
677
    } while (item_sum != end);
656
678
  }
657
679
 
658
680
  if (select_lex->inner_refs_list.elements &&
659
681
      fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array))
660
 
    return(-1);
 
682
    DBUG_RETURN(-1);
 
683
 
 
684
  if (group_list)
 
685
  {
 
686
    /*
 
687
      Because HEAP tables can't index BIT fields we need to use an
 
688
      additional hidden field for grouping because later it will be
 
689
      converted to a LONG field. Original field will remain of the
 
690
      BIT type and will be returned to a client.
 
691
    */
 
692
    for (ORDER *ord= group_list; ord; ord= ord->next)
 
693
    {
 
694
      if ((*ord->item)->type() == Item::FIELD_ITEM &&
 
695
          (*ord->item)->field_type() == MYSQL_TYPE_BIT)
 
696
      {
 
697
        Item_field *field= new Item_field(thd, *(Item_field**)ord->item);
 
698
        int el= all_fields.elements;
 
699
        ref_pointer_array[el]= field;
 
700
        all_fields.push_front(field);
 
701
        ord->item= ref_pointer_array + el;
 
702
      }
 
703
    }
 
704
  }
661
705
 
662
706
  /*
663
707
    Check if there are references to un-aggregated columns when computing 
669
713
  {
670
714
    my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
671
715
               ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
672
 
    return(-1);
 
716
    DBUG_RETURN(-1);
673
717
  }
674
718
  {
675
719
    /* Caclulate the number of groups */
676
720
    send_group_parts= 0;
677
 
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
 
721
    for (ORDER *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
678
722
      send_group_parts++;
679
723
  }
680
724
  
702
746
  if (alloc_func_list())
703
747
    goto err;
704
748
 
705
 
  return(0); // All OK
 
749
  DBUG_RETURN(0); // All OK
706
750
 
707
751
err:
708
 
  return(-1);                           /* purecov: inspected */
 
752
  DBUG_RETURN(-1);                              /* purecov: inspected */
709
753
}
710
754
 
711
755
 
780
824
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
781
825
  if (where)
782
826
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
783
 
  for (uint32_t i = 0; i < join_tab->ref.key_parts; i++)
 
827
  for (uint i = 0; i < join_tab->ref.key_parts; i++)
784
828
  {
785
829
    if (join_tab->ref.cond_guards[i])
786
830
    {
814
858
        NULL-complemented but this function is not called for such tables]
815
859
 
816
860
  RETURN
817
 
    true  - Include table's rowid
818
 
    false - Don't
 
861
    TRUE  - Include table's rowid
 
862
    FALSE - Don't
819
863
*/
820
864
 
821
865
static bool sj_table_is_included(JOIN *join, JOIN_TAB *join_tab)
822
866
{
823
867
  if (join_tab->emb_sj_nest)
824
 
    return false;
 
868
    return FALSE;
825
869
  
826
870
  /* Check if this table is functionally dependent on the tables that
827
871
     are within the same outer join nest
828
872
  */
829
 
  TableList *embedding= join_tab->table->pos_in_table_list->embedding;
 
873
  TABLE_LIST *embedding= join_tab->table->pos_in_table_list->embedding;
830
874
  if (join_tab->type == JT_EQ_REF)
831
875
  {
832
876
    Table_map_iterator it(join_tab->ref.depend_map & ~PSEUDO_TABLE_BITS);
833
 
    uint32_t idx;
 
877
    uint idx;
834
878
    while ((idx= it.next_bit())!=Table_map_iterator::BITMAP_END)
835
879
    {
836
880
      JOIN_TAB *ref_tab= join->join_tab + idx;
837
881
      if (embedding == ref_tab->table->pos_in_table_list->embedding)
838
 
        return true;
 
882
        return TRUE;
839
883
    }
840
884
    /* Ok, functionally dependent */
841
 
    return false;
 
885
    return FALSE;
842
886
  }
843
887
  /* Not functionally dependent => need to include*/
844
 
  return true;
 
888
  return TRUE;
845
889
}
846
890
 
847
891
 
 
892
TABLE *create_duplicate_weedout_tmp_table(THD *thd, uint uniq_tuple_length_arg,
 
893
                                          SJ_TMP_TABLE *sjtbl);
 
894
 
 
895
 
848
896
/*
849
897
  Setup the strategies to eliminate semi-join duplicates.
850
898
  
937
985
    setting appropriate members in join_tab structures.
938
986
 
939
987
  RETURN
940
 
    false  OK 
941
 
    true   Out of memory error
 
988
    FALSE  OK 
 
989
    TRUE   Out of memory error
942
990
*/
943
991
 
944
992
static
945
 
int setup_semijoin_dups_elimination(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
993
int setup_semijoin_dups_elimination(JOIN *join, ulonglong options, uint no_jbuf_after)
946
994
{
947
995
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
948
996
  struct {
952
1000
      2 - Temptable (maybe confluent),
953
1001
      3 - Temptable with join buffering
954
1002
    */
955
 
    uint32_t strategy;
956
 
    uint32_t start_idx; /* Left range bound */
957
 
    uint32_t end_idx;   /* Right range bound */
 
1003
    uint strategy;
 
1004
    uint start_idx; /* Left range bound */
 
1005
    uint end_idx;   /* Right range bound */
958
1006
    /* 
959
1007
      For Temptable strategy: Bitmap of all outer and correlated tables from 
960
1008
      all involved join nests.
962
1010
    table_map outer_tables;
963
1011
  } dups_ranges [MAX_TABLES];
964
1012
 
965
 
  TableList *emb_insideout_nest= NULL;
 
1013
  TABLE_LIST *emb_insideout_nest= NULL;
966
1014
  table_map emb_sj_map= 0;  /* A bitmap of sj-nests (that is, their sj-inner
967
1015
                               tables) whose ranges we're in */
968
1016
  table_map emb_outer_tables= 0; /* sj-outer tables for those sj-nests */
969
1017
  table_map range_start_map= 0; /* table_map at current range start */
970
 
  bool dealing_with_jbuf= false; /* true <=> table within cur range uses join buf */
 
1018
  bool dealing_with_jbuf= FALSE; /* TRUE <=> table within cur range uses join buf */
971
1019
  int cur_range= 0;
972
 
  uint32_t i;
 
1020
  uint i;
973
1021
 
 
1022
  DBUG_ENTER("setup_semijoin_dups_elimination");
974
1023
  /*
975
1024
    First pass: locate the duplicate-generating ranges and pick the strategies.
976
1025
  */
977
1026
  for (i=join->const_tables ; i < join->tables ; i++)
978
1027
  {
979
1028
    JOIN_TAB *tab=join->join_tab+i;
980
 
    Table *table=tab->table;
 
1029
    TABLE *table=tab->table;
981
1030
    cur_map |= table->map;
982
1031
 
983
1032
    if (tab->emb_sj_nest) // Encountered an sj-inner table
1030
1079
          strategy that spans all the tables, starting from the very 1st
1031
1080
          one.
1032
1081
        */
1033
 
        dealing_with_jbuf= true;
1034
 
        emb_insideout_nest= false;
 
1082
        dealing_with_jbuf= TRUE;
 
1083
        emb_insideout_nest= FALSE;
1035
1084
 
1036
1085
        /* 
1037
1086
          Absorb all preceding duplicate-eliminating ranges. Their strategies
1057
1106
           SJ-nests), and all inner, outer, and correlated tables of all 
1058
1107
           sj-nests are in the join order prefix.
1059
1108
      */
1060
 
      bool end_of_range= false;
 
1109
      bool end_of_range= FALSE;
1061
1110
      if (emb_insideout_nest && 
1062
1111
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
1063
1112
      {
1064
1113
        /* Save that this range is handled with InsideOut: */
1065
1114
        dups_ranges[cur_range].strategy= 1;
1066
 
        end_of_range= true;
 
1115
        end_of_range= TRUE;
1067
1116
      }
1068
1117
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
1069
1118
      {
1078
1127
        */
1079
1128
        dups_ranges[cur_range].outer_tables= emb_outer_tables & 
1080
1129
                                             ~range_start_map;
1081
 
        end_of_range= true;
 
1130
        end_of_range= TRUE;
1082
1131
      }
1083
1132
 
1084
1133
      if (end_of_range)
1086
1135
        dups_ranges[cur_range].end_idx= i+1;
1087
1136
        emb_sj_map= emb_outer_tables= 0;
1088
1137
        emb_insideout_nest= NULL;
1089
 
        dealing_with_jbuf= false;
 
1138
        dealing_with_jbuf= FALSE;
1090
1139
        dups_ranges[++cur_range].strategy= 0;
1091
1140
      }
1092
1141
    }
1110
1159
    {
1111
1160
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
1112
1161
      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
 
1162
      uint jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
 
1163
      uint jt_null_bits= 0;    // # null bits in tuple bytes
1115
1164
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
1116
 
      uint32_t rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
 
1165
      uint rowid_keep_flags= JOIN_TAB::CALL_POSITION | JOIN_TAB::KEEP_ROWID;
1117
1166
      JOIN_TAB *last_outer_tab= tab - 1;
1118
1167
      /*
1119
1168
        Walk through the range and remember
1145
1194
      if (jt_rowid_offset) /* Temptable has at least one rowid */
1146
1195
      {
1147
1196
        SJ_TMP_TABLE *sjtbl;
1148
 
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
 
1197
        uint tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
1149
1198
        if (!(sjtbl= (SJ_TMP_TABLE*)thd->alloc(sizeof(SJ_TMP_TABLE))) ||
1150
1199
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) thd->alloc(tabs_size)))
1151
 
          return(true);
 
1200
          DBUG_RETURN(TRUE);
1152
1201
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
1153
1202
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
1154
1203
        sjtbl->rowid_len= jt_rowid_offset;
1181
1230
        jump_to= tab;
1182
1231
    }
1183
1232
  }
1184
 
  return(false);
 
1233
  DBUG_RETURN(FALSE);
1185
1234
}
1186
1235
 
1187
1236
 
1192
1241
  {
1193
1242
    if (sj_tbl->tmp_table)
1194
1243
    {
1195
 
      sj_tbl->tmp_table->free_tmp_table(join->thd);
 
1244
      free_tmp_table(join->thd, sj_tbl->tmp_table);
1196
1245
    }
1197
1246
  }
1198
1247
  join->sj_tmp_tables= NULL;
1199
1248
}
1200
1249
 
1201
 
uint32_t make_join_orderinfo(JOIN *join);
 
1250
uint make_join_orderinfo(JOIN *join);
1202
1251
 
1203
1252
/**
1204
1253
  global select optimisation.
1215
1264
int
1216
1265
JOIN::optimize()
1217
1266
{
 
1267
  DBUG_ENTER("JOIN::optimize");
1218
1268
  // to prevent double initialization on EXPLAIN
1219
1269
  if (optimized)
1220
 
    return(0);
 
1270
    DBUG_RETURN(0);
1221
1271
  optimized= 1;
1222
1272
 
1223
 
  thd->set_proc_info("optimizing");
 
1273
  thd_proc_info(thd, "optimizing");
1224
1274
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
1225
1275
              unit->select_limit_cnt);
1226
1276
  /* select_limit is used to decide if we are likely to scan the whole table */
1254
1304
    }
1255
1305
  }
1256
1306
#endif
1257
 
 
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);
 
1307
  SELECT_LEX *sel= thd->lex->current_select;
 
1308
  if (sel->first_cond_optimization)
 
1309
  {
 
1310
    /*
 
1311
      The following code will allocate the new items in a permanent
 
1312
      MEMROOT for prepared statements and stored procedures.
 
1313
    */
 
1314
    sel->first_cond_optimization= 0;
 
1315
 
 
1316
    /* Convert all outer joins to inner joins if possible */
 
1317
    conds= simplify_joins(this, join_list, conds, TRUE, FALSE);
 
1318
    build_bitmap_for_nested_joins(join_list, 0);
 
1319
 
 
1320
    sel->prep_where= conds ? conds->copy_andor_structure(thd) : 0;
 
1321
  }
1261
1322
 
1262
1323
  conds= optimize_cond(this, conds, join_list, &cond_value);   
1263
1324
  if (thd->is_error())
1264
1325
  {
1265
1326
    error= 1;
1266
 
    return(1);
 
1327
    DBUG_PRINT("error",("Error from optimize_cond"));
 
1328
    DBUG_RETURN(1);
1267
1329
  }
1268
1330
 
1269
1331
  {
1271
1333
    if (thd->is_error())
1272
1334
    {
1273
1335
      error= 1;
1274
 
      return(1);
 
1336
      DBUG_PRINT("error",("Error from optimize_cond"));
 
1337
      DBUG_RETURN(1);
1275
1338
    }
1276
1339
    if (select_lex->where)
1277
1340
      select_lex->cond_value= cond_value;
1281
1344
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE || 
1282
1345
        (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
1283
1346
    {                                           /* Impossible cond */
 
1347
      DBUG_PRINT("info", (having_value == Item::COND_FALSE ? 
 
1348
                            "Impossible HAVING" : "Impossible WHERE"));
1284
1349
      zero_result_cause=  having_value == Item::COND_FALSE ?
1285
1350
                           "Impossible HAVING" : "Impossible WHERE";
1286
1351
      error= 0;
1287
 
      return(0);
 
1352
      DBUG_RETURN(0);
1288
1353
    }
1289
1354
  }
1290
1355
 
1291
 
  /* Optimize count(*), cmin() and cmax() */
 
1356
  /* Optimize count(*), min() and max() */
1292
1357
  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
1293
1358
  {
1294
1359
    int res;
1302
1367
    {
1303
1368
      if (res == HA_ERR_KEY_NOT_FOUND)
1304
1369
      {
 
1370
        DBUG_PRINT("info",("No matching min/max row"));
1305
1371
        zero_result_cause= "No matching min/max row";
1306
1372
        error=0;
1307
 
        return(0);
 
1373
        DBUG_RETURN(0);
1308
1374
      }
1309
1375
      if (res > 1)
1310
1376
      {
1311
1377
        error= res;
1312
 
        return(1);
 
1378
        DBUG_PRINT("error",("Error from opt_sum_query"));
 
1379
        DBUG_RETURN(1);
1313
1380
      }
1314
1381
      if (res < 0)
1315
1382
      {
 
1383
        DBUG_PRINT("info",("No matching min/max row"));
1316
1384
        zero_result_cause= "No matching min/max row";
1317
1385
        error=0;
1318
 
        return(0);
 
1386
        DBUG_RETURN(0);
1319
1387
      }
 
1388
      DBUG_PRINT("info",("Select tables optimized away"));
1320
1389
      zero_result_cause= "Select tables optimized away";
1321
1390
      tables_list= 0;                           // All tables resolved
1322
1391
      /*
1333
1402
      {
1334
1403
        COND *table_independent_conds=
1335
1404
          make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
 
1405
        DBUG_EXECUTE("where",
 
1406
                     print_where(table_independent_conds,
 
1407
                                 "where after opt_sum_query()",
 
1408
                                 QT_ORDINARY););
1336
1409
        conds= table_independent_conds;
1337
1410
      }
1338
1411
    }
1339
1412
  }
1340
1413
  if (!tables_list)
1341
1414
  {
 
1415
    DBUG_PRINT("info",("No tables"));
1342
1416
    error= 0;
1343
 
    return(0);
 
1417
    DBUG_RETURN(0);
1344
1418
  }
1345
1419
  error= -1;                                    // Error is sent to client
1346
1420
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
1347
1421
 
1348
1422
  /* Calculate how to do the join */
1349
 
  thd->set_proc_info("statistics");
 
1423
  thd_proc_info(thd, "statistics");
1350
1424
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
1351
1425
      thd->is_fatal_error)
1352
1426
  {
1353
 
    return(1);
 
1427
    DBUG_PRINT("error",("Error: make_join_statistics() failed"));
 
1428
    DBUG_RETURN(1);
1354
1429
  }
1355
1430
 
1356
1431
  /* Remove distinct if only const tables */
1357
1432
  select_distinct= select_distinct && (const_tables != tables);
1358
 
  thd->set_proc_info("preparing");
 
1433
  thd_proc_info(thd, "preparing");
1359
1434
  if (result->initialize_tables(this))
1360
1435
  {
1361
 
    return(1);                          // error == -1
 
1436
    DBUG_PRINT("error",("Error: initialize_tables() failed"));
 
1437
    DBUG_RETURN(1);                             // error == -1
1362
1438
  }
1363
1439
  if (const_table_map != found_const_table_map &&
1364
1440
      !(select_options & SELECT_DESCRIBE) &&
1367
1443
       select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
1368
1444
  {
1369
1445
    zero_result_cause= "no matching row in const table";
 
1446
    DBUG_PRINT("error",("Error: %s", zero_result_cause));
1370
1447
    error= 0;
1371
 
    return(0);
 
1448
    DBUG_RETURN(0);
1372
1449
  }
1373
1450
  if (!(thd->options & OPTION_BIG_SELECTS) &&
1374
1451
      best_read > (double) thd->variables.max_join_size &&
1376
1453
  {                                             /* purecov: inspected */
1377
1454
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
1378
1455
    error= -1;
1379
 
    return(1);
 
1456
    DBUG_RETURN(1);
1380
1457
  }
1381
1458
  if (const_tables && !thd->locked_tables &&
1382
1459
      !(select_options & SELECT_NO_UNLOCK))
1384
1461
  if (!conds && outer_join)
1385
1462
  {
1386
1463
    /* Handle the case where we have an OUTER JOIN without a WHERE */
1387
 
    conds=new Item_int((int64_t) 1,1);  // Always true
 
1464
    conds=new Item_int((longlong) 1,1); // Always true
1388
1465
  }
1389
1466
  select= make_select(*table, const_table_map,
1390
1467
                      const_table_map, conds, 1, &error);
1391
1468
  if (error)
1392
1469
  {                                             /* purecov: inspected */
1393
1470
    error= -1;                                  /* purecov: inspected */
1394
 
    return(1);
 
1471
    DBUG_PRINT("error",("Error: make_select() failed"));
 
1472
    DBUG_RETURN(1);
1395
1473
  }
1396
1474
  
1397
1475
  reset_nj_counters(join_list);
1407
1485
  {
1408
1486
    conds= substitute_for_best_equal_field(conds, cond_equal, map2table);
1409
1487
    conds->update_used_tables();
 
1488
    DBUG_EXECUTE("where",
 
1489
                 print_where(conds,
 
1490
                             "after substitute_best_equal",
 
1491
                             QT_ORDINARY););
1410
1492
  }
1411
1493
 
1412
1494
  /*
1428
1510
      (select_options & SELECT_DESCRIBE) &&
1429
1511
      select_lex->master_unit() == &thd->lex->unit) // upper level SELECT
1430
1512
  {
1431
 
    conds=new Item_int((int64_t) 0,1);  // Always false
 
1513
    conds=new Item_int((longlong) 0,1); // Always false
1432
1514
  }
1433
1515
  if (make_join_select(this, select, conds))
1434
1516
  {
1435
1517
    zero_result_cause=
1436
1518
      "Impossible WHERE noticed after reading const tables";
1437
 
    return(0);                          // error == 0
 
1519
    DBUG_RETURN(0);                             // error == 0
1438
1520
  }
1439
1521
 
1440
1522
  error= -1;                                    /* if goto err */
1441
1523
 
1442
1524
  /* Optimize distinct away if possible */
1443
1525
  {
1444
 
    order_st *org_order= order;
 
1526
    ORDER *org_order= order;
1445
1527
    order=remove_const(this, order,conds,1, &simple_order);
1446
1528
    if (thd->is_error())
1447
1529
    {
1448
1530
      error= 1;
1449
 
      return(1);
 
1531
      DBUG_PRINT("error",("Error from remove_const"));
 
1532
      DBUG_RETURN(1);
1450
1533
    }
1451
1534
 
1452
1535
    /*
1453
 
      If we are using order_st BY NULL or order_st BY const_expression,
 
1536
      If we are using ORDER BY NULL or ORDER BY const_expression,
1454
1537
      return result in any order (even if we are using a GROUP BY)
1455
1538
    */
1456
1539
    if (!order && org_order)
1484
1567
        We have found that grouping can be removed since groups correspond to
1485
1568
        only one row anyway, but we still have to guarantee correct result
1486
1569
        order. The line below effectively rewrites the query from GROUP BY
1487
 
        <fields> to order_st BY <fields>. There are two exceptions:
 
1570
        <fields> to ORDER BY <fields>. There are two exceptions:
1488
1571
        - if skip_sort_order is set (see above), then we can simply skip
1489
1572
          GROUP BY;
1490
 
        - we can only rewrite order_st BY if the order_st BY fields are 'compatible'
 
1573
        - we can only rewrite ORDER BY if the ORDER BY fields are 'compatible'
1491
1574
          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
 
1575
          We only check if the ORDER BY is a prefix of GROUP BY. In this case
1493
1576
          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
 
1577
          ORDER BY fields.
 
1578
          If GROUP BY is a prefix of ORDER BY, then it is safe to leave
1496
1579
          'order' as is.
1497
1580
       */
1498
1581
      if (!order || test_if_subpart(group_list, order))
1499
1582
          order= skip_sort_order ? 0 : group_list;
1500
1583
      /*
1501
1584
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be 
1502
 
        rewritten to IGNORE INDEX FOR order_st BY(fields).
 
1585
        rewritten to IGNORE INDEX FOR ORDER BY(fields).
1503
1586
      */
1504
1587
      join_tab->table->keys_in_use_for_order_by=
1505
1588
        join_tab->table->keys_in_use_for_group_by;
1524
1607
    /*
1525
1608
      We are only using one table. In this case we change DISTINCT to a
1526
1609
      GROUP BY query if:
1527
 
      - The GROUP BY can be done through indexes (no sort) and the order_st
 
1610
      - The GROUP BY can be done through indexes (no sort) and the ORDER
1528
1611
        BY only uses selected fields.
1529
 
        (In this case we can later optimize away GROUP BY and order_st BY)
 
1612
        (In this case we can later optimize away GROUP BY and ORDER BY)
1530
1613
      - We are scanning the whole table without LIMIT
1531
1614
        This can happen if:
1532
1615
        - We are using CALC_FOUND_ROWS
1533
 
        - We are using an order_st BY that can't be optimized away.
 
1616
        - We are using an ORDER BY that can't be optimized away.
1534
1617
 
1535
1618
      We don't want to use this optimization when we are using LIMIT
1536
1619
      because in this case we can just create a temporary table that
1562
1645
          {
1563
1646
            /*
1564
1647
              Force MySQL to read the table in sorted order to get result in
1565
 
              order_st BY order.
 
1648
              ORDER BY order.
1566
1649
            */
1567
1650
            tmp_table_param.quick_group=0;
1568
1651
          }
1574
1657
        group_list= 0;
1575
1658
    }
1576
1659
    else if (thd->is_fatal_error)                       // End of memory
1577
 
      return(1);
 
1660
      DBUG_RETURN(1);
1578
1661
  }
1579
1662
  simple_group= 0;
1580
1663
  {
1581
 
    order_st *old_group_list;
 
1664
    ORDER *old_group_list;
1582
1665
    group_list= remove_const(this, (old_group_list= group_list), conds,
1583
1666
                             rollup.state == ROLLUP::STATE_NONE,
1584
1667
                             &simple_group);
1585
1668
    if (thd->is_error())
1586
1669
    {
1587
1670
      error= 1;
1588
 
      return(1);
 
1671
      DBUG_PRINT("error",("Error from remove_const"));
 
1672
      DBUG_RETURN(1);
1589
1673
    }
1590
1674
    if (old_group_list && !group_list)
1591
1675
      select_distinct= 0;
1619
1703
    This has to be done if all tables are not already read (const tables)
1620
1704
    and one of the following conditions holds:
1621
1705
    - 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
 
1706
    - We are using an ORDER BY or GROUP BY on fields not in the first table
 
1707
    - We are using different ORDER BY and GROUP BY orders
1624
1708
    - The user wants us to buffer the result.
1625
1709
  */
1626
1710
  need_tmp= (const_tables != tables &&
1628
1712
              (group_list && order) ||
1629
1713
              test(select_options & OPTION_BUFFER_RESULT)));
1630
1714
 
1631
 
  uint32_t no_jbuf_after= make_join_orderinfo(this);
1632
 
  uint64_t select_opts_for_readinfo= 
 
1715
  uint no_jbuf_after= make_join_orderinfo(this);
 
1716
  ulonglong select_opts_for_readinfo= 
1633
1717
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
1634
1718
 
1635
1719
  sj_tmp_tables= NULL;
1639
1723
 
1640
1724
  // No cache for MATCH == 'Don't use join buffering when we use MATCH'.
1641
1725
  if (make_join_readinfo(this, select_opts_for_readinfo, no_jbuf_after))
1642
 
    return(1);
 
1726
    DBUG_RETURN(1);
1643
1727
 
1644
1728
  /* Create all structures needed for materialized subquery execution. */
1645
1729
  if (setup_subquery_materialization())
1646
 
    return(1);
 
1730
    DBUG_RETURN(1);
1647
1731
 
1648
1732
  /*
1649
1733
    is this simple IN subquery?
1663
1747
        save_index_subquery_explain_info(join_tab, where);
1664
1748
        join_tab[0].type= JT_UNIQUE_SUBQUERY;
1665
1749
        error= 0;
1666
 
        return(unit->item->
 
1750
        DBUG_RETURN(unit->item->
1667
1751
                    change_engine(new
1668
1752
                                  subselect_uniquesubquery_engine(thd,
1669
1753
                                                                  join_tab,
1677
1761
        save_index_subquery_explain_info(join_tab, where);
1678
1762
        join_tab[0].type= JT_INDEX_SUBQUERY;
1679
1763
        error= 0;
1680
 
        return(unit->item->
 
1764
        DBUG_RETURN(unit->item->
1681
1765
                    change_engine(new
1682
1766
                                  subselect_indexsubquery_engine(thd,
1683
1767
                                                                 join_tab,
1694
1778
      error= 0;
1695
1779
      conds= remove_additional_cond(conds);
1696
1780
      save_index_subquery_explain_info(join_tab, conds);
1697
 
      return(unit->item->
 
1781
      DBUG_RETURN(unit->item->
1698
1782
                  change_engine(new subselect_indexsubquery_engine(thd,
1699
1783
                                                                   join_tab,
1700
1784
                                                                   unit->item,
1712
1796
  */
1713
1797
  if (need_tmp || select_distinct || group_list || order)
1714
1798
  {
1715
 
    for (uint32_t i = const_tables; i < tables; i++)
 
1799
    for (uint i = const_tables; i < tables; i++)
1716
1800
      join_tab[i].table->prepare_for_position();
1717
1801
  }
1718
1802
 
 
1803
  DBUG_EXECUTE("info",TEST_join(this););
 
1804
 
1719
1805
  if (const_tables != tables)
1720
1806
  {
1721
1807
    /*
1730
1816
        ((order && simple_order) || (group_list && simple_group)))
1731
1817
    {
1732
1818
      if (add_ref_to_table_cond(thd,&join_tab[const_tables])) {
1733
 
        return(1);
 
1819
        DBUG_RETURN(1);
1734
1820
      }
1735
1821
    }
1736
1822
    
1752
1838
        Force using of tmp table if sorting by a SP or UDF function due to
1753
1839
        their expensive and probably non-deterministic nature.
1754
1840
      */
1755
 
      for (order_st *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
 
1841
      for (ORDER *tmp_order= order; tmp_order ; tmp_order=tmp_order->next)
1756
1842
      {
1757
1843
        Item *item= *tmp_order->item;
1758
1844
        if (item->is_expensive())
1769
1855
  if (select_options & SELECT_DESCRIBE)
1770
1856
  {
1771
1857
    error= 0;
1772
 
    return(0);
 
1858
    DBUG_RETURN(0);
1773
1859
  }
1774
1860
  having= 0;
1775
1861
 
1785
1871
    join_tab element of the plan for its access method.
1786
1872
  */
1787
1873
  if (join_tab->is_using_loose_index_scan())
1788
 
    tmp_table_param.precomputed_group_by= true;
 
1874
    tmp_table_param.precomputed_group_by= TRUE;
1789
1875
 
1790
1876
  /* Create a tmp table if distinct or if the sort is too complicated */
1791
1877
  if (need_tmp)
1792
1878
  {
1793
 
    thd->set_proc_info("Creating tmp table");
 
1879
    DBUG_PRINT("info",("Creating tmp table"));
 
1880
    thd_proc_info(thd, "Creating tmp table");
1794
1881
 
1795
1882
    init_items_ref_array();
1796
1883
 
1797
1884
    tmp_table_param.hidden_field_count= (all_fields.elements -
1798
1885
                                         fields_list.elements);
1799
 
    order_st *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
1800
 
                                                             (order_st*) 0);
 
1886
    ORDER *tmp_group= ((!simple_group && !(test_flags & TEST_NO_KEY_GROUP)) ? group_list :
 
1887
                                                             (ORDER*) 0);
1801
1888
    /*
1802
1889
      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
 
1890
      when there is ORDER BY or GROUP BY or there is no GROUP BY, but
1804
1891
      there are aggregate functions, because in all these cases we need
1805
1892
      all result rows.
1806
1893
    */
1818
1905
                           tmp_rows_limit,
1819
1906
                           (char *) "")))
1820
1907
                {
1821
 
      return(1);
 
1908
      DBUG_RETURN(1);
1822
1909
    }
1823
1910
 
1824
1911
    /*
1838
1925
    /* if group or order on first table, sort first */
1839
1926
    if (group_list && simple_group)
1840
1927
    {
1841
 
      thd->set_proc_info("Sorting for group");
 
1928
      DBUG_PRINT("info",("Sorting for group"));
 
1929
      thd_proc_info(thd, "Sorting for group");
1842
1930
      if (create_sort_index(thd, this, group_list,
1843
 
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
 
1931
                            HA_POS_ERROR, HA_POS_ERROR, FALSE) ||
1844
1932
          alloc_group_fields(this, group_list) ||
1845
1933
          make_sum_func_list(all_fields, fields_list, 1) ||
1846
1934
          setup_sum_funcs(thd, sum_funcs))
1847
1935
      {
1848
 
        return(1);
 
1936
        DBUG_RETURN(1);
1849
1937
      }
1850
1938
      group_list=0;
1851
1939
    }
1854
1942
      if (make_sum_func_list(all_fields, fields_list, 0) ||
1855
1943
          setup_sum_funcs(thd, sum_funcs))
1856
1944
      {
1857
 
        return(1);
 
1945
        DBUG_RETURN(1);
1858
1946
      }
1859
1947
 
1860
1948
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1861
1949
      {
1862
 
        thd->set_proc_info("Sorting for order");
 
1950
        DBUG_PRINT("info",("Sorting for order"));
 
1951
        thd_proc_info(thd, "Sorting for order");
1863
1952
        if (create_sort_index(thd, this, order,
1864
 
                              HA_POS_ERROR, HA_POS_ERROR, true))
 
1953
                              HA_POS_ERROR, HA_POS_ERROR, TRUE))
1865
1954
        {
1866
 
          return(1);
 
1955
          DBUG_RETURN(1);
1867
1956
        }
1868
1957
        order=0;
1869
1958
      }
1903
1992
    */
1904
1993
    if (select_lex->uncacheable && !is_top_level_join() &&
1905
1994
        init_save_join_tab())
1906
 
      return(-1);                         /* purecov: inspected */
 
1995
      DBUG_RETURN(-1);                         /* purecov: inspected */
1907
1996
  }
1908
1997
 
1909
1998
  error= 0;
1910
 
  return(0);
 
1999
  DBUG_RETURN(0);
1911
2000
}
1912
2001
 
1913
2002
 
1923
2012
int
1924
2013
JOIN::reinit()
1925
2014
{
 
2015
  DBUG_ENTER("JOIN::reinit");
 
2016
 
1926
2017
  unit->offset_limit_cnt= (ha_rows)(select_lex->offset_limit ?
1927
2018
                                    select_lex->offset_limit->val_uint() :
1928
 
                                    0UL);
 
2019
                                    ULL(0));
1929
2020
 
1930
2021
  first_record= 0;
1931
2022
 
1960
2051
      func->clear();
1961
2052
  }
1962
2053
 
1963
 
  return(0);
 
2054
  DBUG_RETURN(0);
1964
2055
}
1965
2056
 
1966
2057
/**
1990
2081
{
1991
2082
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1992
2083
  {
1993
 
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((unsigned char*) join_tab,
 
2084
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((uchar*) join_tab,
1994
2085
                                                sizeof(JOIN_TAB) * tables)))
1995
2086
      return 1;
1996
2087
  }
2014
2105
{
2015
2106
  List<Item> *columns_list= &fields_list;
2016
2107
  int      tmp_error;
 
2108
  DBUG_ENTER("JOIN::exec");
2017
2109
 
2018
 
  thd->set_proc_info("executing");
 
2110
  thd_proc_info(thd, "executing");
2019
2111
  error= 0;
2020
2112
  (void) result->prepare2(); // Currently, this cannot fail.
2021
2113
 
2022
2114
  if (!tables_list && (tables || !select_lex->with_sum_func))
2023
2115
  {                                           // Only test of functions
2024
2116
    if (select_options & SELECT_DESCRIBE)
2025
 
      select_describe(this, false, false, false,
 
2117
      select_describe(this, FALSE, FALSE, FALSE,
2026
2118
                      (zero_result_cause?zero_result_cause:"No tables used"));
2027
2119
    else
2028
2120
    {
2055
2147
    /* Single select (without union) always returns 0 or 1 row */
2056
2148
    thd->limit_found_rows= send_records;
2057
2149
    thd->examined_row_count= 0;
2058
 
    return;
 
2150
    DBUG_VOID_RETURN;
2059
2151
  }
2060
2152
  /*
2061
2153
    Don't reset the found rows count if there're no tables as
2073
2165
                            select_options,
2074
2166
                            zero_result_cause,
2075
2167
                            having);
2076
 
    return;
 
2168
    DBUG_VOID_RETURN;
2077
2169
  }
2078
2170
 
2079
2171
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) &&
2080
2172
      get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
2081
 
    return;
 
2173
    DBUG_VOID_RETURN;
2082
2174
 
2083
2175
  if (select_options & SELECT_DESCRIBE)
2084
2176
  {
2085
2177
    /*
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
 
2178
      Check if we managed to optimize ORDER BY away and don't use temporary
 
2179
      table to resolve ORDER BY: in that case, we only may need to do
2088
2180
      filesort for GROUP BY.
2089
2181
    */
2090
2182
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
2110
2202
    select_describe(this, need_tmp,
2111
2203
                    order != 0 && !skip_sort_order,
2112
2204
                    select_distinct,
2113
 
                    !tables ? "No tables used" : NULL);
2114
 
    return;
 
2205
                    !tables ? "No tables used" : NullS);
 
2206
    DBUG_VOID_RETURN;
2115
2207
  }
2116
2208
 
2117
2209
  JOIN *curr_join= this;
2118
2210
  List<Item> *curr_all_fields= &all_fields;
2119
2211
  List<Item> *curr_fields_list= &fields_list;
2120
 
  Table *curr_tmp_table= 0;
 
2212
  TABLE *curr_tmp_table= 0;
2121
2213
  /*
2122
2214
    Initialize examined rows here because the values from all join parts
2123
2215
    must be accumulated in examined_row_count. Hence every join
2141
2233
    curr_tmp_table= exec_tmp_table1;
2142
2234
 
2143
2235
    /* Copy data to the temporary table */
2144
 
    thd->set_proc_info("Copying to tmp table");
 
2236
    thd_proc_info(thd, "Copying to tmp table");
 
2237
    DBUG_PRINT("info", ("%s", thd->proc_info));
2145
2238
    if (!curr_join->sort_and_group &&
2146
2239
        curr_join->const_tables != curr_join->tables)
2147
2240
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
2148
2241
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2149
2242
    {
2150
2243
      error= tmp_error;
2151
 
      return;
 
2244
      DBUG_VOID_RETURN;
2152
2245
    }
2153
2246
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
2154
2247
    
2165
2258
        if (change_to_use_tmp_fields(thd, items1,
2166
2259
                                     tmp_fields_list1, tmp_all_fields1,
2167
2260
                                     fields_list.elements, all_fields))
2168
 
          return;
 
2261
          DBUG_VOID_RETURN;
2169
2262
      }
2170
2263
      else
2171
2264
      {
2172
2265
        if (change_refs_to_tmp_fields(thd, items1,
2173
2266
                                      tmp_fields_list1, tmp_all_fields1,
2174
2267
                                      fields_list.elements, all_fields))
2175
 
          return;
 
2268
          DBUG_VOID_RETURN;
2176
2269
      }
2177
2270
      curr_join->tmp_all_fields1= tmp_all_fields1;
2178
2271
      curr_join->tmp_fields_list1= tmp_fields_list1;
2214
2307
 
2215
2308
    if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
2216
2309
    {                                   /* Must copy to another table */
 
2310
      DBUG_PRINT("info",("Creating group table"));
 
2311
      
2217
2312
      /* Free first data from old join */
2218
2313
      curr_join->join_free();
2219
2314
      if (make_simple_join(curr_join, curr_tmp_table))
2220
 
        return;
 
2315
        DBUG_VOID_RETURN;
2221
2316
      calc_group_buffer(curr_join, group_list);
2222
2317
      count_field_types(select_lex, &curr_join->tmp_table_param,
2223
2318
                        curr_join->tmp_all_fields1,
2239
2334
          functions. See extended comment in JOIN::exec.
2240
2335
        */
2241
2336
        if (curr_join->join_tab->is_using_loose_index_scan())
2242
 
          curr_join->tmp_table_param.precomputed_group_by= true;
 
2337
          curr_join->tmp_table_param.precomputed_group_by= TRUE;
2243
2338
 
2244
2339
        if (!(curr_tmp_table=
2245
2340
              exec_tmp_table2= create_tmp_table(thd,
2246
2341
                                                &curr_join->tmp_table_param,
2247
2342
                                                *curr_all_fields,
2248
 
                                                (order_st*) 0,
 
2343
                                                (ORDER*) 0,
2249
2344
                                                curr_join->select_distinct && 
2250
2345
                                                !curr_join->group_list,
2251
2346
                                                1, curr_join->select_options,
2252
2347
                                                HA_POS_ERROR,
2253
2348
                                                (char *) "")))
2254
 
          return;
 
2349
          DBUG_VOID_RETURN;
2255
2350
        curr_join->exec_tmp_table2= exec_tmp_table2;
2256
2351
      }
2257
2352
      if (curr_join->group_list)
2258
2353
      {
2259
 
        thd->set_proc_info("Creating sort index");
 
2354
        thd_proc_info(thd, "Creating sort index");
2260
2355
        if (curr_join->join_tab == join_tab && save_join_tab())
2261
2356
        {
2262
 
          return;
 
2357
          DBUG_VOID_RETURN;
2263
2358
        }
2264
2359
        if (create_sort_index(thd, curr_join, curr_join->group_list,
2265
 
                              HA_POS_ERROR, HA_POS_ERROR, false) ||
 
2360
                              HA_POS_ERROR, HA_POS_ERROR, FALSE) ||
2266
2361
            make_group_fields(this, curr_join))
2267
2362
        {
2268
 
          return;
 
2363
          DBUG_VOID_RETURN;
2269
2364
        }
2270
2365
        sortorder= curr_join->sortorder;
2271
2366
      }
2272
2367
      
2273
 
      thd->set_proc_info("Copying to group table");
 
2368
      thd_proc_info(thd, "Copying to group table");
 
2369
      DBUG_PRINT("info", ("%s", thd->proc_info));
2274
2370
      tmp_error= -1;
2275
2371
      if (curr_join != this)
2276
2372
      {
2287
2383
        }
2288
2384
      }
2289
2385
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2290
 
                                        1, true))
2291
 
        return;
 
2386
                                        1, TRUE))
 
2387
        DBUG_VOID_RETURN;
2292
2388
      curr_join->group_list= 0;
2293
2389
      if (!curr_join->sort_and_group &&
2294
2390
          curr_join->const_tables != curr_join->tables)
2297
2393
          (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2298
2394
      {
2299
2395
        error= tmp_error;
2300
 
        return;
 
2396
        DBUG_VOID_RETURN;
2301
2397
      }
2302
2398
      end_read_record(&curr_join->join_tab->read_record);
2303
2399
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
2310
2406
        if (change_to_use_tmp_fields(thd, items2,
2311
2407
                                     tmp_fields_list2, tmp_all_fields2, 
2312
2408
                                     fields_list.elements, tmp_all_fields1))
2313
 
          return;
 
2409
          DBUG_VOID_RETURN;
2314
2410
        curr_join->tmp_fields_list2= tmp_fields_list2;
2315
2411
        curr_join->tmp_all_fields2= tmp_all_fields2;
2316
2412
      }
2327
2423
    curr_join->join_free();                     /* Free quick selects */
2328
2424
    if (curr_join->select_distinct && ! curr_join->group_list)
2329
2425
    {
2330
 
      thd->set_proc_info("Removing duplicates");
 
2426
      thd_proc_info(thd, "Removing duplicates");
2331
2427
      if (curr_join->tmp_having)
2332
2428
        curr_join->tmp_having->update_used_tables();
2333
2429
      if (remove_duplicates(curr_join, curr_tmp_table,
2334
2430
                            *curr_fields_list, curr_join->tmp_having))
2335
 
        return;
 
2431
        DBUG_VOID_RETURN;
2336
2432
      curr_join->tmp_having=0;
2337
2433
      curr_join->select_distinct=0;
2338
2434
    }
2339
2435
    curr_tmp_table->reginfo.lock_type= TL_UNLOCK;
2340
2436
    if (make_simple_join(curr_join, curr_tmp_table))
2341
 
      return;
 
2437
      DBUG_VOID_RETURN;
2342
2438
    calc_group_buffer(curr_join, curr_join->group_list);
2343
2439
    count_field_types(select_lex, &curr_join->tmp_table_param, 
2344
2440
                      *curr_all_fields, 0);
2349
2445
  {
2350
2446
    if (make_group_fields(this, curr_join))
2351
2447
    {
2352
 
      return;
 
2448
      DBUG_VOID_RETURN;
2353
2449
    }
2354
2450
    if (!items3)
2355
2451
    {
2378
2474
    curr_join->set_items_ref_array(items3);
2379
2475
 
2380
2476
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2381
 
                                      1, true) || 
 
2477
                                      1, TRUE) || 
2382
2478
        setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2383
2479
        thd->is_fatal_error)
2384
 
      return;
 
2480
      DBUG_VOID_RETURN;
2385
2481
  }
2386
2482
  if (curr_join->group_list || curr_join->order)
2387
2483
  {
2388
 
    thd->set_proc_info("Sorting result");
 
2484
    DBUG_PRINT("info",("Sorting for send_fields"));
 
2485
    thd_proc_info(thd, "Sorting result");
2389
2486
    /* If we have already done the group, add HAVING to sorted table */
2390
2487
    if (curr_join->tmp_having && ! curr_join->group_list && 
2391
2488
        ! curr_join->sort_and_group)
2403
2500
      {
2404
2501
        if (!curr_table->select)
2405
2502
          if (!(curr_table->select= new SQL_SELECT))
2406
 
            return;
 
2503
            DBUG_VOID_RETURN;
2407
2504
        if (!curr_table->select->cond)
2408
2505
          curr_table->select->cond= sort_table_cond;
2409
2506
        else                                    // This should never happen
2411
2508
          if (!(curr_table->select->cond=
2412
2509
                new Item_cond_and(curr_table->select->cond,
2413
2510
                                  sort_table_cond)))
2414
 
            return;
 
2511
            DBUG_VOID_RETURN;
2415
2512
          /*
2416
2513
            Item_cond_and do not need fix_fields for execution, its parameters
2417
2514
            are fixed or do not need fix_fields, too
2420
2517
        }
2421
2518
        curr_table->select_cond= curr_table->select->cond;
2422
2519
        curr_table->select_cond->top_level_item();
 
2520
        DBUG_EXECUTE("where",print_where(curr_table->select->cond,
 
2521
                                         "select and having",
 
2522
                                         QT_ORDINARY););
2423
2523
        curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2424
2524
                                                   ~ (table_map) 0,
2425
2525
                                                   ~used_tables, 0);
 
2526
        DBUG_EXECUTE("where",print_where(curr_join->tmp_having,
 
2527
                                         "having after sort",
 
2528
                                         QT_ORDINARY););
2426
2529
      }
2427
2530
    }
2428
2531
    {
2453
2556
      }
2454
2557
      if (curr_join->join_tab == join_tab && save_join_tab())
2455
2558
      {
2456
 
        return;
 
2559
        DBUG_VOID_RETURN;
2457
2560
      }
2458
2561
      /*
2459
 
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
 
2562
        Here we sort rows for ORDER BY/GROUP BY clause, if the optimiser
2460
2563
        chose FILESORT to be faster than INDEX SCAN or there is no 
2461
2564
        suitable index present.
2462
2565
        Note, that create_sort_index calls test_if_skip_sort_order and may
2470
2573
                            curr_join->select_limit,
2471
2574
                            (select_options & OPTION_FOUND_ROWS ?
2472
2575
                             HA_POS_ERROR : unit->select_limit_cnt),
2473
 
                            curr_join->group_list ? true : false))
2474
 
        return;
 
2576
                            curr_join->group_list ? TRUE : FALSE))
 
2577
        DBUG_VOID_RETURN;
2475
2578
      sortorder= curr_join->sortorder;
2476
2579
      if (curr_join->const_tables != curr_join->tables &&
2477
2580
          !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
2489
2592
  if (thd->is_error())
2490
2593
  {
2491
2594
    error= thd->is_error();
2492
 
    return;
 
2595
    DBUG_VOID_RETURN;
2493
2596
  }
2494
2597
  curr_join->having= curr_join->tmp_having;
2495
2598
  curr_join->fields= curr_fields_list;
2496
2599
 
2497
2600
  {
2498
 
    thd->set_proc_info("Sending data");
 
2601
    thd_proc_info(thd, "Sending data");
 
2602
    DBUG_PRINT("info", ("%s", thd->proc_info));
2499
2603
    result->send_fields(*curr_fields_list,
2500
2604
                        Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2501
2605
    error= do_select(curr_join, curr_fields_list, NULL);
2504
2608
 
2505
2609
  /* Accumulate the counts from all join iterations of all join parts. */
2506
2610
  thd->examined_row_count+= curr_join->examined_rows;
 
2611
  DBUG_PRINT("counts", ("thd->examined_row_count: %lu",
 
2612
                        (ulong) thd->examined_row_count));
2507
2613
 
2508
2614
  /* 
2509
2615
    With EXPLAIN EXTENDED we have to restore original ref_array
2515
2621
      select_lex->linkage == DERIVED_TABLE_TYPE)      
2516
2622
    set_items_ref_array(items0);
2517
2623
 
2518
 
  return;
 
2624
  DBUG_VOID_RETURN;
2519
2625
}
2520
2626
 
2521
2627
 
2529
2635
int
2530
2636
JOIN::destroy()
2531
2637
{
 
2638
  DBUG_ENTER("JOIN::destroy");
2532
2639
  select_lex->join= 0;
2533
2640
 
2534
2641
  if (tmp_join)
2541
2648
    }
2542
2649
    tmp_join->tmp_join= 0;
2543
2650
    tmp_table_param.copy_field=0;
2544
 
    return(tmp_join->destroy());
 
2651
    DBUG_RETURN(tmp_join->destroy());
2545
2652
  }
2546
2653
  cond_equal= 0;
2547
2654
 
2548
2655
  cleanup(1);
2549
2656
  if (exec_tmp_table1)
2550
 
    exec_tmp_table1->free_tmp_table(thd);
 
2657
    free_tmp_table(thd, exec_tmp_table1);
2551
2658
  if (exec_tmp_table2)
2552
 
    exec_tmp_table2->free_tmp_table(thd);
 
2659
    free_tmp_table(thd, exec_tmp_table2);
2553
2660
  delete select;
2554
2661
  delete_dynamic(&keyuse);
2555
 
  return(error);
 
2662
  DBUG_RETURN(error);
2556
2663
}
2557
2664
 
2558
2665
 
2576
2683
                              for a, b and c in this list.
2577
2684
  @param conds                top level item of an expression representing
2578
2685
                              WHERE clause of the top level select
2579
 
  @param og_num               total number of order_st BY and GROUP BY clauses
 
2686
  @param og_num               total number of ORDER BY and GROUP BY clauses
2580
2687
                              arguments
2581
 
  @param order                linked list of order_st BY agruments
 
2688
  @param order                linked list of ORDER BY agruments
2582
2689
  @param group                linked list of GROUP BY arguments
2583
2690
  @param having               top level item of HAVING expression
2584
2691
  @param proc_param           list of PROCEDUREs
2596
2703
                              has 2 unions.
2597
2704
 
2598
2705
  @retval
2599
 
    false  success
 
2706
    FALSE  success
2600
2707
  @retval
2601
 
    true   an error
 
2708
    TRUE   an error
2602
2709
*/
2603
2710
 
2604
2711
bool
2605
2712
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,
 
2713
             TABLE_LIST *tables, uint wild_num, List<Item> &fields,
 
2714
             COND *conds, uint og_num,  ORDER *order, ORDER *group,
 
2715
             Item *having, ORDER *proc_param, ulonglong select_options,
2609
2716
             select_result *result, SELECT_LEX_UNIT *unit,
2610
2717
             SELECT_LEX *select_lex)
2611
2718
{
2612
2719
  bool err;
2613
2720
  bool free_join= 1;
 
2721
  DBUG_ENTER("mysql_select");
2614
2722
 
2615
 
  select_lex->context.resolve_in_select_list= true;
 
2723
  select_lex->context.resolve_in_select_list= TRUE;
2616
2724
  JOIN *join;
2617
2725
  if (select_lex->join != 0)
2618
2726
  {
2629
2737
        //here is EXPLAIN of subselect or derived table
2630
2738
        if (join->change_result(result))
2631
2739
        {
2632
 
          return(true);
 
2740
          DBUG_RETURN(TRUE);
2633
2741
        }
2634
2742
      }
2635
2743
      else
2648
2756
  else
2649
2757
  {
2650
2758
    if (!(join= new JOIN(thd, fields, select_options, result)))
2651
 
        return(true);
2652
 
    thd->set_proc_info("init");
 
2759
        DBUG_RETURN(TRUE);
 
2760
    thd_proc_info(thd, "init");
2653
2761
    thd->used_tables=0;                         // Updated by setup_fields
2654
2762
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2655
2763
                           conds, og_num, order, group, having, proc_param,
2659
2767
    }
2660
2768
  }
2661
2769
 
2662
 
  /* dump_TableList_graph(select_lex, select_lex->leaf_tables); */
 
2770
  /* dump_TABLE_LIST_graph(select_lex, select_lex->leaf_tables); */
2663
2771
  if (join->flatten_subqueries())
2664
2772
  {
2665
2773
    err= 1;
2666
2774
    goto err;
2667
2775
  }
2668
 
  /* dump_TableList_struct(select_lex, select_lex->leaf_tables); */
 
2776
  /* dump_TABLE_LIST_struct(select_lex, select_lex->leaf_tables); */
2669
2777
 
2670
2778
  if ((err= join->optimize()))
2671
2779
  {
2692
2800
err:
2693
2801
  if (free_join)
2694
2802
  {
2695
 
    thd->set_proc_info("end");
 
2803
    thd_proc_info(thd, "end");
2696
2804
    err|= select_lex->cleanup();
2697
 
    return(err || thd->is_error());
 
2805
    DBUG_RETURN(err || thd->is_error());
2698
2806
  }
2699
 
  return(join->error);
 
2807
  DBUG_RETURN(join->error);
2700
2808
}
2701
2809
 
2702
2810
 
2714
2822
}
2715
2823
 
2716
2824
 
2717
 
static TableList *alloc_join_nest(THD *thd)
 
2825
static TABLE_LIST *alloc_join_nest(THD *thd)
2718
2826
{
2719
 
  TableList *tbl;
2720
 
  if (!(tbl= (TableList*) thd->calloc(ALIGN_SIZE(sizeof(TableList))+
2721
 
                                       sizeof(nested_join_st))))
 
2827
  TABLE_LIST *tbl;
 
2828
  if (!(tbl= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+
 
2829
                                       sizeof(NESTED_JOIN))))
2722
2830
    return NULL;
2723
 
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl + 
2724
 
                                    ALIGN_SIZE(sizeof(TableList)));
 
2831
  tbl->nested_join= (NESTED_JOIN*) ((uchar*)tbl + 
 
2832
                                    ALIGN_SIZE(sizeof(TABLE_LIST)));
2725
2833
  return tbl;
2726
2834
}
2727
2835
 
2728
2836
 
2729
 
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TableList> *tlist)
 
2837
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TABLE_LIST> *tlist)
2730
2838
{
2731
 
  List_iterator<TableList> it(*tlist);
2732
 
  TableList *table;
 
2839
  List_iterator<TABLE_LIST> it(*tlist);
 
2840
  TABLE_LIST *table;
2733
2841
  while ((table= it++))
2734
2842
  {
2735
2843
    if (table->on_expr)
2741
2849
 
2742
2850
 
2743
2851
/*
2744
 
  Convert a subquery predicate into a TableList semi-join nest
 
2852
  Convert a subquery predicate into a TABLE_LIST semi-join nest
2745
2853
 
2746
2854
  SYNOPSIS
2747
2855
    convert_subq_to_sj()
2750
2858
       subq_pred    Subquery predicate to be converted
2751
2859
  
2752
2860
  DESCRIPTION
2753
 
    Convert a subquery predicate into a TableList semi-join nest. All the 
 
2861
    Convert a subquery predicate into a TABLE_LIST semi-join nest. All the 
2754
2862
    prerequisites are already checked, so the conversion is always successfull.
2755
2863
 
2756
2864
    Prepared Statements: the transformation is permanent:
2757
 
     - Changes in TableList structures are naturally permanent
 
2865
     - Changes in TABLE_LIST structures are naturally permanent
2758
2866
     - Item tree changes are performed on statement MEM_ROOT:
2759
2867
        = we activate statement MEM_ROOT 
2760
2868
        = this function is called before the first fix_prepare_information
2764
2872
    constant for the lifetime of the Prepared Statement.
2765
2873
 
2766
2874
  RETURN
2767
 
    false  OK
2768
 
    true   Out of memory error
 
2875
    FALSE  OK
 
2876
    TRUE   Out of memory error
2769
2877
*/
2770
2878
 
2771
2879
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
2772
2880
{
2773
2881
  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;
 
2882
  TABLE_LIST *emb_tbl_nest= NULL;
 
2883
  List<TABLE_LIST> *emb_join_list= &parent_lex->top_join_list;
2776
2884
  THD *thd= parent_join->thd;
 
2885
  DBUG_ENTER("convert_subq_to_sj");
2777
2886
 
2778
2887
  /*
2779
2888
    1. Find out where to put the predicate into.
2809
2918
    }
2810
2919
    else if (!subq_pred->expr_join_nest->nested_join)
2811
2920
    {
2812
 
      TableList *outer_tbl= subq_pred->expr_join_nest;      
2813
 
      TableList *wrap_nest;
 
2921
      TABLE_LIST *outer_tbl= subq_pred->expr_join_nest;      
 
2922
      TABLE_LIST *wrap_nest;
2814
2923
      /*
2815
2924
        We're dealing with
2816
2925
 
2825
2934
        Q:  other subqueries may be pointing to this element. What to do?
2826
2935
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
2827
2936
            But we'll need to fix other pointers.
2828
 
        A2: Another way: have TableList::next_ptr so the following
 
2937
        A2: Another way: have TABLE_LIST::next_ptr so the following
2829
2938
            subqueries know the table has been nested.
2830
 
        A3: changes in the TableList::outer_join will make everything work
 
2939
        A3: changes in the TABLE_LIST::outer_join will make everything work
2831
2940
            automatically.
2832
2941
      */
2833
2942
      if (!(wrap_nest= alloc_join_nest(parent_join->thd)))
2834
2943
      {
2835
 
        return(true);
 
2944
        DBUG_RETURN(TRUE);
2836
2945
      }
2837
2946
      wrap_nest->embedding= outer_tbl->embedding;
2838
2947
      wrap_nest->join_list= outer_tbl->join_list;
2854
2963
      wrap_nest->on_expr= outer_tbl->on_expr;
2855
2964
      outer_tbl->on_expr= NULL;
2856
2965
 
2857
 
      List_iterator<TableList> li(*wrap_nest->join_list);
2858
 
      TableList *tbl;
 
2966
      List_iterator<TABLE_LIST> li(*wrap_nest->join_list);
 
2967
      TABLE_LIST *tbl;
2859
2968
      while ((tbl= li++))
2860
2969
      {
2861
2970
        if (tbl == outer_tbl)
2873
2982
    }
2874
2983
  }
2875
2984
 
2876
 
  TableList *sj_nest;
2877
 
  nested_join_st *nested_join;
 
2985
  TABLE_LIST *sj_nest;
 
2986
  NESTED_JOIN *nested_join;
2878
2987
  if (!(sj_nest= alloc_join_nest(parent_join->thd)))
2879
2988
  {
2880
 
    return(true);
 
2989
    DBUG_RETURN(TRUE);
2881
2990
  }
2882
2991
  nested_join= sj_nest->nested_join;
2883
2992
 
2899
3008
  */
2900
3009
  st_select_lex *subq_lex= subq_pred->unit->first_select();
2901
3010
  nested_join->join_list.empty();
2902
 
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
2903
 
  TableList *tl, *last_leaf;
 
3011
  List_iterator_fast<TABLE_LIST> li(subq_lex->top_join_list);
 
3012
  TABLE_LIST *tl, *last_leaf;
2904
3013
  while ((tl= li++))
2905
3014
  {
2906
3015
    tl->embedding= sj_nest;
2936
3045
  /*TODO: also reset the 'with_subselect' there. */
2937
3046
 
2938
3047
  /* n. Adjust the parent_join->tables counter */
2939
 
  uint32_t table_no= parent_join->tables;
 
3048
  uint table_no= parent_join->tables;
2940
3049
  /* n. Walk through child's tables and adjust table->map */
2941
3050
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
2942
3051
  {
2944
3053
    tl->table->map= ((table_map)1) << table_no;
2945
3054
    SELECT_LEX *old_sl= tl->select_lex;
2946
3055
    tl->select_lex= parent_join->select_lex; 
2947
 
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
 
3056
    for(TABLE_LIST *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
2948
3057
      emb->select_lex= parent_join->select_lex;
2949
3058
  }
2950
3059
  parent_join->tables += subq_lex->join->tables;
2957
3066
  thd->lex->current_select=subq_lex;
2958
3067
  if (!subq_pred->left_expr->fixed &&
2959
3068
       subq_pred->left_expr->fix_fields(thd, &subq_pred->left_expr))
2960
 
    return(true);
 
3069
    DBUG_RETURN(TRUE);
2961
3070
  thd->lex->current_select=save_lex;
2962
3071
 
2963
3072
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
2994
3103
  }
2995
3104
  else
2996
3105
  {
2997
 
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
 
3106
    for (uint i= 0; i < subq_pred->left_expr->cols(); i++)
2998
3107
    {
2999
3108
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
3000
3109
                                                element_index(i));
3019
3128
  /* Unlink the child select_lex so it doesn't show up in EXPLAIN: */
3020
3129
  subq_lex->master_unit()->exclude_level();
3021
3130
 
 
3131
  DBUG_EXECUTE("where",
 
3132
               print_where(sj_nest->sj_on_expr,"SJ-EXPR", QT_ORDINARY););
 
3133
 
3022
3134
  /* Inject sj_on_expr into the parent's WHERE or ON */
3023
3135
  if (emb_tbl_nest)
3024
3136
  {
3034
3146
    parent_join->select_lex->where= parent_join->conds;
3035
3147
  }
3036
3148
 
3037
 
  return(false);
 
3149
  DBUG_RETURN(FALSE);
3038
3150
}
3039
3151
 
3040
3152
 
3048
3160
    Convert candidate subquery predicates to semi-joins.
3049
3161
 
3050
3162
  RETURN 
3051
 
    false  OK
3052
 
    true   Error
 
3163
    FALSE  OK
 
3164
    TRUE   Error
3053
3165
*/
3054
3166
 
3055
3167
bool JOIN::flatten_subqueries()
3056
3168
{
3057
3169
  Item_in_subselect **in_subq;
3058
3170
  Item_in_subselect **in_subq_end;
 
3171
  DBUG_ENTER("JOIN::flatten_subqueries");
3059
3172
 
3060
3173
  if (sj_subselects.elements() == 0)
3061
 
    return(false);
 
3174
    DBUG_RETURN(FALSE);
3062
3175
 
3063
3176
  /* 1. Fix children subqueries */
3064
3177
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back(); 
3067
3180
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
3068
3181
    child_join->outer_tables = child_join->tables;
3069
3182
    if (child_join->flatten_subqueries())
3070
 
      return(true);
 
3183
      DBUG_RETURN(TRUE);
3071
3184
    (*in_subq)->sj_convert_priority= 
3072
3185
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
3073
3186
  }
3074
3187
 
3075
 
  //dump_TableList_struct(select_lex, select_lex->leaf_tables);
 
3188
  //dump_TABLE_LIST_struct(select_lex, select_lex->leaf_tables);
3076
3189
  /* 
3077
3190
    2. Pick which subqueries to convert:
3078
3191
      sort the subquery array
3087
3200
       tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3088
3201
       in_subq++)
3089
3202
  {
3090
 
    if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
3091
 
      return(true);
 
3203
    if (replace_where_subcondition(this, *in_subq, new Item_int(1), FALSE))
 
3204
      DBUG_RETURN(TRUE);
3092
3205
  }
3093
3206
 
3094
3207
  for (in_subq= sj_subselects.front(); 
3097
3210
       in_subq++)
3098
3211
  {
3099
3212
    if (convert_subq_to_sj(this, *in_subq))
3100
 
      return(true);
 
3213
      DBUG_RETURN(TRUE);
3101
3214
  }
3102
3215
 
3103
3216
  /* 3. Finalize those we didn't convert */
3109
3222
    (*in_subq)->fixed= 0;
3110
3223
    res= (*in_subq)->select_transformer(child_join);
3111
3224
    if (res == Item_subselect::RES_ERROR)
3112
 
      return(true);
 
3225
      DBUG_RETURN(TRUE);
3113
3226
 
3114
3227
    (*in_subq)->changed= 1;
3115
3228
    (*in_subq)->fixed= 1;
3117
3230
    Item *substitute= (*in_subq)->substitution;
3118
3231
    bool do_fix_fields= !(*in_subq)->substitution->fixed;
3119
3232
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
3120
 
      return(true);
 
3233
      DBUG_RETURN(TRUE);
3121
3234
 
3122
3235
    //if ((*in_subq)->fix_fields(thd, (*in_subq)->ref_ptr))
3123
 
    //  return(true);
 
3236
    //  DBUG_RETURN(TRUE);
3124
3237
  }
3125
3238
  sj_subselects.clear();
3126
 
  return(false);
 
3239
  DBUG_RETURN(FALSE);
3127
3240
}
3128
3241
 
3129
3242
 
3146
3259
  IN predicate.
3147
3260
 
3148
3261
  @return Operation status
3149
 
  @retval false     success.
3150
 
  @retval true      error occurred.
 
3262
  @retval FALSE     success.
 
3263
  @retval TRUE      error occurred.
3151
3264
*/
3152
3265
 
3153
3266
bool JOIN::setup_subquery_materialization()
3164
3277
        Item_in_subselect *in_subs= (Item_in_subselect*) subquery_predicate;
3165
3278
        if (in_subs->exec_method == Item_in_subselect::MATERIALIZATION &&
3166
3279
            in_subs->setup_engine())
3167
 
          return true;
 
3280
          return TRUE;
3168
3281
      }
3169
3282
    }
3170
3283
  }
3171
 
  return false;
 
3284
  return FALSE;
3172
3285
}
3173
3286
 
3174
3287
 
3189
3302
    search
3190
3303
 
3191
3304
  RETURN
3192
 
    true  - There exists an eq_ref(outer-tables) candidate
3193
 
    false - Otherwise
 
3305
    TRUE  - There exists an eq_ref(outer-tables) candidate
 
3306
    FALSE - Otherwise
3194
3307
*/
3195
3308
 
3196
 
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
 
3309
bool find_eq_ref_candidate(TABLE *table, table_map sj_inner_tables)
3197
3310
{
3198
3311
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
3199
 
  uint32_t key;
 
3312
  uint key;
3200
3313
 
3201
3314
  if (keyuse)
3202
3315
  {
3205
3318
      key= keyuse->key;
3206
3319
      KEY *keyinfo= table->key_info + key;
3207
3320
      key_part_map bound_parts= 0;
3208
 
      if ((keyinfo->flags & HA_NOSAME) == HA_NOSAME)
 
3321
      if ((keyinfo->flags & (HA_NOSAME | HA_END_SPACE_KEY)) == HA_NOSAME)
3209
3322
      {
3210
3323
        do  /* For all equalities on all key parts */
3211
3324
        {
3219
3332
        } while (keyuse->key == key && keyuse->table == table);
3220
3333
 
3221
3334
        if (bound_parts == PREV_BITS(uint, keyinfo->key_parts))
3222
 
          return true;
 
3335
          return TRUE;
3223
3336
        if (keyuse->table != table)
3224
 
          return false;
 
3337
          return FALSE;
3225
3338
      }
3226
3339
      else
3227
3340
      {
3229
3342
        {
3230
3343
          keyuse++;
3231
3344
          if (keyuse->table != table)
3232
 
            return false;
 
3345
            return FALSE;
3233
3346
        }
3234
3347
        while (keyuse->key == key);
3235
3348
      }
3236
3349
    }
3237
3350
  }
3238
 
  return false;
 
3351
  return FALSE;
3239
3352
}
3240
3353
 
3241
3354
 
3263
3376
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
3264
3377
       tables)
3265
3378
     * Tables that were not pulled out have JOIN_TAB::emb_sj_nest.
3266
 
     * Semi-join nests TableList::sj_inner_tables
 
3379
     * Semi-join nests TABLE_LIST::sj_inner_tables
3267
3380
 
3268
3381
    This operation is (and should be) performed at each PS execution since
3269
3382
    tables may become/cease to be constant across PS reexecutions.
3275
3388
 
3276
3389
int pull_out_semijoin_tables(JOIN *join)
3277
3390
{
3278
 
  TableList *sj_nest;
3279
 
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
 
3391
  TABLE_LIST *sj_nest;
 
3392
  DBUG_ENTER("pull_out_semijoin_tables");
 
3393
  List_iterator<TABLE_LIST> sj_list_it(join->select_lex->sj_nests);
3280
3394
   
3281
3395
  /* Try pulling out of the each of the semi-joins */
3282
3396
  while ((sj_nest= sj_list_it++))
3284
3398
    /* Action #1: Mark the constant tables to be pulled out */
3285
3399
    table_map pulled_tables= 0;
3286
3400
     
3287
 
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
3288
 
    TableList *tbl;
 
3401
    List_iterator<TABLE_LIST> child_li(sj_nest->nested_join->join_list);
 
3402
    TABLE_LIST *tbl;
3289
3403
    while ((tbl= child_li++))
3290
3404
    {
3291
3405
      if (tbl->table)
3294
3408
        if (tbl->table->map & join->const_table_map)
3295
3409
        {
3296
3410
          pulled_tables |= tbl->table->map;
 
3411
          DBUG_PRINT("info", ("Table %s pulled out (reason: constant)",
 
3412
                              tbl->table->alias));
3297
3413
        }
3298
3414
      }
3299
3415
    }
3306
3422
    bool pulled_a_table;
3307
3423
    do 
3308
3424
    {
3309
 
      pulled_a_table= false;
 
3425
      pulled_a_table= FALSE;
3310
3426
      child_li.rewind();
3311
3427
      while ((tbl= child_li++))
3312
3428
      {
3316
3432
                                    sj_nest->nested_join->used_tables & 
3317
3433
                                    ~pulled_tables))
3318
3434
          {
3319
 
            pulled_a_table= true;
 
3435
            pulled_a_table= TRUE;
3320
3436
            pulled_tables |= tbl->table->map;
 
3437
            DBUG_PRINT("info", ("Table %s pulled out (reason: func dep)",
 
3438
                                tbl->table->alias));
3321
3439
          }
3322
3440
        }
3323
3441
      }
3327
3445
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
3328
3446
    {
3329
3447
      (sj_nest)->sj_inner_tables= 0;
 
3448
      DBUG_PRINT("info", ("All semi-join nest tables were pulled out"));
3330
3449
      while ((tbl= child_li++))
3331
3450
      {
3332
3451
        if (tbl->table)
3351
3470
      }
3352
3471
    }
3353
3472
  }
3354
 
  return(0);
 
3473
  DBUG_RETURN(0);
3355
3474
}
3356
3475
 
3357
3476
/*****************************************************************************
3361
3480
 
3362
3481
 
3363
3482
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
3364
 
                                      Table *table,
 
3483
                                      TABLE *table,
3365
3484
                                      const key_map *keys,ha_rows limit)
3366
3485
{
3367
3486
  int error;
 
3487
  DBUG_ENTER("get_quick_record_count");
3368
3488
  if (check_stack_overrun(thd, STACK_MIN_SIZE, NULL))
3369
 
    return(0);                           // Fatal error flag is set
 
3489
    DBUG_RETURN(0);                           // Fatal error flag is set
3370
3490
  if (select)
3371
3491
  {
3372
3492
    select->head=table;
3373
3493
    table->reginfo.impossible_range=0;
3374
3494
    if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
3375
 
                                          limit, 0, false)) == 1)
3376
 
      return(select->quick->records);
 
3495
                                          limit, 0, FALSE)) == 1)
 
3496
      DBUG_RETURN(select->quick->records);
3377
3497
    if (error == -1)
3378
3498
    {
3379
3499
      table->reginfo.impossible_range=1;
3380
 
      return(0);
 
3500
      DBUG_RETURN(0);
3381
3501
    }
 
3502
    DBUG_PRINT("warning",("Couldn't use record count on const keypart"));
3382
3503
  }
3383
 
  return(HA_POS_ERROR);                 /* This shouldn't happend */
 
3504
  DBUG_RETURN(HA_POS_ERROR);                    /* This shouldn't happend */
3384
3505
}
3385
3506
 
3386
3507
/*
3394
3515
{
3395
3516
  Field *field;              /* field against which to check sargability */
3396
3517
  Item **arg_value;          /* values of potential keys for lookups     */
3397
 
  uint32_t num_values;           /* number of values in the above array      */
 
3518
  uint num_values;           /* number of values in the above array      */
3398
3519
} SARGABLE_PARAM;  
3399
3520
 
3400
3521
/**
3407
3528
*/
3408
3529
 
3409
3530
static bool
3410
 
make_join_statistics(JOIN *join, TableList *tables, COND *conds,
 
3531
make_join_statistics(JOIN *join, TABLE_LIST *tables, COND *conds,
3411
3532
                     DYNAMIC_ARRAY *keyuse_array)
3412
3533
{
3413
3534
  int error;
3414
 
  Table *table;
3415
 
  uint32_t i,table_count,const_count,key;
 
3535
  TABLE *table;
 
3536
  uint i,table_count,const_count,key;
3416
3537
  table_map found_const_table_map, all_table_map, found_ref, refs;
3417
3538
  key_map const_ref, eq_part;
3418
 
  Table **table_vector;
 
3539
  TABLE **table_vector;
3419
3540
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
3420
3541
  KEYUSE *keyuse,*start_keyuse;
3421
3542
  table_map outer_join=0;
3422
3543
  SARGABLE_PARAM *sargables= 0;
3423
3544
  JOIN_TAB *stat_vector[MAX_TABLES+1];
 
3545
  DBUG_ENTER("make_join_statistics");
3424
3546
 
3425
3547
  table_count=join->tables;
3426
3548
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
3427
3549
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
3428
 
  table_vector=(Table**) join->thd->alloc(sizeof(Table*)*(table_count*2));
 
3550
  table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2));
3429
3551
  if (!stat || !stat_ref || !table_vector)
3430
 
    return(1);                          // Eom /* purecov: inspected */
 
3552
    DBUG_RETURN(1);                             // Eom /* purecov: inspected */
3431
3553
 
3432
3554
  join->best_ref=stat_vector;
3433
3555
 
3439
3561
       tables;
3440
3562
       s++, tables= tables->next_leaf, i++)
3441
3563
  {
3442
 
    TableList *embedding= tables->embedding;
 
3564
    TABLE_LIST *embedding= tables->embedding;
3443
3565
    stat_vector[i]=s;
3444
3566
    s->keys.init();
3445
3567
    s->const_keys.init();
3451
3573
    if(error)
3452
3574
    {
3453
3575
        table->file->print_error(error, MYF(0));
3454
 
        return(1);
 
3576
        DBUG_RETURN(1);
3455
3577
    }
3456
3578
    table->quick_keys.clear_all();
3457
3579
    table->reginfo.join_tab=s;
3458
3580
    table->reginfo.not_exists_optimize=0;
3459
 
    memset(table->const_key_parts, 0,
3460
 
           sizeof(key_part_map)*table->s->keys);
 
3581
    bzero((char*) table->const_key_parts, sizeof(key_part_map)*table->s->keys);
3461
3582
    all_table_map|= table->map;
3462
3583
    s->join=join;
3463
3584
    s->info=0;                                  // For describe
3490
3611
      s->embedding_map= 0;
3491
3612
      do
3492
3613
      {
3493
 
        nested_join_st *nested_join= embedding->nested_join;
 
3614
        NESTED_JOIN *nested_join= embedding->nested_join;
3494
3615
        s->embedding_map|=nested_join->nj_map;
3495
3616
        s->dependent|= embedding->dep_tables;
3496
3617
        embedding= embedding->embedding;
3499
3620
      while (embedding);
3500
3621
      continue;
3501
3622
    }
3502
 
    if ((table->file->stats.records <= 1) &&
 
3623
    if ((table->s->system || table->file->stats.records <= 1) &&
3503
3624
        !s->dependent &&
3504
 
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
 
3625
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) &&
 
3626
        !table->fulltext_searched && !join->no_const_tables)
3505
3627
    {
3506
3628
      set_position(join,const_count++,s,(KEYUSE*) 0);
3507
3629
    }
3521
3643
    */
3522
3644
    for (i= 0, s= stat ; i < table_count ; i++, s++)
3523
3645
    {
3524
 
      for (uint32_t j= 0 ; j < table_count ; j++)
 
3646
      for (uint j= 0 ; j < table_count ; j++)
3525
3647
      {
3526
3648
        table= stat[j].table;
3527
3649
        if (s->dependent & table->map)
3537
3659
      {
3538
3660
        join->tables=0;                 // Don't use join->table
3539
3661
        my_message(ER_WRONG_OUTER_JOIN, ER(ER_WRONG_OUTER_JOIN), MYF(0));
3540
 
        return(1);
 
3662
        DBUG_RETURN(1);
3541
3663
      }
3542
3664
      s->key_dependent= s->dependent;
3543
3665
    }
3547
3669
    if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables,
3548
3670
                            conds, join->cond_equal,
3549
3671
                            ~outer_join, join->select_lex, &sargables))
3550
 
      return(1);
 
3672
      DBUG_RETURN(1);
3551
3673
 
3552
3674
  /* Read tables with 0 or 1 rows (system tables) */
3553
3675
  join->const_table_map= 0;
3563
3685
    if ((tmp=join_read_const_table(s, p_pos)))
3564
3686
    {
3565
3687
      if (tmp > 0)
3566
 
        return(1);                      // Fatal error
 
3688
        DBUG_RETURN(1);                 // Fatal error
3567
3689
    }
3568
3690
    else
3569
3691
      found_const_table_map|= s->table->map;
3635
3757
          if ((tmp= join_read_const_table(s, join->positions+const_count-1)))
3636
3758
          {
3637
3759
            if (tmp > 0)
3638
 
              return(1);                        // Fatal error
 
3760
              DBUG_RETURN(1);                   // Fatal error
3639
3761
          }
3640
3762
          else
3641
3763
            found_const_table_map|= table->map;
3669
3791
          } while (keyuse->table == table && keyuse->key == key);
3670
3792
 
3671
3793
          if (eq_part.is_prefix(table->key_info[key].key_parts) &&
 
3794
              !table->fulltext_searched && 
3672
3795
              !table->pos_in_table_list->embedding)
3673
3796
          {
3674
 
            if ((table->key_info[key].flags & (HA_NOSAME))
 
3797
            if ((table->key_info[key].flags & (HA_NOSAME | HA_END_SPACE_KEY))
3675
3798
                 == HA_NOSAME)
3676
3799
            {
3677
3800
              if (const_ref == eq_part)
3683
3806
                set_position(join,const_count++,s,start_keyuse);
3684
3807
                if (create_ref_for_key(join, s, start_keyuse,
3685
3808
                                       found_const_table_map))
3686
 
                  return(1);
 
3809
                  DBUG_RETURN(1);
3687
3810
                if ((tmp=join_read_const_table(s,
3688
3811
                                               join->positions+const_count-1)))
3689
3812
                {
3690
3813
                  if (tmp > 0)
3691
 
                    return(1);                  // Fatal error
 
3814
                    DBUG_RETURN(1);                     // Fatal error
3692
3815
                }
3693
3816
                else
3694
3817
                  found_const_table_map|= table->map;
3718
3841
      key_map possible_keys= field->key_start;
3719
3842
      possible_keys.intersect(field->table->keys_in_use_for_query);
3720
3843
      bool is_const= 1;
3721
 
      for (uint32_t j=0; j < sargables->num_values; j++)
 
3844
      for (uint j=0; j < sargables->num_values; j++)
3722
3845
        is_const&= sargables->arg_value[j]->const_item();
3723
3846
      if (is_const)
3724
3847
        join_tab[0].const_keys.merge(possible_keys);
3726
3849
  }
3727
3850
 
3728
3851
  if (pull_out_semijoin_tables(join))
3729
 
    return(true);
 
3852
    DBUG_RETURN(TRUE);
3730
3853
 
3731
3854
  /* Calc how many (possible) matched records in each table */
3732
3855
 
3747
3870
      This is can't be to high as otherwise we are likely to use
3748
3871
      table scan.
3749
3872
    */
3750
 
    s->worst_seeks= cmin((double) s->found_records / 10,
 
3873
    s->worst_seeks= min((double) s->found_records / 10,
3751
3874
                        (double) s->read_time*3);
3752
3875
    if (s->worst_seeks < 2.0)                   // Fix for small tables
3753
3876
      s->worst_seeks=2.0;
3768
3891
                          *s->on_expr_ref ? *s->on_expr_ref : conds,
3769
3892
                          1, &error);
3770
3893
      if (!select)
3771
 
        return(1);
 
3894
        DBUG_RETURN(1);
3772
3895
      records= get_quick_record_count(join->thd, select, s->table,
3773
3896
                                      &s->const_keys, join->row_limit);
3774
3897
      s->quick=select->quick;
3814
3937
  {
3815
3938
    optimize_keyuse(join, keyuse_array);
3816
3939
    if (choose_plan(join, all_table_map & ~join->const_table_map))
3817
 
      return(true);
 
3940
      DBUG_RETURN(TRUE);
3818
3941
  }
3819
3942
  else
3820
3943
  {
3821
 
    memcpy(join->best_positions, join->positions,
3822
 
           sizeof(POSITION)*join->const_tables);
 
3944
    memcpy((uchar*) join->best_positions,(uchar*) join->positions,
 
3945
           sizeof(POSITION)*join->const_tables);
3823
3946
    join->best_read=1.0;
3824
3947
  }
3825
3948
  /* Generate an execution plan from the found optimal join order. */
3826
 
  return(join->thd->killed || get_best_combination(join));
 
3949
  DBUG_RETURN(join->thd->killed || get_best_combination(join));
3827
3950
}
3828
3951
 
3829
3952
 
3848
3971
  */
3849
3972
  bool          null_rejecting; 
3850
3973
  bool          *cond_guard; /* See KEYUSE::cond_guard */
3851
 
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
 
3974
  uint          sj_pred_no; /* See KEYUSE::sj_pred_no */
3852
3975
} KEY_FIELD;
3853
3976
 
3854
3977
/**
3877
4000
 
3878
4001
static KEY_FIELD *
3879
4002
merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end,
3880
 
                 uint32_t and_level)
 
4003
                 uint and_level)
3881
4004
{
3882
4005
  if (start == new_fields)
3883
4006
    return start;                               // Impossible or
3895
4018
      {
3896
4019
        /*
3897
4020
          NOTE: below const_item() call really works as "!used_tables()", i.e.
3898
 
          it can return false where it is feasible to make it return true.
 
4021
          it can return FALSE where it is feasible to make it return TRUE.
3899
4022
          
3900
4023
          The cause is as follows: Some of the tables are already known to be
3901
4024
          const tables (the detection code is in make_join_statistics(),
3902
4025
          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
 
4026
          information about this: TABLE::const_table is not set to TRUE, and
3904
4027
          Item::update_used_tables() hasn't been called for each item.
3905
4028
          The result of this is that we're missing some 'ref' accesses.
3906
4029
          TODO: OptimizerTeam: Fix this
4004
4127
*/
4005
4128
 
4006
4129
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,
 
4130
add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond,
 
4131
              Field *field, bool eq_func, Item **value, uint num_values,
4009
4132
              table_map usable_tables, SARGABLE_PARAM **sargables)
4010
4133
{
4011
 
  uint32_t exists_optimize= 0;
 
4134
  uint exists_optimize= 0;
4012
4135
  if (!(field->flags & PART_KEY_FLAG))
4013
4136
  {
4014
4137
    // Don't remove column IS NULL on a LEFT JOIN table
4016
4139
        !field->table->maybe_null || field->null_ptr)
4017
4140
      return;                                   // Not a key. Skip it
4018
4141
    exists_optimize= KEY_OPTIMIZE_EXISTS;
4019
 
    assert(num_values == 1);
 
4142
    DBUG_ASSERT(num_values == 1);
4020
4143
  }
4021
4144
  else
4022
4145
  {
4023
4146
    table_map used_tables=0;
4024
4147
    bool optimizable=0;
4025
 
    for (uint32_t i=0; i<num_values; i++)
 
4148
    for (uint i=0; i<num_values; i++)
4026
4149
    {
4027
4150
      used_tables|=(value[i])->used_tables();
4028
4151
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
4058
4181
      stat[0].key_dependent|=used_tables;
4059
4182
 
4060
4183
      bool is_const=1;
4061
 
      for (uint32_t i=0; i<num_values; i++)
 
4184
      for (uint i=0; i<num_values; i++)
4062
4185
      {
4063
4186
        if (!(is_const&= value[i]->const_item()))
4064
4187
          break;
4101
4224
            ((Item_func_between*) cond)->negated ||
4102
4225
            !value[0]->eq(value[1], field->binary()))
4103
4226
          return;
4104
 
        eq_func= true;
 
4227
        eq_func= TRUE;
4105
4228
      }
4106
4229
 
4107
4230
      if (field->result_type() == STRING_RESULT)
4128
4251
    For the moment eq_func is always true. This slot is reserved for future
4129
4252
    extensions where we want to remembers other things than just eq comparisons
4130
4253
  */
4131
 
  assert(eq_func);
 
4254
  DBUG_ASSERT(eq_func);
4132
4255
  /* Store possible eq field */
4133
4256
  (*key_fields)->field=         field;
4134
4257
  (*key_fields)->eq_func=       eq_func;
4176
4299
*/
4177
4300
 
4178
4301
static void
4179
 
add_key_equal_fields(KEY_FIELD **key_fields, uint32_t and_level,
 
4302
add_key_equal_fields(KEY_FIELD **key_fields, uint and_level,
4180
4303
                     Item_func *cond, Item_field *field_item,
4181
4304
                     bool eq_func, Item **val,
4182
 
                     uint32_t num_values, table_map usable_tables,
 
4305
                     uint num_values, table_map usable_tables,
4183
4306
                     SARGABLE_PARAM **sargables)
4184
4307
{
4185
4308
  Field *field= field_item->field;
4207
4330
}
4208
4331
 
4209
4332
static void
4210
 
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint32_t *and_level,
 
4333
add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level,
4211
4334
               COND *cond, table_map usable_tables,
4212
4335
               SARGABLE_PARAM **sargables)
4213
4336
{
4289
4412
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
4290
4413
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
4291
4414
        values--;
4292
 
      assert(cond_func->functype() != Item_func::IN_FUNC ||
 
4415
      DBUG_ASSERT(cond_func->functype() != Item_func::IN_FUNC ||
4293
4416
                  cond_func->argument_count() != 2);
4294
4417
      add_key_equal_fields(key_fields, *and_level, cond_func,
4295
4418
                           (Item_field*) (cond_func->key_item()->real_item()),
4300
4423
    if (cond_func->functype() == Item_func::BETWEEN)
4301
4424
    {
4302
4425
      values= cond_func->arguments();
4303
 
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
4426
      for (uint i= 1 ; i < cond_func->argument_count() ; i++)
4304
4427
      {
4305
4428
        Item_field *field_item;
4306
4429
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
4371
4494
      while ((item= it++))
4372
4495
      {
4373
4496
        add_key_field(key_fields, *and_level, cond_func, item->field,
4374
 
                      true, &const_item, 1, usable_tables, sargables);
 
4497
                      TRUE, &const_item, 1, usable_tables, sargables);
4375
4498
      }
4376
4499
    }
4377
4500
    else 
4391
4514
          if (!field->eq(item->field))
4392
4515
          {
4393
4516
            add_key_field(key_fields, *and_level, cond_func, field,
4394
 
                          true, (Item **) &item, 1, usable_tables,
 
4517
                          TRUE, (Item **) &item, 1, usable_tables,
4395
4518
                          sargables);
4396
4519
          }
4397
4520
        }
4411
4534
static uint
4412
4535
max_part_bit(key_part_map bits)
4413
4536
{
4414
 
  uint32_t found;
 
4537
  uint found;
4415
4538
  for (found=0; bits & 1 ; found++,bits>>=1) ;
4416
4539
  return found;
4417
4540
}
4420
4543
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
4421
4544
{
4422
4545
  Field *field=key_field->field;
4423
 
  Table *form= field->table;
 
4546
  TABLE *form= field->table;
4424
4547
  KEYUSE keyuse;
4425
4548
 
4426
4549
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
4427
4550
  {
4428
 
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
4551
    for (uint key=0 ; key < form->s->keys ; key++)
4429
4552
    {
4430
4553
      if (!(form->keys_in_use_for_query.is_set(key)))
4431
4554
        continue;
4432
4555
 
4433
 
      uint32_t key_parts= (uint) form->key_info[key].key_parts;
4434
 
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
4556
      uint key_parts= (uint) form->key_info[key].key_parts;
 
4557
      for (uint part=0 ; part <  key_parts ; part++)
4435
4558
      {
4436
4559
        if (field->eq(form->key_info[key].key_part[part].field))
4437
4560
        {
4445
4568
          keyuse.null_rejecting= key_field->null_rejecting;
4446
4569
          keyuse.cond_guard= key_field->cond_guard;
4447
4570
          keyuse.sj_pred_no= key_field->sj_pred_no;
4448
 
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
4571
          VOID(insert_dynamic(keyuse_array,(uchar*) &keyuse));
4449
4572
        }
4450
4573
      }
4451
4574
    }
4507
4630
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
4508
4631
*/
4509
4632
 
4510
 
static void add_key_fields_for_nj(JOIN *join, TableList *nested_join_table,
4511
 
                                  KEY_FIELD **end, uint32_t *and_level,
 
4633
static void add_key_fields_for_nj(JOIN *join, TABLE_LIST *nested_join_table,
 
4634
                                  KEY_FIELD **end, uint *and_level,
4512
4635
                                  SARGABLE_PARAM **sargables)
4513
4636
{
4514
 
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
4515
 
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
4516
 
  bool have_another = false;
 
4637
  List_iterator<TABLE_LIST> li(nested_join_table->nested_join->join_list);
 
4638
  List_iterator<TABLE_LIST> li2(nested_join_table->nested_join->join_list);
 
4639
  bool have_another = FALSE;
4517
4640
  table_map tables= 0;
4518
 
  TableList *table;
4519
 
  assert(nested_join_table->nested_join);
 
4641
  TABLE_LIST *table;
 
4642
  DBUG_ASSERT(nested_join_table->nested_join);
4520
4643
 
4521
 
  while ((table= li++) || (have_another && (li=li2, have_another=false,
 
4644
  while ((table= li++) || (have_another && (li=li2, have_another=FALSE,
4522
4645
                                            (table= li++))))
4523
4646
  {
4524
4647
    if (table->nested_join)
4526
4649
      if (!table->on_expr)
4527
4650
      {
4528
4651
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
4529
 
        have_another= true;
 
4652
        have_another= TRUE;
4530
4653
        li2= li;
4531
 
        li= List_iterator<TableList>(table->nested_join->join_list); 
 
4654
        li= List_iterator<TABLE_LIST>(table->nested_join->join_list); 
4532
4655
      }
4533
4656
      else
4534
4657
        add_key_fields_for_nj(join, table, end, and_level, sargables);
4566
4689
 
4567
4690
static bool
4568
4691
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)),
 
4692
                    uint tables, COND *cond, COND_EQUAL *cond_equal,
4571
4693
                    table_map normal_tables, SELECT_LEX *select_lex,
4572
4694
                    SARGABLE_PARAM **sargables)
4573
4695
{
4574
4696
  uint  and_level,i,found_eq_constant;
4575
4697
  KEY_FIELD *key_fields, *end, *field;
4576
 
  uint32_t sz;
4577
 
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
 
4698
  uint sz;
 
4699
  uint m= max(select_lex->max_equal_elems,1);
4578
4700
  
4579
4701
  /* 
4580
4702
    We use the same piece of memory to store both  KEY_FIELD 
4597
4719
    can be not more than select_lex->max_equal_elems such 
4598
4720
    substitutions.
4599
4721
  */ 
4600
 
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
 
4722
  sz= max(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
4601
4723
      (((thd->lex->current_select->cond_count+1)*2 +
4602
4724
        thd->lex->current_select->between_count)*m+1);
4603
4725
  if (!(key_fields=(KEY_FIELD*) thd->alloc(sz)))
4604
 
    return true; /* purecov: inspected */
 
4726
    return TRUE; /* purecov: inspected */
4605
4727
  and_level= 0;
4606
4728
  field= end= key_fields;
4607
4729
  *sargables= (SARGABLE_PARAM *) key_fields + 
4610
4732
  (*sargables)[0].field= 0; 
4611
4733
 
4612
4734
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
4613
 
    return true;
 
4735
    return TRUE;
4614
4736
  if (cond)
4615
4737
  {
4616
4738
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
4643
4765
 
4644
4766
  /* Process ON conditions for the nested joins */
4645
4767
  {
4646
 
    List_iterator<TableList> li(*join_tab->join->join_list);
4647
 
    TableList *table;
 
4768
    List_iterator<TABLE_LIST> li(*join_tab->join->join_list);
 
4769
    TABLE_LIST *table;
4648
4770
    while ((table= li++))
4649
4771
    {
4650
4772
      if (table->nested_join)
4665
4787
    - keyparts without previous keyparts
4666
4788
      (e.g. if there is a key(a,b,c) but only b < 5 (or a=2 and c < 3) is
4667
4789
      used in the query, we drop the partial key parts from consideration).
 
4790
    Special treatment for ft-keys.
4668
4791
  */
4669
4792
  if (keyuse->elements)
4670
4793
  {
4673
4796
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
4674
4797
          (qsort_cmp) sort_keyuse);
4675
4798
 
4676
 
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
4677
 
    insert_dynamic(keyuse,(unsigned char*) &key_end);
 
4799
    bzero((char*) &key_end,sizeof(key_end));    /* Add for easy testing */
 
4800
    VOID(insert_dynamic(keyuse,(uchar*) &key_end));
4678
4801
 
4679
4802
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
4680
4803
    prev= &key_end;
4707
4830
      save_pos++;
4708
4831
    }
4709
4832
    i=(uint) (save_pos-(KEYUSE*) keyuse->buffer);
4710
 
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
4833
    VOID(set_dynamic(keyuse,(uchar*) &key_end,i));
4711
4834
    keyuse->elements=i;
4712
4835
  }
4713
 
  return false;
 
4836
  DBUG_EXECUTE("opt", print_keyuse_array(keyuse););
 
4837
  return FALSE;
4714
4838
}
4715
4839
 
4716
4840
/**
4737
4861
        (map= (keyuse->used_tables & ~join->const_table_map &
4738
4862
               ~OUTER_REF_TABLE_BIT)))
4739
4863
    {
4740
 
      uint32_t tablenr;
 
4864
      uint tablenr;
4741
4865
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
4742
4866
      if (map == 1)                     // Only one table
4743
4867
      {
4744
 
        Table *tmp_table=join->all_tables[tablenr];
4745
 
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
 
4868
        TABLE *tmp_table=join->all_tables[tablenr];
 
4869
        keyuse->ref_table_rows= max(tmp_table->file->stats.records, 100);
4746
4870
      }
4747
4871
    }
4748
4872
    /*
4778
4902
{
4779
4903
  List<Item_field> indexed_fields;
4780
4904
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
4781
 
  order_st      *cur_group;
 
4905
  ORDER      *cur_group;
4782
4906
  Item_field *cur_item;
4783
4907
  key_map possible_keys(0);
4784
4908
 
4786
4910
  { /* Collect all query fields referenced in the GROUP clause. */
4787
4911
    for (cur_group= join->group_list; cur_group; cur_group= cur_group->next)
4788
4912
      (*cur_group->item)->walk(&Item::collect_item_field_processor, 0,
4789
 
                               (unsigned char*) &indexed_fields);
 
4913
                               (uchar*) &indexed_fields);
4790
4914
  }
4791
4915
  else if (join->select_distinct)
4792
4916
  { /* Collect all query fields referenced in the SELECT clause. */
4795
4919
    Item *item;
4796
4920
    while ((item= select_items_it++))
4797
4921
      item->walk(&Item::collect_item_field_processor, 0,
4798
 
                 (unsigned char*) &indexed_fields);
 
4922
                 (uchar*) &indexed_fields);
4799
4923
  }
4800
4924
  else
4801
4925
    return;
4824
4948
/** Save const tables first as used tables. */
4825
4949
 
4826
4950
static void
4827
 
set_position(JOIN *join,uint32_t idx,JOIN_TAB *table,KEYUSE *key)
 
4951
set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key)
4828
4952
{
4829
4953
  join->positions[idx].table= table;
4830
4954
  join->positions[idx].key=key;
4861
4985
    Bitmap of bound IN-equalities.
4862
4986
*/
4863
4987
 
4864
 
uint64_t get_bound_sj_equalities(TableList *sj_nest, 
 
4988
ulonglong get_bound_sj_equalities(TABLE_LIST *sj_nest, 
4865
4989
                                  table_map remaining_tables)
4866
4990
{
4867
4991
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
4868
4992
  Item *item;
4869
 
  uint32_t i= 0;
4870
 
  uint64_t res= 0;
 
4993
  uint i= 0;
 
4994
  ulonglong res= 0;
4871
4995
  while ((item= li++))
4872
4996
  {
4873
4997
    /*
4878
5002
    */
4879
5003
    if (!(item->used_tables() & remaining_tables))
4880
5004
    {
4881
 
      res |= 1UL < i;
 
5005
      res |= 1ULL < i;
4882
5006
    }
4883
5007
  }
4884
5008
  return res;
4915
5039
                 JOIN_TAB  *s,
4916
5040
                 THD       *thd,
4917
5041
                 table_map remaining_tables,
4918
 
                 uint32_t      idx,
 
5042
                 uint      idx,
4919
5043
                 double    record_count,
4920
 
                 double    read_time __attribute__((unused)))
 
5044
                 double    read_time)
4921
5045
{
4922
5046
  KEYUSE *best_key=         0;
4923
 
  uint32_t best_max_key_part=   0;
4924
 
  bool found_constraint= 0;
 
5047
  uint best_max_key_part=   0;
 
5048
  my_bool found_constraint= 0;
4925
5049
  double best=              DBL_MAX;
4926
5050
  double best_time=         DBL_MAX;
4927
5051
  double records=           DBL_MAX;
4928
5052
  table_map best_ref_depends_map= 0;
4929
5053
  double tmp;
4930
5054
  ha_rows rec;
4931
 
  uint32_t best_is_sj_inside_out=    0;
 
5055
  uint best_is_sj_inside_out=    0;
 
5056
  DBUG_ENTER("best_access_path");
4932
5057
 
4933
5058
  if (s->keyuse)
4934
5059
  {                                            /* Use key if possible */
4935
 
    Table *table= s->table;
 
5060
    TABLE *table= s->table;
4936
5061
    KEYUSE *keyuse,*start_key=0;
4937
5062
    double best_records= DBL_MAX;
4938
 
    uint32_t max_key_part=0;
4939
 
    uint64_t bound_sj_equalities= 0;
4940
 
    bool try_sj_inside_out= false;
 
5063
    uint max_key_part=0;
 
5064
    ulonglong bound_sj_equalities= 0;
 
5065
    bool try_sj_inside_out= FALSE;
4941
5066
    /*
4942
5067
      Discover the bound equalites. We need to do this, if
4943
5068
        1. The next table is an SJ-inner table, and
4957
5082
      /* This table is an InsideOut scan candidate */
4958
5083
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest, 
4959
5084
                                                   remaining_tables);
4960
 
      try_sj_inside_out= true;
 
5085
      try_sj_inside_out= TRUE;
4961
5086
    }
4962
5087
 
4963
5088
    /* Test how we can use keys */
4966
5091
    {
4967
5092
      key_part_map found_part= 0;
4968
5093
      table_map found_ref= 0;
4969
 
      uint32_t key= keyuse->key;
 
5094
      uint key= keyuse->key;
4970
5095
      KEY *keyinfo= table->key_info+key;
4971
5096
      /* Bitmap of keyparts where the ref access is over 'keypart=const': */
4972
5097
      key_part_map const_part= 0;
4975
5100
 
4976
5101
      /* Calculate how many key segments of the current key we can use */
4977
5102
      start_key= keyuse;
4978
 
      uint64_t handled_sj_equalities=0;
 
5103
      ulonglong handled_sj_equalities=0;
4979
5104
      key_part_map sj_insideout_map= 0;
4980
5105
 
4981
5106
      do /* For each keypart */
4982
5107
      {
4983
 
        uint32_t keypart= keyuse->keypart;
 
5108
        uint keypart= keyuse->keypart;
4984
5109
        table_map best_part_found_ref= 0;
4985
5110
        double best_prev_record_reads= DBL_MAX;
4986
5111
        
5019
5144
          if (try_sj_inside_out && keyuse->sj_pred_no != UINT_MAX)
5020
5145
          {
5021
5146
            if (!(remaining_tables & keyuse->used_tables))
5022
 
              bound_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5147
              bound_sj_equalities |= 1ULL << keyuse->sj_pred_no;
5023
5148
            else
5024
5149
            {
5025
 
              handled_sj_equalities |= 1UL << keyuse->sj_pred_no;
 
5150
              handled_sj_equalities |= 1ULL << keyuse->sj_pred_no;
5026
5151
              sj_insideout_map |= ((key_part_map)1) << keyuse->keypart;
5027
5152
            }
5028
5153
          }
5042
5167
      if (rec < MATCHING_ROWS_IN_OTHER_TABLE)
5043
5168
        rec= MATCHING_ROWS_IN_OTHER_TABLE;      // Fix for small tables
5044
5169
 
5045
 
      bool sj_inside_out_scan= false;
 
5170
      bool sj_inside_out_scan= FALSE;
5046
5171
      {
5047
5172
        found_constraint= 1;
5048
5173
        /*
5054
5179
        if (try_sj_inside_out && 
5055
5180
            table->covering_keys.is_set(key) &&
5056
5181
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
5057
 
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
 
5182
            PREV_BITS(ulonglong, s->emb_sj_nest->sj_in_exprs)) // (1)
5058
5183
        {
5059
 
          uint32_t n_fixed_parts= max_part_bit(found_part);
 
5184
          uint n_fixed_parts= max_part_bit(found_part);
5060
5185
          if (n_fixed_parts != keyinfo->key_parts &&
5061
5186
              (PREV_BITS(uint, n_fixed_parts) | sj_insideout_map) ==
5062
5187
               PREV_BITS(uint, keyinfo->key_parts))
5065
5190
              Not all parts are fixed. Produce bitmap of remaining bits and
5066
5191
              check if all of them are covered.
5067
5192
            */
5068
 
            sj_inside_out_scan= true;
 
5193
            sj_inside_out_scan= TRUE;
 
5194
            DBUG_PRINT("info", ("Using sj InsideOut scan"));
5069
5195
            if (!n_fixed_parts)
5070
5196
            {
5071
5197
              /*
5097
5223
        if (found_part == PREV_BITS(uint,keyinfo->key_parts) &&
5098
5224
            !ref_or_null_part)
5099
5225
        {                                         /* use eq key */
5100
 
          max_key_part= UINT32_MAX;
 
5226
          max_key_part= (uint) ~0;
5101
5227
          if ((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) == HA_NOSAME)
5102
5228
          {
5103
5229
            tmp = prev_record_reads(join, idx, found_ref);
5171
5297
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5172
5298
            }
5173
5299
            else
5174
 
              tmp= record_count*cmin(tmp,s->worst_seeks);
 
5300
              tmp= record_count*min(tmp,s->worst_seeks);
5175
5301
          }
5176
5302
        }
5177
5303
        else
5200
5326
              create quick select over another index), so we can't compare
5201
5327
              them to (**). We'll make indirect judgements instead.
5202
5328
              The sufficient conditions for re-use are:
5203
 
              (C1) All e_i in (**) are constants, i.e. found_ref==false. (if
 
5329
              (C1) All e_i in (**) are constants, i.e. found_ref==FALSE. (if
5204
5330
                   this is not satisfied we have no way to know which ranges
5205
5331
                   will be actually scanned by 'ref' until we execute the 
5206
5332
                   join)
5227
5353
            */
5228
5354
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
5229
5355
                table->quick_key_parts[key] == max_key_part &&          //(C2)
5230
 
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
 
5356
                table->quick_n_ranges[key] == 1+test(ref_or_null_part)) //(C3)
5231
5357
            {
5232
5358
              tmp= records= (double) table->quick_rows[key];
5233
5359
            }
5320
5446
              if (table->quick_keys.is_set(key) &&
5321
5447
                  table->quick_key_parts[key] <= max_key_part &&
5322
5448
                  const_part & (1 << table->quick_key_parts[key]) &&
5323
 
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
5324
 
                                                     const_part) ? 1 : 0) &&
 
5449
                  table->quick_n_ranges[key] == 1 + test(ref_or_null_part &
 
5450
                                                         const_part) &&
5325
5451
                  records > (double) table->quick_rows[key])
5326
5452
              {
5327
5453
                tmp= records= (double) table->quick_rows[key];
5336
5462
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5337
5463
            }
5338
5464
            else
5339
 
              tmp= record_count * cmin(tmp,s->worst_seeks);
 
5465
              tmp= record_count * min(tmp,s->worst_seeks);
5340
5466
          }
5341
5467
          else
5342
5468
            tmp= best_time;                    // Do nothing
5474
5600
    /*
5475
5601
      We estimate the cost of evaluating WHERE clause for found records
5476
5602
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
5477
 
      tmp give us total cost of using Table SCAN
 
5603
      tmp give us total cost of using TABLE SCAN
5478
5604
    */
5479
5605
    if (best == DBL_MAX ||
5480
5606
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
5489
5615
      best_key= 0;
5490
5616
      /* range/index_merge/ALL/index access method are "independent", so: */
5491
5617
      best_ref_depends_map= 0;
5492
 
      best_is_sj_inside_out= false;
 
5618
      best_is_sj_inside_out= FALSE;
5493
5619
    }
5494
5620
  }
5495
5621
 
5505
5631
      idx == join->const_tables &&
5506
5632
      s->table == join->sort_by_table &&
5507
5633
      join->unit->select_limit_cnt >= records)
5508
 
    join->sort_by_table= (Table*) 1;  // Must use temporary table
 
5634
    join->sort_by_table= (TABLE*) 1;  // Must use temporary table
5509
5635
 
5510
 
  return;
 
5636
  DBUG_VOID_RETURN;
5511
5637
}
5512
5638
 
5513
5639
 
5529
5655
    the greedy version. Will be removed when greedy_search is approved.
5530
5656
 
5531
5657
  @retval
5532
 
    false       ok
 
5658
    FALSE       ok
5533
5659
  @retval
5534
 
    true        Fatal error
 
5660
    TRUE        Fatal error
5535
5661
*/
5536
5662
 
5537
5663
static bool
5538
5664
choose_plan(JOIN *join, table_map join_tables)
5539
5665
{
5540
 
  uint32_t search_depth= join->thd->variables.optimizer_search_depth;
5541
 
  uint32_t prune_level=  join->thd->variables.optimizer_prune_level;
 
5666
  uint search_depth= join->thd->variables.optimizer_search_depth;
 
5667
  uint prune_level=  join->thd->variables.optimizer_prune_level;
5542
5668
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
 
5669
  DBUG_ENTER("choose_plan");
5543
5670
 
5544
5671
  join->cur_embedding_map= 0;
5545
5672
  reset_nj_counters(join->join_list);
5568
5695
      */
5569
5696
      join->best_read= DBL_MAX;
5570
5697
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
5571
 
        return(true);
 
5698
        DBUG_RETURN(TRUE);
5572
5699
    } 
5573
5700
    else
5574
5701
    {
5576
5703
        /* Automatically determine a reasonable value for 'search_depth' */
5577
5704
        search_depth= determine_search_depth(join);
5578
5705
      if (greedy_search(join, join_tables, search_depth, prune_level))
5579
 
        return(true);
 
5706
        DBUG_RETURN(TRUE);
5580
5707
    }
5581
5708
  }
5582
5709
 
5588
5715
  */
5589
5716
  if (join->thd->lex->is_single_level_stmt())
5590
5717
    join->thd->status_var.last_query_cost= join->best_read;
5591
 
  return(false);
 
5718
  DBUG_RETURN(FALSE);
5592
5719
}
5593
5720
 
5594
5721
 
5672
5799
 
5673
5800
  @todo
5674
5801
    this value should be determined dynamically, based on statistics:
5675
 
    uint32_t max_tables_for_exhaustive_opt= 7;
 
5802
    uint max_tables_for_exhaustive_opt= 7;
5676
5803
 
5677
5804
  @todo
5678
5805
    this value could be determined by some mapping of the form:
5687
5814
static uint
5688
5815
determine_search_depth(JOIN *join)
5689
5816
{
5690
 
  uint32_t table_count=  join->tables - join->const_tables;
5691
 
  uint32_t search_depth;
 
5817
  uint table_count=  join->tables - join->const_tables;
 
5818
  uint search_depth;
5692
5819
  /* TODO: this value should be determined dynamically, based on statistics: */
5693
 
  uint32_t max_tables_for_exhaustive_opt= 7;
 
5820
  uint max_tables_for_exhaustive_opt= 7;
5694
5821
 
5695
5822
  if (table_count <= max_tables_for_exhaustive_opt)
5696
5823
    search_depth= table_count+1; // use exhaustive for small number of tables
5732
5859
optimize_straight_join(JOIN *join, table_map join_tables)
5733
5860
{
5734
5861
  JOIN_TAB *s;
5735
 
  uint32_t idx= join->const_tables;
 
5862
  uint idx= join->const_tables;
5736
5863
  double    record_count= 1.0;
5737
5864
  double    read_time=    0.0;
5738
5865
 
5753
5880
  if (join->sort_by_table &&
5754
5881
      join->sort_by_table != join->positions[join->const_tables].table->table)
5755
5882
    read_time+= record_count;  // We have to make a temp table
5756
 
  memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
5883
  memcpy((uchar*) join->best_positions, (uchar*) join->positions,
 
5884
         sizeof(POSITION)*idx);
5757
5885
  join->best_read= read_time;
5758
5886
}
5759
5887
 
5834
5962
                          search
5835
5963
 
5836
5964
  @retval
5837
 
    false       ok
 
5965
    FALSE       ok
5838
5966
  @retval
5839
 
    true        Fatal error
 
5967
    TRUE        Fatal error
5840
5968
*/
5841
5969
 
5842
5970
static bool
5843
5971
greedy_search(JOIN      *join,
5844
5972
              table_map remaining_tables,
5845
 
              uint32_t      search_depth,
5846
 
              uint32_t      prune_level)
 
5973
              uint      search_depth,
 
5974
              uint      prune_level)
5847
5975
{
5848
5976
  double    record_count= 1.0;
5849
5977
  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
 
5978
  uint      idx= join->const_tables; // index into 'join->best_ref'
 
5979
  uint      best_idx;
 
5980
  uint      size_remain;    // cardinality of remaining_tables
5853
5981
  POSITION  best_pos;
5854
5982
  JOIN_TAB  *best_table; // the next plan node to be added to the curr QEP
5855
5983
 
 
5984
  DBUG_ENTER("greedy_search");
 
5985
 
5856
5986
  /* number of tables that remain to be optimized */
5857
5987
  size_remain= my_count_bits(remaining_tables);
5858
5988
 
5861
5991
    join->best_read= DBL_MAX;
5862
5992
    if (best_extension_by_limited_search(join, remaining_tables, idx, record_count,
5863
5993
                                         read_time, search_depth, prune_level))
5864
 
      return(true);
 
5994
      DBUG_RETURN(TRUE);
5865
5995
 
5866
5996
    if (size_remain <= search_depth)
5867
5997
    {
5869
5999
        'join->best_positions' contains a complete optimal extension of the
5870
6000
        current partial QEP.
5871
6001
      */
5872
 
      return(false);
 
6002
      DBUG_EXECUTE("opt", print_plan(join, join->tables,
 
6003
                                     record_count, read_time, read_time,
 
6004
                                     "optimal"););
 
6005
      DBUG_RETURN(FALSE);
5873
6006
    }
5874
6007
 
5875
6008
    /* select the first table in the optimal extension as most promising */
5887
6020
    JOIN_TAB *pos= join->best_ref[best_idx];
5888
6021
    while (pos && best_table != pos)
5889
6022
      pos= join->best_ref[++best_idx];
5890
 
    assert((pos != NULL)); // should always find 'best_table'
 
6023
    DBUG_ASSERT((pos != NULL)); // should always find 'best_table'
5891
6024
    /* 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]);
 
6025
    swap_variables(JOIN_TAB*, join->best_ref[idx], join->best_ref[best_idx]);
5893
6026
 
5894
6027
    /* compute the cost of the new plan extended with 'best_table' */
5895
6028
    record_count*= join->positions[idx].records_read;
5898
6031
    remaining_tables&= ~(best_table->table->map);
5899
6032
    --size_remain;
5900
6033
    ++idx;
5901
 
  } while (true);
 
6034
 
 
6035
    DBUG_EXECUTE("opt", print_plan(join, join->tables,
 
6036
                                   record_count, read_time, read_time,
 
6037
                                   "extended"););
 
6038
  } while (TRUE);
5902
6039
}
5903
6040
 
5904
6041
 
6014
6151
                          (values: 0 = EXHAUSTIVE, 1 = PRUNE_BY_TIME_OR_ROWS)
6015
6152
 
6016
6153
  @retval
6017
 
    false       ok
 
6154
    FALSE       ok
6018
6155
  @retval
6019
 
    true        Fatal error
 
6156
    TRUE        Fatal error
6020
6157
*/
6021
6158
 
6022
6159
static bool
6023
6160
best_extension_by_limited_search(JOIN      *join,
6024
6161
                                 table_map remaining_tables,
6025
 
                                 uint32_t      idx,
 
6162
                                 uint      idx,
6026
6163
                                 double    record_count,
6027
6164
                                 double    read_time,
6028
 
                                 uint32_t      search_depth,
6029
 
                                 uint32_t      prune_level)
 
6165
                                 uint      search_depth,
 
6166
                                 uint      prune_level)
6030
6167
{
 
6168
  DBUG_ENTER("best_extension_by_limited_search");
 
6169
 
6031
6170
  THD *thd= join->thd;
6032
6171
  if (thd->killed)  // Abort
6033
 
    return(true);
 
6172
    DBUG_RETURN(TRUE);
 
6173
 
 
6174
  DBUG_EXECUTE("opt", print_plan(join, idx, read_time, record_count, idx,
 
6175
                                 "SOFAR:"););
6034
6176
 
6035
6177
  /* 
6036
6178
     'join' is a partial plan with lower cost than the best plan so far,
6040
6182
  double best_record_count= DBL_MAX;
6041
6183
  double best_read_time=    DBL_MAX;
6042
6184
 
 
6185
  DBUG_EXECUTE("opt", print_plan(join, idx, record_count, read_time, read_time,
 
6186
                                "part_plan"););
 
6187
 
6043
6188
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
6044
6189
  {
6045
6190
    table_map real_table_bit= s->table->map;
6068
6213
      if ((current_read_time +
6069
6214
           current_record_count / (double) TIME_FOR_COMPARE) >= join->best_read)
6070
6215
      {
 
6216
        DBUG_EXECUTE("opt", print_plan(join, idx+1,
 
6217
                                       current_record_count,
 
6218
                                       read_time,
 
6219
                                       (current_read_time +
 
6220
                                        current_record_count / 
 
6221
                                        (double) TIME_FOR_COMPARE),
 
6222
                                       "prune_by_cost"););
6071
6223
        restore_prev_nj_state(s);
6072
6224
        restore_prev_sj_state(remaining_tables, s);
6073
6225
        continue;
6095
6247
        }
6096
6248
        else
6097
6249
        {
 
6250
          DBUG_EXECUTE("opt", print_plan(join, idx+1,
 
6251
                                         current_record_count,
 
6252
                                         read_time,
 
6253
                                         current_read_time,
 
6254
                                         "pruned_by_heuristic"););
6098
6255
          restore_prev_nj_state(s);
6099
6256
          restore_prev_sj_state(remaining_tables, s);
6100
6257
          continue;
6103
6260
 
6104
6261
      if ( (search_depth > 1) && (remaining_tables & ~real_table_bit) )
6105
6262
      { /* Recursively expand the current partial plan */
6106
 
        std::swap(join->best_ref[idx], *pos);
 
6263
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6107
6264
        if (best_extension_by_limited_search(join,
6108
6265
                                             remaining_tables & ~real_table_bit,
6109
6266
                                             idx + 1,
6111
6268
                                             current_read_time,
6112
6269
                                             search_depth - 1,
6113
6270
                                             prune_level))
6114
 
          return(true);
6115
 
        std::swap(join->best_ref[idx], *pos);
 
6271
          DBUG_RETURN(TRUE);
 
6272
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6116
6273
      }
6117
6274
      else
6118
6275
      { /*
6127
6284
          current_read_time+= current_record_count;
6128
6285
        if ((search_depth == 1) || (current_read_time < join->best_read))
6129
6286
        {
6130
 
          memcpy(join->best_positions, join->positions,
 
6287
          memcpy((uchar*) join->best_positions, (uchar*) join->positions,
6131
6288
                 sizeof(POSITION) * (idx + 1));
6132
6289
          join->best_read= current_read_time - 0.001;
6133
6290
        }
 
6291
        DBUG_EXECUTE("opt", print_plan(join, idx+1,
 
6292
                                       current_record_count,
 
6293
                                       read_time,
 
6294
                                       current_read_time,
 
6295
                                       "full_plan"););
6134
6296
      }
6135
6297
      restore_prev_nj_state(s);
6136
6298
      restore_prev_sj_state(remaining_tables, s);
6137
6299
    }
6138
6300
  }
6139
 
  return(false);
 
6301
  DBUG_RETURN(FALSE);
6140
6302
}
6141
6303
 
6142
6304
 
6146
6308
  tested and accepted.
6147
6309
 
6148
6310
  RETURN VALUES
6149
 
    false       ok
6150
 
    true        Fatal error
 
6311
    FALSE       ok
 
6312
    TRUE        Fatal error
6151
6313
*/
6152
6314
static bool
6153
 
find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count,
 
6315
find_best(JOIN *join,table_map rest_tables,uint idx,double record_count,
6154
6316
          double read_time)
6155
6317
{
 
6318
  DBUG_ENTER("find_best");
6156
6319
  THD *thd= join->thd;
6157
6320
  if (thd->killed)
6158
 
    return(true);
 
6321
    DBUG_RETURN(TRUE);
6159
6322
  if (!rest_tables)
6160
6323
  {
 
6324
    DBUG_PRINT("best",("read_time: %g  record_count: %g",read_time,
 
6325
                       record_count));
 
6326
 
6161
6327
    read_time+=record_count/(double) TIME_FOR_COMPARE;
6162
6328
    if (join->sort_by_table &&
6163
6329
        join->sort_by_table !=
6165
6331
      read_time+=record_count;                  // We have to make a temp table
6166
6332
    if (read_time < join->best_read)
6167
6333
    {
6168
 
      memcpy(join->best_positions, join->positions, sizeof(POSITION)*idx);
 
6334
      memcpy((uchar*) join->best_positions,(uchar*) join->positions,
 
6335
             sizeof(POSITION)*idx);
6169
6336
      join->best_read= read_time - 0.001;
6170
6337
    }
6171
 
    return(false);
 
6338
    DBUG_RETURN(FALSE);
6172
6339
  }
6173
6340
  if (read_time+record_count/(double) TIME_FOR_COMPARE >= join->best_read)
6174
 
    return(false);                                      /* Found better before */
 
6341
    DBUG_RETURN(FALSE);                                 /* Found better before */
6175
6342
 
6176
6343
  JOIN_TAB *s;
6177
6344
  double best_record_count=DBL_MAX,best_read_time=DBL_MAX;
6204
6371
          best_record_count=current_record_count;
6205
6372
          best_read_time=current_read_time;
6206
6373
        }
6207
 
        std::swap(join->best_ref[idx], *pos);
 
6374
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6208
6375
        if (find_best(join,rest_tables & ~real_table_bit,idx+1,
6209
6376
                      current_record_count,current_read_time))
6210
 
          return(true);
6211
 
        std::swap(join->best_ref[idx], *pos);
 
6377
          DBUG_RETURN(TRUE);
 
6378
        swap_variables(JOIN_TAB*, join->best_ref[idx], *pos);
6212
6379
      }
6213
6380
      restore_prev_nj_state(s);
6214
6381
      restore_prev_sj_state(rest_tables, s);
6216
6383
        break;                          // Don't test all combinations
6217
6384
    }
6218
6385
  }
6219
 
  return(false);
 
6386
  DBUG_RETURN(FALSE);
6220
6387
}
6221
6388
 
6222
6389
 
6224
6391
  Find how much space the prevous read not const tables takes in cache.
6225
6392
*/
6226
6393
 
6227
 
static void calc_used_field_length(THD *thd __attribute__((unused)),
6228
 
                                   JOIN_TAB *join_tab)
 
6394
static void calc_used_field_length(THD *thd, JOIN_TAB *join_tab)
6229
6395
{
6230
 
  uint32_t null_fields,blobs,fields,rec_length;
 
6396
  uint null_fields,blobs,fields,rec_length;
6231
6397
  Field **f_ptr,*field;
6232
6398
  MY_BITMAP *read_set= join_tab->table->read_set;;
6233
6399
 
6236
6402
  {
6237
6403
    if (bitmap_is_set(read_set, field->field_index))
6238
6404
    {
6239
 
      uint32_t flags=field->flags;
 
6405
      uint flags=field->flags;
6240
6406
      fields++;
6241
6407
      rec_length+=field->pack_length();
6242
6408
      if (flags & BLOB_FLAG)
6246
6412
    }
6247
6413
  }
6248
6414
  if (null_fields)
6249
 
    rec_length+=(join_tab->table->getNullFields() + 7)/8;
 
6415
    rec_length+=(join_tab->table->s->null_fields+7)/8;
6250
6416
  if (join_tab->table->maybe_null)
6251
 
    rec_length+=sizeof(bool);
 
6417
    rec_length+=sizeof(my_bool);
6252
6418
  if (blobs)
6253
6419
  {
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);
 
6420
    uint blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
 
6421
                             (join_tab->table->s->reclength- rec_length));
 
6422
    rec_length+=(uint) max(4,blob_length);
6257
6423
  }
6258
6424
  join_tab->used_fields=fields;
6259
6425
  join_tab->used_fieldlength=rec_length;
6262
6428
 
6263
6429
 
6264
6430
static uint
6265
 
cache_record_length(JOIN *join,uint32_t idx)
 
6431
cache_record_length(JOIN *join,uint idx)
6266
6432
{
6267
 
  uint32_t length=0;
 
6433
  uint length=0;
6268
6434
  JOIN_TAB **pos,**end;
6269
6435
  THD *thd=join->thd;
6270
6436
 
6333
6499
*/
6334
6500
 
6335
6501
static double
6336
 
prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref)
 
6502
prev_record_reads(JOIN *join, uint idx, table_map found_ref)
6337
6503
{
6338
6504
  double found=1.0;
6339
6505
  POSITION *pos_end= join->positions - 1;
6373
6539
static bool
6374
6540
get_best_combination(JOIN *join)
6375
6541
{
6376
 
  uint32_t i,tablenr;
 
6542
  uint i,tablenr;
6377
6543
  table_map used_tables;
6378
6544
  JOIN_TAB *join_tab,*j;
6379
6545
  KEYUSE *keyuse;
6380
 
  uint32_t table_count;
 
6546
  uint table_count;
6381
6547
  THD *thd=join->thd;
 
6548
  DBUG_ENTER("get_best_combination");
6382
6549
 
6383
6550
  table_count=join->tables;
6384
6551
  if (!(join->join_tab=join_tab=
6385
6552
        (JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)*table_count)))
6386
 
    return(true);
 
6553
    DBUG_RETURN(TRUE);
6387
6554
 
6388
6555
  join->full_join=0;
6389
6556
 
6390
6557
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
6391
6558
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
6392
6559
  {
6393
 
    Table *form;
 
6560
    TABLE *form;
6394
6561
    *j= *join->best_positions[tablenr].table;
6395
6562
    form=join->table[tablenr]=j->table;
6396
6563
    used_tables|= form->map;
6397
6564
    form->reginfo.join_tab=j;
6398
6565
    if (!*j->on_expr_ref)
6399
6566
      form->reginfo.not_exists_optimize=0;      // Only with LEFT JOIN
 
6567
    DBUG_PRINT("info",("type: %d", j->type));
6400
6568
    if (j->type == JT_CONST)
6401
6569
      continue;                                 // Handled in make_join_stat..
6402
6570
 
6412
6580
        join->full_join=1;
6413
6581
    }
6414
6582
    else if (create_ref_for_key(join, j, keyuse, used_tables))
6415
 
      return(true);                        // Something went wrong
 
6583
      DBUG_RETURN(TRUE);                        // Something went wrong
6416
6584
  }
6417
6585
 
6418
6586
  for (i=0 ; i < table_count ; i++)
6419
6587
    join->map2table[join->join_tab[i].table->tablenr]=join->join_tab+i;
6420
6588
  update_depend_map(join);
6421
 
  return(0);
 
6589
  DBUG_RETURN(0);
6422
6590
}
6423
6591
 
6424
6592
 
6427
6595
{
6428
6596
  KEYUSE *keyuse=org_keyuse;
6429
6597
  THD  *thd= join->thd;
6430
 
  uint32_t keyparts,length,key;
6431
 
  Table *table;
 
6598
  uint keyparts,length,key;
 
6599
  TABLE *table;
6432
6600
  KEY *keyinfo;
 
6601
  DBUG_ENTER("create_ref_for_key");
6433
6602
 
6434
6603
  /*  Use best key from find_best */
6435
6604
  table=j->table;
6438
6607
 
6439
6608
  {
6440
6609
    keyparts=length=0;
6441
 
    uint32_t found_part_ref_or_null= 0;
 
6610
    uint found_part_ref_or_null= 0;
6442
6611
    /*
6443
6612
      Calculate length for the used key
6444
6613
      Stop if there is a missing key part or when we find second key_part
6465
6634
  j->ref.key_parts=keyparts;
6466
6635
  j->ref.key_length=length;
6467
6636
  j->ref.key=(int) key;
6468
 
  if (!(j->ref.key_buff= (unsigned char*) thd->calloc(ALIGN_SIZE(length)*2)) ||
 
6637
  if (!(j->ref.key_buff= (uchar*) thd->calloc(ALIGN_SIZE(length)*2)) ||
6469
6638
      !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) *
6470
6639
                                                   (keyparts+1)))) ||
6471
6640
      !(j->ref.items=    (Item**) thd->alloc(sizeof(Item*)*keyparts)) ||
6472
6641
      !(j->ref.cond_guards= (bool**) thd->alloc(sizeof(uint*)*keyparts)))
6473
6642
  {
6474
 
    return(true);
 
6643
    DBUG_RETURN(TRUE);
6475
6644
  }
6476
6645
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
6477
6646
  j->ref.key_err=1;
6478
6647
  j->ref.null_rejecting= 0;
6479
 
  j->ref.disable_cache= false;
 
6648
  j->ref.disable_cache= FALSE;
6480
6649
  keyuse=org_keyuse;
6481
6650
 
6482
6651
  store_key **ref_key= j->ref.key_copy;
6483
 
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
6484
 
  bool keyuse_uses_no_tables= true;
 
6652
  uchar *key_buff=j->ref.key_buff, *null_ref_key= 0;
 
6653
  bool keyuse_uses_no_tables= TRUE;
6485
6654
  {
6486
 
    uint32_t i;
 
6655
    uint i;
6487
6656
    for (i=0 ; i < keyparts ; keyuse++,i++)
6488
6657
    {
6489
6658
      while (keyuse->keypart != i ||
6490
6659
             ((~used_tables) & keyuse->used_tables))
6491
6660
        keyuse++;                               /* Skip other parts */
6492
6661
 
6493
 
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
 
6662
      uint maybe_null= test(keyinfo->key_part[i].null_bit);
6494
6663
      j->ref.items[i]=keyuse->val;              // Save for cond removal
6495
6664
      j->ref.cond_guards[i]= keyuse->cond_guard;
6496
6665
      if (keyuse->null_rejecting) 
6504
6673
                           maybe_null ?  key_buff : 0,
6505
6674
                           keyinfo->key_part[i].length, keyuse->val);
6506
6675
        if (thd->is_fatal_error)
6507
 
          return(true);
 
6676
          DBUG_RETURN(TRUE);
6508
6677
        tmp.copy();
6509
6678
      }
6510
6679
      else
6525
6694
  *ref_key=0;                           // end_marker
6526
6695
  if (j->type == JT_CONST)
6527
6696
    j->table->const_table= 1;
6528
 
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
6529
 
           keyparts != keyinfo->key_parts || null_ref_key)
 
6697
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY |
 
6698
                               HA_END_SPACE_KEY)) != HA_NOSAME) ||
 
6699
           keyparts != keyinfo->key_parts || null_ref_key)
6530
6700
  {
6531
6701
    /* Must read with repeat */
6532
6702
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
6545
6715
  }
6546
6716
  else
6547
6717
    j->type=JT_EQ_REF;
6548
 
  return(0);
 
6718
  DBUG_RETURN(0);
6549
6719
}
6550
6720
 
6551
6721
 
6552
6722
 
6553
6723
static store_key *
6554
6724
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)
 
6725
              KEY_PART_INFO *key_part, uchar *key_buff, uint maybe_null)
6556
6726
{
6557
6727
  if (!((~used_tables) & keyuse->used_tables))          // if const item
6558
6728
  {
6595
6765
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
6596
6766
{
6597
6767
  bool error;
6598
 
  Table *table= field->table;
 
6768
  TABLE *table= field->table;
6599
6769
  THD *thd= table->in_use;
6600
6770
  ha_rows cuted_fields=thd->cuted_fields;
 
6771
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
 
6772
                                                   table->write_set);
6601
6773
 
6602
6774
  /*
6603
6775
    we should restore old value of count_cuted_fields because
6608
6780
  thd->count_cuted_fields= check_flag;
6609
6781
  error= item->save_in_field(field, 1);
6610
6782
  thd->count_cuted_fields= old_count_cuted_fields;
 
6783
  dbug_tmp_restore_column_map(table->write_set, old_map);
6611
6784
  return error || cuted_fields != thd->cuted_fields;
6612
6785
}
6613
6786
 
6614
6787
 
6615
6788
static bool
6616
 
make_simple_join(JOIN *join,Table *tmp_table)
 
6789
make_simple_join(JOIN *join,TABLE *tmp_table)
6617
6790
{
6618
 
  Table **tableptr;
 
6791
  TABLE **tableptr;
6619
6792
  JOIN_TAB *join_tab;
 
6793
  DBUG_ENTER("make_simple_join");
6620
6794
 
6621
6795
  /*
6622
 
    Reuse Table * and JOIN_TAB if already allocated by a previous call
 
6796
    Reuse TABLE * and JOIN_TAB if already allocated by a previous call
6623
6797
    to this function through JOIN::exec (may happen for sub-queries).
6624
6798
  */
6625
6799
  if (!join->table_reexec)
6626
6800
  {
6627
 
    if (!(join->table_reexec= (Table**) join->thd->alloc(sizeof(Table*))))
6628
 
      return(true);                        /* purecov: inspected */
 
6801
    if (!(join->table_reexec= (TABLE**) join->thd->alloc(sizeof(TABLE*))))
 
6802
      DBUG_RETURN(TRUE);                        /* purecov: inspected */
6629
6803
    if (join->tmp_join)
6630
6804
      join->tmp_join->table_reexec= join->table_reexec;
6631
6805
  }
6633
6807
  {
6634
6808
    if (!(join->join_tab_reexec=
6635
6809
          (JOIN_TAB*) join->thd->alloc(sizeof(JOIN_TAB))))
6636
 
      return(true);                        /* purecov: inspected */
 
6810
      DBUG_RETURN(TRUE);                        /* purecov: inspected */
6637
6811
    if (join->tmp_join)
6638
6812
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
6639
6813
  }
6673
6847
  join_tab->ref.key_parts= 0;
6674
6848
  join_tab->flush_weedout_table= join_tab->check_weed_out_table= NULL;
6675
6849
  join_tab->do_firstmatch= NULL;
6676
 
  memset(&join_tab->read_record, 0, sizeof(join_tab->read_record));
 
6850
  bzero((char*) &join_tab->read_record,sizeof(join_tab->read_record));
6677
6851
  tmp_table->status=0;
6678
6852
  tmp_table->null_row=0;
6679
 
  return(false);
 
6853
  DBUG_RETURN(FALSE);
6680
6854
}
6681
6855
 
6682
6856
 
6749
6923
 
6750
6924
static void add_not_null_conds(JOIN *join)
6751
6925
{
6752
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
6926
  DBUG_ENTER("add_not_null_conds");
 
6927
  for (uint i=join->const_tables ; i < join->tables ; i++)
6753
6928
  {
6754
6929
    JOIN_TAB *tab=join->join_tab+i;
6755
6930
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF || 
6756
6931
         tab->type == JT_REF_OR_NULL) &&
6757
6932
        !tab->table->maybe_null)
6758
6933
    {
6759
 
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
 
6934
      for (uint keypart= 0; keypart < tab->ref.key_parts; keypart++)
6760
6935
      {
6761
6936
        if (tab->ref.null_rejecting & (1 << keypart))
6762
6937
        {
6763
6938
          Item *item= tab->ref.items[keypart];
6764
6939
          Item *notnull;
6765
 
          assert(item->type() == Item::FIELD_ITEM);
 
6940
          DBUG_ASSERT(item->type() == Item::FIELD_ITEM);
6766
6941
          Item_field *not_null_item= (Item_field*)item;
6767
6942
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
6768
6943
          /*
6773
6948
          if (!referred_tab || referred_tab->join != join)
6774
6949
            continue;
6775
6950
          if (!(notnull= new Item_func_isnotnull(not_null_item)))
6776
 
            return;
 
6951
            DBUG_VOID_RETURN;
6777
6952
          /*
6778
6953
            We need to do full fix_fields() call here in order to have correct
6779
6954
            notnull->const_item(). This is needed e.g. by test_quick_select 
6781
6956
            called.
6782
6957
          */
6783
6958
          if (notnull->fix_fields(join->thd, &notnull))
6784
 
            return;
 
6959
            DBUG_VOID_RETURN;
 
6960
          DBUG_EXECUTE("where",print_where(notnull,
 
6961
                                           referred_tab->table->alias,
 
6962
                                           QT_ORDINARY););
6785
6963
          add_cond_and_fix(&referred_tab->select_cond, notnull);
6786
6964
        }
6787
6965
      }
6788
6966
    }
6789
6967
  }
6790
 
  return;
 
6968
  DBUG_VOID_RETURN;
6791
6969
}
6792
6970
 
6793
6971
/**
6810
6988
add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab)
6811
6989
{
6812
6990
  COND *tmp;
6813
 
  assert(cond != 0);
 
6991
  DBUG_ASSERT(cond != 0);
6814
6992
  if (tab == root_tab)
6815
6993
    return cond;
6816
6994
  if ((tmp= add_found_match_trig_cond(tab->first_upper, cond, root_tab)))
6869
7047
static void
6870
7048
make_outerjoin_info(JOIN *join)
6871
7049
{
6872
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
7050
  DBUG_ENTER("make_outerjoin_info");
 
7051
  for (uint i=join->const_tables ; i < join->tables ; i++)
6873
7052
  {
6874
7053
    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;
 
7054
    TABLE *table=tab->table;
 
7055
    TABLE_LIST *tbl= table->pos_in_table_list;
 
7056
    TABLE_LIST *embedding= tbl->embedding;
6878
7057
 
6879
7058
    if (tbl->outer_join)
6880
7059
    {
6894
7073
      /* Ignore sj-nests: */
6895
7074
      if (!embedding->on_expr)
6896
7075
        continue;
6897
 
      nested_join_st *nested_join= embedding->nested_join;
 
7076
      NESTED_JOIN *nested_join= embedding->nested_join;
6898
7077
      if (!nested_join->counter_)
6899
7078
      {
6900
7079
        /* 
6915
7094
      nested_join->first_nested->last_inner= tab;
6916
7095
    }
6917
7096
  }
6918
 
  return;
 
7097
  DBUG_VOID_RETURN;
6919
7098
}
6920
7099
 
6921
7100
 
6923
7102
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
6924
7103
{
6925
7104
  THD *thd= join->thd;
 
7105
  DBUG_ENTER("make_join_select");
6926
7106
  if (select)
6927
7107
  {
6928
7108
    add_not_null_conds(join);
6940
7120
          make_cond_for_table(cond,
6941
7121
                              join->const_table_map,
6942
7122
                              (table_map) 0, 1);
 
7123
        DBUG_EXECUTE("where",print_where(const_cond,"constants", QT_ORDINARY););
6943
7124
        for (JOIN_TAB *tab= join->join_tab+join->const_tables;
6944
7125
             tab < join->join_tab+join->tables ; tab++)
6945
7126
        {
6953
7134
              continue;
6954
7135
            tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
6955
7136
            if (!tmp)
6956
 
              return(1);
 
7137
              DBUG_RETURN(1);
6957
7138
            tmp->quick_fix_field();
6958
7139
            cond_tab->select_cond= !cond_tab->select_cond ? tmp :
6959
7140
                                    new Item_cond_and(cond_tab->select_cond,
6960
7141
                                                      tmp);
6961
7142
            if (!cond_tab->select_cond)
6962
 
              return(1);
 
7143
              DBUG_RETURN(1);
6963
7144
            cond_tab->select_cond->quick_fix_field();
6964
7145
          }       
6965
7146
        }
6966
7147
        if (const_cond && !const_cond->val_int())
6967
7148
        {
6968
 
          return(1);     // Impossible const condition
 
7149
          DBUG_PRINT("info",("Found impossible WHERE condition"));
 
7150
          DBUG_RETURN(1);        // Impossible const condition
6969
7151
        }
6970
7152
      }
6971
7153
    }
6972
7154
    used_tables=((select->const_tables=join->const_table_map) |
6973
7155
                 OUTER_REF_TABLE_BIT | RAND_TABLE_BIT);
6974
 
    for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
7156
    for (uint i=join->const_tables ; i < join->tables ; i++)
6975
7157
    {
6976
7158
      JOIN_TAB *tab=join->join_tab+i;
6977
7159
      /*
7032
7214
            in the ON part of an OUTER JOIN. In this case we want the code
7033
7215
            below to check if we should use 'quick' instead.
7034
7216
          */
7035
 
          tmp= new Item_int((int64_t) 1,1);     // Always true
 
7217
          DBUG_PRINT("info", ("Item_int"));
 
7218
          tmp= new Item_int((longlong) 1,1);    // Always true
7036
7219
        }
7037
7220
 
7038
7221
      }
7039
7222
      if (tmp || !cond || tab->type == JT_REF || tab->type == JT_REF_OR_NULL ||
7040
7223
          tab->type == JT_EQ_REF)
7041
7224
      {
 
7225
        DBUG_EXECUTE("where",print_where(tmp,tab->table->alias, QT_ORDINARY););
7042
7226
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
7043
 
                                       thd->memdup((unsigned char*) select,
 
7227
                                       thd->memdup((uchar*) select,
7044
7228
                                                   sizeof(*select)));
7045
7229
        if (!sel)
7046
 
          return(1);                    // End of memory
 
7230
          DBUG_RETURN(1);                       // End of memory
7047
7231
        /*
7048
7232
          If tab is an inner table of an outer join operation,
7049
7233
          add a match guard to the pushed down predicate.
7057
7241
            a cond, so neutralize the hack above.
7058
7242
          */
7059
7243
          if (!(tmp= add_found_match_trig_cond(first_inner_tab, tmp, 0)))
7060
 
            return(1);
 
7244
            DBUG_RETURN(1);
7061
7245
          tab->select_cond=sel->cond=tmp;
7062
7246
          /* Push condition to storage engine if this is enabled
7063
7247
             and the condition is not guarded */
7078
7262
          tab->select_cond= sel->cond= NULL;
7079
7263
 
7080
7264
        sel->head=tab->table;
 
7265
        DBUG_EXECUTE("where",print_where(tmp,tab->table->alias, QT_ORDINARY););
7081
7266
        if (tab->quick)
7082
7267
        {
7083
7268
          /* Use quick key read if it's a constant and it's not used
7095
7280
          }
7096
7281
          tab->quick=0;
7097
7282
        }
7098
 
        uint32_t ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
 
7283
        uint ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
7099
7284
        if (i == join->const_tables && ref_key)
7100
7285
        {
7101
7286
          if (!tab->const_keys.is_clear_all() &&
7102
7287
              tab->table->reginfo.impossible_range)
7103
 
            return(1);
 
7288
            DBUG_RETURN(1);
7104
7289
        }
7105
7290
        else if (tab->type == JT_ALL && ! use_quick_range)
7106
7291
        {
7107
7292
          if (!tab->const_keys.is_clear_all() &&
7108
7293
              tab->table->reginfo.impossible_range)
7109
 
            return(1);                          // Impossible range
 
7294
            DBUG_RETURN(1);                             // Impossible range
7110
7295
          /*
7111
7296
            We plan to scan all rows.
7112
7297
            Check again if we should use an index.
7137
7322
                                        OPTION_FOUND_ROWS ?
7138
7323
                                        HA_POS_ERROR :
7139
7324
                                        join->unit->select_limit_cnt), 0,
7140
 
                                        false) < 0)
 
7325
                                        FALSE) < 0)
7141
7326
            {
7142
7327
              /*
7143
7328
                Before reporting "Impossible WHERE" for the whole query
7151
7336
                                          OPTION_FOUND_ROWS ?
7152
7337
                                          HA_POS_ERROR :
7153
7338
                                          join->unit->select_limit_cnt),0,
7154
 
                                          false) < 0)
7155
 
                return(1);                      // Impossible WHERE
 
7339
                                          FALSE) < 0)
 
7340
                DBUG_RETURN(1);                 // Impossible WHERE
7156
7341
            }
7157
7342
            else
7158
7343
              sel->cond=orig_cond;
7186
7371
                                         current_map,
7187
7372
                                         current_map, 0)))
7188
7373
            {
 
7374
              DBUG_EXECUTE("where",print_where(tmp,"cache", QT_ORDINARY););
7189
7375
              tab->cache.select=(SQL_SELECT*)
7190
 
                thd->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
7376
                thd->memdup((uchar*) sel, sizeof(SQL_SELECT));
7191
7377
              tab->cache.select->cond=tmp;
7192
7378
              tab->cache.select->read_tables=join->const_table_map;
7193
7379
            }
7218
7404
            continue;
7219
7405
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
7220
7406
          if (!tmp)
7221
 
            return(1);
 
7407
            DBUG_RETURN(1);
7222
7408
          tmp->quick_fix_field();
7223
7409
          cond_tab->select_cond= !cond_tab->select_cond ? tmp :
7224
7410
                                    new Item_cond_and(cond_tab->select_cond,tmp);
7225
7411
          if (!cond_tab->select_cond)
7226
 
            return(1);
 
7412
            DBUG_RETURN(1);
7227
7413
          cond_tab->select_cond->quick_fix_field();
7228
7414
        }       
7229
7415
      }
7256
7442
            if (!(tmp_cond= add_found_match_trig_cond(cond_tab->first_inner,
7257
7443
                                                     tmp_cond,
7258
7444
                                                     first_inner_tab)))
7259
 
              return(1);
 
7445
              DBUG_RETURN(1);
7260
7446
            /* 
7261
7447
              Now add the guard turning the predicate off for 
7262
7448
              the null complemented row.
7263
7449
            */ 
 
7450
            DBUG_PRINT("info", ("Item_func_trig_cond"));
7264
7451
            tmp_cond= new Item_func_trig_cond(tmp_cond,
7265
7452
                                              &first_inner_tab->
7266
7453
                                              not_null_compl);
 
7454
            DBUG_PRINT("info", ("Item_func_trig_cond 0x%lx",
 
7455
                                (ulong) tmp_cond));
7267
7456
            if (tmp_cond)
7268
7457
              tmp_cond->quick_fix_field();
7269
7458
            /* Add the predicate to other pushed down predicates */
 
7459
            DBUG_PRINT("info", ("Item_cond_and"));
7270
7460
            cond_tab->select_cond= !cond_tab->select_cond ? tmp_cond :
7271
7461
                                  new Item_cond_and(cond_tab->select_cond,
7272
7462
                                                    tmp_cond);
 
7463
            DBUG_PRINT("info", ("Item_cond_and 0x%lx",
 
7464
                                (ulong)cond_tab->select_cond));
7273
7465
            if (!cond_tab->select_cond)
7274
 
              return(1);
 
7466
              DBUG_RETURN(1);
7275
7467
            cond_tab->select_cond->quick_fix_field();
7276
7468
          }              
7277
7469
        }
7279
7471
      }
7280
7472
    }
7281
7473
  }
7282
 
  return(0);
 
7474
  DBUG_RETURN(0);
7283
7475
}
7284
7476
 
7285
7477
 
7291
7483
      item           Expression to check
7292
7484
      tbl            The table having the index
7293
7485
      keyno          The index number
7294
 
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7486
      other_tbls_ok  TRUE <=> Fields of other non-const tables are allowed
7295
7487
 
7296
7488
  DESCRIPTION
7297
7489
    Check if given expression only uses fields covered by index #keyno in the
7301
7493
    handled outside of this function.
7302
7494
 
7303
7495
  RETURN
7304
 
    true   Yes
7305
 
    false  No
 
7496
    TRUE   Yes
 
7497
    FALSE  No
7306
7498
*/
7307
7499
 
7308
 
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, 
 
7500
bool uses_index_fields_only(Item *item, TABLE *tbl, uint keyno, 
7309
7501
                            bool other_tbls_ok)
7310
7502
{
7311
7503
  if (item->const_item())
7312
 
    return true;
 
7504
    return TRUE;
7313
7505
 
7314
7506
  /* 
7315
7507
    Don't push down the triggered conditions. Nested outer joins execution 
7322
7514
  */
7323
7515
  if (item->type() == Item::FUNC_ITEM && 
7324
7516
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
7325
 
    return false;
 
7517
    return FALSE;
7326
7518
 
7327
7519
  if (!(item->used_tables() & tbl->map))
7328
7520
    return other_tbls_ok;
7338
7530
      for (child= item_func->arguments(); child != item_end; child++)
7339
7531
      {
7340
7532
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
7341
 
          return false;
 
7533
          return FALSE;
7342
7534
      }
7343
 
      return true;
 
7535
      return TRUE;
7344
7536
    }
7345
7537
  case Item::COND_ITEM:
7346
7538
    {
7350
7542
      while ((item=li++))
7351
7543
      {
7352
7544
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
7353
 
          return false;
 
7545
          return FALSE;
7354
7546
      }
7355
 
      return true;
 
7547
      return TRUE;
7356
7548
    }
7357
7549
  case Item::FIELD_ITEM:
7358
7550
    {
7359
7551
      Item_field *item_field= (Item_field*)item;
7360
7552
      if (item_field->field->table != tbl) 
7361
 
        return true;
 
7553
        return TRUE;
7362
7554
      return item_field->field->part_of_key.is_set(keyno);
7363
7555
    }
7364
7556
  case Item::REF_ITEM:
7365
7557
    return uses_index_fields_only(item->real_item(), tbl, keyno,
7366
7558
                                  other_tbls_ok);
7367
7559
  default:
7368
 
    return false; /* Play it safe, don't push unknown non-const items */
 
7560
    return FALSE; /* Play it safe, don't push unknown non-const items */
7369
7561
  }
7370
7562
}
7371
7563
 
7381
7573
      table          The table that is partially available
7382
7574
      keyno          The index in the above table. Only fields covered by the index
7383
7575
                     are available
7384
 
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7576
      other_tbls_ok  TRUE <=> Fields of other non-const tables are allowed
7385
7577
 
7386
7578
  DESCRIPTION
7387
7579
    Get a part of the condition that can be checked when for the given table 
7400
7592
    Index condition, or NULL if no condition could be inferred.
7401
7593
*/
7402
7594
 
7403
 
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno,
 
7595
Item *make_cond_for_index(Item *cond, TABLE *table, uint keyno,
7404
7596
                          bool other_tbls_ok)
7405
7597
{
7406
7598
  if (!cond)
7407
7599
    return NULL;
7408
7600
  if (cond->type() == Item::COND_ITEM)
7409
7601
  {
7410
 
    uint32_t n_marked= 0;
 
7602
    uint n_marked= 0;
7411
7603
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
7412
7604
    {
7413
7605
      Item_cond_and *new_cond=new Item_cond_and;
7509
7701
      Item *item;
7510
7702
      while ((item=li++))
7511
7703
      {
7512
 
        Item *fix= make_cond_remainder(item, false);
 
7704
        Item *fix= make_cond_remainder(item, FALSE);
7513
7705
        if (!fix)
7514
7706
          return (COND*) 0;
7515
7707
        new_cond->argument_list()->push_back(fix);
7533
7725
      tab            A join tab that has tab->table->file and its condition
7534
7726
                     in tab->select_cond
7535
7727
      keyno          Index for which extract and push the condition
7536
 
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
7728
      other_tbls_ok  TRUE <=> Fields of other non-const tables are allowed
7537
7729
 
7538
7730
  DESCRIPTION
7539
7731
    Try to extract and push the index condition down to table handler
7540
7732
*/
7541
7733
 
7542
 
static void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
 
7734
static void push_index_cond(JOIN_TAB *tab, uint keyno, bool other_tbls_ok)
7543
7735
{
 
7736
  DBUG_ENTER("push_index_cond");
7544
7737
  Item *idx_cond;
7545
7738
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
7546
7739
      tab->join->thd->variables.engine_condition_pushdown)
7547
7740
  {
 
7741
    DBUG_EXECUTE("where",
 
7742
                 print_where(tab->select_cond, "full cond", QT_ORDINARY););
 
7743
 
7548
7744
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
7549
7745
                                  other_tbls_ok);
7550
7746
 
 
7747
    DBUG_EXECUTE("where",
 
7748
                 print_where(idx_cond, "idx cond", QT_ORDINARY););
 
7749
 
7551
7750
    if (idx_cond)
7552
7751
    {
7553
7752
      tab->pre_idx_push_select_cond= tab->select_cond;
7563
7762
        pushdown APIs.
7564
7763
      */
7565
7764
      if (idx_remainder_cond != idx_cond)
7566
 
        tab->ref.disable_cache= true;
7567
 
 
7568
 
      Item *row_cond= make_cond_remainder(tab->select_cond, true);
7569
 
 
 
7765
        tab->ref.disable_cache= TRUE;
 
7766
 
 
7767
      Item *row_cond= make_cond_remainder(tab->select_cond, TRUE);
 
7768
 
 
7769
      DBUG_EXECUTE("where",
 
7770
                   print_where(row_cond, "remainder cond", QT_ORDINARY););
 
7771
      
7570
7772
      if (row_cond)
7571
7773
      {
7572
7774
        if (!idx_remainder_cond)
7583
7785
        tab->select_cond= idx_remainder_cond;
7584
7786
      if (tab->select)
7585
7787
      {
 
7788
        DBUG_EXECUTE("where",
 
7789
                     print_where(tab->select->cond,
 
7790
                                 "select_cond",
 
7791
                                 QT_ORDINARY););
 
7792
 
7586
7793
        tab->select->cond= tab->select_cond;
7587
7794
      }
7588
7795
    }
7589
7796
  }
7590
 
  return;
 
7797
  DBUG_VOID_RETURN;
7591
7798
}
7592
7799
 
7593
7800
 
7594
7801
 
7595
7802
    /*
7596
 
      Determine if the set is already ordered for order_st BY, so it can 
 
7803
      Determine if the set is already ordered for ORDER BY, so it can 
7597
7804
      disable join cache because it will change the ordering of the results.
7598
7805
      Code handles sort table that is at any location (not only first after 
7599
7806
      the const tables) despite the fact that it's currently prohibited.
7601
7808
      ordered. If there is a temp table the ordering is done as a last
7602
7809
      operation and doesn't prevent join cache usage.
7603
7810
    */
7604
 
uint32_t make_join_orderinfo(JOIN *join)
 
7811
uint make_join_orderinfo(JOIN *join)
7605
7812
{
7606
 
  uint32_t i;
 
7813
  uint i;
7607
7814
  if (join->need_tmp)
7608
7815
    return join->tables;
7609
7816
 
7610
7817
  for (i=join->const_tables ; i < join->tables ; i++)
7611
7818
  {
7612
7819
    JOIN_TAB *tab=join->join_tab+i;
7613
 
    Table *table=tab->table;
 
7820
    TABLE *table=tab->table;
7614
7821
    if ((table == join->sort_by_table && 
7615
7822
         (!join->order || join->skip_sort_order)) ||
7616
 
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
 
7823
        (join->sort_by_table == (TABLE *) 1 && i != join->const_tables))
7617
7824
    {
7618
7825
      break;
7619
7826
    }
7640
7847
      - etc
7641
7848
 
7642
7849
  RETURN 
7643
 
    false - OK
7644
 
    true  - Out of memory
 
7850
    FALSE - OK
 
7851
    TRUE  - Out of memory
7645
7852
*/
7646
7853
 
7647
7854
static bool
7648
 
make_join_readinfo(JOIN *join, uint64_t options, uint32_t no_jbuf_after)
 
7855
make_join_readinfo(JOIN *join, ulonglong options, uint no_jbuf_after)
7649
7856
{
7650
 
  uint32_t i;
 
7857
  uint i;
7651
7858
  bool statistics= test(!(join->select_options & SELECT_DESCRIBE));
7652
7859
  bool sorted= 1;
 
7860
  DBUG_ENTER("make_join_readinfo");
7653
7861
 
7654
7862
  for (i=join->const_tables ; i < join->tables ; i++)
7655
7863
  {
7656
7864
    JOIN_TAB *tab=join->join_tab+i;
7657
 
    Table *table=tab->table;
 
7865
    TABLE *table=tab->table;
7658
7866
    bool using_join_cache;
7659
7867
    tab->read_record.table= table;
7660
7868
    tab->read_record.file=table->file;
7667
7875
    sorted= 0;                                  // only first must be sorted
7668
7876
    if (tab->insideout_match_tab)
7669
7877
    {
7670
 
      if (!(tab->insideout_buf= (unsigned char*)join->thd->alloc(tab->table->key_info
 
7878
      if (!(tab->insideout_buf= (uchar*)join->thd->alloc(tab->table->key_info
7671
7879
                                                         [tab->index].
7672
7880
                                                         key_length)))
7673
 
        return true;
 
7881
        return TRUE;
7674
7882
    }
7675
7883
    switch (tab->type) {
7676
7884
    case JT_SYSTEM:                             // Only happens with left join
7707
7915
        table->file->extra(HA_EXTRA_KEYREAD);
7708
7916
      }
7709
7917
      else
7710
 
        push_index_cond(tab, tab->ref.key, true);
 
7918
        push_index_cond(tab, tab->ref.key, TRUE);
7711
7919
      break;
7712
7920
    case JT_REF_OR_NULL:
7713
7921
    case JT_REF:
7726
7934
        table->file->extra(HA_EXTRA_KEYREAD);
7727
7935
      }
7728
7936
      else
7729
 
        push_index_cond(tab, tab->ref.key, true);
 
7937
        push_index_cond(tab, tab->ref.key, TRUE);
7730
7938
      if (tab->type == JT_REF)
7731
7939
      {
7732
7940
        tab->read_first_record= join_read_always_key;
7745
7953
        If the incoming data set is already sorted don't use cache.
7746
7954
      */
7747
7955
      table->status=STATUS_NO_RECORD;
7748
 
      using_join_cache= false;
 
7956
      using_join_cache= FALSE;
7749
7957
      if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
7750
7958
          tab->use_quick != 2 && !tab->first_inner && i <= no_jbuf_after &&
7751
7959
          !tab->insideout_match_tab)
7754
7962
            !join_init_cache(join->thd,join->join_tab+join->const_tables,
7755
7963
                             i-join->const_tables))
7756
7964
        {
7757
 
          using_join_cache= true;
 
7965
          using_join_cache= TRUE;
7758
7966
          tab[-1].next_select=sub_select_cache; /* Patch previous */
7759
7967
        }
7760
7968
      }
7819
8027
                  table->file->primary_key_is_clustered())
7820
8028
                tab->index= table->s->primary_key;
7821
8029
              else
7822
 
                tab->index= table->find_shortest_key(&table->covering_keys);
 
8030
                tab->index=find_shortest_key(table, & table->covering_keys);
7823
8031
            }
7824
8032
            tab->read_first_record= join_read_first;
7825
8033
            tab->type=JT_NEXT;          // Read with index_first / index_next
7831
8039
      }
7832
8040
      break;
7833
8041
    default:
 
8042
      DBUG_PRINT("error",("Table type %d found",tab->type)); /* purecov: deadcode */
7834
8043
      break;                                    /* purecov: deadcode */
7835
8044
    case JT_UNKNOWN:
7836
8045
    case JT_MAYBE_REF:
7838
8047
    }
7839
8048
  }
7840
8049
  join->join_tab[join->tables-1].next_select=0; /* Set by do_select */
7841
 
  return(false);
 
8050
  DBUG_RETURN(FALSE);
7842
8051
}
7843
8052
 
7844
8053
 
7883
8092
  select= 0;
7884
8093
  delete quick;
7885
8094
  quick= 0;
7886
 
  if (cache.buff)
7887
 
    free(cache.buff);
 
8095
  x_free(cache.buff);
7888
8096
  cache.buff= 0;
7889
8097
  limit= 0;
7890
8098
  if (table)
7938
8146
    a correlated subquery itself, but has subqueries, we can free it
7939
8147
    fully and also free JOINs of all its subqueries. The exception
7940
8148
    is a subquery in SELECT list, e.g: @n
7941
 
    SELECT a, (select cmax(b) from t1) group by c @n
 
8149
    SELECT a, (select max(b) from t1) group by c @n
7942
8150
    This subquery will not be evaluated at first sweep and its value will
7943
8151
    not be inserted into the temporary table. Instead, it's evaluated
7944
8152
    when selecting from the temporary table. Therefore, it can't be freed
7958
8166
  */
7959
8167
  bool full= (!select_lex->uncacheable && !thd->lex->describe);
7960
8168
  bool can_unlock= full;
 
8169
  DBUG_ENTER("JOIN::join_free");
7961
8170
 
7962
8171
  cleanup(full);
7963
8172
 
7974
8183
        used any more anyway.
7975
8184
        If this join is not yet evaluated, we still must clean it up to
7976
8185
        close its table cursors -- it may never get evaluated, as in case of
7977
 
        ... HAVING false OR a IN (SELECT ...))
 
8186
        ... HAVING FALSE OR a IN (SELECT ...))
7978
8187
        but all table cursors must be closed before the unlock.
7979
8188
      */
7980
8189
      sl->cleanup_all_joins(full_local);
8000
8209
    lock= 0;
8001
8210
  }
8002
8211
 
8003
 
  return;
 
8212
  DBUG_VOID_RETURN;
8004
8213
}
8005
8214
 
8006
8215
 
8018
8227
 
8019
8228
void JOIN::cleanup(bool full)
8020
8229
{
 
8230
  DBUG_ENTER("JOIN::cleanup");
 
8231
 
8021
8232
  if (table)
8022
8233
  {
8023
8234
    JOIN_TAB *tab,*end;
8077
8288
    }
8078
8289
    tmp_table_param.cleanup();
8079
8290
  }
8080
 
  return;
 
8291
  DBUG_VOID_RETURN;
8081
8292
}
8082
8293
 
8083
8294
 
8084
8295
/**
8085
 
  Remove the following expressions from order_st BY and GROUP BY:
 
8296
  Remove the following expressions from ORDER BY and GROUP BY:
8086
8297
  Constant expressions @n
8087
8298
  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.
 
8299
  is in the ORDER list or if all refereed tables are of the above type.
8089
8300
 
8090
8301
  In the following, the X field can be removed:
8091
8302
  @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
 
8303
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
 
8304
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
8094
8305
  @endcode
8095
8306
 
8096
8307
  These can't be optimized:
8097
8308
  @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
 
8309
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
 
8310
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
 
8311
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
8101
8312
  @endcode
8102
8313
*/
8103
8314
 
8104
8315
static bool
8105
 
eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
 
8316
eq_ref_table(JOIN *join, ORDER *start_order, JOIN_TAB *tab)
8106
8317
{
8107
8318
  if (tab->cached_eq_ref_table)                 // If cached
8108
8319
    return tab->eq_ref_table;
8114
8325
    return (tab->eq_ref_table=0);               // We must use this
8115
8326
  Item **ref_item=tab->ref.items;
8116
8327
  Item **end=ref_item+tab->ref.key_parts;
8117
 
  uint32_t found=0;
 
8328
  uint found=0;
8118
8329
  table_map map=tab->table->map;
8119
8330
 
8120
8331
  for (; ref_item != end ; ref_item++)
8121
8332
  {
8122
8333
    if (! (*ref_item)->const_item())
8123
8334
    {                                           // Not a const ref
8124
 
      order_st *order;
 
8335
      ORDER *order;
8125
8336
      for (order=start_order ; order ; order=order->next)
8126
8337
      {
8127
8338
        if ((*ref_item)->eq(order->item[0],0))
8130
8341
      if (order)
8131
8342
      {
8132
8343
        found++;
8133
 
        assert(!(order->used & map));
 
8344
        DBUG_ASSERT(!(order->used & map));
8134
8345
        order->used|=map;
8135
 
        continue;                               // Used in order_st BY
 
8346
        continue;                               // Used in ORDER BY
8136
8347
      }
8137
8348
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
8138
8349
        return (tab->eq_ref_table=0);
8154
8365
 
8155
8366
 
8156
8367
static bool
8157
 
only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
 
8368
only_eq_ref_tables(JOIN *join,ORDER *order,table_map tables)
8158
8369
{
 
8370
  if (specialflag &  SPECIAL_SAFE_MODE)
 
8371
    return 0;                   // skip this optimize /* purecov: inspected */
8159
8372
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
8160
8373
  {
8161
8374
    if (tables & 1 && !eq_ref_table(join, order, *tab))
8176
8389
    TABLE_REF *ref= &join_tab->ref;
8177
8390
    table_map depend_map=0;
8178
8391
    Item **item=ref->items;
8179
 
    uint32_t i;
 
8392
    uint i;
8180
8393
    for (i=0 ; i < ref->key_parts ; i++,item++)
8181
8394
      depend_map|=(*item)->used_tables();
8182
8395
    ref->depend_map=depend_map & ~OUTER_REF_TABLE_BIT;
8194
8407
 
8195
8408
/** Update the dependency map for the sort order. */
8196
8409
 
8197
 
static void update_depend_map(JOIN *join, order_st *order)
 
8410
static void update_depend_map(JOIN *join, ORDER *order)
8198
8411
{
8199
8412
  for (; order ; order=order->next)
8200
8413
  {
8218
8431
 
8219
8432
 
8220
8433
/**
8221
 
  Remove all constants and check if order_st only contains simple
 
8434
  Remove all constants and check if ORDER only contains simple
8222
8435
  expressions.
8223
8436
 
8224
8437
  simple_order is set to 1 if sort_order only uses fields from head table
8236
8449
    Returns new sort order
8237
8450
*/
8238
8451
 
8239
 
static order_st *
8240
 
remove_const(JOIN *join,order_st *first_order, COND *cond,
 
8452
static ORDER *
 
8453
remove_const(JOIN *join,ORDER *first_order, COND *cond,
8241
8454
             bool change_list, bool *simple_order)
8242
8455
{
8243
8456
  if (join->tables == join->const_tables)
8244
8457
    return change_list ? 0 : first_order;               // No need to sort
8245
8458
 
8246
 
  order_st *order,**prev_ptr;
 
8459
  ORDER *order,**prev_ptr;
8247
8460
  table_map first_table= join->join_tab[join->const_tables].table->map;
8248
8461
  table_map not_const_tables= ~join->const_table_map;
8249
8462
  table_map ref;
 
8463
  DBUG_ENTER("remove_const");
8250
8464
 
8251
8465
  prev_ptr= &first_order;
8252
8466
  *simple_order= *join->join_tab[join->const_tables].on_expr_ref ? 0 : 1;
8263
8477
    {
8264
8478
      if (order->item[0]->with_subselect)
8265
8479
        order->item[0]->val_str(&order->item[0]->str_value);
 
8480
      DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
8266
8481
      continue;                                 // skip const item
8267
8482
    }
8268
8483
    else
8274
8489
        Item *comp_item=0;
8275
8490
        if (cond && const_expression_in_where(cond,order->item[0], &comp_item))
8276
8491
        {
 
8492
          DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
8277
8493
          continue;
8278
8494
        }
8279
8495
        if ((ref=order_tables & (not_const_tables ^ first_table)))
8281
8497
          if (!(order_tables & first_table) &&
8282
8498
              only_eq_ref_tables(join,first_order, ref))
8283
8499
          {
 
8500
            DBUG_PRINT("info",("removing: %s", order->item[0]->full_name()));
8284
8501
            continue;
8285
8502
          }
8286
8503
          *simple_order=0;                      // Must do a temp table to sort
8295
8512
    *prev_ptr=0;
8296
8513
  if (prev_ptr == &first_order)                 // Nothing to sort/group
8297
8514
    *simple_order=1;
8298
 
  return(first_order);
 
8515
  DBUG_PRINT("exit",("simple_order: %d",(int) *simple_order));
 
8516
  DBUG_RETURN(first_order);
8299
8517
}
8300
8518
 
8301
8519
 
8302
8520
static int
8303
 
return_zero_rows(JOIN *join, select_result *result,TableList *tables,
8304
 
                 List<Item> &fields, bool send_row, uint64_t select_options,
 
8521
return_zero_rows(JOIN *join, select_result *result,TABLE_LIST *tables,
 
8522
                 List<Item> &fields, bool send_row, ulonglong select_options,
8305
8523
                 const char *info, Item *having)
8306
8524
{
 
8525
  DBUG_ENTER("return_zero_rows");
 
8526
 
8307
8527
  if (select_options & SELECT_DESCRIBE)
8308
8528
  {
8309
 
    select_describe(join, false, false, false, info);
8310
 
    return(0);
 
8529
    select_describe(join, FALSE, FALSE, FALSE, info);
 
8530
    DBUG_RETURN(0);
8311
8531
  }
8312
8532
 
8313
8533
  join->join_free();
8314
8534
 
8315
8535
  if (send_row)
8316
8536
  {
8317
 
    for (TableList *table= tables; table; table= table->next_leaf)
 
8537
    for (TABLE_LIST *table= tables; table; table= table->next_leaf)
8318
8538
      mark_as_null_row(table->table);           // All fields are NULL
8319
8539
    if (having && having->val_int() == 0)
8320
8540
      send_row=0;
8334
8554
  }
8335
8555
  /* Update results for FOUND_ROWS */
8336
8556
  join->thd->limit_found_rows= join->thd->examined_row_count= 0;
8337
 
  return(0);
 
8557
  DBUG_RETURN(0);
8338
8558
}
8339
8559
 
8340
8560
/*
8346
8566
    must clear only the non-const tables, as const tables
8347
8567
    are not re-calculated.
8348
8568
  */
8349
 
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
 
8569
  for (uint i=join->const_tables ; i < join->tables ; i++)
8350
8570
    mark_as_null_row(join->table[i]);           // All fields are NULL
8351
8571
}
8352
8572
 
8356
8576
  Remove all dummy tests 'item = item', 'const op const'.
8357
8577
  Remove all 'item is NULL', when item can never be null!
8358
8578
  item->marker should be 0 for all items on entry
8359
 
  Return in cond_value false if condition is impossible (1 = 2)
 
8579
  Return in cond_value FALSE if condition is impossible (1 = 2)
8360
8580
*****************************************************************************/
8361
8581
 
8362
8582
class COND_CMP :public ilink {
8386
8606
  The function retrieves the multiple equalities accessed through
8387
8607
  the con_equal structure from current level and up looking for
8388
8608
  an equality containing field. It stops retrieval as soon as the equality
8389
 
  is found and set up inherited_fl to true if it's found on upper levels.
 
8609
  is found and set up inherited_fl to TRUE if it's found on upper levels.
8390
8610
 
8391
8611
  @param cond_equal          multiple equalities to search in
8392
8612
  @param field               field to look for
8393
 
  @param[out] inherited_fl   set up to true if multiple equality is found
 
8613
  @param[out] inherited_fl   set up to TRUE if multiple equality is found
8394
8614
                             on upper levels (not on current level of
8395
8615
                             cond_equal)
8396
8616
 
8403
8623
                            bool *inherited_fl)
8404
8624
{
8405
8625
  Item_equal *item= 0;
8406
 
  bool in_upper_level= false;
 
8626
  bool in_upper_level= FALSE;
8407
8627
  while (cond_equal)
8408
8628
  {
8409
8629
    List_iterator_fast<Item_equal> li(cond_equal->current_level);
8412
8632
      if (item->contains(field))
8413
8633
        goto finish;
8414
8634
    }
8415
 
    in_upper_level= true;
 
8635
    in_upper_level= TRUE;
8416
8636
    cond_equal= cond_equal->upper_levels;
8417
8637
  }
8418
 
  in_upper_level= false;
 
8638
  in_upper_level= FALSE;
8419
8639
finish:
8420
8640
  *inherited_fl= in_upper_level;
8421
8641
  return item;
8498
8718
                     equality
8499
8719
 
8500
8720
  @retval
8501
 
    true    if the predicate is a simple equality predicate to be used
 
8721
    TRUE    if the predicate is a simple equality predicate to be used
8502
8722
    for building multiple equalities
8503
8723
  @retval
8504
 
    false   otherwise
 
8724
    FALSE   otherwise
8505
8725
*/
8506
8726
 
8507
8727
static bool check_simple_equality(Item *left_item, Item *right_item,
8511
8731
      ((Item_ref*)left_item)->ref_type() == Item_ref::VIEW_REF)
8512
8732
  {
8513
8733
    if (((Item_ref*)left_item)->depended_from)
8514
 
      return false;
 
8734
      return FALSE;
8515
8735
    left_item= left_item->real_item();
8516
8736
  }
8517
8737
  if (right_item->type() == Item::REF_ITEM &&
8518
8738
      ((Item_ref*)right_item)->ref_type() == Item_ref::VIEW_REF)
8519
8739
  {
8520
8740
    if (((Item_ref*)right_item)->depended_from)
8521
 
      return false;
 
8741
      return FALSE;
8522
8742
    right_item= right_item->real_item();
8523
8743
  }
8524
8744
  if (left_item->type() == Item::FIELD_ITEM &&
8532
8752
    Field *right_field= ((Item_field*) right_item)->field;
8533
8753
 
8534
8754
    if (!left_field->eq_def(right_field))
8535
 
      return false;
 
8755
      return FALSE;
8536
8756
 
8537
8757
    /* Search for multiple equalities containing field1 and/or field2 */
8538
8758
    bool left_copyfl, right_copyfl;
8541
8761
    Item_equal *right_item_equal= 
8542
8762
               find_item_equal(cond_equal, right_field, &right_copyfl);
8543
8763
 
8544
 
    /* As (NULL=NULL) != true we can't just remove the predicate f=f */
 
8764
    /* As (NULL=NULL) != TRUE we can't just remove the predicate f=f */
8545
8765
    if (left_field->eq(right_field)) /* f = f */
8546
8766
      return (!(left_field->maybe_null() && !left_item_equal)); 
8547
8767
 
8552
8772
        multiple equalities, i.e the condition is already covered
8553
8773
        by upper level equalities
8554
8774
      */
8555
 
       return true;
 
8775
       return TRUE;
8556
8776
    }
8557
8777
    
8558
8778
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name && 
8609
8829
          item_equal->name = item->name;
8610
8830
      }
8611
8831
    }
8612
 
    return true;
 
8832
    return TRUE;
8613
8833
  }
8614
8834
 
8615
8835
  {
8638
8858
 
8639
8859
      if (field_item->result_type() == STRING_RESULT)
8640
8860
      {
8641
 
        const CHARSET_INFO * const cs= ((Field_str*) field_item->field)->charset();
 
8861
        CHARSET_INFO *cs= ((Field_str*) field_item->field)->charset();
8642
8862
        if (!item)
8643
8863
        {
8644
8864
          Item_func_eq *eq_item;
8645
8865
          if ((eq_item= new Item_func_eq(left_item, right_item)))
8646
 
            return false;
 
8866
            return FALSE;
8647
8867
          eq_item->set_cmp_func();
8648
8868
          eq_item->quick_fix_field();
8649
8869
          item= eq_item;
8650
8870
        }  
8651
8871
        if ((cs != ((Item_func *) item)->compare_collation()) ||
8652
8872
            !cs->coll->propagate(cs, 0, 0))
8653
 
          return false;
 
8873
          return FALSE;
8654
8874
      }
8655
8875
 
8656
8876
      Item_equal *item_equal = find_item_equal(cond_equal,
8674
8894
        item_equal= new Item_equal(const_item, field_item);
8675
8895
        cond_equal->current_level.push_back(item_equal);
8676
8896
      }
8677
 
      return true;
 
8897
      return TRUE;
8678
8898
    }
8679
8899
  }
8680
 
  return false;
 
8900
  return FALSE;
8681
8901
}
8682
8902
 
8683
8903
 
8702
8922
                    simple enough to form multiple equalities
8703
8923
 
8704
8924
  @retval
8705
 
    true    if conversion has succeeded (no fatal error)
 
8925
    TRUE    if conversion has succeeded (no fatal error)
8706
8926
  @retval
8707
 
    false   otherwise
 
8927
    FALSE   otherwise
8708
8928
*/
8709
8929
 
8710
8930
static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row,
8711
8931
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
8712
8932
8713
 
  uint32_t n= left_row->cols();
8714
 
  for (uint32_t i= 0 ; i < n; i++)
 
8933
  uint n= left_row->cols();
 
8934
  for (uint i= 0 ; i < n; i++)
8715
8935
  {
8716
8936
    bool is_converted;
8717
8937
    Item *left_item= left_row->element_index(i);
8736
8956
    {
8737
8957
      Item_func_eq *eq_item;
8738
8958
      if (!(eq_item= new Item_func_eq(left_item, right_item)))
8739
 
        return false;
 
8959
        return FALSE;
8740
8960
      eq_item->set_cmp_func();
8741
8961
      eq_item->quick_fix_field();
8742
8962
      eq_list->push_back(eq_item);
8743
8963
    }
8744
8964
  }
8745
 
  return true;
 
8965
  return TRUE;
8746
8966
}
8747
8967
 
8748
8968
 
8768
8988
                    simple enough to form multiple equalities
8769
8989
 
8770
8990
  @retval
8771
 
    true   if re-writing rules have been applied
 
8991
    TRUE   if re-writing rules have been applied
8772
8992
  @retval
8773
 
    false  otherwise, i.e.
 
8993
    FALSE  otherwise, i.e.
8774
8994
           if the predicate is not an equality,
8775
8995
           or, if the equality is neither a simple one nor a row equality,
8776
8996
           or, if the procedure fails by a fatal error.
8797
9017
    else 
8798
9018
      return check_simple_equality(left_item, right_item, item, cond_equal);
8799
9019
  } 
8800
 
  return false;
 
9020
  return FALSE;
8801
9021
}
8802
9022
 
8803
9023
                          
8955
9175
    {
8956
9176
      int n= cond_equal.current_level.elements + eq_list.elements;
8957
9177
      if (n == 0)
8958
 
        return new Item_int((int64_t) 1,1);
 
9178
        return new Item_int((longlong) 1,1);
8959
9179
      else if (n == 1)
8960
9180
      {
8961
9181
        if ((item_equal= cond_equal.current_level.pop()))
8998
9218
      as soon the field is not of a string type or the field reference is
8999
9219
      an argument of a comparison predicate. 
9000
9220
    */ 
9001
 
    unsigned char *is_subst_valid= (unsigned char *) 1;
 
9221
    uchar *is_subst_valid= (uchar *) 1;
9002
9222
    cond= cond->compile(&Item::subst_argument_checker,
9003
9223
                        &is_subst_valid, 
9004
9224
                        &Item::equal_fields_propagator,
9005
 
                        (unsigned char *) inherited);
 
9225
                        (uchar *) inherited);
9006
9226
    cond->update_used_tables();
9007
9227
  }
9008
9228
  return cond;
9077
9297
   
9078
9298
static COND *build_equal_items(THD *thd, COND *cond,
9079
9299
                               COND_EQUAL *inherited,
9080
 
                               List<TableList> *join_list,
 
9300
                               List<TABLE_LIST> *join_list,
9081
9301
                               COND_EQUAL **cond_equal_ref)
9082
9302
{
9083
9303
  COND_EQUAL *cond_equal= 0;
9105
9325
 
9106
9326
  if (join_list)
9107
9327
  {
9108
 
    TableList *table;
9109
 
    List_iterator<TableList> li(*join_list);
 
9328
    TABLE_LIST *table;
 
9329
    List_iterator<TABLE_LIST> li(*join_list);
9110
9330
 
9111
9331
    while ((table= li++))
9112
9332
    {
9113
9333
      if (table->on_expr)
9114
9334
      {
9115
 
        List<TableList> *nested_join_list= table->nested_join ?
 
9335
        List<TABLE_LIST> *nested_join_list= table->nested_join ?
9116
9336
          &table->nested_join->join_list : NULL;
9117
9337
        /*
9118
9338
          We can modify table->on_expr because its old value will
9219
9439
  List<Item> eq_list;
9220
9440
  Item_func_eq *eq_item= 0;
9221
9441
  if (((Item *) item_equal)->const_item() && !item_equal->val_int())
9222
 
    return new Item_int((int64_t) 0,1); 
 
9442
    return new Item_int((longlong) 0,1); 
9223
9443
  Item *item_const= item_equal->get_const();
9224
9444
  Item_equal_iterator it(*item_equal);
9225
9445
  Item *head;
9264
9484
  if (!cond && !eq_list.head())
9265
9485
  {
9266
9486
    if (!eq_item)
9267
 
      return new Item_int((int64_t) 1,1);
 
9487
      return new Item_int((longlong) 1,1);
9268
9488
    return eq_item;
9269
9489
  }
9270
9490
 
9274
9494
    cond= new Item_cond_and(eq_list);
9275
9495
  else
9276
9496
  {
9277
 
    assert(cond->type() == Item::COND_ITEM);
 
9497
    DBUG_ASSERT(cond->type() == Item::COND_ITEM);
9278
9498
    ((Item_cond *) cond)->add_at_head(&eq_list);
9279
9499
  }
9280
9500
 
9366
9586
    }
9367
9587
    if (cond->type() == Item::COND_ITEM &&
9368
9588
        !((Item_cond*)cond)->argument_list()->elements)
9369
 
      cond= new Item_int((int32_t)cond->val_bool());
 
9589
      cond= new Item_int((int32)cond->val_bool());
9370
9590
 
9371
9591
  }
9372
9592
  else if (cond->type() == Item::FUNC_ITEM && 
9436
9656
        */  
9437
9657
        if (!possible_keys.is_clear_all())
9438
9658
        {
9439
 
          Table *tab= field->table;
 
9659
          TABLE *tab= field->table;
9440
9660
          KEYUSE *use;
9441
9661
          for (use= stat->keyuse; use && use->table == tab; use++)
9442
9662
            if (possible_keys.is_set(use->key) && 
9748
9968
*/
9749
9969
 
9750
9970
static COND *
9751
 
simplify_joins(JOIN *join, List<TableList> *join_list, COND *conds, bool top,
 
9971
simplify_joins(JOIN *join, List<TABLE_LIST> *join_list, COND *conds, bool top,
9752
9972
               bool in_sj)
9753
9973
{
9754
 
  TableList *table;
9755
 
  nested_join_st *nested_join;
9756
 
  TableList *prev_table= 0;
9757
 
  List_iterator<TableList> li(*join_list);
 
9974
  TABLE_LIST *table;
 
9975
  NESTED_JOIN *nested_join;
 
9976
  TABLE_LIST *prev_table= 0;
 
9977
  List_iterator<TABLE_LIST> li(*join_list);
 
9978
  DBUG_ENTER("simplify_joins");
9758
9979
 
9759
9980
  /* 
9760
9981
    Try to simplify join operations from join_list.
9783
10004
           the corresponding on expression is added to E. 
9784
10005
        */ 
9785
10006
        expr= simplify_joins(join, &nested_join->join_list,
9786
 
                             expr, false, in_sj || table->sj_on_expr);
 
10007
                             expr, FALSE, in_sj || table->sj_on_expr);
9787
10008
 
9788
10009
        if (!table->prep_on_expr || expr != table->on_expr)
9789
10010
        {
9790
 
          assert(expr);
 
10011
          DBUG_ASSERT(expr);
9791
10012
 
9792
10013
          table->on_expr= expr;
9793
10014
          table->prep_on_expr= expr->copy_andor_structure(join->thd);
9830
10051
          conds= and_conds(conds, table->on_expr);
9831
10052
          conds->top_level_item();
9832
10053
          /* conds is always a new item as both cond and on_expr existed */
9833
 
          assert(!conds->fixed);
 
10054
          DBUG_ASSERT(!conds->fixed);
9834
10055
          conds->fix_fields(join->thd, &conds);
9835
10056
        }
9836
10057
        else
9904
10125
    }
9905
10126
    else if (nested_join && !table->on_expr)
9906
10127
    {
9907
 
      TableList *tbl;
9908
 
      List_iterator<TableList> it(nested_join->join_list);
 
10128
      TABLE_LIST *tbl;
 
10129
      List_iterator<TABLE_LIST> it(nested_join->join_list);
9909
10130
      while ((tbl= it++))
9910
10131
      {
9911
10132
        tbl->embedding= table->embedding;
9914
10135
      li.replace(nested_join->join_list);
9915
10136
    }
9916
10137
  }
9917
 
  return(conds); 
 
10138
  DBUG_RETURN(conds); 
9918
10139
}
9919
10140
 
9920
10141
 
9938
10159
    First unused bit in nested_join_map after the call.
9939
10160
*/
9940
10161
 
9941
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, 
9942
 
                                          uint32_t first_unused)
 
10162
static uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list, 
 
10163
                                          uint first_unused)
9943
10164
{
9944
 
  List_iterator<TableList> li(*join_list);
9945
 
  TableList *table;
 
10165
  List_iterator<TABLE_LIST> li(*join_list);
 
10166
  TABLE_LIST *table;
 
10167
  DBUG_ENTER("build_bitmap_for_nested_joins");
9946
10168
  while ((table= li++))
9947
10169
  {
9948
 
    nested_join_st *nested_join;
 
10170
    NESTED_JOIN *nested_join;
9949
10171
    if ((nested_join= table->nested_join))
9950
10172
    {
9951
10173
      /*
9969
10191
      }
9970
10192
    }
9971
10193
  }
9972
 
  return(first_unused);
 
10194
  DBUG_RETURN(first_unused);
9973
10195
}
9974
10196
 
9975
10197
 
9976
10198
/**
9977
 
  Set nested_join_st::counter=0 in all nested joins in passed list.
 
10199
  Set NESTED_JOIN::counter=0 in all nested joins in passed list.
9978
10200
 
9979
 
    Recursively set nested_join_st::counter=0 for all nested joins contained in
 
10201
    Recursively set NESTED_JOIN::counter=0 for all nested joins contained in
9980
10202
    the passed join_list.
9981
10203
 
9982
10204
  @param join_list  List of nested joins to process. It may also contain base
9983
10205
                    tables which will be ignored.
9984
10206
*/
9985
10207
 
9986
 
static void reset_nj_counters(List<TableList> *join_list)
 
10208
static void reset_nj_counters(List<TABLE_LIST> *join_list)
9987
10209
{
9988
 
  List_iterator<TableList> li(*join_list);
9989
 
  TableList *table;
 
10210
  List_iterator<TABLE_LIST> li(*join_list);
 
10211
  TABLE_LIST *table;
 
10212
  DBUG_ENTER("reset_nj_counters");
9990
10213
  while ((table= li++))
9991
10214
  {
9992
 
    nested_join_st *nested_join;
 
10215
    NESTED_JOIN *nested_join;
9993
10216
    if ((nested_join= table->nested_join))
9994
10217
    {
9995
10218
      nested_join->counter_= 0;
9996
10219
      reset_nj_counters(&nested_join->join_list);
9997
10220
    }
9998
10221
  }
9999
 
  return;
 
10222
  DBUG_VOID_RETURN;
10000
10223
}
10001
10224
 
10002
10225
 
10012
10235
 
10013
10236
  @verbatim
10014
10237
     IMPLEMENTATION 
10015
 
       LIMITATIONS ON JOIN order_st
 
10238
       LIMITATIONS ON JOIN ORDER
10016
10239
         The nested [outer] joins executioner algorithm imposes these limitations
10017
10240
         on join order:
10018
10241
         1. "Outer tables first" -  any "outer" table must be before any 
10076
10299
         position:
10077
10300
          1. join->cur_embedding_map - bitmap of pairs of brackets (aka nested
10078
10301
             joins) we've opened but didn't close.
10079
 
          2. {each nested_join_st structure not simplified away}->counter - number
 
10302
          2. {each NESTED_JOIN structure not simplified away}->counter - number
10080
10303
             of this nested join's children that have already been added to to
10081
10304
             the partial join order.
10082
10305
  @endverbatim
10087
10310
  @param next_tab   Table we're going to extend the current partial join with
10088
10311
 
10089
10312
  @retval
10090
 
    false  Join order extended, nested joins info about current join
 
10313
    FALSE  Join order extended, nested joins info about current join
10091
10314
    order (see NOTE section) updated.
10092
10315
  @retval
10093
 
    true   Requested join order extension not allowed.
 
10316
    TRUE   Requested join order extension not allowed.
10094
10317
*/
10095
10318
 
10096
10319
static bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
10097
10320
{
10098
 
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
 
10321
  TABLE_LIST *next_emb= next_tab->table->pos_in_table_list->embedding;
10099
10322
  JOIN *join= last_tab->join;
10100
10323
 
10101
10324
  if (join->cur_embedding_map & ~next_tab->embedding_map)
10104
10327
      next_tab is outside of the "pair of brackets" we're currently in.
10105
10328
      Cannot add it.
10106
10329
    */
10107
 
    return true;
 
10330
    return TRUE;
10108
10331
  }
10109
10332
   
10110
10333
  /*
10134
10357
    */
10135
10358
    join->cur_embedding_map &= ~next_emb->nested_join->nj_map;
10136
10359
  }
10137
 
  return false;
 
10360
  return FALSE;
10138
10361
}
10139
10362
 
10140
10363
 
10152
10375
 
10153
10376
static void restore_prev_nj_state(JOIN_TAB *last)
10154
10377
{
10155
 
  TableList *last_emb= last->table->pos_in_table_list->embedding;
 
10378
  TABLE_LIST *last_emb= last->table->pos_in_table_list->embedding;
10156
10379
  JOIN *join= last->join;
10157
10380
  while (last_emb)
10158
10381
  {
10175
10398
static 
10176
10399
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
10177
10400
{
10178
 
  TableList *emb_sj_nest;
 
10401
  TABLE_LIST *emb_sj_nest;
10179
10402
  if ((emb_sj_nest= tab->emb_sj_nest))
10180
10403
  {
10181
10404
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
10193
10416
static void restore_prev_sj_state(const table_map remaining_tables, 
10194
10417
                                  const JOIN_TAB *tab)
10195
10418
{
10196
 
  TableList *emb_sj_nest;
 
10419
  TABLE_LIST *emb_sj_nest;
10197
10420
  if ((emb_sj_nest= tab->emb_sj_nest))
10198
10421
  {
10199
10422
    /* If we're removing the last SJ-inner table, remove the sj-nest */
10207
10430
 
10208
10431
 
10209
10432
static COND *
10210
 
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
 
10433
optimize_cond(JOIN *join, COND *conds, List<TABLE_LIST> *join_list,
10211
10434
              Item::cond_result *cond_value)
10212
10435
{
10213
10436
  THD *thd= join->thd;
 
10437
  DBUG_ENTER("optimize_cond");
10214
10438
 
10215
10439
  if (!conds)
10216
10440
    *cond_value= Item::COND_TRUE;
10224
10448
      predicate. Substitute a constant instead of this field if the
10225
10449
      multiple equality contains a constant.
10226
10450
    */ 
 
10451
    DBUG_EXECUTE("where", print_where(conds, "original", QT_ORDINARY););
10227
10452
    conds= build_equal_items(join->thd, conds, NULL, join_list,
10228
10453
                             &join->cond_equal);
 
10454
    DBUG_EXECUTE("where",print_where(conds,"after equal_items", QT_ORDINARY););
10229
10455
 
10230
10456
    /* change field = field to field = const for each found field = const */
10231
10457
    propagate_cond_constants(thd, (I_List<COND_CMP> *) 0, conds, conds);
10233
10459
      Remove all instances of item == item
10234
10460
      Remove all and-levels where CONST item != CONST item
10235
10461
    */
 
10462
    DBUG_EXECUTE("where",print_where(conds,"after const change", QT_ORDINARY););
10236
10463
    conds= remove_eq_conds(thd, conds, cond_value) ;
 
10464
    DBUG_EXECUTE("info",print_where(conds,"after remove", QT_ORDINARY););
10237
10465
  }
10238
 
  return(conds);
 
10466
  DBUG_RETURN(conds);
10239
10467
}
10240
10468
 
10241
10469
 
10270
10498
        li.remove();
10271
10499
      else if (item != new_item)
10272
10500
      {
10273
 
        li.replace(new_item);
 
10501
        VOID(li.replace(new_item));
10274
10502
        should_fix_fields=1;
10275
10503
      }
10276
10504
      if (*cond_value == Item::COND_UNDEF)
10277
10505
        *cond_value=tmp_cond_value;
10278
10506
      switch (tmp_cond_value) {
10279
 
      case Item::COND_OK:                       // Not true or false
 
10507
      case Item::COND_OK:                       // Not TRUE or FALSE
10280
10508
        if (and_level || *cond_value == Item::COND_FALSE)
10281
10509
          *cond_value=tmp_cond_value;
10282
10510
        break;
10352
10580
          IS NULL should be mapped to LAST_INSERT_ID only for first row, so
10353
10581
          clear for next row
10354
10582
        */
10355
 
        thd->substitute_null_with_insert_id= false;
 
10583
        thd->substitute_null_with_insert_id= FALSE;
10356
10584
      }
10357
10585
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
10358
 
      else if (((field->type() == DRIZZLE_TYPE_NEWDATE) ||
10359
 
                (field->type() == DRIZZLE_TYPE_DATETIME)) &&
 
10586
      else if (((field->type() == MYSQL_TYPE_DATE) ||
 
10587
                (field->type() == MYSQL_TYPE_DATETIME)) &&
10360
10588
                (field->flags & NOT_NULL_FLAG) &&
10361
10589
               !field->table->maybe_null)
10362
10590
      {
10429
10657
    well as the collation of the arguments.
10430
10658
  
10431
10659
  RETURN VALUE  
10432
 
    true    can be used
10433
 
    false   cannot be used
 
10660
    TRUE    can be used
 
10661
    FALSE   cannot be used
10434
10662
*/
10435
10663
static bool
10436
10664
test_if_equality_guarantees_uniqueness(Item *l, Item *r)
10446
10674
}
10447
10675
 
10448
10676
/**
10449
 
  Return true if the item is a const value in all the WHERE clause.
 
10677
  Return TRUE if the item is a const value in all the WHERE clause.
10450
10678
*/
10451
10679
 
10452
10680
static bool
10503
10731
  return 0;
10504
10732
}
10505
10733
 
 
10734
/****************************************************************************
 
10735
  Create internal temporary table
 
10736
****************************************************************************/
 
10737
 
 
10738
/**
 
10739
  Create field for temporary table from given field.
 
10740
 
 
10741
  @param thd           Thread handler
 
10742
  @param org_field    field from which new field will be created
 
10743
  @param name         New field name
 
10744
  @param table         Temporary table
 
10745
  @param item          !=NULL if item->result_field should point to new field.
 
10746
                      This is relevant for how fill_record() is going to work:
 
10747
                      If item != NULL then fill_record() will update
 
10748
                      the record in the original table.
 
10749
                      If item == NULL then fill_record() will update
 
10750
                      the temporary table
 
10751
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
10752
                               field instead of blob.
 
10753
 
 
10754
  @retval
 
10755
    NULL                on error
 
10756
  @retval
 
10757
    new_created field
 
10758
*/
 
10759
 
 
10760
Field *create_tmp_field_from_field(THD *thd, Field *org_field,
 
10761
                                   const char *name, TABLE *table,
 
10762
                                   Item_field *item, uint convert_blob_length)
 
10763
{
 
10764
  Field *new_field;
 
10765
 
 
10766
  /* 
 
10767
    Make sure that the blob fits into a Field_varstring which has 
 
10768
    2-byte lenght. 
 
10769
  */
 
10770
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
 
10771
      (org_field->flags & BLOB_FLAG))
 
10772
    new_field= new Field_varstring(convert_blob_length,
 
10773
                                   org_field->maybe_null(),
 
10774
                                   org_field->field_name, table->s,
 
10775
                                   org_field->charset());
 
10776
  else
 
10777
    new_field= org_field->new_field(thd->mem_root, table,
 
10778
                                    table == org_field->table);
 
10779
  if (new_field)
 
10780
  {
 
10781
    new_field->init(table);
 
10782
    new_field->orig_table= org_field->orig_table;
 
10783
    if (item)
 
10784
      item->result_field= new_field;
 
10785
    else
 
10786
      new_field->field_name= name;
 
10787
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
 
10788
    if (org_field->maybe_null() || (item && item->maybe_null))
 
10789
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
 
10790
    if (org_field->type() == MYSQL_TYPE_VAR_STRING ||
 
10791
        org_field->type() == MYSQL_TYPE_VARCHAR)
 
10792
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
 
10793
    else if (org_field->type() == FIELD_TYPE_DOUBLE)
 
10794
      ((Field_double *) new_field)->not_fixed= TRUE;
 
10795
  }
 
10796
  return new_field;
 
10797
}
 
10798
 
 
10799
/**
 
10800
  Create field for temporary table using type of given item.
 
10801
 
 
10802
  @param thd                   Thread handler
 
10803
  @param item                  Item to create a field for
 
10804
  @param table                 Temporary table
 
10805
  @param copy_func             If set and item is a function, store copy of
 
10806
                               item in this array
 
10807
  @param modify_item           1 if item->result_field should point to new
 
10808
                               item. This is relevent for how fill_record()
 
10809
                               is going to work:
 
10810
                               If modify_item is 1 then fill_record() will
 
10811
                               update the record in the original table.
 
10812
                               If modify_item is 0 then fill_record() will
 
10813
                               update the temporary table
 
10814
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
 
10815
                               field instead of blob.
 
10816
 
 
10817
  @retval
 
10818
    0  on error
 
10819
  @retval
 
10820
    new_created field
 
10821
*/
 
10822
 
 
10823
static Field *create_tmp_field_from_item(THD *thd, Item *item, TABLE *table,
 
10824
                                         Item ***copy_func, bool modify_item,
 
10825
                                         uint convert_blob_length)
 
10826
{
 
10827
  bool maybe_null= item->maybe_null;
 
10828
  Field *new_field;
 
10829
 
 
10830
  switch (item->result_type()) {
 
10831
  case REAL_RESULT:
 
10832
    new_field= new Field_double(item->max_length, maybe_null,
 
10833
                                item->name, item->decimals, TRUE);
 
10834
    break;
 
10835
  case INT_RESULT:
 
10836
    /* 
 
10837
      Select an integer type with the minimal fit precision.
 
10838
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
 
10839
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into 
 
10840
      Field_long : make them Field_longlong.  
 
10841
    */
 
10842
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
 
10843
      new_field=new Field_longlong(item->max_length, maybe_null,
 
10844
                                   item->name, item->unsigned_flag);
 
10845
    else
 
10846
      new_field=new Field_long(item->max_length, maybe_null,
 
10847
                               item->name, item->unsigned_flag);
 
10848
    break;
 
10849
  case STRING_RESULT:
 
10850
    DBUG_ASSERT(item->collation.collation);
 
10851
  
 
10852
    enum enum_field_types type;
 
10853
    /*
 
10854
      DATE/TIME fields have STRING_RESULT result type. 
 
10855
      To preserve type they needed to be handled separately.
 
10856
    */
 
10857
    if ((type= item->field_type()) == MYSQL_TYPE_DATETIME ||
 
10858
        type == MYSQL_TYPE_TIME || type == MYSQL_TYPE_DATE ||
 
10859
        type == MYSQL_TYPE_TIMESTAMP)
 
10860
      new_field= item->tmp_table_field_from_field_type(table, 1);
 
10861
    /* 
 
10862
      Make sure that the blob fits into a Field_varstring which has 
 
10863
      2-byte lenght. 
 
10864
    */
 
10865
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
 
10866
             convert_blob_length <= Field_varstring::MAX_SIZE && 
 
10867
             convert_blob_length)
 
10868
      new_field= new Field_varstring(convert_blob_length, maybe_null,
 
10869
                                     item->name, table->s,
 
10870
                                     item->collation.collation);
 
10871
    else
 
10872
      new_field= item->make_string_field(table);
 
10873
    new_field->set_derivation(item->collation.derivation);
 
10874
    break;
 
10875
  case DECIMAL_RESULT:
 
10876
  {
 
10877
    uint8 dec= item->decimals;
 
10878
    uint8 intg= ((Item_decimal *) item)->decimal_precision() - dec;
 
10879
    uint32 len= item->max_length;
 
10880
 
 
10881
    /*
 
10882
      Trying to put too many digits overall in a DECIMAL(prec,dec)
 
10883
      will always throw a warning. We must limit dec to
 
10884
      DECIMAL_MAX_SCALE however to prevent an assert() later.
 
10885
    */
 
10886
 
 
10887
    if (dec > 0)
 
10888
    {
 
10889
      signed int overflow;
 
10890
 
 
10891
      dec= min(dec, DECIMAL_MAX_SCALE);
 
10892
 
 
10893
      /*
 
10894
        If the value still overflows the field with the corrected dec,
 
10895
        we'll throw out decimals rather than integers. This is still
 
10896
        bad and of course throws a truncation warning.
 
10897
        +1: for decimal point
 
10898
      */
 
10899
 
 
10900
      overflow= my_decimal_precision_to_length(intg + dec, dec,
 
10901
                                               item->unsigned_flag) - len;
 
10902
 
 
10903
      if (overflow > 0)
 
10904
        dec= max(0, dec - overflow);            // too long, discard fract
 
10905
      else
 
10906
        len -= item->decimals - dec;            // corrected value fits
 
10907
    }
 
10908
 
 
10909
    new_field= new Field_new_decimal(len, maybe_null, item->name,
 
10910
                                     dec, item->unsigned_flag);
 
10911
    break;
 
10912
  }
 
10913
  case ROW_RESULT:
 
10914
  default:
 
10915
    // This case should never be choosen
 
10916
    DBUG_ASSERT(0);
 
10917
    new_field= 0;
 
10918
    break;
 
10919
  }
 
10920
  if (new_field)
 
10921
    new_field->init(table);
 
10922
    
 
10923
  if (copy_func && item->is_result_field())
 
10924
    *((*copy_func)++) = item;                   // Save for copy_funcs
 
10925
  if (modify_item)
 
10926
    item->set_result_field(new_field);
 
10927
  if (item->type() == Item::NULL_ITEM)
 
10928
    new_field->is_created_from_null_item= TRUE;
 
10929
  return new_field;
 
10930
}
 
10931
 
 
10932
 
 
10933
/**
 
10934
  Create field for information schema table.
 
10935
 
 
10936
  @param thd            Thread handler
 
10937
  @param table          Temporary table
 
10938
  @param item           Item to create a field for
 
10939
 
 
10940
  @retval
 
10941
    0                   on error
 
10942
  @retval
 
10943
    new_created field
 
10944
*/
 
10945
 
 
10946
Field *create_tmp_field_for_schema(THD *thd, Item *item, TABLE *table)
 
10947
{
 
10948
  if (item->field_type() == MYSQL_TYPE_VARCHAR)
 
10949
  {
 
10950
    Field *field;
 
10951
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
 
10952
      field= new Field_blob(item->max_length, item->maybe_null,
 
10953
                            item->name, item->collation.collation);
 
10954
    else
 
10955
      field= new Field_varstring(item->max_length, item->maybe_null,
 
10956
                                 item->name,
 
10957
                                 table->s, item->collation.collation);
 
10958
    if (field)
 
10959
      field->init(table);
 
10960
    return field;
 
10961
  }
 
10962
  return item->tmp_table_field_from_field_type(table, 0);
 
10963
}
 
10964
 
 
10965
 
 
10966
/**
 
10967
  Create field for temporary table.
 
10968
 
 
10969
  @param thd            Thread handler
 
10970
  @param table          Temporary table
 
10971
  @param item           Item to create a field for
 
10972
  @param type           Type of item (normally item->type)
 
10973
  @param copy_func      If set and item is a function, store copy of item
 
10974
                       in this array
 
10975
  @param from_field    if field will be created using other field as example,
 
10976
                       pointer example field will be written here
 
10977
  @param default_field  If field has a default value field, store it here
 
10978
  @param group          1 if we are going to do a relative group by on result
 
10979
  @param modify_item    1 if item->result_field should point to new item.
 
10980
                       This is relevent for how fill_record() is going to
 
10981
                       work:
 
10982
                       If modify_item is 1 then fill_record() will update
 
10983
                       the record in the original table.
 
10984
                       If modify_item is 0 then fill_record() will update
 
10985
                       the temporary table
 
10986
  @param convert_blob_length If >0 create a varstring(convert_blob_length)
 
10987
                             field instead of blob.
 
10988
 
 
10989
  @retval
 
10990
    0                   on error
 
10991
  @retval
 
10992
    new_created field
 
10993
*/
 
10994
 
 
10995
Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
 
10996
                        Item ***copy_func, Field **from_field,
 
10997
                        Field **default_field,
 
10998
                        bool group, bool modify_item,
 
10999
                        bool table_cant_handle_bit_fields,
 
11000
                        bool make_copy_field,
 
11001
                        uint convert_blob_length)
 
11002
{
 
11003
  Field *result;
 
11004
  Item::Type orig_type= type;
 
11005
  Item *orig_item= 0;
 
11006
 
 
11007
  if (type != Item::FIELD_ITEM &&
 
11008
      item->real_item()->type() == Item::FIELD_ITEM)
 
11009
  {
 
11010
    orig_item= item;
 
11011
    item= item->real_item();
 
11012
    type= Item::FIELD_ITEM;
 
11013
  }
 
11014
 
 
11015
  switch (type) {
 
11016
  case Item::SUM_FUNC_ITEM:
 
11017
  {
 
11018
    Item_sum *item_sum=(Item_sum*) item;
 
11019
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
 
11020
    if (!result)
 
11021
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
 
11022
    return result;
 
11023
  }
 
11024
  case Item::FIELD_ITEM:
 
11025
  case Item::DEFAULT_VALUE_ITEM:
 
11026
  {
 
11027
    Item_field *field= (Item_field*) item;
 
11028
    bool orig_modify= modify_item;
 
11029
    if (orig_type == Item::REF_ITEM)
 
11030
      modify_item= 0;
 
11031
    /*
 
11032
      If item have to be able to store NULLs but underlaid field can't do it,
 
11033
      create_tmp_field_from_field() can't be used for tmp field creation.
 
11034
    */
 
11035
    if (field->maybe_null && !field->field->maybe_null())
 
11036
    {
 
11037
      result= create_tmp_field_from_item(thd, item, table, NULL,
 
11038
                                         modify_item, convert_blob_length);
 
11039
      *from_field= field->field;
 
11040
      if (result && modify_item)
 
11041
        field->result_field= result;
 
11042
    } 
 
11043
    else if (table_cant_handle_bit_fields && field->field->type() ==
 
11044
             MYSQL_TYPE_BIT)
 
11045
    {
 
11046
      *from_field= field->field;
 
11047
      result= create_tmp_field_from_item(thd, item, table, copy_func,
 
11048
                                        modify_item, convert_blob_length);
 
11049
      if (result && modify_item)
 
11050
        field->result_field= result;
 
11051
    }
 
11052
    else
 
11053
      result= create_tmp_field_from_field(thd, (*from_field= field->field),
 
11054
                                          orig_item ? orig_item->name :
 
11055
                                          item->name,
 
11056
                                          table,
 
11057
                                          modify_item ? field :
 
11058
                                          NULL,
 
11059
                                          convert_blob_length);
 
11060
    if (orig_type == Item::REF_ITEM && orig_modify)
 
11061
      ((Item_ref*)orig_item)->set_result_field(result);
 
11062
    if (field->field->eq_def(result))
 
11063
      *default_field= field->field;
 
11064
    return result;
 
11065
  }
 
11066
  /* Fall through */
 
11067
  case Item::FUNC_ITEM:
 
11068
    /* Fall through */
 
11069
  case Item::COND_ITEM:
 
11070
  case Item::FIELD_AVG_ITEM:
 
11071
  case Item::FIELD_STD_ITEM:
 
11072
  case Item::SUBSELECT_ITEM:
 
11073
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
 
11074
  case Item::PROC_ITEM:
 
11075
  case Item::INT_ITEM:
 
11076
  case Item::REAL_ITEM:
 
11077
  case Item::DECIMAL_ITEM:
 
11078
  case Item::STRING_ITEM:
 
11079
  case Item::REF_ITEM:
 
11080
  case Item::NULL_ITEM:
 
11081
  case Item::VARBIN_ITEM:
 
11082
    if (make_copy_field)
 
11083
    {
 
11084
      DBUG_ASSERT(((Item_result_field*)item)->result_field);
 
11085
      *from_field= ((Item_result_field*)item)->result_field;
 
11086
    }
 
11087
    return create_tmp_field_from_item(thd, item, table,
 
11088
                                      (make_copy_field ? 0 : copy_func),
 
11089
                                       modify_item, convert_blob_length);
 
11090
  case Item::TYPE_HOLDER:  
 
11091
    result= ((Item_type_holder *)item)->make_field_by_type(table);
 
11092
    result->set_derivation(item->collation.derivation);
 
11093
    return result;
 
11094
  default:                                      // Dosen't have to be stored
 
11095
    return 0;
 
11096
  }
 
11097
}
 
11098
 
 
11099
/*
 
11100
  Set up column usage bitmaps for a temporary table
 
11101
 
 
11102
  IMPLEMENTATION
 
11103
    For temporary tables, we need one bitmap with all columns set and
 
11104
    a tmp_set bitmap to be used by things like filesort.
 
11105
*/
 
11106
 
 
11107
void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps)
 
11108
{
 
11109
  uint field_count= table->s->fields;
 
11110
  bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count,
 
11111
              FALSE);
 
11112
  bitmap_init(&table->tmp_set,
 
11113
              (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)),
 
11114
              field_count, FALSE);
 
11115
  /* write_set and all_set are copies of read_set */
 
11116
  table->def_write_set= table->def_read_set;
 
11117
  table->s->all_set= table->def_read_set;
 
11118
  bitmap_set_all(&table->s->all_set);
 
11119
  table->default_column_bitmaps();
 
11120
}
 
11121
 
 
11122
 
 
11123
/**
 
11124
  Create a temp table according to a field list.
 
11125
 
 
11126
  Given field pointers are changed to point at tmp_table for
 
11127
  send_fields. The table object is self contained: it's
 
11128
  allocated in its own memory root, as well as Field objects
 
11129
  created for table columns.
 
11130
  This function will replace Item_sum items in 'fields' list with
 
11131
  corresponding Item_field items, pointing at the fields in the
 
11132
  temporary table, unless this was prohibited by TRUE
 
11133
  value of argument save_sum_fields. The Item_field objects
 
11134
  are created in THD memory root.
 
11135
 
 
11136
  @param thd                  thread handle
 
11137
  @param param                a description used as input to create the table
 
11138
  @param fields               list of items that will be used to define
 
11139
                              column types of the table (also see NOTES)
 
11140
  @param group                TODO document
 
11141
  @param distinct             should table rows be distinct
 
11142
  @param save_sum_fields      see NOTES
 
11143
  @param select_options
 
11144
  @param rows_limit
 
11145
  @param table_alias          possible name of the temporary table that can
 
11146
                              be used for name resolving; can be "".
 
11147
*/
 
11148
 
 
11149
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
 
11150
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
 
11151
#define RATIO_TO_PACK_ROWS             2
 
11152
#define MIN_STRING_LENGTH_TO_PACK_ROWS   10
 
11153
 
 
11154
TABLE *
 
11155
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
 
11156
                 ORDER *group, bool distinct, bool save_sum_fields,
 
11157
                 ulonglong select_options, ha_rows rows_limit,
 
11158
                 char *table_alias)
 
11159
{
 
11160
  MEM_ROOT *mem_root_save, own_root;
 
11161
  TABLE *table;
 
11162
  TABLE_SHARE *share;
 
11163
  uint  i,field_count,null_count,null_pack_length;
 
11164
  uint  copy_func_count= param->func_count;
 
11165
  uint  hidden_null_count, hidden_null_pack_length, hidden_field_count;
 
11166
  uint  blob_count,group_null_items, string_count;
 
11167
  uint  temp_pool_slot=MY_BIT_NONE;
 
11168
  uint fieldnr= 0;
 
11169
  ulong reclength, string_total_length;
 
11170
  bool  using_unique_constraint= 0;
 
11171
  bool  use_packed_rows= 0;
 
11172
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
 
11173
  char  *tmpname,path[FN_REFLEN];
 
11174
  uchar *pos, *group_buff, *bitmaps;
 
11175
  uchar *null_flags;
 
11176
  Field **reg_field, **from_field, **default_field;
 
11177
  uint *blob_field;
 
11178
  Copy_field *copy=0;
 
11179
  KEY *keyinfo;
 
11180
  KEY_PART_INFO *key_part_info;
 
11181
  Item **copy_func;
 
11182
  MI_COLUMNDEF *recinfo;
 
11183
  uint total_uneven_bit_length= 0;
 
11184
  bool force_copy_fields= param->force_copy_fields;
 
11185
  DBUG_ENTER("create_tmp_table");
 
11186
  DBUG_PRINT("enter",
 
11187
             ("distinct: %d  save_sum_fields: %d  rows_limit: %lu  group: %d",
 
11188
              (int) distinct, (int) save_sum_fields,
 
11189
              (ulong) rows_limit,test(group)));
 
11190
 
 
11191
  status_var_increment(thd->status_var.created_tmp_tables);
 
11192
 
 
11193
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
11194
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
11195
 
 
11196
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
11197
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
 
11198
            current_pid, temp_pool_slot);
 
11199
  else
 
11200
  {
 
11201
    /* if we run out of slots or we are not using tempool */
 
11202
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
 
11203
            thd->thread_id, thd->tmp_table++);
 
11204
  }
 
11205
 
 
11206
  /*
 
11207
    No need to change table name to lower case as we are only creating
 
11208
    MyISAM or HEAP tables here
 
11209
  */
 
11210
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
11211
 
 
11212
 
 
11213
  if (group)
 
11214
  {
 
11215
    if (!param->quick_group)
 
11216
      group=0;                                  // Can't use group key
 
11217
    else for (ORDER *tmp=group ; tmp ; tmp=tmp->next)
 
11218
    {
 
11219
      /*
 
11220
        marker == 4 means two things:
 
11221
        - store NULLs in the key, and
 
11222
        - convert BIT fields to 64-bit long, needed because MEMORY tables
 
11223
          can't index BIT fields.
 
11224
      */
 
11225
      (*tmp->item)->marker= 4;
 
11226
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
 
11227
        using_unique_constraint=1;
 
11228
    }
 
11229
    if (param->group_length >= MAX_BLOB_WIDTH)
 
11230
      using_unique_constraint=1;
 
11231
    if (group)
 
11232
      distinct=0;                               // Can't use distinct
 
11233
  }
 
11234
 
 
11235
  field_count=param->field_count+param->func_count+param->sum_func_count;
 
11236
  hidden_field_count=param->hidden_field_count;
 
11237
 
 
11238
  /*
 
11239
    When loose index scan is employed as access method, it already
 
11240
    computes all groups and the result of all aggregate functions. We
 
11241
    make space for the items of the aggregate function in the list of
 
11242
    functions TMP_TABLE_PARAM::items_to_copy, so that the values of
 
11243
    these items are stored in the temporary table.
 
11244
  */
 
11245
  if (param->precomputed_group_by)
 
11246
    copy_func_count+= param->sum_func_count;
 
11247
  
 
11248
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
11249
 
 
11250
  if (!multi_alloc_root(&own_root,
 
11251
                        &table, sizeof(*table),
 
11252
                        &share, sizeof(*share),
 
11253
                        &reg_field, sizeof(Field*) * (field_count+1),
 
11254
                        &default_field, sizeof(Field*) * (field_count),
 
11255
                        &blob_field, sizeof(uint)*(field_count+1),
 
11256
                        &from_field, sizeof(Field*)*field_count,
 
11257
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
 
11258
                        &param->keyinfo, sizeof(*param->keyinfo),
 
11259
                        &key_part_info,
 
11260
                        sizeof(*key_part_info)*(param->group_parts+1),
 
11261
                        &param->start_recinfo,
 
11262
                        sizeof(*param->recinfo)*(field_count*2+4),
 
11263
                        &tmpname, (uint) strlen(path)+1,
 
11264
                        &group_buff, (group && ! using_unique_constraint ?
 
11265
                                      param->group_length : 0),
 
11266
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
11267
                        NullS))
 
11268
  {
 
11269
    if (temp_pool_slot != MY_BIT_NONE)
 
11270
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11271
    DBUG_RETURN(NULL);                          /* purecov: inspected */
 
11272
  }
 
11273
  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
 
11274
  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
 
11275
  {
 
11276
    if (temp_pool_slot != MY_BIT_NONE)
 
11277
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11278
    free_root(&own_root, MYF(0));               /* purecov: inspected */
 
11279
    DBUG_RETURN(NULL);                          /* purecov: inspected */
 
11280
  }
 
11281
  param->items_to_copy= copy_func;
 
11282
  strmov(tmpname,path);
 
11283
  /* make table according to fields */
 
11284
 
 
11285
  bzero((char*) table,sizeof(*table));
 
11286
  bzero((char*) reg_field,sizeof(Field*)*(field_count+1));
 
11287
  bzero((char*) default_field, sizeof(Field*) * (field_count));
 
11288
  bzero((char*) from_field,sizeof(Field*)*field_count);
 
11289
 
 
11290
  table->mem_root= own_root;
 
11291
  mem_root_save= thd->mem_root;
 
11292
  thd->mem_root= &table->mem_root;
 
11293
 
 
11294
  table->field=reg_field;
 
11295
  table->alias= table_alias;
 
11296
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
 
11297
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
 
11298
  table->map=1;
 
11299
  table->temp_pool_slot = temp_pool_slot;
 
11300
  table->copy_blobs= 1;
 
11301
  table->in_use= thd;
 
11302
  table->quick_keys.init();
 
11303
  table->covering_keys.init();
 
11304
  table->keys_in_use_for_query.init();
 
11305
 
 
11306
  table->s= share;
 
11307
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
 
11308
  share->blob_field= blob_field;
 
11309
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
11310
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
11311
  share->table_charset= param->table_charset;
 
11312
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
11313
  share->keys_for_keyread.init();
 
11314
  share->keys_in_use.init();
 
11315
 
 
11316
  /* Calculate which type of fields we will store in the temporary table */
 
11317
 
 
11318
  reclength= string_total_length= 0;
 
11319
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
 
11320
  param->using_indirect_summary_function=0;
 
11321
 
 
11322
  List_iterator_fast<Item> li(fields);
 
11323
  Item *item;
 
11324
  Field **tmp_from_field=from_field;
 
11325
  while ((item=li++))
 
11326
  {
 
11327
    Item::Type type=item->type();
 
11328
    if (not_all_columns)
 
11329
    {
 
11330
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
 
11331
      {
 
11332
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
 
11333
          item->update_used_tables();
 
11334
        if (type == Item::SUBSELECT_ITEM ||
 
11335
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
 
11336
        {
 
11337
          /*
 
11338
            Mark that the we have ignored an item that refers to a summary
 
11339
            function. We need to know this if someone is going to use
 
11340
            DISTINCT on the result.
 
11341
          */
 
11342
          param->using_indirect_summary_function=1;
 
11343
          continue;
 
11344
        }
 
11345
      }
 
11346
      if (item->const_item() && (int) hidden_field_count <= 0)
 
11347
        continue; // We don't have to store this
 
11348
    }
 
11349
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
 
11350
    {                                           /* Can't calc group yet */
 
11351
      ((Item_sum*) item)->result_field=0;
 
11352
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
 
11353
      {
 
11354
        Item **argp= ((Item_sum*) item)->args + i;
 
11355
        Item *arg= *argp;
 
11356
        if (!arg->const_item())
 
11357
        {
 
11358
          Field *new_field=
 
11359
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
 
11360
                             tmp_from_field, &default_field[fieldnr],
 
11361
                             group != 0,not_all_columns,
 
11362
                             distinct, 0,
 
11363
                             param->convert_blob_length);
 
11364
          if (!new_field)
 
11365
            goto err;                                   // Should be OOM
 
11366
          tmp_from_field++;
 
11367
          reclength+=new_field->pack_length();
 
11368
          if (new_field->flags & BLOB_FLAG)
 
11369
          {
 
11370
            *blob_field++= fieldnr;
 
11371
            blob_count++;
 
11372
          }
 
11373
          if (new_field->type() == MYSQL_TYPE_BIT)
 
11374
            total_uneven_bit_length+= new_field->field_length & 7;
 
11375
          *(reg_field++)= new_field;
 
11376
          if (new_field->real_type() == MYSQL_TYPE_STRING ||
 
11377
              new_field->real_type() == MYSQL_TYPE_VARCHAR)
 
11378
          {
 
11379
            string_count++;
 
11380
            string_total_length+= new_field->pack_length();
 
11381
          }
 
11382
          thd->mem_root= mem_root_save;
 
11383
          thd->change_item_tree(argp, new Item_field(new_field));
 
11384
          thd->mem_root= &table->mem_root;
 
11385
          if (!(new_field->flags & NOT_NULL_FLAG))
 
11386
          {
 
11387
            null_count++;
 
11388
            /*
 
11389
              new_field->maybe_null() is still false, it will be
 
11390
              changed below. But we have to setup Item_field correctly
 
11391
            */
 
11392
            (*argp)->maybe_null=1;
 
11393
          }
 
11394
          new_field->field_index= fieldnr++;
 
11395
        }
 
11396
      }
 
11397
    }
 
11398
    else
 
11399
    {
 
11400
      /*
 
11401
        The last parameter to create_tmp_field() is a bit tricky:
 
11402
 
 
11403
        We need to set it to 0 in union, to get fill_record() to modify the
 
11404
        temporary table.
 
11405
        We need to set it to 1 on multi-table-update and in select to
 
11406
        write rows to the temporary table.
 
11407
        We here distinguish between UNION and multi-table-updates by the fact
 
11408
        that in the later case group is set to the row pointer.
 
11409
      */
 
11410
      Field *new_field= (param->schema_table) ?
 
11411
        create_tmp_field_for_schema(thd, item, table) :
 
11412
        create_tmp_field(thd, table, item, type, &copy_func,
 
11413
                         tmp_from_field, &default_field[fieldnr],
 
11414
                         group != 0,
 
11415
                         !force_copy_fields &&
 
11416
                           (not_all_columns || group !=0),
 
11417
                         /*
 
11418
                           If item->marker == 4 then we force create_tmp_field
 
11419
                           to create a 64-bit longs for BIT fields because HEAP
 
11420
                           tables can't index BIT fields directly. We do the same
 
11421
                           for distinct, as we want the distinct index to be
 
11422
                           usable in this case too.
 
11423
                         */
 
11424
                         item->marker == 4 || param->bit_fields_as_long,
 
11425
                         force_copy_fields,
 
11426
                         param->convert_blob_length);
 
11427
 
 
11428
      if (!new_field)
 
11429
      {
 
11430
        if (thd->is_fatal_error)
 
11431
          goto err;                             // Got OOM
 
11432
        continue;                               // Some kindf of const item
 
11433
      }
 
11434
      if (type == Item::SUM_FUNC_ITEM)
 
11435
        ((Item_sum *) item)->result_field= new_field;
 
11436
      tmp_from_field++;
 
11437
      reclength+=new_field->pack_length();
 
11438
      if (!(new_field->flags & NOT_NULL_FLAG))
 
11439
        null_count++;
 
11440
      if (new_field->type() == MYSQL_TYPE_BIT)
 
11441
        total_uneven_bit_length+= new_field->field_length & 7;
 
11442
      if (new_field->flags & BLOB_FLAG)
 
11443
      {
 
11444
        *blob_field++= fieldnr;
 
11445
        blob_count++;
 
11446
      }
 
11447
      if (item->marker == 4 && item->maybe_null)
 
11448
      {
 
11449
        group_null_items++;
 
11450
        new_field->flags|= GROUP_FLAG;
 
11451
      }
 
11452
      new_field->field_index= fieldnr++;
 
11453
      *(reg_field++)= new_field;
 
11454
    }
 
11455
    if (!--hidden_field_count)
 
11456
    {
 
11457
      /*
 
11458
        This was the last hidden field; Remember how many hidden fields could
 
11459
        have null
 
11460
      */
 
11461
      hidden_null_count=null_count;
 
11462
      /*
 
11463
        We need to update hidden_field_count as we may have stored group
 
11464
        functions with constant arguments
 
11465
      */
 
11466
      param->hidden_field_count= fieldnr;
 
11467
      null_count= 0;
 
11468
    }
 
11469
  }
 
11470
  DBUG_ASSERT(fieldnr == (uint) (reg_field - table->field));
 
11471
  DBUG_ASSERT(field_count >= (uint) (reg_field - table->field));
 
11472
  field_count= fieldnr;
 
11473
  *reg_field= 0;
 
11474
  *blob_field= 0;                               // End marker
 
11475
  share->fields= field_count;
 
11476
 
 
11477
  /* If result table is small; use a heap */
 
11478
  /* future: storage engine selection can be made dynamic? */
 
11479
  if (blob_count || using_unique_constraint ||
 
11480
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
11481
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
 
11482
  {
 
11483
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
11484
    table->file= get_new_handler(share, &table->mem_root,
 
11485
                                 share->db_type());
 
11486
    if (group &&
 
11487
        (param->group_parts > table->file->max_key_parts() ||
 
11488
         param->group_length > table->file->max_key_length()))
 
11489
      using_unique_constraint=1;
 
11490
  }
 
11491
  else
 
11492
  {
 
11493
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
11494
    table->file= get_new_handler(share, &table->mem_root,
 
11495
                                 share->db_type());
 
11496
  }
 
11497
  if (!table->file)
 
11498
    goto err;
 
11499
 
 
11500
 
 
11501
  if (!using_unique_constraint)
 
11502
    reclength+= group_null_items;       // null flag is stored separately
 
11503
 
 
11504
  share->blob_fields= blob_count;
 
11505
  if (blob_count == 0)
 
11506
  {
 
11507
    /* We need to ensure that first byte is not 0 for the delete link */
 
11508
    if (param->hidden_field_count)
 
11509
      hidden_null_count++;
 
11510
    else
 
11511
      null_count++;
 
11512
  }
 
11513
  hidden_null_pack_length=(hidden_null_count+7)/8;
 
11514
  null_pack_length= (hidden_null_pack_length +
 
11515
                     (null_count + total_uneven_bit_length + 7) / 8);
 
11516
  reclength+=null_pack_length;
 
11517
  if (!reclength)
 
11518
    reclength=1;                                // Dummy select
 
11519
  /* Use packed rows if there is blobs or a lot of space to gain */
 
11520
  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)))
 
11521
    use_packed_rows= 1;
 
11522
 
 
11523
  share->reclength= reclength;
 
11524
  {
 
11525
    uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
 
11526
    share->rec_buff_length= alloc_length;
 
11527
    if (!(table->record[0]= (uchar*)
 
11528
                            alloc_root(&table->mem_root, alloc_length*3)))
 
11529
      goto err;
 
11530
    table->record[1]= table->record[0]+alloc_length;
 
11531
    share->default_values= table->record[1]+alloc_length;
 
11532
  }
 
11533
  copy_func[0]=0;                               // End marker
 
11534
  param->func_count= copy_func - param->items_to_copy; 
 
11535
 
 
11536
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
11537
 
 
11538
  recinfo=param->start_recinfo;
 
11539
  null_flags=(uchar*) table->record[0];
 
11540
  pos=table->record[0]+ null_pack_length;
 
11541
  if (null_pack_length)
 
11542
  {
 
11543
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11544
    recinfo->type=FIELD_NORMAL;
 
11545
    recinfo->length=null_pack_length;
 
11546
    recinfo++;
 
11547
    bfill(null_flags,null_pack_length,255);     // Set null fields
 
11548
 
 
11549
    table->null_flags= (uchar*) table->record[0];
 
11550
    share->null_fields= null_count+ hidden_null_count;
 
11551
    share->null_bytes= null_pack_length;
 
11552
  }
 
11553
  null_count= (blob_count == 0) ? 1 : 0;
 
11554
  hidden_field_count=param->hidden_field_count;
 
11555
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
 
11556
  {
 
11557
    Field *field= *reg_field;
 
11558
    uint length;
 
11559
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
11560
 
 
11561
    if (!(field->flags & NOT_NULL_FLAG))
 
11562
    {
 
11563
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
 
11564
      {
 
11565
        /*
 
11566
          We have to reserve one byte here for NULL bits,
 
11567
          as this is updated by 'end_update()'
 
11568
        */
 
11569
        *pos++=0;                               // Null is stored here
 
11570
        recinfo->length=1;
 
11571
        recinfo->type=FIELD_NORMAL;
 
11572
        recinfo++;
 
11573
        bzero((uchar*) recinfo,sizeof(*recinfo));
 
11574
      }
 
11575
      else
 
11576
      {
 
11577
        recinfo->null_bit= 1 << (null_count & 7);
 
11578
        recinfo->null_pos= null_count/8;
 
11579
      }
 
11580
      field->move_field(pos,null_flags+null_count/8,
 
11581
                        1 << (null_count & 7));
 
11582
      null_count++;
 
11583
    }
 
11584
    else
 
11585
      field->move_field(pos,(uchar*) 0,0);
 
11586
    if (field->type() == MYSQL_TYPE_BIT)
 
11587
    {
 
11588
      /* We have to reserve place for extra bits among null bits */
 
11589
      ((Field_bit*) field)->set_bit_ptr(null_flags + null_count / 8,
 
11590
                                        null_count & 7);
 
11591
      null_count+= (field->field_length & 7);
 
11592
    }
 
11593
    field->reset();
 
11594
 
 
11595
    /*
 
11596
      Test if there is a default field value. The test for ->ptr is to skip
 
11597
      'offset' fields generated by initalize_tables
 
11598
    */
 
11599
    if (default_field[i] && default_field[i]->ptr)
 
11600
    {
 
11601
      /* 
 
11602
         default_field[i] is set only in the cases  when 'field' can
 
11603
         inherit the default value that is defined for the field referred
 
11604
         by the Item_field object from which 'field' has been created.
 
11605
      */
 
11606
      my_ptrdiff_t diff;
 
11607
      Field *orig_field= default_field[i];
 
11608
      /* Get the value from default_values */
 
11609
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
 
11610
                            orig_field->table->record[0]);
 
11611
      orig_field->move_field_offset(diff);      // Points now at default_values
 
11612
      if (orig_field->is_real_null())
 
11613
        field->set_null();
 
11614
      else
 
11615
      {
 
11616
        field->set_notnull();
 
11617
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
 
11618
      }
 
11619
      orig_field->move_field_offset(-diff);     // Back to record[0]
 
11620
    } 
 
11621
 
 
11622
    if (from_field[i])
 
11623
    {                                           /* Not a table Item */
 
11624
      copy->set(field,from_field[i],save_sum_fields);
 
11625
      copy++;
 
11626
    }
 
11627
    length=field->pack_length();
 
11628
    pos+= length;
 
11629
 
 
11630
    /* Make entry for create table */
 
11631
    recinfo->length=length;
 
11632
    if (field->flags & BLOB_FLAG)
 
11633
      recinfo->type= (int) FIELD_BLOB;
 
11634
    else if (use_packed_rows &&
 
11635
             field->real_type() == MYSQL_TYPE_STRING &&
 
11636
             length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
 
11637
      recinfo->type=FIELD_SKIP_ENDSPACE;
 
11638
    else
 
11639
      recinfo->type=FIELD_NORMAL;
 
11640
    if (!--hidden_field_count)
 
11641
      null_count=(null_count+7) & ~7;           // move to next byte
 
11642
 
 
11643
    // fix table name in field entry
 
11644
    field->table_name= &table->alias;
 
11645
  }
 
11646
 
 
11647
  param->copy_field_end=copy;
 
11648
  param->recinfo=recinfo;
 
11649
  store_record(table,s->default_values);        // Make empty default record
 
11650
 
 
11651
  if (thd->variables.tmp_table_size == ~ (ulonglong) 0)         // No limit
 
11652
    share->max_rows= ~(ha_rows) 0;
 
11653
  else
 
11654
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
11655
                                 min(thd->variables.tmp_table_size,
 
11656
                                     thd->variables.max_heap_table_size) :
 
11657
                                 thd->variables.tmp_table_size) /
 
11658
                                 share->reclength);
 
11659
  set_if_bigger(share->max_rows,1);             // For dummy start options
 
11660
  /*
 
11661
    Push the LIMIT clause to the temporary table creation, so that we
 
11662
    materialize only up to 'rows_limit' records instead of all result records.
 
11663
  */
 
11664
  set_if_smaller(share->max_rows, rows_limit);
 
11665
  param->end_write_records= rows_limit;
 
11666
 
 
11667
  keyinfo= param->keyinfo;
 
11668
 
 
11669
  if (group)
 
11670
  {
 
11671
    DBUG_PRINT("info",("Creating group key in temporary table"));
 
11672
    table->group=group;                         /* Table is grouped by key */
 
11673
    param->group_buff=group_buff;
 
11674
    share->keys=1;
 
11675
    share->uniques= test(using_unique_constraint);
 
11676
    table->key_info=keyinfo;
 
11677
    keyinfo->key_part=key_part_info;
 
11678
    keyinfo->flags=HA_NOSAME;
 
11679
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
 
11680
    keyinfo->key_length=0;
 
11681
    keyinfo->rec_per_key=0;
 
11682
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
11683
    keyinfo->name= (char*) "group_key";
 
11684
    ORDER *cur_group= group;
 
11685
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
 
11686
    {
 
11687
      Field *field=(*cur_group->item)->get_tmp_table_field();
 
11688
      bool maybe_null=(*cur_group->item)->maybe_null;
 
11689
      key_part_info->null_bit=0;
 
11690
      key_part_info->field=  field;
 
11691
      key_part_info->offset= field->offset(table->record[0]);
 
11692
      key_part_info->length= (uint16) field->key_length();
 
11693
      key_part_info->type=   (uint8) field->key_type();
 
11694
      key_part_info->key_type =
 
11695
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
 
11696
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
 
11697
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
 
11698
        0 : FIELDFLAG_BINARY;
 
11699
      if (!using_unique_constraint)
 
11700
      {
 
11701
        cur_group->buff=(char*) group_buff;
 
11702
        if (!(cur_group->field= field->new_key_field(thd->mem_root,table,
 
11703
                                                     group_buff +
 
11704
                                                     test(maybe_null),
 
11705
                                                     field->null_ptr,
 
11706
                                                     field->null_bit)))
 
11707
          goto err; /* purecov: inspected */
 
11708
        if (maybe_null)
 
11709
        {
 
11710
          /*
 
11711
            To be able to group on NULL, we reserved place in group_buff
 
11712
            for the NULL flag just before the column. (see above).
 
11713
            The field data is after this flag.
 
11714
            The NULL flag is updated in 'end_update()' and 'end_write()'
 
11715
          */
 
11716
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
 
11717
          key_part_info->null_bit=field->null_bit;
 
11718
          key_part_info->null_offset= (uint) (field->null_ptr -
 
11719
                                              (uchar*) table->record[0]);
 
11720
          cur_group->buff++;                        // Pointer to field data
 
11721
          group_buff++;                         // Skipp null flag
 
11722
        }
 
11723
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
 
11724
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
 
11725
        group_buff+= cur_group->field->pack_length();
 
11726
      }
 
11727
      keyinfo->key_length+=  key_part_info->length;
 
11728
    }
 
11729
  }
 
11730
 
 
11731
  if (distinct && field_count != param->hidden_field_count)
 
11732
  {
 
11733
    /*
 
11734
      Create an unique key or an unique constraint over all columns
 
11735
      that should be in the result.  In the temporary table, there are
 
11736
      'param->hidden_field_count' extra columns, whose null bits are stored
 
11737
      in the first 'hidden_null_pack_length' bytes of the row.
 
11738
    */
 
11739
    DBUG_PRINT("info",("hidden_field_count: %d", param->hidden_field_count));
 
11740
 
 
11741
    if (blob_count)
 
11742
    {
 
11743
      /*
 
11744
        Special mode for index creation in MyISAM used to support unique
 
11745
        indexes on blobs with arbitrary length. Such indexes cannot be
 
11746
        used for lookups.
 
11747
      */
 
11748
      share->uniques= 1;
 
11749
    }
 
11750
    null_pack_length-=hidden_null_pack_length;
 
11751
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
 
11752
                         (share->uniques ? test(null_pack_length) : 0));
 
11753
    table->distinct= 1;
 
11754
    share->keys= 1;
 
11755
    if (!(key_part_info= (KEY_PART_INFO*)
 
11756
          alloc_root(&table->mem_root,
 
11757
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
 
11758
      goto err;
 
11759
    bzero((void*) key_part_info, keyinfo->key_parts * sizeof(KEY_PART_INFO));
 
11760
    table->key_info=keyinfo;
 
11761
    keyinfo->key_part=key_part_info;
 
11762
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
 
11763
    keyinfo->key_length=(uint16) reclength;
 
11764
    keyinfo->name= (char*) "distinct_key";
 
11765
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
11766
    keyinfo->rec_per_key=0;
 
11767
 
 
11768
    /*
 
11769
      Create an extra field to hold NULL bits so that unique indexes on
 
11770
      blobs can distinguish NULL from 0. This extra field is not needed
 
11771
      when we do not use UNIQUE indexes for blobs.
 
11772
    */
 
11773
    if (null_pack_length && share->uniques)
 
11774
    {
 
11775
      key_part_info->null_bit=0;
 
11776
      key_part_info->offset=hidden_null_pack_length;
 
11777
      key_part_info->length=null_pack_length;
 
11778
      key_part_info->field= new Field_string(table->record[0],
 
11779
                                             (uint32) key_part_info->length,
 
11780
                                             (uchar*) 0,
 
11781
                                             (uint) 0,
 
11782
                                             Field::NONE,
 
11783
                                             NullS, &my_charset_bin);
 
11784
      if (!key_part_info->field)
 
11785
        goto err;
 
11786
      key_part_info->field->init(table);
 
11787
      key_part_info->key_type=FIELDFLAG_BINARY;
 
11788
      key_part_info->type=    HA_KEYTYPE_BINARY;
 
11789
      key_part_info++;
 
11790
    }
 
11791
    /* Create a distinct key over the columns we are going to return */
 
11792
    for (i=param->hidden_field_count, reg_field=table->field + i ;
 
11793
         i < field_count;
 
11794
         i++, reg_field++, key_part_info++)
 
11795
    {
 
11796
      key_part_info->null_bit=0;
 
11797
      key_part_info->field=    *reg_field;
 
11798
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
 
11799
      key_part_info->length=   (uint16) (*reg_field)->pack_length();
 
11800
      /* TODO:
 
11801
        The below method of computing the key format length of the
 
11802
        key part is a copy/paste from opt_range.cc, and table.cc.
 
11803
        This should be factored out, e.g. as a method of Field.
 
11804
        In addition it is not clear if any of the Field::*_length
 
11805
        methods is supposed to compute the same length. If so, it
 
11806
        might be reused.
 
11807
      */
 
11808
      key_part_info->store_length= key_part_info->length;
 
11809
 
 
11810
      if ((*reg_field)->real_maybe_null())
 
11811
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
 
11812
      if ((*reg_field)->type() == MYSQL_TYPE_BLOB || 
 
11813
          (*reg_field)->real_type() == MYSQL_TYPE_VARCHAR)
 
11814
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
 
11815
 
 
11816
      key_part_info->type=     (uint8) (*reg_field)->key_type();
 
11817
      key_part_info->key_type =
 
11818
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
 
11819
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
 
11820
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
 
11821
        0 : FIELDFLAG_BINARY;
 
11822
    }
 
11823
  }
 
11824
 
 
11825
  if (thd->is_fatal_error)                              // If end of memory
 
11826
    goto err;                                    /* purecov: inspected */
 
11827
  share->db_record_offset= 1;
 
11828
  if (share->db_type() == myisam_hton)
 
11829
  {
 
11830
    if (create_myisam_tmp_table(table, param->keyinfo, param->start_recinfo,
 
11831
                                &param->recinfo, select_options))
 
11832
      goto err;
 
11833
  }
 
11834
  if (open_tmp_table(table))
 
11835
    goto err;
 
11836
 
 
11837
  thd->mem_root= mem_root_save;
 
11838
 
 
11839
  DBUG_RETURN(table);
 
11840
 
 
11841
err:
 
11842
  thd->mem_root= mem_root_save;
 
11843
  free_tmp_table(thd,table);                    /* purecov: inspected */
 
11844
  if (temp_pool_slot != MY_BIT_NONE)
 
11845
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11846
  DBUG_RETURN(NULL);                            /* purecov: inspected */
 
11847
}
 
11848
 
 
11849
 
 
11850
 
 
11851
 
 
11852
/*
 
11853
  Create a temporary table to weed out duplicate rowid combinations
 
11854
 
 
11855
  SYNOPSIS
 
11856
 
 
11857
    create_duplicate_weedout_tmp_table()
 
11858
      thd
 
11859
      uniq_tuple_length_arg
 
11860
      SJ_TMP_TABLE 
 
11861
 
 
11862
  DESCRIPTION
 
11863
    Create a temporary table to weed out duplicate rowid combinations. The
 
11864
    table has a single column that is a concatenation of all rowids in the
 
11865
    combination. 
 
11866
 
 
11867
    Depending on the needed length, there are two cases:
 
11868
 
 
11869
    1. When the length of the column < max_key_length:
 
11870
 
 
11871
      CREATE TABLE tmp (col VARBINARY(n) NOT NULL, UNIQUE KEY(col));
 
11872
 
 
11873
    2. Otherwise (not a valid SQL syntax but internally supported):
 
11874
 
 
11875
      CREATE TABLE tmp (col VARBINARY NOT NULL, UNIQUE CONSTRAINT(col));
 
11876
 
 
11877
    The code in this function was produced by extraction of relevant parts
 
11878
    from create_tmp_table().
 
11879
 
 
11880
  RETURN
 
11881
    created table
 
11882
    NULL on error
 
11883
*/
 
11884
 
 
11885
TABLE *create_duplicate_weedout_tmp_table(THD *thd, 
 
11886
                                          uint uniq_tuple_length_arg,
 
11887
                                          SJ_TMP_TABLE *sjtbl)
 
11888
{
 
11889
  MEM_ROOT *mem_root_save, own_root;
 
11890
  TABLE *table;
 
11891
  TABLE_SHARE *share;
 
11892
  uint  temp_pool_slot=MY_BIT_NONE;
 
11893
  char  *tmpname,path[FN_REFLEN];
 
11894
  Field **reg_field;
 
11895
  KEY_PART_INFO *key_part_info;
 
11896
  KEY *keyinfo;
 
11897
  uchar *group_buff;
 
11898
  uchar *bitmaps;
 
11899
  uint *blob_field;
 
11900
  MI_COLUMNDEF *recinfo, *start_recinfo;
 
11901
  bool using_unique_constraint=FALSE;
 
11902
  bool use_packed_rows= FALSE;
 
11903
  Field *field, *key_field;
 
11904
  uint blob_count, null_pack_length, null_count;
 
11905
  uchar *null_flags;
 
11906
  uchar *pos;
 
11907
  DBUG_ENTER("create_duplicate_weedout_tmp_table");
 
11908
  
 
11909
  /*
 
11910
    STEP 1: Get temporary table name
 
11911
  */
 
11912
  statistic_increment(thd->status_var.created_tmp_tables, &LOCK_status);
 
11913
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
 
11914
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
 
11915
 
 
11916
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
 
11917
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
 
11918
            current_pid, temp_pool_slot);
 
11919
  else
 
11920
  {
 
11921
    /* if we run out of slots or we are not using tempool */
 
11922
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
 
11923
            thd->thread_id, thd->tmp_table++);
 
11924
  }
 
11925
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
 
11926
 
 
11927
  /* STEP 2: Figure if we'll be using a key or blob+constraint */
 
11928
  if (uniq_tuple_length_arg >= CONVERT_IF_BIGGER_TO_BLOB)
 
11929
    using_unique_constraint= TRUE;
 
11930
 
 
11931
  /* STEP 3: Allocate memory for temptable description */
 
11932
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
 
11933
  if (!multi_alloc_root(&own_root,
 
11934
                        &table, sizeof(*table),
 
11935
                        &share, sizeof(*share),
 
11936
                        &reg_field, sizeof(Field*) * (1+1),
 
11937
                        &blob_field, sizeof(uint)*2,
 
11938
                        &keyinfo, sizeof(*keyinfo),
 
11939
                        &key_part_info, sizeof(*key_part_info) * 2,
 
11940
                        &start_recinfo,
 
11941
                        sizeof(*recinfo)*(1*2+4),
 
11942
                        &tmpname, (uint) strlen(path)+1,
 
11943
                        &group_buff, (!using_unique_constraint ?
 
11944
                                      uniq_tuple_length_arg : 0),
 
11945
                        &bitmaps, bitmap_buffer_size(1)*2,
 
11946
                        NullS))
 
11947
  {
 
11948
    if (temp_pool_slot != MY_BIT_NONE)
 
11949
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
11950
    DBUG_RETURN(NULL);
 
11951
  }
 
11952
  strmov(tmpname,path);
 
11953
  
 
11954
 
 
11955
  /* STEP 4: Create TABLE description */
 
11956
  bzero((char*) table,sizeof(*table));
 
11957
  bzero((char*) reg_field,sizeof(Field*)*2);
 
11958
 
 
11959
  table->mem_root= own_root;
 
11960
  mem_root_save= thd->mem_root;
 
11961
  thd->mem_root= &table->mem_root;
 
11962
 
 
11963
  table->field=reg_field;
 
11964
  table->alias= "weedout-tmp";
 
11965
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
 
11966
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
 
11967
  table->map=1;
 
11968
  table->temp_pool_slot = temp_pool_slot;
 
11969
  table->copy_blobs= 1;
 
11970
  table->in_use= thd;
 
11971
  table->quick_keys.init();
 
11972
  table->covering_keys.init();
 
11973
  table->keys_in_use_for_query.init();
 
11974
 
 
11975
  table->s= share;
 
11976
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
 
11977
  share->blob_field= blob_field;
 
11978
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
11979
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
 
11980
  share->table_charset= NULL;
 
11981
  share->primary_key= MAX_KEY;               // Indicate no primary key
 
11982
  share->keys_for_keyread.init();
 
11983
  share->keys_in_use.init();
 
11984
 
 
11985
  blob_count= 0;
 
11986
 
 
11987
  /* Create the field */
 
11988
  {
 
11989
    /*
 
11990
      For the sake of uniformity, always use Field_varstring (altough we could
 
11991
      use Field_string for shorter keys)
 
11992
    */
 
11993
    field= new Field_varstring(uniq_tuple_length_arg, FALSE, "rowids", share,
 
11994
                               &my_charset_bin);
 
11995
    if (!field)
 
11996
      DBUG_RETURN(0);
 
11997
    field->table= table;
 
11998
    field->key_start.init(0);
 
11999
    field->part_of_key.init(0);
 
12000
    field->part_of_sortkey.init(0);
 
12001
    field->unireg_check= Field::NONE;
 
12002
    field->flags= (NOT_NULL_FLAG | BINARY_FLAG | NO_DEFAULT_VALUE_FLAG);
 
12003
    field->reset_fields();
 
12004
    field->init(table);
 
12005
    field->orig_table= NULL;
 
12006
     
 
12007
    field->field_index= 0;
 
12008
    
 
12009
    *(reg_field++)= field;
 
12010
    *blob_field= 0;
 
12011
    *reg_field= 0;
 
12012
 
 
12013
    share->fields= 1;
 
12014
    share->blob_fields= 0;
 
12015
  }
 
12016
 
 
12017
  uint reclength= field->pack_length();
 
12018
  if (using_unique_constraint)
 
12019
  { 
 
12020
    share->db_plugin= ha_lock_engine(0, myisam_hton);
 
12021
    table->file= get_new_handler(share, &table->mem_root,
 
12022
                                 share->db_type());
 
12023
    DBUG_ASSERT(uniq_tuple_length_arg <= table->file->max_key_length());
 
12024
  }
 
12025
  else
 
12026
  {
 
12027
    share->db_plugin= ha_lock_engine(0, heap_hton);
 
12028
    table->file= get_new_handler(share, &table->mem_root,
 
12029
                                 share->db_type());
 
12030
  }
 
12031
  if (!table->file)
 
12032
    goto err;
 
12033
 
 
12034
  null_count=1;
 
12035
  
 
12036
  null_pack_length= 1;
 
12037
  reclength += null_pack_length;
 
12038
 
 
12039
  share->reclength= reclength;
 
12040
  {
 
12041
    uint alloc_length=ALIGN_SIZE(share->reclength + MI_UNIQUE_HASH_LENGTH+1);
 
12042
    share->rec_buff_length= alloc_length;
 
12043
    if (!(table->record[0]= (uchar*)
 
12044
                            alloc_root(&table->mem_root, alloc_length*3)))
 
12045
      goto err;
 
12046
    table->record[1]= table->record[0]+alloc_length;
 
12047
    share->default_values= table->record[1]+alloc_length;
 
12048
  }
 
12049
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
12050
 
 
12051
  recinfo= start_recinfo;
 
12052
  null_flags=(uchar*) table->record[0];
 
12053
  pos=table->record[0]+ null_pack_length;
 
12054
  if (null_pack_length)
 
12055
  {
 
12056
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
12057
    recinfo->type=FIELD_NORMAL;
 
12058
    recinfo->length=null_pack_length;
 
12059
    recinfo++;
 
12060
    bfill(null_flags,null_pack_length,255);     // Set null fields
 
12061
 
 
12062
    table->null_flags= (uchar*) table->record[0];
 
12063
    share->null_fields= null_count;
 
12064
    share->null_bytes= null_pack_length;
 
12065
  }
 
12066
  null_count=1;
 
12067
 
 
12068
  {
 
12069
    //Field *field= *reg_field;
 
12070
    uint length;
 
12071
    bzero((uchar*) recinfo,sizeof(*recinfo));
 
12072
    field->move_field(pos,(uchar*) 0,0);
 
12073
 
 
12074
    field->reset();
 
12075
    /*
 
12076
      Test if there is a default field value. The test for ->ptr is to skip
 
12077
      'offset' fields generated by initalize_tables
 
12078
    */
 
12079
    // Initialize the table field:
 
12080
    bzero(field->ptr, field->pack_length());
 
12081
 
 
12082
    length=field->pack_length();
 
12083
    pos+= length;
 
12084
 
 
12085
    /* Make entry for create table */
 
12086
    recinfo->length=length;
 
12087
    if (field->flags & BLOB_FLAG)
 
12088
      recinfo->type= (int) FIELD_BLOB;
 
12089
    else if (use_packed_rows &&
 
12090
             field->real_type() == MYSQL_TYPE_STRING &&
 
12091
             length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
 
12092
      recinfo->type=FIELD_SKIP_ENDSPACE;
 
12093
    else
 
12094
      recinfo->type=FIELD_NORMAL;
 
12095
 
 
12096
    field->table_name= &table->alias;
 
12097
  }
 
12098
 
 
12099
  //param->recinfo=recinfo;
 
12100
  //store_record(table,s->default_values);        // Make empty default record
 
12101
 
 
12102
  if (thd->variables.tmp_table_size == ~ (ulonglong) 0)         // No limit
 
12103
    share->max_rows= ~(ha_rows) 0;
 
12104
  else
 
12105
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
 
12106
                                 min(thd->variables.tmp_table_size,
 
12107
                                     thd->variables.max_heap_table_size) :
 
12108
                                 thd->variables.tmp_table_size) /
 
12109
                                 share->reclength);
 
12110
  set_if_bigger(share->max_rows,1);             // For dummy start options
 
12111
 
 
12112
 
 
12113
  //// keyinfo= param->keyinfo;
 
12114
  if (TRUE)
 
12115
  {
 
12116
    DBUG_PRINT("info",("Creating group key in temporary table"));
 
12117
    share->keys=1;
 
12118
    share->uniques= test(using_unique_constraint);
 
12119
    table->key_info=keyinfo;
 
12120
    keyinfo->key_part=key_part_info;
 
12121
    keyinfo->flags=HA_NOSAME;
 
12122
    keyinfo->usable_key_parts= keyinfo->key_parts= 1;
 
12123
    keyinfo->key_length=0;
 
12124
    keyinfo->rec_per_key=0;
 
12125
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
 
12126
    keyinfo->name= (char*) "weedout_key";
 
12127
    {
 
12128
      key_part_info->null_bit=0;
 
12129
      key_part_info->field=  field;
 
12130
      key_part_info->offset= field->offset(table->record[0]);
 
12131
      key_part_info->length= (uint16) field->key_length();
 
12132
      key_part_info->type=   (uint8) field->key_type();
 
12133
      key_part_info->key_type = FIELDFLAG_BINARY;
 
12134
      if (!using_unique_constraint)
 
12135
      {
 
12136
        if (!(key_field= field->new_key_field(thd->mem_root, table,
 
12137
                                              group_buff,
 
12138
                                              field->null_ptr,
 
12139
                                              field->null_bit)))
 
12140
          goto err;
 
12141
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL; //todo need this?
 
12142
      }
 
12143
      keyinfo->key_length+=  key_part_info->length;
 
12144
    }
 
12145
  }
 
12146
 
 
12147
  if (thd->is_fatal_error)                              // If end of memory
 
12148
    goto err;
 
12149
  share->db_record_offset= 1;
 
12150
  if (share->db_type() == myisam_hton)
 
12151
  {
 
12152
    recinfo++;
 
12153
    if (create_myisam_tmp_table(table, keyinfo, start_recinfo, &recinfo, 0))
 
12154
      goto err;
 
12155
  }
 
12156
  sjtbl->start_recinfo= start_recinfo;
 
12157
  sjtbl->recinfo=       recinfo;
 
12158
  if (open_tmp_table(table))
 
12159
    goto err;
 
12160
 
 
12161
  thd->mem_root= mem_root_save;
 
12162
  DBUG_RETURN(table);
 
12163
 
 
12164
err:
 
12165
  thd->mem_root= mem_root_save;
 
12166
  free_tmp_table(thd,table);                    /* purecov: inspected */
 
12167
  if (temp_pool_slot != MY_BIT_NONE)
 
12168
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
 
12169
  DBUG_RETURN(NULL);                            /* purecov: inspected */
 
12170
}
 
12171
 
 
12172
/****************************************************************************/
 
12173
 
 
12174
/**
 
12175
  Create a reduced TABLE object with properly set up Field list from a
 
12176
  list of field definitions.
 
12177
 
 
12178
    The created table doesn't have a table handler associated with
 
12179
    it, has no keys, no group/distinct, no copy_funcs array.
 
12180
    The sole purpose of this TABLE object is to use the power of Field
 
12181
    class to read/write data to/from table->record[0]. Then one can store
 
12182
    the record in any container (RB tree, hash, etc).
 
12183
    The table is created in THD mem_root, so are the table's fields.
 
12184
    Consequently, if you don't BLOB fields, you don't need to free it.
 
12185
 
 
12186
  @param thd         connection handle
 
12187
  @param field_list  list of column definitions
 
12188
 
 
12189
  @return
 
12190
    0 if out of memory, TABLE object in case of success
 
12191
*/
 
12192
 
 
12193
TABLE *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
 
12194
{
 
12195
  uint field_count= field_list.elements;
 
12196
  uint blob_count= 0;
 
12197
  Field **field;
 
12198
  Create_field *cdef;                           /* column definition */
 
12199
  uint record_length= 0;
 
12200
  uint null_count= 0;                 /* number of columns which may be null */
 
12201
  uint null_pack_length;              /* NULL representation array length */
 
12202
  uint *blob_field;
 
12203
  uchar *bitmaps;
 
12204
  TABLE *table;
 
12205
  TABLE_SHARE *share;
 
12206
 
 
12207
  if (!multi_alloc_root(thd->mem_root,
 
12208
                        &table, sizeof(*table),
 
12209
                        &share, sizeof(*share),
 
12210
                        &field, (field_count + 1) * sizeof(Field*),
 
12211
                        &blob_field, (field_count+1) *sizeof(uint),
 
12212
                        &bitmaps, bitmap_buffer_size(field_count)*2,
 
12213
                        NullS))
 
12214
    return 0;
 
12215
 
 
12216
  bzero(table, sizeof(*table));
 
12217
  bzero(share, sizeof(*share));
 
12218
  table->field= field;
 
12219
  table->s= share;
 
12220
  share->blob_field= blob_field;
 
12221
  share->fields= field_count;
 
12222
  share->blob_ptr_size= portable_sizeof_char_ptr;
 
12223
  setup_tmp_table_column_bitmaps(table, bitmaps);
 
12224
 
 
12225
  /* Create all fields and calculate the total length of record */
 
12226
  List_iterator_fast<Create_field> it(field_list);
 
12227
  while ((cdef= it++))
 
12228
  {
 
12229
    *field= make_field(share, 0, cdef->length,
 
12230
                       (uchar*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
 
12231
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
 
12232
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
 
12233
                       cdef->unireg_check,
 
12234
                       cdef->interval, cdef->field_name);
 
12235
    if (!*field)
 
12236
      goto error;
 
12237
    (*field)->init(table);
 
12238
    record_length+= (*field)->pack_length();
 
12239
    if (! ((*field)->flags & NOT_NULL_FLAG))
 
12240
      null_count++;
 
12241
 
 
12242
    if ((*field)->flags & BLOB_FLAG)
 
12243
      share->blob_field[blob_count++]= (uint) (field - table->field);
 
12244
 
 
12245
    field++;
 
12246
  }
 
12247
  *field= NULL;                             /* mark the end of the list */
 
12248
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
 
12249
  share->blob_fields= blob_count;
 
12250
 
 
12251
  null_pack_length= (null_count + 7)/8;
 
12252
  share->reclength= record_length + null_pack_length;
 
12253
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
 
12254
  table->record[0]= (uchar*) thd->alloc(share->rec_buff_length);
 
12255
  if (!table->record[0])
 
12256
    goto error;
 
12257
 
 
12258
  if (null_pack_length)
 
12259
  {
 
12260
    table->null_flags= (uchar*) table->record[0];
 
12261
    share->null_fields= null_count;
 
12262
    share->null_bytes= null_pack_length;
 
12263
  }
 
12264
 
 
12265
  table->in_use= thd;           /* field->reset() may access table->in_use */
 
12266
  {
 
12267
    /* Set up field pointers */
 
12268
    uchar *null_pos= table->record[0];
 
12269
    uchar *field_pos= null_pos + share->null_bytes;
 
12270
    uint null_bit= 1;
 
12271
 
 
12272
    for (field= table->field; *field; ++field)
 
12273
    {
 
12274
      Field *cur_field= *field;
 
12275
      if ((cur_field->flags & NOT_NULL_FLAG))
 
12276
        cur_field->move_field(field_pos);
 
12277
      else
 
12278
      {
 
12279
        cur_field->move_field(field_pos, (uchar*) null_pos, null_bit);
 
12280
        null_bit<<= 1;
 
12281
        if (null_bit == (1 << 8))
 
12282
        {
 
12283
          ++null_pos;
 
12284
          null_bit= 1;
 
12285
        }
 
12286
      }
 
12287
      cur_field->reset();
 
12288
 
 
12289
      field_pos+= cur_field->pack_length();
 
12290
    }
 
12291
  }
 
12292
  return table;
 
12293
error:
 
12294
  for (field= table->field; *field; ++field)
 
12295
    delete *field;                         /* just invokes field destructor */
 
12296
  return 0;
 
12297
}
 
12298
 
 
12299
 
 
12300
static bool open_tmp_table(TABLE *table)
 
12301
{
 
12302
  int error;
 
12303
  if ((error=table->file->ha_open(table, table->s->table_name.str,O_RDWR,
 
12304
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
 
12305
  {
 
12306
    table->file->print_error(error,MYF(0)); /* purecov: inspected */
 
12307
    table->db_stat=0;
 
12308
    return(1);
 
12309
  }
 
12310
  (void) table->file->extra(HA_EXTRA_QUICK);            /* Faster */
 
12311
  return(0);
 
12312
}
 
12313
 
 
12314
 
 
12315
/*
 
12316
  Create MyISAM temporary table
 
12317
 
 
12318
  SYNOPSIS
 
12319
    create_myisam_tmp_table()
 
12320
      table           Table object that descrimes the table to be created
 
12321
      keyinfo         Description of the index (there is always one index)
 
12322
      start_recinfo   MyISAM's column descriptions
 
12323
      recinfo INOUT   End of MyISAM's column descriptions
 
12324
      options         Option bits
 
12325
   
 
12326
  DESCRIPTION
 
12327
    Create a MyISAM temporary table according to passed description. The is
 
12328
    assumed to have one unique index or constraint.
 
12329
 
 
12330
    The passed array or MI_COLUMNDEF structures must have this form:
 
12331
 
 
12332
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
 
12333
         when there are many nullable columns)
 
12334
      2. Table columns
 
12335
      3. One free MI_COLUMNDEF element (*recinfo points here)
 
12336
   
 
12337
    This function may use the free element to create hash column for unique
 
12338
    constraint.
 
12339
 
 
12340
   RETURN
 
12341
     FALSE - OK
 
12342
     TRUE  - Error
 
12343
*/
 
12344
 
 
12345
static bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo, 
 
12346
                                    MI_COLUMNDEF *start_recinfo,
 
12347
                                    MI_COLUMNDEF **recinfo, 
 
12348
                                    ulonglong options)
 
12349
{
 
12350
  int error;
 
12351
  MI_KEYDEF keydef;
 
12352
  MI_UNIQUEDEF uniquedef;
 
12353
  TABLE_SHARE *share= table->s;
 
12354
  DBUG_ENTER("create_myisam_tmp_table");
 
12355
 
 
12356
  if (share->keys)
 
12357
  {                                             // Get keys for ni_create
 
12358
    bool using_unique_constraint=0;
 
12359
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&table->mem_root,
 
12360
                                            sizeof(*seg) * keyinfo->key_parts);
 
12361
    if (!seg)
 
12362
      goto err;
 
12363
 
 
12364
    bzero(seg, sizeof(*seg) * keyinfo->key_parts);
 
12365
    if (keyinfo->key_length >= table->file->max_key_length() ||
 
12366
        keyinfo->key_parts > table->file->max_key_parts() ||
 
12367
        share->uniques)
 
12368
    {
 
12369
      /* Can't create a key; Make a unique constraint instead of a key */
 
12370
      share->keys=    0;
 
12371
      share->uniques= 1;
 
12372
      using_unique_constraint=1;
 
12373
      bzero((char*) &uniquedef,sizeof(uniquedef));
 
12374
      uniquedef.keysegs=keyinfo->key_parts;
 
12375
      uniquedef.seg=seg;
 
12376
      uniquedef.null_are_equal=1;
 
12377
 
 
12378
      /* Create extra column for hash value */
 
12379
      bzero((uchar*) *recinfo,sizeof(**recinfo));
 
12380
      (*recinfo)->type= FIELD_CHECK;
 
12381
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
 
12382
      (*recinfo)++;
 
12383
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
 
12384
    }
 
12385
    else
 
12386
    {
 
12387
      /* Create an unique key */
 
12388
      bzero((char*) &keydef,sizeof(keydef));
 
12389
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
 
12390
      keydef.keysegs=  keyinfo->key_parts;
 
12391
      keydef.seg= seg;
 
12392
    }
 
12393
    for (uint i=0; i < keyinfo->key_parts ; i++,seg++)
 
12394
    {
 
12395
      Field *field=keyinfo->key_part[i].field;
 
12396
      seg->flag=     0;
 
12397
      seg->language= field->charset()->number;
 
12398
      seg->length=   keyinfo->key_part[i].length;
 
12399
      seg->start=    keyinfo->key_part[i].offset;
 
12400
      if (field->flags & BLOB_FLAG)
 
12401
      {
 
12402
        seg->type=
 
12403
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
 
12404
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
 
12405
        seg->bit_start= (uint8)(field->pack_length() - share->blob_ptr_size);
 
12406
        seg->flag= HA_BLOB_PART;
 
12407
        seg->length=0;                  // Whole blob in unique constraint
 
12408
      }
 
12409
      else
 
12410
      {
 
12411
        seg->type= keyinfo->key_part[i].type;
 
12412
        /* Tell handler if it can do suffic space compression */
 
12413
        if (field->real_type() == MYSQL_TYPE_STRING &&
 
12414
            keyinfo->key_part[i].length > 4)
 
12415
          seg->flag|= HA_SPACE_PACK;
 
12416
      }
 
12417
      if (!(field->flags & NOT_NULL_FLAG))
 
12418
      {
 
12419
        seg->null_bit= field->null_bit;
 
12420
        seg->null_pos= (uint) (field->null_ptr - (uchar*) table->record[0]);
 
12421
        /*
 
12422
          We are using a GROUP BY on something that contains NULL
 
12423
          In this case we have to tell MyISAM that two NULL should
 
12424
          on INSERT be regarded at the same value
 
12425
        */
 
12426
        if (!using_unique_constraint)
 
12427
          keydef.flag|= HA_NULL_ARE_EQUAL;
 
12428
      }
 
12429
    }
 
12430
  }
 
12431
  MI_CREATE_INFO create_info;
 
12432
  bzero((char*) &create_info,sizeof(create_info));
 
12433
 
 
12434
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
 
12435
      OPTION_BIG_TABLES)
 
12436
    create_info.data_file_length= ~(ulonglong) 0;
 
12437
 
 
12438
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
 
12439
                       (uint) (*recinfo-start_recinfo),
 
12440
                       start_recinfo,
 
12441
                       share->uniques, &uniquedef,
 
12442
                       &create_info,
 
12443
                       HA_CREATE_TMP_TABLE)))
 
12444
  {
 
12445
    table->file->print_error(error,MYF(0));     /* purecov: inspected */
 
12446
    table->db_stat=0;
 
12447
    goto err;
 
12448
  }
 
12449
  status_var_increment(table->in_use->status_var.created_tmp_disk_tables);
 
12450
  share->db_record_offset= 1;
 
12451
  DBUG_RETURN(0);
 
12452
 err:
 
12453
  DBUG_RETURN(1);
 
12454
}
 
12455
 
 
12456
 
 
12457
void
 
12458
free_tmp_table(THD *thd, TABLE *entry)
 
12459
{
 
12460
  MEM_ROOT own_root= entry->mem_root;
 
12461
  const char *save_proc_info;
 
12462
  DBUG_ENTER("free_tmp_table");
 
12463
  DBUG_PRINT("enter",("table: %s",entry->alias));
 
12464
 
 
12465
  save_proc_info=thd->proc_info;
 
12466
  thd_proc_info(thd, "removing tmp table");
 
12467
 
 
12468
  if (entry->file)
 
12469
  {
 
12470
    if (entry->db_stat)
 
12471
      entry->file->ha_drop_table(entry->s->table_name.str);
 
12472
    else
 
12473
      entry->file->ha_delete_table(entry->s->table_name.str);
 
12474
    delete entry->file;
 
12475
  }
 
12476
 
 
12477
  /* free blobs */
 
12478
  for (Field **ptr=entry->field ; *ptr ; ptr++)
 
12479
    (*ptr)->free();
 
12480
  free_io_cache(entry);
 
12481
 
 
12482
  if (entry->temp_pool_slot != MY_BIT_NONE)
 
12483
    bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot);
 
12484
 
 
12485
  plugin_unlock(0, entry->s->db_plugin);
 
12486
 
 
12487
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
 
12488
  thd_proc_info(thd, save_proc_info);
 
12489
 
 
12490
  DBUG_VOID_RETURN;
 
12491
}
 
12492
 
 
12493
/**
 
12494
  If a HEAP table gets full, create a MyISAM table and copy all rows
 
12495
  to this.
 
12496
*/
 
12497
 
 
12498
bool create_myisam_from_heap(THD *thd, TABLE *table,
 
12499
                             MI_COLUMNDEF *start_recinfo,
 
12500
                             MI_COLUMNDEF **recinfo, 
 
12501
                             int error, bool ignore_last_dupp_key_error)
 
12502
{
 
12503
  TABLE new_table;
 
12504
  TABLE_SHARE share;
 
12505
  const char *save_proc_info;
 
12506
  int write_err;
 
12507
  DBUG_ENTER("create_myisam_from_heap");
 
12508
 
 
12509
  if (table->s->db_type() != heap_hton || 
 
12510
      error != HA_ERR_RECORD_FILE_FULL)
 
12511
  {
 
12512
    table->file->print_error(error,MYF(0));
 
12513
    DBUG_RETURN(1);
 
12514
  }
 
12515
  new_table= *table;
 
12516
  share= *table->s;
 
12517
  new_table.s= &share;
 
12518
  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
 
12519
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
 
12520
                                        new_table.s->db_type())))
 
12521
    DBUG_RETURN(1);                             // End of memory
 
12522
 
 
12523
  save_proc_info=thd->proc_info;
 
12524
  thd_proc_info(thd, "converting HEAP to MyISAM");
 
12525
 
 
12526
  if (create_myisam_tmp_table(&new_table, table->key_info, start_recinfo,
 
12527
                              recinfo, thd->lex->select_lex.options | 
 
12528
                                               thd->options))
 
12529
    goto err2;
 
12530
  if (open_tmp_table(&new_table))
 
12531
    goto err1;
 
12532
  if (table->file->indexes_are_disabled())
 
12533
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
 
12534
  table->file->ha_index_or_rnd_end();
 
12535
  table->file->ha_rnd_init(1);
 
12536
  if (table->no_rows)
 
12537
  {
 
12538
    new_table.file->extra(HA_EXTRA_NO_ROWS);
 
12539
    new_table.no_rows=1;
 
12540
  }
 
12541
 
 
12542
#ifdef TO_BE_DONE_LATER_IN_4_1
 
12543
  /*
 
12544
    To use start_bulk_insert() (which is new in 4.1) we need to find
 
12545
    all places where a corresponding end_bulk_insert() should be put.
 
12546
  */
 
12547
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
 
12548
  new_table.file->ha_start_bulk_insert(table->file->stats.records);
 
12549
#else
 
12550
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
 
12551
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
 
12552
#endif
 
12553
 
 
12554
  /*
 
12555
    copy all old rows from heap table to MyISAM table
 
12556
    This is the only code that uses record[1] to read/write but this
 
12557
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
 
12558
  */
 
12559
  while (!table->file->rnd_next(new_table.record[1]))
 
12560
  {
 
12561
    write_err= new_table.file->ha_write_row(new_table.record[1]);
 
12562
    DBUG_EXECUTE_IF("raise_error", write_err= HA_ERR_FOUND_DUPP_KEY ;);
 
12563
    if (write_err)
 
12564
      goto err;
 
12565
  }
 
12566
  /* copy row that filled HEAP table */
 
12567
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
 
12568
  {
 
12569
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
 
12570
        !ignore_last_dupp_key_error)
 
12571
      goto err;
 
12572
  }
 
12573
 
 
12574
  /* remove heap table and change to use myisam table */
 
12575
  (void) table->file->ha_rnd_end();
 
12576
  (void) table->file->close();                  // This deletes the table !
 
12577
  delete table->file;
 
12578
  table->file=0;
 
12579
  plugin_unlock(0, table->s->db_plugin);
 
12580
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
 
12581
  new_table.s= table->s;                       // Keep old share
 
12582
  *table= new_table;
 
12583
  *table->s= share;
 
12584
  
 
12585
  table->file->change_table_ptr(table, table->s);
 
12586
  table->use_all_columns();
 
12587
  if (save_proc_info)
 
12588
  {
 
12589
    const char *new_proc_info=
 
12590
      (!strcmp(save_proc_info,"Copying to tmp table") ?
 
12591
      "Copying to tmp table on disk" : save_proc_info);
 
12592
    thd_proc_info(thd, new_proc_info);
 
12593
  }
 
12594
  DBUG_RETURN(0);
 
12595
 
 
12596
 err:
 
12597
  DBUG_PRINT("error",("Got error: %d",write_err));
 
12598
  table->file->print_error(write_err, MYF(0));
 
12599
  (void) table->file->ha_rnd_end();
 
12600
  (void) new_table.file->close();
 
12601
 err1:
 
12602
  new_table.file->ha_delete_table(new_table.s->table_name.str);
 
12603
 err2:
 
12604
  delete new_table.file;
 
12605
  thd_proc_info(thd, save_proc_info);
 
12606
  table->mem_root= new_table.mem_root;
 
12607
  DBUG_RETURN(1);
 
12608
}
 
12609
 
10506
12610
 
10507
12611
/**
10508
12612
  @details
10518
12622
 
10519
12623
Next_select_func setup_end_select_func(JOIN *join)
10520
12624
{
10521
 
  Table *table= join->tmp_table;
 
12625
  TABLE *table= join->tmp_table;
10522
12626
  TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param;
10523
12627
  Next_select_func end_select;
10524
12628
 
10530
12634
    {
10531
12635
      if (table->s->keys)
10532
12636
      {
 
12637
        DBUG_PRINT("info",("Using end_update"));
10533
12638
        end_select=end_update;
10534
12639
      }
10535
12640
      else
10536
12641
      {
 
12642
        DBUG_PRINT("info",("Using end_unique_update"));
10537
12643
        end_select=end_unique_update;
10538
12644
      }
10539
12645
    }
10540
12646
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
10541
12647
    {
 
12648
      DBUG_PRINT("info",("Using end_write_group"));
10542
12649
      end_select=end_write_group;
10543
12650
    }
10544
12651
    else
10545
12652
    {
 
12653
      DBUG_PRINT("info",("Using end_write"));
10546
12654
      end_select=end_write;
10547
12655
      if (tmp_tbl->precomputed_group_by)
10548
12656
      {
10584
12692
*/
10585
12693
 
10586
12694
static int
10587
 
do_select(JOIN *join,List<Item> *fields,Table *table)
 
12695
do_select(JOIN *join,List<Item> *fields,TABLE *table)
10588
12696
{
10589
12697
  int rc= 0;
10590
12698
  enum_nested_loop_state error= NESTED_LOOP_OK;
10591
12699
  JOIN_TAB *join_tab= NULL;
 
12700
  DBUG_ENTER("do_select");
10592
12701
  
10593
12702
  join->tmp_table= table;                       /* Save for easy recursion */
10594
12703
  join->fields= fields;
10595
12704
 
10596
12705
  if (table)
10597
12706
  {
10598
 
    table->file->extra(HA_EXTRA_WRITE_CACHE);
 
12707
    VOID(table->file->extra(HA_EXTRA_WRITE_CACHE));
10599
12708
    empty_record(table);
10600
12709
    if (table->group && join->tmp_table_param.sum_func_count &&
10601
12710
        table->s->keys && !table->file->inited)
10629
12738
      */
10630
12739
      join->examined_rows++;
10631
12740
      join->thd->row_count++;
10632
 
      assert(join->examined_rows <= 1);
 
12741
      DBUG_ASSERT(join->examined_rows <= 1);
10633
12742
    }
10634
12743
    else if (join->send_row_on_empty_set())
10635
12744
    {
10639
12748
  }
10640
12749
  else
10641
12750
  {
10642
 
    assert(join->tables);
 
12751
    DBUG_ASSERT(join->tables);
10643
12752
    error= sub_select(join,join_tab,0);
10644
12753
    if (error == NESTED_LOOP_OK || error == NESTED_LOOP_NO_MORE_ROWS)
10645
12754
      error= sub_select(join,join_tab,1);
10665
12774
      if (join->result->send_eof())
10666
12775
        rc= 1;                                  // Don't send error
10667
12776
    }
 
12777
    DBUG_PRINT("info",("%ld records output", (long) join->send_records));
10668
12778
  }
10669
12779
  else
10670
12780
    rc= -1;
10673
12783
    int tmp, new_errno= 0;
10674
12784
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
10675
12785
    {
 
12786
      DBUG_PRINT("error",("extra(HA_EXTRA_NO_CACHE) failed"));
10676
12787
      new_errno= tmp;
10677
12788
    }
10678
12789
    if ((tmp=table->file->ha_index_or_rnd_end()))
10679
12790
    {
 
12791
      DBUG_PRINT("error",("ha_index_or_rnd_end() failed"));
10680
12792
      new_errno= tmp;
10681
12793
    }
10682
12794
    if (new_errno)
10683
12795
      table->file->print_error(new_errno,MYF(0));
10684
12796
  }
10685
 
  return(join->thd->is_error() ? -1 : rc);
 
12797
#ifndef DBUG_OFF
 
12798
  if (rc)
 
12799
  {
 
12800
    DBUG_PRINT("error",("Error: do_select() failed"));
 
12801
  }
 
12802
#endif
 
12803
  DBUG_RETURN(join->thd->is_error() ? -1 : rc);
10686
12804
}
10687
12805
 
10688
12806
 
10693
12811
 
10694
12812
  if (end_of_records)
10695
12813
  {
10696
 
    rc= flush_cached_records(join,join_tab,false);
 
12814
    rc= flush_cached_records(join,join_tab,FALSE);
10697
12815
    if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS)
10698
12816
      rc= sub_select(join,join_tab,end_of_records);
10699
12817
    return rc;
10707
12825
  {
10708
12826
    if (!store_record_in_cache(&join_tab->cache))
10709
12827
      return NESTED_LOOP_OK;                     // There is more room in cache
10710
 
    return flush_cached_records(join,join_tab,false);
 
12828
    return flush_cached_records(join,join_tab,FALSE);
10711
12829
  }
10712
 
  rc= flush_cached_records(join, join_tab, true);
 
12830
  rc= flush_cached_records(join, join_tab, TRUE);
10713
12831
  if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS)
10714
12832
    rc= sub_select(join, join_tab, end_of_records);
10715
12833
  return rc;
10859
12977
      rc= (*join_tab->next_select)(join, join_tab + 1, 0);
10860
12978
    else
10861
12979
    {
10862
 
      join->resume_nested_loop= false;
 
12980
      join->resume_nested_loop= FALSE;
10863
12981
      rc= NESTED_LOOP_OK;
10864
12982
    }
10865
12983
  }
10923
13041
  int error;
10924
13042
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
10925
13043
  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;
 
13044
  uchar *ptr= sjtbl->tmp_table->record[0] + 1;
 
13045
  uchar *nulls_ptr= ptr;
10928
13046
  
10929
13047
  /* Put the the rowids tuple into table->record[0]: */
10930
13048
 
10931
13049
  // 1. Store the length 
10932
13050
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
10933
13051
  {
10934
 
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
 
13052
    *ptr= (uchar)(sjtbl->rowid_len + sjtbl->null_bytes);
10935
13053
    ptr++;
10936
13054
  }
10937
13055
  else
10943
13061
  // 2. Zero the null bytes 
10944
13062
  if (sjtbl->null_bytes)
10945
13063
  {
10946
 
    memset(ptr, 0, sjtbl->null_bytes);
 
13064
    bzero(ptr, sjtbl->null_bytes);
10947
13065
    ptr += sjtbl->null_bytes; 
10948
13066
  }
10949
13067
 
10950
13068
  // 3. Put the rowids
10951
 
  for (uint32_t i=0; tab != tab_end; tab++, i++)
 
13069
  for (uint i=0; tab != tab_end; tab++, i++)
10952
13070
  {
10953
13071
    handler *h= tab->join_tab->table->file;
10954
13072
    if (tab->join_tab->table->maybe_null && tab->join_tab->table->null_row)
10955
13073
    {
10956
13074
      /* It's a NULL-complemented row */
10957
13075
      *(nulls_ptr + tab->null_byte) |= tab->null_bit;
10958
 
      memset(ptr + tab->rowid_offset, 0, h->ref_length);
 
13076
      bzero(ptr + tab->rowid_offset, h->ref_length);
10959
13077
    }
10960
13078
    else
10961
13079
    {
11017
13135
    join->thd->send_kill_message();
11018
13136
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
11019
13137
  }
 
13138
  DBUG_PRINT("info", ("select cond 0x%lx", (ulong)select_cond));
11020
13139
  if (!select_cond || select_cond->val_int())
11021
13140
  {
11022
13141
    /*
11074
13193
    }
11075
13194
 
11076
13195
    JOIN_TAB *return_tab= join->return_tab;
11077
 
    join_tab->found_match= true;
 
13196
    join_tab->found_match= TRUE;
11078
13197
    if (join_tab->check_weed_out_table)
11079
13198
    {
11080
13199
      int res= do_sj_dups_weedout(join->thd, join_tab->check_weed_out_table);
11099
13218
    */
11100
13219
    join->examined_rows++;
11101
13220
    join->thd->row_count++;
 
13221
    DBUG_PRINT("counts", ("join->examined_rows++: %lu",
 
13222
                          (ulong) join->examined_rows));
11102
13223
 
11103
13224
    if (found)
11104
13225
    {
11249
13370
    if (rc == NESTED_LOOP_OK &&
11250
13371
        (!join_tab->cache.select || !join_tab->cache.select->skip_record()))
11251
13372
    {
11252
 
      uint32_t i;
 
13373
      uint i;
11253
13374
      reset_cache_read(&join_tab->cache);
11254
13375
      for (i=(join_tab->cache.records- (skip_last ? 1 : 0)) ; i-- > 0 ;)
11255
13376
      {
11284
13405
  return NESTED_LOOP_OK;
11285
13406
}
11286
13407
 
 
13408
 
 
13409
/*****************************************************************************
 
13410
  The different ways to read a record
 
13411
  Returns -1 if row was not found, 0 if row was found and 1 on errors
 
13412
*****************************************************************************/
 
13413
 
 
13414
/** Help function when we get some an error from the table handler. */
 
13415
 
 
13416
int report_error(TABLE *table, int error)
 
13417
{
 
13418
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
 
13419
  {
 
13420
    table->status= STATUS_GARBAGE;
 
13421
    return -1;                                  // key not found; ok
 
13422
  }
 
13423
  /*
 
13424
    Locking reads can legally return also these errors, do not
 
13425
    print them to the .err log
 
13426
  */
 
13427
  if (error != HA_ERR_LOCK_DEADLOCK && error != HA_ERR_LOCK_WAIT_TIMEOUT)
 
13428
    sql_print_error("Got error %d when reading table '%s'",
 
13429
                    error, table->s->path.str);
 
13430
  table->file->print_error(error,MYF(0));
 
13431
  return 1;
 
13432
}
 
13433
 
 
13434
 
11287
13435
int safe_index_read(JOIN_TAB *tab)
11288
13436
{
11289
13437
  int error;
11290
 
  Table *table= tab->table;
 
13438
  TABLE *table= tab->table;
11291
13439
  if ((error=table->file->index_read_map(table->record[0],
11292
13440
                                         tab->ref.key_buff,
11293
13441
                                         make_prev_keypart_map(tab->ref.key_parts),
11294
13442
                                         HA_READ_KEY_EXACT)))
11295
 
    return table->report_error(error);
 
13443
    return report_error(table, error);
11296
13444
  return 0;
11297
13445
}
11298
13446
 
11301
13449
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
11302
13450
{
11303
13451
  int error;
11304
 
  Table *table=tab->table;
 
13452
  DBUG_ENTER("join_read_const_table");
 
13453
  TABLE *table=tab->table;
11305
13454
  table->const_table=1;
11306
13455
  table->null_row=0;
11307
13456
  table->status=STATUS_NO_RECORD;
11315
13464
      pos->records_read=0.0;
11316
13465
      pos->ref_depend_map= 0;
11317
13466
      if (!table->maybe_null || error > 0)
11318
 
        return(error);
 
13467
        DBUG_RETURN(error);
11319
13468
    }
11320
13469
  }
11321
13470
  else
11341
13490
      pos->records_read=0.0;
11342
13491
      pos->ref_depend_map= 0;
11343
13492
      if (!table->maybe_null || error > 0)
11344
 
        return(error);
 
13493
        DBUG_RETURN(error);
11345
13494
    }
11346
13495
  }
11347
13496
  if (*tab->on_expr_ref && !table->null_row)
11356
13505
  JOIN *join= tab->join;
11357
13506
  if (join->conds)
11358
13507
    update_const_equal_items(join->conds, tab);
11359
 
  TableList *tbl;
 
13508
  TABLE_LIST *tbl;
11360
13509
  for (tbl= join->select_lex->leaf_tables; tbl; tbl= tbl->next_leaf)
11361
13510
  {
11362
 
    TableList *embedded;
11363
 
    TableList *embedding= tbl;
 
13511
    TABLE_LIST *embedded;
 
13512
    TABLE_LIST *embedding= tbl;
11364
13513
    do
11365
13514
    {
11366
13515
      embedded= embedding;
11372
13521
           embedding->nested_join->join_list.head() == embedded);
11373
13522
  }
11374
13523
 
11375
 
  return(0);
 
13524
  DBUG_RETURN(0);
11376
13525
}
11377
13526
 
11378
13527
 
11379
13528
static int
11380
13529
join_read_system(JOIN_TAB *tab)
11381
13530
{
11382
 
  Table *table= tab->table;
 
13531
  TABLE *table= tab->table;
11383
13532
  int error;
11384
13533
  if (table->status & STATUS_GARBAGE)           // If first read
11385
13534
  {
11387
13536
                                           table->s->primary_key)))
11388
13537
    {
11389
13538
      if (error != HA_ERR_END_OF_FILE)
11390
 
        return table->report_error(error);
 
13539
        return report_error(table, error);
11391
13540
      mark_as_null_row(tab->table);
11392
13541
      empty_record(table);                      // Make empty record
11393
13542
      return -1;
11394
13543
    }
11395
 
    update_virtual_fields_marked_for_write(table);
11396
13544
    store_record(table,record[1]);
11397
13545
  }
11398
13546
  else if (!table->status)                      // Only happens with left join
11419
13567
join_read_const(JOIN_TAB *tab)
11420
13568
{
11421
13569
  int error;
11422
 
  Table *table= tab->table;
 
13570
  TABLE *table= tab->table;
11423
13571
  if (table->status & STATUS_GARBAGE)           // If first read
11424
13572
  {
11425
13573
    table->status= 0;
11426
 
    if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13574
    if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11427
13575
      error=HA_ERR_KEY_NOT_FOUND;
11428
13576
    else
11429
13577
    {
11430
13578
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
11431
 
                                            (unsigned char*) tab->ref.key_buff,
 
13579
                                            (uchar*) tab->ref.key_buff,
11432
13580
                                            make_prev_keypart_map(tab->ref.key_parts),
11433
13581
                                            HA_READ_KEY_EXACT);
11434
13582
    }
11438
13586
      mark_as_null_row(tab->table);
11439
13587
      empty_record(table);
11440
13588
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11441
 
        return table->report_error(error);
 
13589
        return report_error(table, error);
11442
13590
      return -1;
11443
13591
    }
11444
 
    update_virtual_fields_marked_for_write(table);
11445
13592
    store_record(table,record[1]);
11446
13593
  }
11447
13594
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
11475
13622
join_read_key(JOIN_TAB *tab)
11476
13623
{
11477
13624
  int error;
11478
 
  Table *table= tab->table;
 
13625
  TABLE *table= tab->table;
11479
13626
 
11480
13627
  if (!table->file->inited)
11481
13628
  {
11496
13643
                                      make_prev_keypart_map(tab->ref.key_parts),
11497
13644
                                      HA_READ_KEY_EXACT);
11498
13645
    if (error && error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11499
 
      return table->report_error(error);
 
13646
      return report_error(table, error);
11500
13647
  }
11501
13648
  table->null_row=0;
11502
13649
  return table->status ? -1 : 0;
11526
13673
join_read_always_key(JOIN_TAB *tab)
11527
13674
{
11528
13675
  int error;
11529
 
  Table *table= tab->table;
 
13676
  TABLE *table= tab->table;
11530
13677
 
11531
13678
  /* Initialize the index first */
11532
13679
  if (!table->file->inited)
11533
13680
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11534
13681
 
11535
13682
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
11536
 
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
 
13683
  for (uint i= 0 ; i < tab->ref.key_parts ; i++)
11537
13684
  {
11538
13685
    if ((tab->ref.null_rejecting & 1 << i) && tab->ref.items[i]->is_null())
11539
13686
        return -1;
11540
13687
  }
11541
13688
 
11542
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13689
  if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11543
13690
    return -1;
11544
13691
  if ((error=table->file->index_read_map(table->record[0],
11545
13692
                                         tab->ref.key_buff,
11547
13694
                                         HA_READ_KEY_EXACT)))
11548
13695
  {
11549
13696
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11550
 
      return table->report_error(error);
 
13697
      return report_error(table, error);
11551
13698
    return -1; /* purecov: inspected */
11552
13699
  }
11553
 
  update_virtual_fields_marked_for_write(table);
11554
13700
  return 0;
11555
13701
}
11556
13702
 
11557
13703
 
11558
13704
/**
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.
 
13705
  This function is used when optimizing away ORDER BY in 
 
13706
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
11561
13707
*/
11562
13708
  
11563
13709
static int
11564
13710
join_read_last_key(JOIN_TAB *tab)
11565
13711
{
11566
13712
  int error;
11567
 
  Table *table= tab->table;
 
13713
  TABLE *table= tab->table;
11568
13714
 
11569
13715
  if (!table->file->inited)
11570
13716
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11571
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
13717
  if (cp_buffer_from_ref(tab->join->thd, table, &tab->ref))
11572
13718
    return -1;
11573
13719
  if ((error=table->file->index_read_last_map(table->record[0],
11574
13720
                                              tab->ref.key_buff,
11575
13721
                                              make_prev_keypart_map(tab->ref.key_parts))))
11576
13722
  {
11577
13723
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11578
 
      return table->report_error(error);
 
13724
      return report_error(table, error);
11579
13725
    return -1; /* purecov: inspected */
11580
13726
  }
11581
13727
  return 0;
11592
13738
static int
11593
13739
join_read_next_same_diff(READ_RECORD *info)
11594
13740
{
11595
 
  Table *table= info->table;
 
13741
  TABLE *table= info->table;
11596
13742
  JOIN_TAB *tab=table->reginfo.join_tab;
11597
13743
  if (tab->insideout_match_tab->found_match)
11598
13744
  {
11608
13754
                                              tab->ref.key_length)))
11609
13755
      {
11610
13756
        if (error != HA_ERR_END_OF_FILE)
11611
 
          return table->report_error(error);
 
13757
          return report_error(table, error);
11612
13758
        table->status= STATUS_GARBAGE;
11613
13759
        return -1;
11614
13760
      }
11625
13771
join_read_next_same(READ_RECORD *info)
11626
13772
{
11627
13773
  int error;
11628
 
  Table *table= info->table;
 
13774
  TABLE *table= info->table;
11629
13775
  JOIN_TAB *tab=table->reginfo.join_tab;
11630
13776
 
11631
13777
  if ((error=table->file->index_next_same(table->record[0],
11633
13779
                                          tab->ref.key_length)))
11634
13780
  {
11635
13781
    if (error != HA_ERR_END_OF_FILE)
11636
 
      return table->report_error(error);
 
13782
      return report_error(table, error);
11637
13783
    table->status= STATUS_GARBAGE;
11638
13784
    return -1;
11639
13785
  }
11640
 
  update_virtual_fields_marked_for_write(table);
11641
13786
  return 0;
11642
13787
}
11643
13788
 
11646
13791
join_read_prev_same(READ_RECORD *info)
11647
13792
{
11648
13793
  int error;
11649
 
  Table *table= info->table;
 
13794
  TABLE *table= info->table;
11650
13795
  JOIN_TAB *tab=table->reginfo.join_tab;
11651
13796
 
11652
13797
  if ((error=table->file->index_prev(table->record[0])))
11653
 
    return table->report_error(error);
 
13798
    return report_error(table, error);
11654
13799
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
11655
13800
                      tab->ref.key_length))
11656
13801
  {
11657
13802
    table->status=STATUS_NOT_FOUND;
11658
13803
    error= -1;
11659
13804
  }
11660
 
  update_virtual_fields_marked_for_write(table);
11661
13805
  return error;
11662
13806
}
11663
13807
 
11687
13831
  tab->select->quick=0;
11688
13832
  return tab->select->test_quick_select(tab->join->thd, tab->keys,
11689
13833
                                        (table_map) 0, HA_POS_ERROR, 0,
11690
 
                                        false);
 
13834
                                        FALSE);
11691
13835
}
11692
13836
 
11693
13837
 
11706
13850
join_read_first(JOIN_TAB *tab)
11707
13851
{
11708
13852
  int error;
11709
 
  Table *table=tab->table;
 
13853
  TABLE *table=tab->table;
11710
13854
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
11711
13855
      !table->no_keyread)
11712
13856
  {
11735
13879
  if ((error=tab->table->file->index_first(tab->table->record[0])))
11736
13880
  {
11737
13881
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11738
 
      table->report_error(error);
 
13882
      report_error(table, error);
11739
13883
    return -1;
11740
13884
  }
11741
 
  if (not error)
11742
 
    update_virtual_fields_marked_for_write(tab->table);
11743
13885
  return 0;
11744
13886
}
11745
13887
 
11758
13900
      key_copy(tab->insideout_buf, info->record, key, 0);
11759
13901
 
11760
13902
      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);
 
13903
        return report_error(info->table, error);
 
13904
      
11764
13905
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
11765
13906
                      tab->insideout_buf, key->key_length));
11766
13907
    tab->insideout_match_tab->found_match= 0;
11776
13917
{
11777
13918
  int error;
11778
13919
  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);
 
13920
    return report_error(info->table, error);
11782
13921
  return 0;
11783
13922
}
11784
13923
 
11786
13925
static int
11787
13926
join_read_last(JOIN_TAB *tab)
11788
13927
{
11789
 
  Table *table=tab->table;
 
13928
  TABLE *table=tab->table;
11790
13929
  int error;
11791
13930
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
11792
13931
      !table->no_keyread)
11803
13942
  if (!table->file->inited)
11804
13943
    table->file->ha_index_init(tab->index, 1);
11805
13944
  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);
 
13945
    return report_error(table, error);
11809
13946
  return 0;
11810
13947
}
11811
13948
 
11815
13952
{
11816
13953
  int error;
11817
13954
  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);
 
13955
    return report_error(info->table, error);
11821
13956
  return 0;
11822
13957
}
11823
13958
 
11887
14022
end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
11888
14023
         bool end_of_records)
11889
14024
{
 
14025
  DBUG_ENTER("end_send");
11890
14026
  if (!end_of_records)
11891
14027
  {
11892
14028
    int error;
11893
14029
    if (join->having && join->having->val_int() == 0)
11894
 
      return(NESTED_LOOP_OK);               // Didn't match having
 
14030
      DBUG_RETURN(NESTED_LOOP_OK);               // Didn't match having
11895
14031
    error=0;
11896
14032
    if (join->do_send_rows)
11897
14033
      error=join->result->send_data(*join->fields);
11898
14034
    if (error)
11899
 
      return(NESTED_LOOP_ERROR); /* purecov: inspected */
 
14035
      DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */
11900
14036
    if (++join->send_records >= join->unit->select_limit_cnt &&
11901
14037
        join->do_send_rows)
11902
14038
    {
11910
14046
            (jt->ref.key < 0))
11911
14047
        {
11912
14048
          /* Join over all rows in table;  Return number of found rows */
11913
 
          Table *table=jt->table;
 
14049
          TABLE *table=jt->table;
11914
14050
 
11915
14051
          join->select_options ^= OPTION_FOUND_ROWS;
11916
14052
          if (table->sort.record_pointers ||
11930
14066
          join->do_send_rows= 0;
11931
14067
          if (join->unit->fake_select_lex)
11932
14068
            join->unit->fake_select_lex->select_limit= 0;
11933
 
          return(NESTED_LOOP_OK);
 
14069
          DBUG_RETURN(NESTED_LOOP_OK);
11934
14070
        }
11935
14071
      }
11936
 
      return(NESTED_LOOP_QUERY_LIMIT);      // Abort nicely
 
14072
      DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT);      // Abort nicely
11937
14073
    }
11938
14074
    else if (join->send_records >= join->fetch_limit)
11939
14075
    {
11941
14077
        There is a server side cursor and all rows for
11942
14078
        this fetch request are sent.
11943
14079
      */
11944
 
      return(NESTED_LOOP_CURSOR_LIMIT);
 
14080
      DBUG_RETURN(NESTED_LOOP_CURSOR_LIMIT);
11945
14081
    }
11946
14082
  }
11947
14083
 
11948
 
  return(NESTED_LOOP_OK);
 
14084
  DBUG_RETURN(NESTED_LOOP_OK);
11949
14085
}
11950
14086
 
11951
14087
 
11956
14092
{
11957
14093
  int idx= -1;
11958
14094
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
 
14095
  DBUG_ENTER("end_send_group");
11959
14096
 
11960
14097
  if (!join->first_record || end_of_records ||
11961
14098
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
11992
14129
          }
11993
14130
        }
11994
14131
        if (error > 0)
11995
 
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
 
14132
          DBUG_RETURN(NESTED_LOOP_ERROR);        /* purecov: inspected */
11996
14133
        if (end_of_records)
11997
 
          return(NESTED_LOOP_OK);
 
14134
          DBUG_RETURN(NESTED_LOOP_OK);
11998
14135
        if (join->send_records >= join->unit->select_limit_cnt &&
11999
14136
            join->do_send_rows)
12000
14137
        {
12001
14138
          if (!(join->select_options & OPTION_FOUND_ROWS))
12002
 
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
 
14139
            DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
12003
14140
          join->do_send_rows=0;
12004
14141
          join->unit->select_limit_cnt = HA_POS_ERROR;
12005
14142
        }
12020
14157
    else
12021
14158
    {
12022
14159
      if (end_of_records)
12023
 
        return(NESTED_LOOP_OK);
 
14160
        DBUG_RETURN(NESTED_LOOP_OK);
12024
14161
      join->first_record=1;
12025
 
      test_if_item_cache_changed(join->group_fields);
 
14162
      VOID(test_if_item_cache_changed(join->group_fields));
12026
14163
    }
12027
14164
    if (idx < (int) join->send_group_parts)
12028
14165
    {
12032
14169
      */
12033
14170
      copy_fields(&join->tmp_table_param);
12034
14171
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
12035
 
        return(NESTED_LOOP_ERROR);
12036
 
      return(ok_code);
 
14172
        DBUG_RETURN(NESTED_LOOP_ERROR);
 
14173
      DBUG_RETURN(ok_code);
12037
14174
    }
12038
14175
  }
12039
14176
  if (update_sum_func(join->sum_funcs))
12040
 
    return(NESTED_LOOP_ERROR);
12041
 
  return(NESTED_LOOP_OK);
 
14177
    DBUG_RETURN(NESTED_LOOP_ERROR);
 
14178
  DBUG_RETURN(NESTED_LOOP_OK);
12042
14179
}
12043
14180
 
12044
14181
 
12047
14184
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12048
14185
          bool end_of_records)
12049
14186
{
12050
 
  Table *table=join->tmp_table;
 
14187
  TABLE *table=join->tmp_table;
 
14188
  DBUG_ENTER("end_write");
12051
14189
 
12052
14190
  if (join->thd->killed)                        // Aborted by user
12053
14191
  {
12054
14192
    join->thd->send_kill_message();
12055
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
14193
    DBUG_RETURN(NESTED_LOOP_KILLED);             /* purecov: inspected */
12056
14194
  }
12057
14195
  if (!end_of_records)
12058
14196
  {
12062
14200
    if (!table->uniques)                        // If not unique handling
12063
14201
    {
12064
14202
      /* Copy null values from group to row */
12065
 
      order_st   *group;
 
14203
      ORDER   *group;
12066
14204
      for (group=table->group ; group ; group=group->next)
12067
14205
      {
12068
14206
        Item *item= *group->item;
12069
14207
        if (item->maybe_null)
12070
14208
        {
12071
14209
          Field *field=item->get_tmp_table_field();
12072
 
          field->ptr[-1]= (unsigned char) (field->is_null() ? 1 : 0);
 
14210
          field->ptr[-1]= (uchar) (field->is_null() ? 1 : 0);
12073
14211
        }
12074
14212
      }
12075
14213
    }
12086
14224
                                    join->tmp_table_param.start_recinfo,
12087
14225
                                    &join->tmp_table_param.recinfo,
12088
14226
                                    error, 1))
12089
 
          return(NESTED_LOOP_ERROR);        // Not a table_is_full error
 
14227
          DBUG_RETURN(NESTED_LOOP_ERROR);        // Not a table_is_full error
12090
14228
        table->s->uniques=0;                    // To ensure rows are the same
12091
14229
      }
12092
14230
      if (++join->send_records >= join->tmp_table_param.end_write_records &&
12093
14231
          join->do_send_rows)
12094
14232
      {
12095
14233
        if (!(join->select_options & OPTION_FOUND_ROWS))
12096
 
          return(NESTED_LOOP_QUERY_LIMIT);
 
14234
          DBUG_RETURN(NESTED_LOOP_QUERY_LIMIT);
12097
14235
        join->do_send_rows=0;
12098
14236
        join->unit->select_limit_cnt = HA_POS_ERROR;
12099
 
        return(NESTED_LOOP_OK);
 
14237
        DBUG_RETURN(NESTED_LOOP_OK);
12100
14238
      }
12101
14239
    }
12102
14240
  }
12103
14241
end:
12104
 
  return(NESTED_LOOP_OK);
 
14242
  DBUG_RETURN(NESTED_LOOP_OK);
12105
14243
}
12106
14244
 
12107
14245
/* ARGSUSED */
12111
14249
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12112
14250
           bool end_of_records)
12113
14251
{
12114
 
  Table *table=join->tmp_table;
12115
 
  order_st   *group;
 
14252
  TABLE *table=join->tmp_table;
 
14253
  ORDER   *group;
12116
14254
  int     error;
 
14255
  DBUG_ENTER("end_update");
12117
14256
 
12118
14257
  if (end_of_records)
12119
 
    return(NESTED_LOOP_OK);
 
14258
    DBUG_RETURN(NESTED_LOOP_OK);
12120
14259
  if (join->thd->killed)                        // Aborted by user
12121
14260
  {
12122
14261
    join->thd->send_kill_message();
12123
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
14262
    DBUG_RETURN(NESTED_LOOP_KILLED);             /* purecov: inspected */
12124
14263
  }
12125
14264
 
12126
14265
  join->found_records++;
12145
14284
                                          table->record[0])))
12146
14285
    {
12147
14286
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12148
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
14287
      DBUG_RETURN(NESTED_LOOP_ERROR);            /* purecov: inspected */
12149
14288
    }
12150
 
    return(NESTED_LOOP_OK);
 
14289
    DBUG_RETURN(NESTED_LOOP_OK);
12151
14290
  }
12152
14291
 
12153
14292
  /*
12171
14310
                                join->tmp_table_param.start_recinfo,
12172
14311
                                &join->tmp_table_param.recinfo,
12173
14312
                                error, 0))
12174
 
      return(NESTED_LOOP_ERROR);            // Not a table_is_full error
 
14313
      DBUG_RETURN(NESTED_LOOP_ERROR);            // Not a table_is_full error
12175
14314
    /* Change method to update rows */
12176
14315
    table->file->ha_index_init(0, 0);
12177
14316
    join->join_tab[join->tables-1].next_select=end_unique_update;
12178
14317
  }
12179
14318
  join->send_records++;
12180
 
  return(NESTED_LOOP_OK);
 
14319
  DBUG_RETURN(NESTED_LOOP_OK);
12181
14320
}
12182
14321
 
12183
14322
 
12187
14326
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12188
14327
                  bool end_of_records)
12189
14328
{
12190
 
  Table *table=join->tmp_table;
 
14329
  TABLE *table=join->tmp_table;
12191
14330
  int     error;
 
14331
  DBUG_ENTER("end_unique_update");
12192
14332
 
12193
14333
  if (end_of_records)
12194
 
    return(NESTED_LOOP_OK);
 
14334
    DBUG_RETURN(NESTED_LOOP_OK);
12195
14335
  if (join->thd->killed)                        // Aborted by user
12196
14336
  {
12197
14337
    join->thd->send_kill_message();
12198
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
14338
    DBUG_RETURN(NESTED_LOOP_KILLED);             /* purecov: inspected */
12199
14339
  }
12200
14340
 
12201
14341
  init_tmptable_sum_functions(join->sum_funcs);
12209
14349
    if ((int) table->file->get_dup_key(error) < 0)
12210
14350
    {
12211
14351
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12212
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
14352
      DBUG_RETURN(NESTED_LOOP_ERROR);            /* purecov: inspected */
12213
14353
    }
12214
14354
    if (table->file->rnd_pos(table->record[1],table->file->dup_ref))
12215
14355
    {
12216
14356
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12217
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
14357
      DBUG_RETURN(NESTED_LOOP_ERROR);            /* purecov: inspected */
12218
14358
    }
12219
14359
    restore_record(table,record[1]);
12220
14360
    update_tmptable_sum_func(join->sum_funcs,table);
12222
14362
                                          table->record[0])))
12223
14363
    {
12224
14364
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12225
 
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
 
14365
      DBUG_RETURN(NESTED_LOOP_ERROR);            /* purecov: inspected */
12226
14366
    }
12227
14367
  }
12228
 
  return(NESTED_LOOP_OK);
 
14368
  DBUG_RETURN(NESTED_LOOP_OK);
12229
14369
}
12230
14370
 
12231
14371
 
12234
14374
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12235
14375
                bool end_of_records)
12236
14376
{
12237
 
  Table *table=join->tmp_table;
 
14377
  TABLE *table=join->tmp_table;
12238
14378
  int     idx= -1;
 
14379
  DBUG_ENTER("end_write_group");
12239
14380
 
12240
14381
  if (join->thd->killed)
12241
14382
  {                                             // Aborted by user
12242
14383
    join->thd->send_kill_message();
12243
 
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
 
14384
    DBUG_RETURN(NESTED_LOOP_KILLED);             /* purecov: inspected */
12244
14385
  }
12245
14386
  if (!join->first_record || end_of_records ||
12246
14387
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
12264
14405
                                               join->tmp_table_param.start_recinfo,
12265
14406
                                                &join->tmp_table_param.recinfo,
12266
14407
                                               error, 0))
12267
 
            return(NESTED_LOOP_ERROR);
 
14408
            DBUG_RETURN(NESTED_LOOP_ERROR);
12268
14409
        }
12269
14410
        if (join->rollup.state != ROLLUP::STATE_NONE)
12270
14411
        {
12271
14412
          if (join->rollup_write_data((uint) (idx+1), table))
12272
 
            return(NESTED_LOOP_ERROR);
 
14413
            DBUG_RETURN(NESTED_LOOP_ERROR);
12273
14414
        }
12274
14415
        if (end_of_records)
12275
 
          return(NESTED_LOOP_OK);
 
14416
          DBUG_RETURN(NESTED_LOOP_OK);
12276
14417
      }
12277
14418
    }
12278
14419
    else
12279
14420
    {
12280
14421
      if (end_of_records)
12281
 
        return(NESTED_LOOP_OK);
 
14422
        DBUG_RETURN(NESTED_LOOP_OK);
12282
14423
      join->first_record=1;
12283
 
      test_if_item_cache_changed(join->group_fields);
 
14424
      VOID(test_if_item_cache_changed(join->group_fields));
12284
14425
    }
12285
14426
    if (idx < (int) join->send_group_parts)
12286
14427
    {
12287
14428
      copy_fields(&join->tmp_table_param);
12288
14429
      copy_funcs(join->tmp_table_param.items_to_copy);
12289
14430
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
12290
 
        return(NESTED_LOOP_ERROR);
12291
 
      return(NESTED_LOOP_OK);
 
14431
        DBUG_RETURN(NESTED_LOOP_ERROR);
 
14432
      DBUG_RETURN(NESTED_LOOP_OK);
12292
14433
    }
12293
14434
  }
12294
14435
  if (update_sum_func(join->sum_funcs))
12295
 
    return(NESTED_LOOP_ERROR);
12296
 
  return(NESTED_LOOP_OK);
 
14436
    DBUG_RETURN(NESTED_LOOP_ERROR);
 
14437
  DBUG_RETURN(NESTED_LOOP_OK);
12297
14438
}
12298
14439
 
12299
14440
 
12341
14482
          frequent case?
12342
14483
        */
12343
14484
        if (field->binary() &&
12344
 
            field->real_type() != DRIZZLE_TYPE_VARCHAR &&
12345
 
            field->decimals() == 0)
 
14485
            field->real_type() != MYSQL_TYPE_STRING &&
 
14486
            field->real_type() != MYSQL_TYPE_VARCHAR &&
 
14487
            (field->type() != MYSQL_TYPE_FLOAT || field->decimals() == 0))
12346
14488
        {
12347
14489
          return !store_val_in_field(field, right_item, CHECK_FIELD_WARN);
12348
14490
        }
12376
14518
    join->conds= new_cond;
12377
14519
    if (do_fix_fields)
12378
14520
      new_cond->fix_fields(join->thd, &join->conds);
12379
 
    return false;
 
14521
    return FALSE;
12380
14522
  }
12381
14523
  
12382
14524
  if (join->conds->type() == Item::COND_ITEM) {
12388
14530
        li.replace(new_cond);
12389
14531
        if (do_fix_fields)
12390
14532
          new_cond->fix_fields(join->thd, li.ref());
12391
 
        return false;
 
14533
        return FALSE;
12392
14534
      }
12393
14535
  }
12394
14536
 
12395
 
  return true;
 
14537
  return TRUE;
12396
14538
}
12397
14539
 
12398
14540
/*
12542
14684
 
12543
14685
 
12544
14686
static Item *
12545
 
part_of_refkey(Table *table,Field *field)
 
14687
part_of_refkey(TABLE *table,Field *field)
12546
14688
{
12547
14689
  if (!table->reginfo.join_tab)
12548
14690
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
12549
14691
 
12550
 
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
 
14692
  uint ref_parts=table->reginfo.join_tab->ref.key_parts;
12551
14693
  if (ref_parts)
12552
14694
  {
12553
14695
    KEY_PART_INFO *key_part=
12554
14696
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
12555
 
    uint32_t part;
 
14697
    uint part;
12556
14698
 
12557
14699
    for (part=0 ; part < ref_parts ; part++)
12558
14700
    {
12570
14712
 
12571
14713
 
12572
14714
/**
12573
 
  Test if one can use the key to resolve order_st BY.
 
14715
  Test if one can use the key to resolve ORDER BY.
12574
14716
 
12575
14717
  @param order                 Sort order
12576
14718
  @param table                 Table to sort
12590
14732
    -1   Reverse key can be used
12591
14733
*/
12592
14734
 
12593
 
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx,
12594
 
                                uint32_t *used_key_parts)
 
14735
static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
 
14736
                                uint *used_key_parts)
12595
14737
{
12596
14738
  KEY_PART_INFO *key_part,*key_part_end;
12597
14739
  key_part=table->key_info[idx].key_part;
12598
14740
  key_part_end=key_part+table->key_info[idx].key_parts;
12599
14741
  key_part_map const_key_parts=table->const_key_parts[idx];
12600
14742
  int reverse=0;
12601
 
  bool on_primary_key= false;
 
14743
  my_bool on_primary_key= FALSE;
 
14744
  DBUG_ENTER("test_if_order_by_key");
12602
14745
 
12603
14746
  for (; order ; order=order->next, const_key_parts>>=1)
12604
14747
  {
12607
14750
 
12608
14751
    /*
12609
14752
      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()
 
14753
      These are already skipped in the ORDER BY by const_expression_in_where()
12611
14754
    */
12612
14755
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
12613
14756
      key_part++; 
12623
14766
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
12624
14767
          table->s->primary_key != MAX_KEY)
12625
14768
      {
12626
 
        on_primary_key= true;
 
14769
        on_primary_key= TRUE;
12627
14770
        key_part= table->key_info[table->s->primary_key].key_part;
12628
14771
        key_part_end=key_part+table->key_info[table->s->primary_key].key_parts;
12629
14772
        const_key_parts=table->const_key_parts[table->s->primary_key];
12635
14778
         one row).  The sorting doesn't matter.
12636
14779
        */
12637
14780
        if (key_part == key_part_end && reverse == 0)
12638
 
          return(1);
 
14781
          DBUG_RETURN(1);
12639
14782
      }
12640
14783
      else
12641
 
        return(0);
 
14784
        DBUG_RETURN(0);
12642
14785
    }
12643
14786
 
12644
14787
    if (key_part->field != field)
12645
 
      return(0);
 
14788
      DBUG_RETURN(0);
12646
14789
 
12647
14790
    /* set flag to 1 if we can use read-next on key, else to -1 */
12648
14791
    flag= ((order->asc == !(key_part->key_part_flag & HA_REVERSE_SORT)) ?
12649
14792
           1 : -1);
12650
14793
    if (reverse && flag != reverse)
12651
 
      return(0);
 
14794
      DBUG_RETURN(0);
12652
14795
    reverse=flag;                               // Remember if reverse
12653
14796
    key_part++;
12654
14797
  }
12657
14800
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
12658
14801
                         HA_READ_PREV))
12659
14802
    reverse= 0;                                 // Index can't be used
12660
 
  return(reverse);
12661
 
}
12662
 
 
 
14803
  DBUG_RETURN(reverse);
 
14804
}
 
14805
 
 
14806
 
 
14807
uint find_shortest_key(TABLE *table, const key_map *usable_keys)
 
14808
{
 
14809
  uint min_length= (uint) ~0;
 
14810
  uint best= MAX_KEY;
 
14811
  if (!usable_keys->is_clear_all())
 
14812
  {
 
14813
    for (uint nr=0; nr < table->s->keys ; nr++)
 
14814
    {
 
14815
      if (usable_keys->is_set(nr))
 
14816
      {
 
14817
        if (table->key_info[nr].key_length < min_length)
 
14818
        {
 
14819
          min_length=table->key_info[nr].key_length;
 
14820
          best=nr;
 
14821
        }
 
14822
      }
 
14823
    }
 
14824
  }
 
14825
  return best;
 
14826
}
12663
14827
 
12664
14828
/**
12665
14829
  Test if a second key is the subkey of the first one.
12700
14864
*/
12701
14865
 
12702
14866
static uint
12703
 
test_if_subkey(order_st *order, Table *table, uint32_t ref, uint32_t ref_key_parts,
 
14867
test_if_subkey(ORDER *order, TABLE *table, uint ref, uint ref_key_parts,
12704
14868
               const key_map *usable_keys)
12705
14869
{
12706
 
  uint32_t nr;
12707
 
  uint32_t min_length= UINT32_MAX;
12708
 
  uint32_t best= MAX_KEY;
12709
 
  uint32_t not_used;
 
14870
  uint nr;
 
14871
  uint min_length= (uint) ~0;
 
14872
  uint best= MAX_KEY;
 
14873
  uint not_used;
12710
14874
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
12711
14875
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
12712
14876
 
12760
14924
*/
12761
14925
 
12762
14926
static bool
12763
 
list_contains_unique_index(Table *table,
 
14927
list_contains_unique_index(TABLE *table,
12764
14928
                          bool (*find_func) (Field *, void *), void *data)
12765
14929
{
12766
 
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
 
14930
  for (uint keynr= 0; keynr < table->s->keys; keynr++)
12767
14931
  {
12768
14932
    if (keynr == table->s->primary_key ||
12769
14933
         (table->key_info[keynr].flags & HA_NOSAME))
12790
14954
 
12791
14955
/**
12792
14956
  Helper function for list_contains_unique_index.
12793
 
  Find a field reference in a list of order_st structures.
 
14957
  Find a field reference in a list of ORDER structures.
12794
14958
  Finds a direct reference of the Field in the list.
12795
14959
 
12796
14960
  @param field                The field to search for.
12797
 
  @param data                 order_st *.The list to search in
 
14961
  @param data                 ORDER *.The list to search in
12798
14962
 
12799
14963
  @retval
12800
14964
    1                    found
12805
14969
static bool
12806
14970
find_field_in_order_list (Field *field, void *data)
12807
14971
{
12808
 
  order_st *group= (order_st *) data;
 
14972
  ORDER *group= (ORDER *) data;
12809
14973
  bool part_found= 0;
12810
 
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
14974
  for (ORDER *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
12811
14975
  {
12812
14976
    Item *item= (*tmp_group->item)->real_item();
12813
14977
    if (item->type() == Item::FIELD_ITEM &&
12857
15021
 
12858
15022
 
12859
15023
/**
12860
 
  Test if we can skip the order_st BY by using an index.
 
15024
  Test if we can skip the ORDER BY by using an index.
12861
15025
 
12862
15026
  SYNOPSIS
12863
15027
    test_if_skip_sort_order()
12883
15047
*/
12884
15048
 
12885
15049
static bool
12886
 
test_if_skip_sort_order(JOIN_TAB *tab,order_st *order,ha_rows select_limit,
 
15050
test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
12887
15051
                        bool no_changes, const key_map *map)
12888
15052
{
12889
 
  int32_t ref_key;
12890
 
  uint32_t ref_key_parts;
 
15053
  int ref_key;
 
15054
  uint ref_key_parts;
12891
15055
  int order_direction;
12892
 
  uint32_t used_key_parts;
12893
 
  Table *table=tab->table;
 
15056
  uint used_key_parts;
 
15057
  TABLE *table=tab->table;
12894
15058
  SQL_SELECT *select=tab->select;
12895
15059
  key_map usable_keys;
12896
15060
  QUICK_SELECT_I *save_quick= 0;
 
15061
  DBUG_ENTER("test_if_skip_sort_order");
12897
15062
 
12898
15063
  /*
12899
 
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
 
15064
    Keys disabled by ALTER TABLE ... DISABLE KEYS should have already
12900
15065
    been taken into account.
12901
15066
  */
12902
15067
  usable_keys= *map;
12903
15068
 
12904
 
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
15069
  for (ORDER *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
12905
15070
  {
12906
15071
    Item *item= (*tmp_order->item)->real_item();
12907
15072
    if (item->type() != Item::FIELD_ITEM)
12908
15073
    {
12909
15074
      usable_keys.clear_all();
12910
 
      return(0);
 
15075
      DBUG_RETURN(0);
12911
15076
    }
12912
15077
    usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey);
12913
15078
    if (usable_keys.is_clear_all())
12914
 
      return(0);                                        // No usable keys
 
15079
      DBUG_RETURN(0);                                   // No usable keys
12915
15080
  }
12916
15081
 
12917
15082
  ref_key= -1;
12921
15086
    ref_key=       tab->ref.key;
12922
15087
    ref_key_parts= tab->ref.key_parts;
12923
15088
    if (tab->type == JT_REF_OR_NULL)
12924
 
      return(0);
 
15089
      DBUG_RETURN(0);
12925
15090
  }
12926
15091
  else if (select && select->quick)             // Range found by opt_range
12927
15092
  {
12936
15101
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE || 
12937
15102
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || 
12938
15103
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
12939
 
      return(0);
 
15104
      DBUG_RETURN(0);
12940
15105
    ref_key=       select->quick->index;
12941
15106
    ref_key_parts= select->quick->used_key_parts;
12942
15107
  }
12951
15116
      /*
12952
15117
        We come here when ref_key is not among usable_keys
12953
15118
      */
12954
 
      uint32_t new_ref_key;
 
15119
      uint new_ref_key;
12955
15120
      /*
12956
15121
        If using index only read, only consider other possible index only
12957
15122
        keys
12980
15145
 
12981
15146
          if (create_ref_for_key(tab->join, tab, keyuse, 
12982
15147
                                 tab->join->const_table_map))
12983
 
            return(0);
 
15148
            DBUG_RETURN(0);
12984
15149
        }
12985
15150
        else
12986
15151
        {
13001
15166
                                         OPTION_FOUND_ROWS) ?
13002
15167
                                        HA_POS_ERROR :
13003
15168
                                        tab->join->unit->select_limit_cnt,0,
13004
 
                                        true) <=
 
15169
                                        TRUE) <=
13005
15170
              0)
13006
 
            return(0);
 
15171
            DBUG_RETURN(0);
13007
15172
        }
13008
15173
        ref_key= new_ref_key;
13009
15174
      }
13019
15184
      Check whether there is an index compatible with the given order
13020
15185
      usage of which is cheaper than usage of the ref_key index (ref_key>=0)
13021
15186
      or a table scan.
13022
 
      It may be the case if order_st/GROUP BY is used with LIMIT.
 
15187
      It may be the case if ORDER/GROUP BY is used with LIMIT.
13023
15188
    */
13024
 
    uint32_t nr;
 
15189
    uint nr;
13025
15190
    key_map keys;
13026
 
    uint32_t best_key_parts= 0;
 
15191
    uint best_key_parts= 0;
13027
15192
    int best_key_direction= 0;
13028
15193
    ha_rows best_records= 0;
13029
15194
    double read_time;
13030
15195
    int best_key= -1;
13031
 
    bool is_best_covering= false;
 
15196
    bool is_best_covering= FALSE;
13032
15197
    double fanout= 1;
13033
15198
    JOIN *join= tab->join;
13034
 
    uint32_t tablenr= tab - join->join_tab;
 
15199
    uint tablenr= tab - join->join_tab;
13035
15200
    ha_rows table_records= table->file->stats.records;
13036
15201
    bool group= join->group && order == join->group_list;
13037
15202
 
13047
15212
        index order and not using join cache
13048
15213
        */
13049
15214
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
13050
 
        return(0);
 
15215
        DBUG_RETURN(0);
13051
15216
      keys= *table->file->keys_to_use_for_scanning();
13052
15217
      keys.merge(table->covering_keys);
13053
15218
 
13054
15219
      /*
13055
15220
        We are adding here also the index specified in FORCE INDEX clause, 
13056
15221
        if any.
13057
 
        This is to allow users to use index in order_st BY.
 
15222
        This is to allow users to use index in ORDER BY.
13058
15223
      */
13059
15224
      if (table->force_index) 
13060
15225
        keys.merge(group ? table->keys_in_use_for_group_by :
13065
15230
      keys= usable_keys;
13066
15231
 
13067
15232
    read_time= join->best_positions[tablenr].read_time;
13068
 
    for (uint32_t i= tablenr+1; i < join->tables; i++)
 
15233
    for (uint i= tablenr+1; i < join->tables; i++)
13069
15234
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
13070
15235
 
13071
15236
    for (nr=0; nr < table->s->keys ; nr++)
13077
15242
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13078
15243
        
13079
15244
        /* 
13080
 
          Don't use an index scan with order_st BY without limit.
 
15245
          Don't use an index scan with ORDER BY without limit.
13081
15246
          For GROUP BY without limit always use index scan
13082
15247
          if there is a suitable index. 
13083
15248
          Why we hold to this asymmetry hardly can be explained
13150
15315
            index entry.
13151
15316
          */
13152
15317
          index_scan_time= select_limit/rec_per_key *
13153
 
                           cmin(rec_per_key, table->file->scan_time());
 
15318
                           min(rec_per_key, table->file->scan_time());
13154
15319
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
13155
15320
              index_scan_time < read_time)
13156
15321
          {
13160
15325
            if (table->quick_keys.is_set(nr))
13161
15326
              quick_records= table->quick_rows[nr];
13162
15327
            if (best_key < 0 ||
13163
 
                (select_limit <= cmin(quick_records,best_records) ?
 
15328
                (select_limit <= min(quick_records,best_records) ?
13164
15329
                 keyinfo->key_parts < best_key_parts :
13165
15330
                 quick_records < best_records))
13166
15331
            {
13176
15341
    }
13177
15342
    if (best_key >= 0)
13178
15343
    {
13179
 
      bool quick_created= false;
 
15344
      bool quick_created= FALSE;
13180
15345
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
13181
15346
      {
13182
15347
        key_map map;
13187
15352
                                    join->select_options & OPTION_FOUND_ROWS ?
13188
15353
                                    HA_POS_ERROR :
13189
15354
                                    join->unit->select_limit_cnt,
13190
 
                                    true, false) > 0;
 
15355
                                    TRUE, FALSE) > 0;
13191
15356
      }
13192
15357
      if (!no_changes)
13193
15358
      {
13223
15388
            We need to change the access method so as the quick access
13224
15389
            method is actually used.
13225
15390
          */
13226
 
          assert(tab->select->quick);
 
15391
          DBUG_ASSERT(tab->select->quick);
13227
15392
          tab->type=JT_ALL;
13228
15393
          tab->use_quick=1;
13229
15394
          tab->ref.key= -1;
13238
15403
      order_direction= best_key_direction;
13239
15404
    }
13240
15405
    else
13241
 
      return(0); 
 
15406
      DBUG_RETURN(0); 
13242
15407
  } 
13243
15408
 
13244
15409
check_reverse_order:                  
13245
 
  if (order_direction == -1)            // If order_st BY ... DESC
 
15410
  if (order_direction == -1)            // If ORDER BY ... DESC
13246
15411
  {
13247
15412
    if (select && select->quick)
13248
15413
    {
13253
15418
      if (!select->quick->reverse_sorted())
13254
15419
      {
13255
15420
        QUICK_SELECT_DESC *tmp;
13256
 
        bool error= false;
 
15421
        bool error= FALSE;
13257
15422
        int quick_type= select->quick->get_type();
13258
15423
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
13259
15424
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
13262
15427
        {
13263
15428
          tab->limit= 0;
13264
15429
          select->quick= save_quick;
13265
 
          return(0);                   // Use filesort
 
15430
          DBUG_RETURN(0);                   // Use filesort
13266
15431
        }
13267
15432
            
13268
 
        /* order_st BY range_key DESC */
 
15433
        /* ORDER BY range_key DESC */
13269
15434
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
13270
15435
                                    used_key_parts, &error);
13271
15436
        if (!tmp || error)
13273
15438
          delete tmp;
13274
15439
          select->quick= save_quick;
13275
15440
          tab->limit= 0;
13276
 
          return(0);            // Reverse sort not supported
 
15441
          DBUG_RETURN(0);               // Reverse sort not supported
13277
15442
        }
13278
15443
        select->quick=tmp;
13279
15444
      }
13282
15447
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
13283
15448
    {
13284
15449
      /*
13285
 
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
 
15450
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
13286
15451
 
13287
15452
        Use a traversal function that starts by reading the last row
13288
15453
        with key part (A) and then traverse the index backwards.
13293
15458
  }
13294
15459
  else if (select && select->quick)
13295
15460
    select->quick->sorted= 1;
13296
 
  return(1);
 
15461
  DBUG_RETURN(1);
13297
15462
}
13298
15463
 
13299
15464
 
13308
15473
     filesort_limit     Max number of rows that needs to be sorted
13309
15474
     select_limit       Max number of rows in final output
13310
15475
                        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
 
15476
     is_order_by        true if we are sorting on ORDER BY, false if GROUP BY
13312
15477
                        Used to decide if we should use index or not     
13313
15478
 
13314
15479
 
13327
15492
*/
13328
15493
 
13329
15494
static int
13330
 
create_sort_index(THD *thd, JOIN *join, order_st *order,
 
15495
create_sort_index(THD *thd, JOIN *join, ORDER *order,
13331
15496
                  ha_rows filesort_limit, ha_rows select_limit,
13332
15497
                  bool is_order_by)
13333
15498
{
13334
 
  uint32_t length= 0;
 
15499
  uint length= 0;
13335
15500
  ha_rows examined_rows;
13336
 
  Table *table;
 
15501
  TABLE *table;
13337
15502
  SQL_SELECT *select;
13338
15503
  JOIN_TAB *tab;
 
15504
  DBUG_ENTER("create_sort_index");
13339
15505
 
13340
15506
  if (join->tables == join->const_tables)
13341
 
    return(0);                          // One row, no need to sort
 
15507
    DBUG_RETURN(0);                             // One row, no need to sort
13342
15508
  tab=    join->join_tab + join->const_tables;
13343
15509
  table=  tab->table;
13344
15510
  select= tab->select;
13355
15521
      test_if_skip_sort_order(tab,order,select_limit,0, 
13356
15522
                              is_order_by ?  &table->keys_in_use_for_order_by :
13357
15523
                              &table->keys_in_use_for_group_by))
13358
 
    return(0);
13359
 
  for (order_st *ord= join->order; ord; ord= ord->next)
 
15524
    DBUG_RETURN(0);
 
15525
  for (ORDER *ord= join->order; ord; ord= ord->next)
13360
15526
    length++;
13361
15527
  if (!(join->sortorder= 
13362
15528
        make_unireg_sortorder(order, &length, join->sortorder)))
13424
15590
    table->key_read=0;
13425
15591
    table->file->extra(HA_EXTRA_NO_KEYREAD);
13426
15592
  }
13427
 
  return(table->sort.found_records == HA_POS_ERROR);
 
15593
  DBUG_RETURN(table->sort.found_records == HA_POS_ERROR);
13428
15594
err:
13429
 
  return(-1);
 
15595
  DBUG_RETURN(-1);
 
15596
}
 
15597
 
 
15598
/*****************************************************************************
 
15599
  Remove duplicates from tmp table
 
15600
  This should be recoded to add a unique index to the table and remove
 
15601
  duplicates
 
15602
  Table is a locked single thread table
 
15603
  fields is the number of fields to check (from the end)
 
15604
*****************************************************************************/
 
15605
 
 
15606
static bool compare_record(TABLE *table, Field **ptr)
 
15607
{
 
15608
  for (; *ptr ; ptr++)
 
15609
  {
 
15610
    if ((*ptr)->cmp_offset(table->s->rec_buff_length))
 
15611
      return 1;
 
15612
  }
 
15613
  return 0;
13430
15614
}
13431
15615
 
13432
15616
static bool copy_blobs(Field **ptr)
13451
15635
 
13452
15636
 
13453
15637
static int
13454
 
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
 
15638
remove_duplicates(JOIN *join, TABLE *entry,List<Item> &fields, Item *having)
13455
15639
{
13456
15640
  int error;
13457
15641
  ulong reclength,offset;
13458
 
  uint32_t field_count;
 
15642
  uint field_count;
13459
15643
  THD *thd= join->thd;
 
15644
  DBUG_ENTER("remove_duplicates");
13460
15645
 
13461
15646
  entry->reginfo.lock_type=TL_WRITE;
13462
15647
 
13473
15658
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having) 
13474
15659
  {                    // only const items with no OPTION_FOUND_ROWS
13475
15660
    join->unit->select_limit_cnt= 1;            // Only send first row
13476
 
    return(0);
 
15661
    DBUG_RETURN(0);
13477
15662
  }
13478
15663
  Field **first_field=entry->field+entry->s->fields - field_count;
13479
15664
  offset= (field_count ? 
13495
15680
                                  having);
13496
15681
 
13497
15682
  free_blobs(first_field);
13498
 
  return(error);
 
15683
  DBUG_RETURN(error);
13499
15684
}
13500
15685
 
13501
15686
 
13502
 
static int remove_dup_with_compare(THD *thd, Table *table, Field **first_field,
 
15687
static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field,
13503
15688
                                   ulong offset, Item *having)
13504
15689
{
13505
15690
  handler *file=table->file;
13506
15691
  char *org_record,*new_record;
13507
 
  unsigned char *record;
 
15692
  uchar *record;
13508
15693
  int error;
13509
15694
  ulong reclength= table->s->reclength-offset;
 
15695
  DBUG_ENTER("remove_dup_with_compare");
13510
15696
 
13511
15697
  org_record=(char*) (record=table->record[0])+offset;
13512
15698
  new_record=(char*) table->record[1]+offset;
13556
15742
          break;
13557
15743
        goto err;
13558
15744
      }
13559
 
      if (table->compare_record(first_field) == 0)
 
15745
      if (compare_record(table, first_field) == 0)
13560
15746
      {
13561
15747
        if ((error=file->ha_delete_row(record)))
13562
15748
          goto err;
13574
15760
  }
13575
15761
 
13576
15762
  file->extra(HA_EXTRA_NO_CACHE);
13577
 
  return(0);
 
15763
  DBUG_RETURN(0);
13578
15764
err:
13579
15765
  file->extra(HA_EXTRA_NO_CACHE);
13580
15766
  if (error)
13581
15767
    file->print_error(error,MYF(0));
13582
 
  return(1);
 
15768
  DBUG_RETURN(1);
13583
15769
}
13584
15770
 
13585
15771
 
13590
15776
    Note that this will not work on tables with blobs!
13591
15777
*/
13592
15778
 
13593
 
static int remove_dup_with_hash_index(THD *thd, Table *table,
13594
 
                                      uint32_t field_count,
 
15779
static int remove_dup_with_hash_index(THD *thd, TABLE *table,
 
15780
                                      uint field_count,
13595
15781
                                      Field **first_field,
13596
15782
                                      ulong key_length,
13597
15783
                                      Item *having)
13598
15784
{
13599
 
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
 
15785
  uchar *key_buffer, *key_pos, *record=table->record[0];
13600
15786
  int error;
13601
15787
  handler *file= table->file;
13602
15788
  ulong extra_length= ALIGN_SIZE(key_length)-key_length;
13603
 
  uint32_t *field_lengths,*field_length;
 
15789
  uint *field_lengths,*field_length;
13604
15790
  HASH hash;
 
15791
  DBUG_ENTER("remove_dup_with_hash_index");
13605
15792
 
13606
15793
  if (!my_multi_malloc(MYF(MY_WME),
13607
15794
                       &key_buffer,
13609
15796
                               (long) file->stats.records),
13610
15797
                       &field_lengths,
13611
15798
                       (uint) (field_count*sizeof(*field_lengths)),
13612
 
                       NULL))
13613
 
    return(1);
 
15799
                       NullS))
 
15800
    DBUG_RETURN(1);
13614
15801
 
13615
15802
  {
13616
15803
    Field **ptr;
13617
15804
    ulong total_length= 0;
13618
15805
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
13619
15806
    {
13620
 
      uint32_t length= (*ptr)->sort_length();
 
15807
      uint length= (*ptr)->sort_length();
13621
15808
      (*field_length++)= length;
13622
15809
      total_length+= length;
13623
15810
    }
13624
 
    assert(total_length <= key_length);
 
15811
    DBUG_PRINT("info",("field_count: %u  key_length: %lu  total_length: %lu",
 
15812
                       field_count, key_length, total_length));
 
15813
    DBUG_ASSERT(total_length <= key_length);
13625
15814
    key_length= total_length;
13626
15815
    extra_length= ALIGN_SIZE(key_length)-key_length;
13627
15816
  }
13629
15818
  if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, 
13630
15819
                key_length, (hash_get_key) 0, 0, 0))
13631
15820
  {
13632
 
    free((char*) key_buffer);
13633
 
    return(1);
 
15821
    my_free((char*) key_buffer,MYF(0));
 
15822
    DBUG_RETURN(1);
13634
15823
  }
13635
15824
 
13636
15825
  file->ha_rnd_init(1);
13637
15826
  key_pos=key_buffer;
13638
15827
  for (;;)
13639
15828
  {
13640
 
    unsigned char *org_key_pos;
 
15829
    uchar *org_key_pos;
13641
15830
    if (thd->killed)
13642
15831
    {
13643
15832
      thd->send_kill_message();
13678
15867
      (void) my_hash_insert(&hash, org_key_pos);
13679
15868
    key_pos+=extra_length;
13680
15869
  }
13681
 
  free((char*) key_buffer);
 
15870
  my_free((char*) key_buffer,MYF(0));
13682
15871
  hash_free(&hash);
13683
15872
  file->extra(HA_EXTRA_NO_CACHE);
13684
15873
  (void) file->ha_rnd_end();
13685
 
  return(0);
 
15874
  DBUG_RETURN(0);
13686
15875
 
13687
15876
err:
13688
 
  free((char*) key_buffer);
 
15877
  my_free((char*) key_buffer,MYF(0));
13689
15878
  hash_free(&hash);
13690
15879
  file->extra(HA_EXTRA_NO_CACHE);
13691
15880
  (void) file->ha_rnd_end();
13692
15881
  if (error)
13693
15882
    file->print_error(error,MYF(0));
13694
 
  return(1);
 
15883
  DBUG_RETURN(1);
13695
15884
}
13696
15885
 
13697
15886
 
13698
 
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length,
 
15887
SORT_FIELD *make_unireg_sortorder(ORDER *order, uint *length,
13699
15888
                                  SORT_FIELD *sortorder)
13700
15889
{
13701
 
  uint32_t count;
 
15890
  uint count;
13702
15891
  SORT_FIELD *sort,*pos;
 
15892
  DBUG_ENTER("make_unireg_sortorder");
13703
15893
 
13704
15894
  count=0;
13705
 
  for (order_st *tmp = order; tmp; tmp=tmp->next)
 
15895
  for (ORDER *tmp = order; tmp; tmp=tmp->next)
13706
15896
    count++;
13707
15897
  if (!sortorder)
13708
15898
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
13709
 
                                       (cmax(count, *length) + 1));
 
15899
                                       (max(count, *length) + 1));
13710
15900
  pos= sort= sortorder;
13711
15901
 
13712
15902
  if (!pos)
13729
15919
    pos->reverse=! order->asc;
13730
15920
  }
13731
15921
  *length=count;
13732
 
  return(sort);
 
15922
  DBUG_RETURN(sort);
13733
15923
}
13734
15924
 
13735
15925
 
13741
15931
******************************************************************************/
13742
15932
 
13743
15933
static int
13744
 
join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count)
 
15934
join_init_cache(THD *thd,JOIN_TAB *tables,uint table_count)
13745
15935
{
13746
15936
  register unsigned int i;
13747
15937
  unsigned int length, blobs;
13749
15939
  CACHE_FIELD *copy,**blob_ptr;
13750
15940
  JOIN_CACHE  *cache;
13751
15941
  JOIN_TAB *join_tab;
 
15942
  DBUG_ENTER("join_init_cache");
13752
15943
 
13753
15944
  cache= &tables[table_count].cache;
13754
15945
  cache->fields=blobs=0;
13773
15964
 
13774
15965
                  sizeof(CACHE_FIELD*))))
13775
15966
  {
13776
 
    free((unsigned char*) cache->buff);         /* purecov: inspected */
 
15967
    my_free((uchar*) cache->buff,MYF(0));               /* purecov: inspected */
13777
15968
    cache->buff=0;                              /* purecov: inspected */
13778
 
    return(1);                          /* purecov: inspected */
 
15969
    DBUG_RETURN(1);                             /* purecov: inspected */
13779
15970
  }
13780
15971
  copy=cache->field;
13781
15972
  blob_ptr=cache->blob_ptr=(CACHE_FIELD**)
13784
15975
  length=0;
13785
15976
  for (i=0 ; i < table_count ; i++)
13786
15977
  {
13787
 
    uint32_t null_fields=0, used_fields;
 
15978
    uint null_fields=0,used_fields;
13788
15979
    Field **f_ptr,*field;
13789
15980
    MY_BITMAP *read_set= tables[i].table->read_set;
13790
15981
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
13805
15996
      }
13806
15997
    }
13807
15998
    /* Copy null bits from table */
13808
 
    if (null_fields && tables[i].table->getNullFields())
 
15999
    if (null_fields && tables[i].table->s->null_fields)
13809
16000
    {                                           /* must copy null bits */
13810
16001
      copy->str= tables[i].table->null_flags;
13811
16002
      copy->length= tables[i].table->s->null_bytes;
13819
16010
    /* If outer join table, copy null_row flag */
13820
16011
    if (tables[i].table->maybe_null)
13821
16012
    {
13822
 
      copy->str= (unsigned char*) &tables[i].table->null_row;
 
16013
      copy->str= (uchar*) &tables[i].table->null_row;
13823
16014
      copy->length=sizeof(tables[i].table->null_row);
13824
16015
      copy->strip=0;
13825
16016
      copy->blob_field=0;
13850
16041
  cache->length=length+blobs*sizeof(char*);
13851
16042
  cache->blobs=blobs;
13852
16043
  *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))))
13855
 
    return(1);                          /* Don't use cache */ /* purecov: inspected */
 
16044
  size=max(thd->variables.join_buff_size, cache->length);
 
16045
  if (!(cache->buff=(uchar*) my_malloc(size,MYF(0))))
 
16046
    DBUG_RETURN(1);                             /* Don't use cache */ /* purecov: inspected */
13856
16047
  cache->end=cache->buff+size;
13857
16048
  reset_cache_write(cache);
13858
 
  return(0);
 
16049
  DBUG_RETURN(0);
13859
16050
}
13860
16051
 
13861
16052
 
13862
16053
static ulong
13863
16054
used_blob_length(CACHE_FIELD **ptr)
13864
16055
{
13865
 
  uint32_t length,blob_length;
 
16056
  uint length,blob_length;
13866
16057
  for (length=0 ; *ptr ; ptr++)
13867
16058
  {
13868
16059
    (*ptr)->blob_length=blob_length=(*ptr)->blob_field->get_length();
13876
16067
static bool
13877
16068
store_record_in_cache(JOIN_CACHE *cache)
13878
16069
{
13879
 
  uint32_t length;
13880
 
  unsigned char *pos;
 
16070
  uint length;
 
16071
  uchar *pos;
13881
16072
  CACHE_FIELD *copy,*end_field;
13882
16073
  bool last_record;
13883
16074
 
13919
16110
 
13920
16111
      if (copy->strip)
13921
16112
      {
13922
 
        unsigned char *str,*end;
 
16113
        uchar *str,*end;
13923
16114
        for (str=copy->str,end= str+copy->length;
13924
16115
             end > str && end[-1] == ' ' ;
13925
16116
             end--) ;
13952
16143
{
13953
16144
  reset_cache_read(cache);
13954
16145
  cache->records= 0;
13955
 
  cache->ptr_record= UINT32_MAX;
 
16146
  cache->ptr_record= (uint) ~0;
13956
16147
}
13957
16148
 
13958
16149
 
13959
16150
static void
13960
16151
read_cached_record(JOIN_TAB *tab)
13961
16152
{
13962
 
  unsigned char *pos;
13963
 
  uint32_t length;
 
16153
  uchar *pos;
 
16154
  uint length;
13964
16155
  bool last_record;
13965
16156
  CACHE_FIELD *copy,*end_field;
13966
16157
 
14018
16209
    the lookup - the record has been already fetched)
14019
16210
 
14020
16211
  RETURN 
14021
 
    true   No cached record for the key, or failed to create the key (due to
 
16212
    TRUE   No cached record for the key, or failed to create the key (due to
14022
16213
           out-of-domain error)
14023
 
    false  The created key is the same as the previous one (and the record 
 
16214
    FALSE  The created key is the same as the previous one (and the record 
14024
16215
           is already in table->record)
14025
16216
*/
14026
16217
 
14037
16228
    }
14038
16229
  }
14039
16230
  else 
14040
 
    no_prev_key= true;
14041
 
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, &tab->ref)) ||
 
16231
    no_prev_key= TRUE;
 
16232
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, tab->table,
 
16233
                                            &tab->ref)) ||
14042
16234
      no_prev_key)
14043
16235
    return 1;
14044
16236
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
14047
16239
 
14048
16240
 
14049
16241
bool
14050
 
cp_buffer_from_ref(THD *thd, TABLE_REF *ref)
 
16242
cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref)
14051
16243
{
14052
16244
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
14053
16245
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
16246
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
14054
16247
  bool result= 0;
14055
16248
 
14056
16249
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
14062
16255
    }
14063
16256
  }
14064
16257
  thd->count_cuted_fields= save_count_cuted_fields;
 
16258
  dbug_tmp_restore_column_map(table->write_set, old_map);
14065
16259
  return result;
14066
16260
}
14067
16261
 
14071
16265
*****************************************************************************/
14072
16266
 
14073
16267
/**
14074
 
  Resolve an order_st BY or GROUP BY column reference.
 
16268
  Resolve an ORDER BY or GROUP BY column reference.
14075
16269
 
14076
 
  Given a column reference (represented by 'order') from a GROUP BY or order_st
 
16270
  Given a column reference (represented by 'order') from a GROUP BY or ORDER
14077
16271
  BY clause, find the actual column it represents. If the column being
14078
16272
  resolved is from the GROUP BY clause, the procedure searches the SELECT
14079
16273
  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.
 
16274
  the ORDER BY clause, only the SELECT list is being searched.
14081
16275
 
14082
16276
  If 'order' is resolved to an Item, then order->item is set to the found
14083
16277
  Item. If there is no item for the found column (that is, it was resolved
14095
16289
    SELECT list)
14096
16290
  @param[in,out] all_fields         All select, group and order by fields
14097
16291
  @param[in] is_group_field         True if order is a GROUP field, false if
14098
 
    order_st by field
 
16292
    ORDER by field
14099
16293
 
14100
16294
  @retval
14101
 
    false if OK
 
16295
    FALSE if OK
14102
16296
  @retval
14103
 
    true  if error occurred
 
16297
    TRUE  if error occurred
14104
16298
*/
14105
16299
 
14106
16300
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,
 
16301
find_order_in_list(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16302
                   ORDER *order, List<Item> &fields, List<Item> &all_fields,
14109
16303
                   bool is_group_field)
14110
16304
{
14111
 
  Item *order_item= *order->item; /* The item from the GROUP/order_st caluse. */
 
16305
  Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */
14112
16306
  Item::Type order_item_type;
14113
16307
  Item **select_item; /* The corresponding item from the SELECT clause. */
14114
16308
  Field *from_field;  /* The corresponding field from the FROM clause. */
14115
 
  uint32_t counter;
 
16309
  uint counter;
14116
16310
  enum_resolution_type resolution;
14117
16311
 
14118
16312
  /*
14121
16315
  */
14122
16316
  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
14123
16317
  {                                             /* Order by position */
14124
 
    uint32_t count= (uint) order_item->val_int();
 
16318
    uint count= (uint) order_item->val_int();
14125
16319
    if (!count || count > fields.elements)
14126
16320
    {
14127
16321
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
14128
16322
               order_item->full_name(), thd->where);
14129
 
      return true;
 
16323
      return TRUE;
14130
16324
    }
14131
16325
    order->item= ref_pointer_array + count - 1;
14132
16326
    order->in_field_list= 1;
14133
16327
    order->counter= count;
14134
16328
    order->counter_used= 1;
14135
 
    return false;
 
16329
    return FALSE;
14136
16330
  }
14137
 
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
 
16331
  /* Lookup the current GROUP/ORDER field in the SELECT clause. */
14138
16332
  select_item= find_item_in_list(order_item, fields, &counter,
14139
16333
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
14140
16334
  if (!select_item)
14141
 
    return true; /* The item is not unique, or some other error occured. */
 
16335
    return TRUE; /* The item is not unique, or some other error occured. */
14142
16336
 
14143
16337
 
14144
16338
  /* Check whether the resolved field is not ambiguos. */
14152
16346
    */
14153
16347
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
14154
16348
        order_item->fix_fields(thd, order->item))
14155
 
      return true;
 
16349
      return TRUE;
14156
16350
 
14157
16351
    /* Lookup the current GROUP field in the FROM clause. */
14158
16352
    order_item_type= order_item->type();
14161
16355
        order_item_type == Item::REF_ITEM)
14162
16356
    {
14163
16357
      from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables,
14164
 
                                       NULL, &view_ref, IGNORE_ERRORS, true,
14165
 
                                       false);
 
16358
                                       NULL, &view_ref, IGNORE_ERRORS, TRUE,
 
16359
                                       FALSE);
14166
16360
      if (!from_field)
14167
16361
        from_field= (Field*) not_found_field;
14168
16362
    }
14190
16384
      */
14191
16385
      order->item= ref_pointer_array + counter;
14192
16386
      order->in_field_list=1;
14193
 
      return false;
 
16387
      return FALSE;
14194
16388
    }
14195
16389
    else
14196
16390
    {
14200
16394
        warning so the user knows that the field from the FROM clause
14201
16395
        overshadows the column reference from the SELECT list.
14202
16396
      */
14203
 
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
16397
      push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
14204
16398
                          ER(ER_NON_UNIQ_ERROR),
14205
16399
                          ((Item_ident*) order_item)->field_name,
14206
16400
                          current_thd->where);
14223
16417
      (order_item->fix_fields(thd, order->item) ||
14224
16418
       (order_item= *order->item)->check_cols(1) ||
14225
16419
       thd->is_fatal_error))
14226
 
    return true; /* Wrong field. */
 
16420
    return TRUE; /* Wrong field. */
14227
16421
 
14228
 
  uint32_t el= all_fields.elements;
 
16422
  uint el= all_fields.elements;
14229
16423
  all_fields.push_front(order_item); /* Add new field to field list. */
14230
16424
  ref_pointer_array[el]= order_item;
14231
16425
  order->item= ref_pointer_array + el;
14232
 
  return false;
 
16426
  return FALSE;
14233
16427
}
14234
16428
 
14235
16429
 
14240
16434
  the field list.
14241
16435
*/
14242
16436
 
14243
 
int setup_order(THD *thd, Item **ref_pointer_array, TableList *tables,
14244
 
                List<Item> &fields, List<Item> &all_fields, order_st *order)
 
16437
int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16438
                List<Item> &fields, List<Item> &all_fields, ORDER *order)
14245
16439
{
14246
16440
  thd->where="order clause";
14247
16441
  for (; order; order=order->next)
14248
16442
  {
14249
16443
    if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
14250
 
                           all_fields, false))
 
16444
                           all_fields, FALSE))
14251
16445
      return 1;
14252
16446
  }
14253
16447
  return 0;
14281
16475
*/
14282
16476
 
14283
16477
int
14284
 
setup_group(THD *thd, Item **ref_pointer_array, TableList *tables,
14285
 
            List<Item> &fields, List<Item> &all_fields, order_st *order,
 
16478
setup_group(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
 
16479
            List<Item> &fields, List<Item> &all_fields, ORDER *order,
14286
16480
            bool *hidden_group_fields)
14287
16481
{
14288
16482
  *hidden_group_fields=0;
14289
 
  order_st *ord;
 
16483
  ORDER *ord;
14290
16484
 
14291
16485
  if (!order)
14292
16486
    return 0;                           /* Everything is ok */
14293
16487
 
14294
 
  uint32_t org_fields=all_fields.elements;
 
16488
  uint org_fields=all_fields.elements;
14295
16489
 
14296
16490
  thd->where="group statement";
14297
16491
  for (ord= order; ord; ord= ord->next)
14298
16492
  {
14299
16493
    if (find_order_in_list(thd, ref_pointer_array, tables, ord, fields,
14300
 
                           all_fields, true))
 
16494
                           all_fields, TRUE))
14301
16495
      return 1;
14302
16496
    (*ord->item)->marker= UNDEF_POS;            /* Mark found */
14303
16497
    if ((*ord->item)->with_sum_func)
14377
16571
  optimize away 'order by'.
14378
16572
*/
14379
16573
 
14380
 
static order_st *
 
16574
static ORDER *
14381
16575
create_distinct_group(THD *thd, Item **ref_pointer_array,
14382
 
                      order_st *order_list, List<Item> &fields,
14383
 
                      List<Item> &all_fields __attribute__((unused)),
14384
 
                      bool *all_order_by_fields_used)
 
16576
                      ORDER *order_list, List<Item> &fields,
 
16577
                      List<Item> &all_fields,
 
16578
                      bool *all_order_by_fields_used)
14385
16579
{
14386
16580
  List_iterator<Item> li(fields);
14387
 
  Item *item;
14388
 
  order_st *order,*group,**prev;
 
16581
  Item *item, **orig_ref_pointer_array= ref_pointer_array;
 
16582
  ORDER *order,*group,**prev;
14389
16583
 
14390
16584
  *all_order_by_fields_used= 1;
14391
16585
  while ((item=li++))
14396
16590
  {
14397
16591
    if (order->in_field_list)
14398
16592
    {
14399
 
      order_st *ord=(order_st*) thd->memdup((char*) order,sizeof(order_st));
 
16593
      ORDER *ord=(ORDER*) thd->memdup((char*) order,sizeof(ORDER));
14400
16594
      if (!ord)
14401
16595
        return 0;
14402
16596
      *prev=ord;
14416
16610
        Don't put duplicate columns from the SELECT list into the 
14417
16611
        GROUP BY list.
14418
16612
      */
14419
 
      order_st *ord_iter;
 
16613
      ORDER *ord_iter;
14420
16614
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
14421
16615
        if ((*ord_iter->item)->eq(item, 1))
14422
16616
          goto next_item;
14423
16617
      
14424
 
      order_st *ord=(order_st*) thd->calloc(sizeof(order_st));
 
16618
      ORDER *ord=(ORDER*) thd->calloc(sizeof(ORDER));
14425
16619
      if (!ord)
14426
16620
        return 0;
14427
16621
 
14428
 
      /*
14429
 
        We have here only field_list (not all_field_list), so we can use
14430
 
        simple indexing of ref_pointer_array (order in the array and in the
14431
 
        list are same)
14432
 
      */
14433
 
      ord->item= ref_pointer_array;
 
16622
      if (item->type() == Item::FIELD_ITEM &&
 
16623
          item->field_type() == MYSQL_TYPE_BIT)
 
16624
      {
 
16625
        /*
 
16626
          Because HEAP tables can't index BIT fields we need to use an
 
16627
          additional hidden field for grouping because later it will be
 
16628
          converted to a LONG field. Original field will remain of the
 
16629
          BIT type and will be returned to a client.
 
16630
        */
 
16631
        Item_field *new_item= new Item_field(thd, (Item_field*)item);
 
16632
        int el= all_fields.elements;
 
16633
        orig_ref_pointer_array[el]= new_item;
 
16634
        all_fields.push_front(new_item);
 
16635
        ord->item= orig_ref_pointer_array + el;
 
16636
      }
 
16637
      else
 
16638
      {
 
16639
        /*
 
16640
          We have here only field_list (not all_field_list), so we can use
 
16641
          simple indexing of ref_pointer_array (order in the array and in the
 
16642
          list are same)
 
16643
        */
 
16644
        ord->item= ref_pointer_array;
 
16645
      }
14434
16646
      ord->asc=1;
14435
16647
      *prev=ord;
14436
16648
      prev= &ord->next;
14474
16686
            param->quick_group=0;                       // UDF SUM function
14475
16687
          param->sum_func_count++;
14476
16688
 
14477
 
          for (uint32_t i=0 ; i < sum_item->arg_count ; i++)
 
16689
          for (uint i=0 ; i < sum_item->arg_count ; i++)
14478
16690
          {
14479
16691
            if (sum_item->args[0]->real_item()->type() == Item::FIELD_ITEM)
14480
16692
              param->field_count++;
14503
16715
*/
14504
16716
 
14505
16717
static bool
14506
 
test_if_subpart(order_st *a,order_st *b)
 
16718
test_if_subpart(ORDER *a,ORDER *b)
14507
16719
{
14508
16720
  for (; a && b; a=a->next,b=b->next)
14509
16721
  {
14520
16732
  and group and order is compatible, else return 0.
14521
16733
*/
14522
16734
 
14523
 
static Table *
14524
 
get_sort_by_table(order_st *a,order_st *b,TableList *tables)
 
16735
static TABLE *
 
16736
get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables)
14525
16737
{
14526
16738
  table_map map= (table_map) 0;
 
16739
  DBUG_ENTER("get_sort_by_table");
14527
16740
 
14528
16741
  if (!a)
14529
16742
    a=b;                                        // Only one need to be given
14533
16746
  for (; a && b; a=a->next,b=b->next)
14534
16747
  {
14535
16748
    if (!(*a->item)->eq(*b->item,1))
14536
 
      return(0);
 
16749
      DBUG_RETURN(0);
14537
16750
    map|=a->item[0]->used_tables();
14538
16751
  }
14539
16752
  if (!map || (map & (RAND_TABLE_BIT | OUTER_REF_TABLE_BIT)))
14540
 
    return(0);
 
16753
    DBUG_RETURN(0);
14541
16754
 
14542
16755
  for (; !(map & tables->table->map); tables= tables->next_leaf) {};
14543
16756
  if (map != tables->table->map)
14544
 
    return(0);                          // More than one table
14545
 
  return(tables->table);
 
16757
    DBUG_RETURN(0);                             // More than one table
 
16758
  DBUG_PRINT("exit",("sort by table: %d",tables->table->tablenr));
 
16759
  DBUG_RETURN(tables->table);
14546
16760
}
14547
16761
 
14548
16762
 
14551
16765
*/
14552
16766
 
14553
16767
static void
14554
 
calc_group_buffer(JOIN *join,order_st *group)
 
16768
calc_group_buffer(JOIN *join,ORDER *group)
14555
16769
{
14556
 
  uint32_t key_length=0, parts=0, null_parts=0;
 
16770
  uint key_length=0, parts=0, null_parts=0;
14557
16771
 
14558
16772
  if (group)
14559
16773
    join->group= 1;
14564
16778
    if (field)
14565
16779
    {
14566
16780
      enum_field_types type;
14567
 
      if ((type= field->type()) == DRIZZLE_TYPE_BLOB)
 
16781
      if ((type= field->type()) == MYSQL_TYPE_BLOB)
14568
16782
        key_length+=MAX_BLOB_WIDTH;             // Can't be used as a key
14569
 
      else if (type == DRIZZLE_TYPE_VARCHAR)
 
16783
      else if (type == MYSQL_TYPE_VARCHAR || type == MYSQL_TYPE_VAR_STRING)
14570
16784
        key_length+= field->field_length + HA_KEY_BLOB_LENGTH;
 
16785
      else if (type == MYSQL_TYPE_BIT)
 
16786
      {
 
16787
        /* Bit is usually stored as a longlong key for group fields */
 
16788
        key_length+= 8;                         // Big enough
 
16789
      }
14571
16790
      else
14572
16791
        key_length+= field->pack_length();
14573
16792
    }
14578
16797
        key_length+= sizeof(double);
14579
16798
        break;
14580
16799
      case INT_RESULT:
14581
 
        key_length+= sizeof(int64_t);
 
16800
        key_length+= sizeof(longlong);
14582
16801
        break;
14583
16802
      case DECIMAL_RESULT:
14584
16803
        key_length+= my_decimal_get_binary_size(group_item->max_length - 
14593
16812
          have STRING_RESULT result type, we increase the length 
14594
16813
          by 8 as maximum pack length of such fields.
14595
16814
        */
14596
 
        if (type == DRIZZLE_TYPE_TIME ||
14597
 
            type == DRIZZLE_TYPE_NEWDATE ||
14598
 
            type == DRIZZLE_TYPE_DATETIME ||
14599
 
            type == DRIZZLE_TYPE_TIMESTAMP)
 
16815
        if (type == MYSQL_TYPE_TIME ||
 
16816
            type == MYSQL_TYPE_DATE ||
 
16817
            type == MYSQL_TYPE_DATETIME ||
 
16818
            type == MYSQL_TYPE_TIMESTAMP)
14600
16819
        {
14601
16820
          key_length+= 8;
14602
16821
        }
14613
16832
      }
14614
16833
      default:
14615
16834
        /* This case should never be choosen */
14616
 
        assert(0);
 
16835
        DBUG_ASSERT(0);
14617
16836
        my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
14618
16837
      }
14619
16838
    }
14665
16884
*/
14666
16885
 
14667
16886
static bool
14668
 
alloc_group_fields(JOIN *join,order_st *group)
 
16887
alloc_group_fields(JOIN *join,ORDER *group)
14669
16888
{
14670
16889
  if (group)
14671
16890
  {
14672
16891
    for (; group ; group=group->next)
14673
16892
    {
14674
 
      Cached_item *tmp=new_Cached_item(join->thd, *group->item, false);
 
16893
      Cached_item *tmp=new_Cached_item(join->thd, *group->item, FALSE);
14675
16894
      if (!tmp || join->group_fields.push_front(tmp))
14676
 
        return true;
 
16895
        return TRUE;
14677
16896
    }
14678
16897
  }
14679
16898
  join->sort_and_group=1;                       /* Mark for do_select */
14680
 
  return false;
 
16899
  return FALSE;
14681
16900
}
14682
16901
 
14683
16902
 
14696
16915
 
14697
16916
int test_if_item_cache_changed(List<Cached_item> &list)
14698
16917
{
 
16918
  DBUG_ENTER("test_if_item_cache_changed");
14699
16919
  List_iterator<Cached_item> li(list);
14700
16920
  int idx= -1,i;
14701
16921
  Cached_item *buff;
14705
16925
    if (buff->cmp())
14706
16926
      idx=i;
14707
16927
  }
14708
 
  return(idx);
 
16928
  DBUG_PRINT("info", ("idx: %d", idx));
 
16929
  DBUG_RETURN(idx);
14709
16930
}
14710
16931
 
14711
16932
 
14742
16963
setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
14743
16964
                  Item **ref_pointer_array,
14744
16965
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
14745
 
                  uint32_t elements, List<Item> &all_fields)
 
16966
                  uint elements, List<Item> &all_fields)
14746
16967
{
14747
16968
  Item *pos;
14748
16969
  List_iterator_fast<Item> li(all_fields);
14751
16972
  res_all_fields.empty();
14752
16973
  List_iterator_fast<Item> itr(res_all_fields);
14753
16974
  List<Item> extra_funcs;
14754
 
  uint32_t i, border= all_fields.elements - elements;
 
16975
  uint i, border= all_fields.elements - elements;
 
16976
  DBUG_ENTER("setup_copy_fields");
14755
16977
 
14756
16978
  if (param->field_count && 
14757
16979
      !(copy=param->copy_field= new Copy_field[param->field_count]))
14761
16983
  for (i= 0; (pos= li++); i++)
14762
16984
  {
14763
16985
    Field *field;
14764
 
    unsigned char *tmp;
 
16986
    uchar *tmp;
14765
16987
    Item *real_pos= pos->real_item();
14766
16988
    if (real_pos->type() == Item::FIELD_ITEM)
14767
16989
    {
14804
17026
        /*
14805
17027
          We need to allocate one extra byte for null handling and
14806
17028
          another extra byte to not get warnings from purify in
14807
 
          Field_varstring::val_int
 
17029
          Field_string::val_int
14808
17030
        */
14809
 
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
 
17031
        if (!(tmp= (uchar*) sql_alloc(field->pack_length()+2)))
14810
17032
          goto err;
14811
17033
        if (copy)
14812
17034
        {
14834
17056
      */
14835
17057
      if (!(pos=new Item_copy_string(pos)))
14836
17058
        goto err;
14837
 
      if (i < border)                           // HAVING, order_st and GROUP BY
 
17059
      if (i < border)                           // HAVING, ORDER and GROUP BY
14838
17060
      {
14839
17061
        if (extra_funcs.push_back(pos))
14840
17062
          goto err;
14852
17074
    itr++;
14853
17075
  itr.sublist(res_selected_fields, elements);
14854
17076
  /*
14855
 
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
 
17077
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
14856
17078
    reference used in these will resolve to a item that is already calculated
14857
17079
  */
14858
17080
  param->copy_funcs.concat(&extra_funcs);
14859
17081
 
14860
 
  return(0);
 
17082
  DBUG_RETURN(0);
14861
17083
 
14862
17084
 err:
14863
17085
  if (copy)
14864
17086
    delete [] param->copy_field;                        // This is never 0
14865
17087
  param->copy_field=0;
14866
17088
err2:
14867
 
  return(true);
 
17089
  DBUG_RETURN(TRUE);
14868
17090
}
14869
17091
 
14870
17092
 
14903
17125
 
14904
17126
bool JOIN::alloc_func_list()
14905
17127
{
14906
 
  uint32_t func_count, group_parts;
 
17128
  uint func_count, group_parts;
 
17129
  DBUG_ENTER("alloc_func_list");
14907
17130
 
14908
17131
  func_count= tmp_table_param.sum_func_count;
14909
17132
  /*
14922
17145
  {
14923
17146
    group_parts+= fields_list.elements;
14924
17147
    /*
14925
 
      If the order_st clause is specified then it's possible that
 
17148
      If the ORDER clause is specified then it's possible that
14926
17149
      it also will be optimized, so reserve space for it too
14927
17150
    */
14928
17151
    if (order)
14929
17152
    {
14930
 
      order_st *ord;
 
17153
      ORDER *ord;
14931
17154
      for (ord= order; ord; ord= ord->next)
14932
17155
        group_parts++;
14933
17156
    }
14937
17160
  sum_funcs= (Item_sum**) thd->calloc(sizeof(Item_sum**) * (func_count+1) +
14938
17161
                                      sizeof(Item_sum***) * (group_parts+1));
14939
17162
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
14940
 
  return(sum_funcs == 0);
 
17163
  DBUG_RETURN(sum_funcs == 0);
14941
17164
}
14942
17165
 
14943
17166
 
14947
17170
  @param field_list        All items
14948
17171
  @param send_fields       Items in select list
14949
17172
  @param before_group_by   Set to 1 if this is called before GROUP BY handling
14950
 
  @param recompute         Set to true if sum_funcs must be recomputed
 
17173
  @param recompute         Set to TRUE if sum_funcs must be recomputed
14951
17174
 
14952
17175
  @retval
14953
17176
    0  ok
14961
17184
  List_iterator_fast<Item> it(field_list);
14962
17185
  Item_sum **func;
14963
17186
  Item *item;
 
17187
  DBUG_ENTER("make_sum_func_list");
14964
17188
 
14965
17189
  if (*sum_funcs && !recompute)
14966
 
    return(false); /* We have already initialized sum_funcs. */
 
17190
    DBUG_RETURN(FALSE); /* We have already initialized sum_funcs. */
14967
17191
 
14968
17192
  func= sum_funcs;
14969
17193
  while ((item=it++))
14977
17201
  {
14978
17202
    rollup.state= ROLLUP::STATE_READY;
14979
17203
    if (rollup_make_fields(field_list, send_fields, &func))
14980
 
      return(true);                     // Should never happen
 
17204
      DBUG_RETURN(TRUE);                        // Should never happen
14981
17205
  }
14982
17206
  else if (rollup.state == ROLLUP::STATE_NONE)
14983
17207
  {
14984
 
    for (uint32_t i=0 ; i <= send_group_parts ;i++)
 
17208
    for (uint i=0 ; i <= send_group_parts ;i++)
14985
17209
      sum_funcs_end[i]= func;
14986
17210
  }
14987
17211
  else if (rollup.state == ROLLUP::STATE_READY)
14988
 
    return(false);                         // Don't put end marker
 
17212
    DBUG_RETURN(FALSE);                         // Don't put end marker
14989
17213
  *func=0;                                      // End marker
14990
 
  return(false);
 
17214
  DBUG_RETURN(FALSE);
14991
17215
}
14992
17216
 
14993
17217
 
15012
17236
change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
15013
17237
                         List<Item> &res_selected_fields,
15014
17238
                         List<Item> &res_all_fields,
15015
 
                         uint32_t elements, List<Item> &all_fields)
 
17239
                         uint elements, List<Item> &all_fields)
15016
17240
{
15017
17241
  List_iterator_fast<Item> it(all_fields);
15018
17242
  Item *item_field,*item;
 
17243
  DBUG_ENTER("change_to_use_tmp_fields");
15019
17244
 
15020
17245
  res_selected_fields.empty();
15021
17246
  res_all_fields.empty();
15022
17247
 
15023
 
  uint32_t i, border= all_fields.elements - elements;
 
17248
  uint i, border= all_fields.elements - elements;
15024
17249
  for (i= 0; (item= it++); i++)
15025
17250
  {
15026
17251
    Field *field;
15042
17267
        else
15043
17268
          item_field= (Item*) new Item_field(field);
15044
17269
        if (!item_field)
15045
 
          return(true);                    // Fatal error
 
17270
          DBUG_RETURN(TRUE);                    // Fatal error
15046
17271
 
15047
17272
        if (item->real_item()->type() != Item::FIELD_ITEM)
15048
17273
          field->orig_table= 0;
15054
17279
          ifield->table_name= iref->table_name;
15055
17280
          ifield->db_name= iref->db_name;
15056
17281
        }
 
17282
#ifndef DBUG_OFF
 
17283
        if (!item_field->name)
 
17284
        {
 
17285
          char buff[256];
 
17286
          String str(buff,sizeof(buff),&my_charset_bin);
 
17287
          str.length(0);
 
17288
          item->print(&str, QT_ORDINARY);
 
17289
          item_field->name= sql_strmake(str.ptr(),str.length());
 
17290
        }
 
17291
#endif
15057
17292
      }
15058
17293
      else
15059
17294
        item_field= item;
15067
17302
  for (i= 0; i < border; i++)
15068
17303
    itr++;
15069
17304
  itr.sublist(res_selected_fields, elements);
15070
 
  return(false);
 
17305
  DBUG_RETURN(FALSE);
15071
17306
}
15072
17307
 
15073
17308
 
15091
17326
static bool
15092
17327
change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
15093
17328
                          List<Item> &res_selected_fields,
15094
 
                          List<Item> &res_all_fields, uint32_t elements,
 
17329
                          List<Item> &res_all_fields, uint elements,
15095
17330
                          List<Item> &all_fields)
15096
17331
{
15097
17332
  List_iterator_fast<Item> it(all_fields);
15099
17334
  res_selected_fields.empty();
15100
17335
  res_all_fields.empty();
15101
17336
 
15102
 
  uint32_t i, border= all_fields.elements - elements;
 
17337
  uint i, border= all_fields.elements - elements;
15103
17338
  for (i= 0; (item= it++); i++)
15104
17339
  {
15105
17340
    res_all_fields.push_back(new_item= item->get_tmp_table_item(thd));
15129
17364
  @param func_ptr      sum function list
15130
17365
 
15131
17366
  @retval
15132
 
    false  ok
 
17367
    FALSE  ok
15133
17368
  @retval
15134
 
    true   error
 
17369
    TRUE   error
15135
17370
*/
15136
17371
 
15137
17372
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr)
15138
17373
{
15139
17374
  Item_sum *func;
 
17375
  DBUG_ENTER("setup_sum_funcs");
15140
17376
  while ((func= *(func_ptr++)))
15141
17377
  {
15142
17378
    if (func->setup(thd))
15143
 
      return(true);
 
17379
      DBUG_RETURN(TRUE);
15144
17380
  }
15145
 
  return(false);
 
17381
  DBUG_RETURN(FALSE);
15146
17382
}
15147
17383
 
15148
17384
 
15159
17395
 
15160
17396
static void
15161
17397
update_tmptable_sum_func(Item_sum **func_ptr,
15162
 
                         Table *tmp_table __attribute__((unused)))
 
17398
                         TABLE *tmp_table __attribute__((unused)))
15163
17399
{
15164
17400
  Item_sum *func;
15165
17401
  while ((func= *(func_ptr++)))
15224
17460
 
15225
17461
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab)
15226
17462
{
 
17463
  DBUG_ENTER("add_ref_to_table_cond");
15227
17464
  if (!join_tab->ref.key_parts)
15228
 
    return(false);
 
17465
    DBUG_RETURN(FALSE);
15229
17466
 
15230
17467
  Item_cond_and *cond=new Item_cond_and();
15231
 
  Table *table=join_tab->table;
 
17468
  TABLE *table=join_tab->table;
15232
17469
  int error;
15233
17470
  if (!cond)
15234
 
    return(true);
 
17471
    DBUG_RETURN(TRUE);
15235
17472
 
15236
 
  for (uint32_t i=0 ; i < join_tab->ref.key_parts ; i++)
 
17473
  for (uint i=0 ; i < join_tab->ref.key_parts ; i++)
15237
17474
  {
15238
17475
    Field *field=table->field[table->key_info[join_tab->ref.key].key_part[i].
15239
17476
                              fieldnr-1];
15241
17478
    cond->add(new Item_func_equal(new Item_field(field), value));
15242
17479
  }
15243
17480
  if (thd->is_fatal_error)
15244
 
    return(true);
 
17481
    DBUG_RETURN(TRUE);
15245
17482
 
15246
17483
  if (!cond->fixed)
15247
17484
    cond->fix_fields(thd, (Item**)&cond);
15254
17491
                                          &error)))
15255
17492
    join_tab->select_cond=cond;
15256
17493
 
15257
 
  return(error ? true : false);
 
17494
  DBUG_RETURN(error ? TRUE : FALSE);
15258
17495
}
15259
17496
 
15260
17497
 
15265
17502
  @param select   pointer to st_select_lex which subselects joins we will free
15266
17503
*/
15267
17504
 
15268
 
void free_underlaid_joins(THD *thd __attribute__((unused)),
15269
 
                          SELECT_LEX *select)
 
17505
void free_underlaid_joins(THD *thd, SELECT_LEX *select)
15270
17506
{
15271
17507
  for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
15272
17508
       unit;
15318
17554
    1   on error
15319
17555
*/
15320
17556
 
15321
 
static bool change_group_ref(THD *thd, Item_func *expr, order_st *group_list,
 
17557
static bool change_group_ref(THD *thd, Item_func *expr, ORDER *group_list,
15322
17558
                             bool *changed)
15323
17559
{
15324
17560
  if (expr->arg_count)
15325
17561
  {
15326
17562
    Name_resolution_context *context= &thd->lex->current_select->context;
15327
17563
    Item **arg,**arg_end;
15328
 
    bool arg_changed= false;
 
17564
    bool arg_changed= FALSE;
15329
17565
    for (arg= expr->arguments(),
15330
17566
         arg_end= expr->arguments()+expr->arg_count;
15331
17567
         arg != arg_end; arg++)
15333
17569
      Item *item= *arg;
15334
17570
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
15335
17571
      {
15336
 
        order_st *group_tmp;
 
17572
        ORDER *group_tmp;
15337
17573
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
15338
17574
        {
15339
17575
          if (item->eq(*group_tmp->item,0))
15343
17579
                                        item->name)))
15344
17580
              return 1;                                 // fatal_error is set
15345
17581
            thd->change_item_tree(arg, new_item);
15346
 
            arg_changed= true;
 
17582
            arg_changed= TRUE;
15347
17583
          }
15348
17584
        }
15349
17585
      }
15356
17592
    if (arg_changed)
15357
17593
    {
15358
17594
      expr->maybe_null= 1;
15359
 
      *changed= true;
 
17595
      *changed= TRUE;
15360
17596
    }
15361
17597
  }
15362
17598
  return 0;
15367
17603
 
15368
17604
bool JOIN::rollup_init()
15369
17605
{
15370
 
  uint32_t i,j;
 
17606
  uint i,j;
15371
17607
  Item **ref_array;
15372
17608
 
15373
17609
  tmp_table_param.quick_group= 0;       // Can't create groups in tmp table
15411
17647
  Item *item;
15412
17648
  while ((item= it++))
15413
17649
  {
15414
 
    order_st *group_tmp;
 
17650
    ORDER *group_tmp;
15415
17651
    bool found_in_group= 0;
15416
17652
 
15417
17653
    for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
15440
17676
            return 1;
15441
17677
          new_item->fix_fields(thd, (Item **) 0);
15442
17678
          thd->change_item_tree(it.ref(), new_item);
15443
 
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
 
17679
          for (ORDER *tmp= group_tmp; tmp; tmp= tmp->next)
15444
17680
          { 
15445
17681
            if (*tmp->item == item)
15446
17682
              thd->change_item_tree(tmp->item, new_item);
15450
17686
    }
15451
17687
    if (item->type() == Item::FUNC_ITEM && !found_in_group)
15452
17688
    {
15453
 
      bool changed= false;
 
17689
      bool changed= FALSE;
15454
17690
      if (change_group_ref(thd, (Item_func *) item, group_list, &changed))
15455
17691
        return 1;
15456
17692
      /*
15487
17723
{
15488
17724
  List_iterator_fast<Item> it(fields_arg);
15489
17725
  Item *first_field= sel_fields.head();
15490
 
  uint32_t level;
 
17726
  uint level;
15491
17727
 
15492
17728
  /*
15493
17729
    Create field lists for the different levels
15512
17748
 
15513
17749
  for (level=0 ; level < send_group_parts ; level++)
15514
17750
  {
15515
 
    uint32_t i;
15516
 
    uint32_t pos= send_group_parts - level -1;
 
17751
    uint i;
 
17752
    uint pos= send_group_parts - level -1;
15517
17753
    bool real_fields= 0;
15518
17754
    Item *item;
15519
17755
    List_iterator<Item> new_it(rollup.fields[pos]);
15520
17756
    Item **ref_array_start= rollup.ref_pointer_arrays[pos];
15521
 
    order_st *start_group;
 
17757
    ORDER *start_group;
15522
17758
 
15523
17759
    /* Point to first hidden field */
15524
17760
    Item **ref_array= ref_array_start + fields_arg.elements-1;
15562
17798
      else 
15563
17799
      {
15564
17800
        /* Check if this is something that is part of this group by */
15565
 
        order_st *group_tmp;
 
17801
        ORDER *group_tmp;
15566
17802
        for (group_tmp= start_group, i= pos ;
15567
17803
             group_tmp ; group_tmp= group_tmp->next, i++)
15568
17804
        {
15616
17852
    1   If send_data_failed()
15617
17853
*/
15618
17854
 
15619
 
int JOIN::rollup_send_data(uint32_t idx)
 
17855
int JOIN::rollup_send_data(uint idx)
15620
17856
{
15621
 
  uint32_t i;
 
17857
  uint i;
15622
17858
  for (i= send_group_parts ; i-- > idx ; )
15623
17859
  {
15624
17860
    /* Get reference pointers to sum functions in place */
15625
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
17861
    memcpy((char*) ref_pointer_array,
 
17862
           (char*) rollup.ref_pointer_arrays[i],
15626
17863
           ref_pointer_array_size);
15627
17864
    if ((!having || having->val_int()))
15628
17865
    {
15657
17894
    1   if write_data_failed()
15658
17895
*/
15659
17896
 
15660
 
int JOIN::rollup_write_data(uint32_t idx, Table *table_arg)
 
17897
int JOIN::rollup_write_data(uint idx, TABLE *table_arg)
15661
17898
{
15662
 
  uint32_t i;
 
17899
  uint i;
15663
17900
  for (i= send_group_parts ; i-- > idx ; )
15664
17901
  {
15665
17902
    /* Get reference pointers to sum functions in place */
15666
 
    memcpy(ref_pointer_array, rollup.ref_pointer_arrays[i],
 
17903
    memcpy((char*) ref_pointer_array,
 
17904
           (char*) rollup.ref_pointer_arrays[i],
15667
17905
           ref_pointer_array_size);
15668
17906
    if ((!having || having->val_int()))
15669
17907
    {
15723
17961
  THD *thd=join->thd;
15724
17962
  select_result *result=join->result;
15725
17963
  Item *item_null= new Item_null();
15726
 
  const CHARSET_INFO * const cs= system_charset_info;
 
17964
  CHARSET_INFO *cs= system_charset_info;
15727
17965
  int quick_type;
 
17966
  DBUG_ENTER("select_describe");
 
17967
  DBUG_PRINT("info", ("Select 0x%lx, type %s, message %s",
 
17968
                      (ulong)join->select_lex, join->select_lex->type,
 
17969
                      message ? message : "NULL"));
15728
17970
  /* Don't log this into the slow query log */
15729
17971
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
15730
17972
  join->unit->offset_limit_cnt= 0;
15735
17977
  */
15736
17978
  if (message)
15737
17979
  {
15738
 
    item_list.push_back(new Item_int((int32_t)
 
17980
    item_list.push_back(new Item_int((int32)
15739
17981
                                     join->select_lex->select_number));
15740
17982
    item_list.push_back(new Item_string(join->select_lex->type,
15741
17983
                                        strlen(join->select_lex->type), cs));
15742
 
    for (uint32_t i=0 ; i < 7; i++)
 
17984
    for (uint i=0 ; i < 7; i++)
15743
17985
      item_list.push_back(item_null);
15744
17986
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
15745
17987
      item_list.push_back(item_null);
15768
18010
    /* table */
15769
18011
    {
15770
18012
      SELECT_LEX *sl= join->unit->first_select();
15771
 
      uint32_t len= 6, lastop= 0;
 
18013
      uint len= 6, lastop= 0;
15772
18014
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
15773
18015
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
15774
18016
      {
15775
18017
        len+= lastop;
15776
 
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
15777
 
                         "%u,", sl->select_number);
 
18018
        lastop= my_snprintf(table_name_buffer + len, NAME_LEN - len,
 
18019
                            "%u,", sl->select_number);
15778
18020
      }
15779
18021
      if (sl || len + lastop >= NAME_LEN)
15780
18022
      {
15818
18060
  else
15819
18061
  {
15820
18062
    table_map used_tables=0;
15821
 
    for (uint32_t i=0 ; i < join->tables ; i++)
 
18063
    for (uint i=0 ; i < join->tables ; i++)
15822
18064
    {
15823
18065
      JOIN_TAB *tab=join->join_tab+i;
15824
 
      Table *table=tab->table;
15825
 
      TableList *table_list= tab->table->pos_in_table_list;
 
18066
      TABLE *table=tab->table;
 
18067
      TABLE_LIST *table_list= tab->table->pos_in_table_list;
15826
18068
      char buff[512]; 
15827
18069
      char buff1[512], buff2[512], buff3[512];
15828
18070
      char keylen_str_buf[64];
15839
18081
      quick_type= -1;
15840
18082
      item_list.empty();
15841
18083
      /* id */
15842
 
      item_list.push_back(new Item_uint((uint32_t)
 
18084
      item_list.push_back(new Item_uint((uint32)
15843
18085
                                       join->select_lex->select_number));
15844
18086
      /* select_type */
15845
18087
      item_list.push_back(new Item_string(join->select_lex->type,
15859
18101
      if (table->derived_select_number)
15860
18102
      {
15861
18103
        /* Derived table name generation */
15862
 
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
15863
 
                          "<derived%u>",
15864
 
                          table->derived_select_number);
 
18104
        int len= my_snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
18105
                             "<derived%u>",
 
18106
                             table->derived_select_number);
15865
18107
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
15866
18108
      }
15867
18109
      else
15868
18110
      {
15869
 
        TableList *real_table= table->pos_in_table_list; 
 
18111
        TABLE_LIST *real_table= table->pos_in_table_list; 
15870
18112
        item_list.push_back(new Item_string(real_table->alias,
15871
18113
                                            strlen(real_table->alias),
15872
18114
                                            cs));
15878
18120
      /* Build "possible_keys" value and add it to item_list */
15879
18121
      if (!tab->keys.is_clear_all())
15880
18122
      {
15881
 
        uint32_t j;
 
18123
        uint j;
15882
18124
        for (j=0 ; j < table->s->keys ; j++)
15883
18125
        {
15884
18126
          if (tab->keys.is_set(j))
15900
18142
      if (tab->ref.key_parts)
15901
18143
      {
15902
18144
        KEY *key_info=table->key_info+ tab->ref.key;
15903
 
        register uint32_t length;
 
18145
        register uint length;
15904
18146
        item_list.push_back(new Item_string(key_info->name,
15905
18147
                                            strlen(key_info->name),
15906
18148
                                            system_charset_info));
15907
 
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) - 
 
18149
        length= longlong2str(tab->ref.key_length, keylen_str_buf, 10) - 
15908
18150
                keylen_str_buf;
15909
18151
        item_list.push_back(new Item_string(keylen_str_buf, length,
15910
18152
                                            system_charset_info));
15920
18162
      else if (tab->type == JT_NEXT)
15921
18163
      {
15922
18164
        KEY *key_info=table->key_info+ tab->index;
15923
 
        register uint32_t length;
 
18165
        register uint length;
15924
18166
        item_list.push_back(new Item_string(key_info->name,
15925
18167
                                            strlen(key_info->name),cs));
15926
 
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) - 
 
18168
        length= longlong2str(key_info->key_length, keylen_str_buf, 10) - 
15927
18169
                keylen_str_buf;
15928
18170
        item_list.push_back(new Item_string(keylen_str_buf, 
15929
18171
                                            length,
15939
18181
      }
15940
18182
      else
15941
18183
      {
15942
 
        if (table_list->schema_table && table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
 
18184
        if (table_list->schema_table &&
 
18185
            table_list->schema_table->i_s_requested_object & OPTIMIZE_I_S_TABLE)
15943
18186
        {
15944
18187
          const char *tmp_buff;
15945
18188
          int f_idx;
15988
18231
        else
15989
18232
          examined_rows= join->best_positions[i].records_read; 
15990
18233
 
15991
 
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows, 
 
18234
        item_list.push_back(new Item_int((longlong) (ulonglong) examined_rows, 
15992
18235
                                         MY_INT64_NUM_DECIMAL_DIGITS));
15993
18236
 
15994
18237
        /* Add "filtered" field to item_list. */
16003
18246
      }
16004
18247
 
16005
18248
      /* Build "Extra" field and add it to item_list. */
16006
 
      bool key_read=table->key_read;
 
18249
      my_bool key_read=table->key_read;
16007
18250
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
16008
18251
          table->covering_keys.is_set(tab->index))
16009
18252
        key_read=1;
16023
18266
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
16024
18267
        /* Skip initial "; "*/
16025
18268
        const char *str= extra.ptr();
16026
 
        uint32_t len= extra.length();
 
18269
        uint32 len= extra.length();
16027
18270
        if (len)
16028
18271
        {
16029
18272
          str += 2;
16033
18276
      }
16034
18277
      else
16035
18278
      {
16036
 
        uint32_t keyno= MAX_KEY;
 
18279
        uint keyno= MAX_KEY;
16037
18280
        if (tab->ref.key_parts)
16038
18281
          keyno= tab->ref.key;
16039
18282
        else if (tab->select && tab->select->quick)
16139
18382
        else if (tab->do_firstmatch)
16140
18383
        {
16141
18384
          extra.append(STRING_WITH_LEN("; FirstMatch("));
16142
 
          Table *prev_table=tab->do_firstmatch->table;
 
18385
          TABLE *prev_table=tab->do_firstmatch->table;
16143
18386
          if (prev_table->derived_select_number)
16144
18387
          {
16145
18388
            char namebuf[NAME_LEN];
16146
18389
            /* Derived table name generation */
16147
 
            int len= snprintf(namebuf, sizeof(namebuf)-1,
16148
 
                              "<derived%u>",
16149
 
                              prev_table->derived_select_number);
 
18390
            int len= my_snprintf(namebuf, sizeof(namebuf)-1,
 
18391
                                 "<derived%u>",
 
18392
                                 prev_table->derived_select_number);
16150
18393
            extra.append(namebuf, len);
16151
18394
          }
16152
18395
          else
16154
18397
          extra.append(STRING_WITH_LEN(")"));
16155
18398
        }
16156
18399
 
16157
 
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
18400
        for (uint part= 0; part < tab->ref.key_parts; part++)
16158
18401
        {
16159
18402
          if (tab->ref.cond_guards[part])
16160
18403
          {
16168
18411
 
16169
18412
        /* Skip initial "; "*/
16170
18413
        const char *str= extra.ptr();
16171
 
        uint32_t len= extra.length();
 
18414
        uint32 len= extra.length();
16172
18415
        if (len)
16173
18416
        {
16174
18417
          str += 2;
16187
18430
       unit= unit->next_unit())
16188
18431
  {
16189
18432
    if (mysql_explain_union(thd, unit, result))
16190
 
      return;
 
18433
      DBUG_VOID_RETURN;
16191
18434
  }
16192
 
  return;
 
18435
  DBUG_VOID_RETURN;
16193
18436
}
16194
18437
 
16195
18438
 
16196
18439
bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result)
16197
18440
{
 
18441
  DBUG_ENTER("mysql_explain_union");
16198
18442
  bool res= 0;
16199
18443
  SELECT_LEX *first= unit->first_select();
16200
18444
 
16203
18447
       sl= sl->next_select())
16204
18448
  {
16205
18449
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
16206
 
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
18450
    uint8 uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
16207
18451
    sl->type= (((&thd->lex->select_lex)==sl)?
16208
18452
               (sl->first_inner_unit() || sl->next_select() ? 
16209
18453
                "PRIMARY" : "SIMPLE"):
16234
18478
    thd->lex->current_select= first;
16235
18479
    unit->set_limit(unit->global_parameters);
16236
18480
    res= mysql_select(thd, &first->ref_pointer_array,
16237
 
                        (TableList*) first->table_list.first,
 
18481
                        (TABLE_LIST*) first->table_list.first,
16238
18482
                        first->with_wild, first->item_list,
16239
18483
                        first->where,
16240
18484
                        first->order_list.elements +
16241
18485
                        first->group_list.elements,
16242
 
                        (order_st*) first->order_list.first,
16243
 
                        (order_st*) first->group_list.first,
 
18486
                        (ORDER*) first->order_list.first,
 
18487
                        (ORDER*) first->group_list.first,
16244
18488
                        first->having,
16245
 
                        (order_st*) thd->lex->proc_list.first,
 
18489
                        (ORDER*) thd->lex->proc_list.first,
16246
18490
                        first->options | thd->options | SELECT_DESCRIBE,
16247
18491
                        result, unit, first);
16248
18492
  }
16249
 
  return(res || thd->is_error());
 
18493
  DBUG_RETURN(res || thd->is_error());
16250
18494
}
16251
18495
 
16252
18496
 
16253
 
static void print_table_array(THD *thd, String *str, TableList **table, 
16254
 
                              TableList **end)
 
18497
static void print_table_array(THD *thd, String *str, TABLE_LIST **table, 
 
18498
                              TABLE_LIST **end)
16255
18499
{
16256
18500
  (*table)->print(thd, str, QT_ORDINARY);
16257
18501
 
16258
 
  for (TableList **tbl= table + 1; tbl < end; tbl++)
 
18502
  for (TABLE_LIST **tbl= table + 1; tbl < end; tbl++)
16259
18503
  {
16260
 
    TableList *curr= *tbl;
 
18504
    TABLE_LIST *curr= *tbl;
16261
18505
    if (curr->outer_join)
16262
18506
    {
16263
18507
      /* MySQL converts right to left joins */
16290
18534
 
16291
18535
static void print_join(THD *thd,
16292
18536
                       String *str,
16293
 
                       List<TableList> *tables,
16294
 
                       enum_query_type query_type __attribute__((unused)))
 
18537
                       List<TABLE_LIST> *tables,
 
18538
                       enum_query_type query_type)
16295
18539
{
16296
18540
  /* List is reversed => we should reverse it before using */
16297
 
  List_iterator_fast<TableList> ti(*tables);
16298
 
  TableList **table= (TableList **)thd->alloc(sizeof(TableList*) *
 
18541
  List_iterator_fast<TABLE_LIST> ti(*tables);
 
18542
  TABLE_LIST **table= (TABLE_LIST **)thd->alloc(sizeof(TABLE_LIST*) *
16299
18543
                                                tables->elements);
16300
18544
  if (table == 0)
16301
18545
    return;  // out of memory
16302
18546
 
16303
 
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
 
18547
  for (TABLE_LIST **t= table + (tables->elements - 1); t >= table; t--)
16304
18548
    *t= ti++;
16305
18549
  
16306
18550
  /* 
16309
18553
  */
16310
18554
  if ((*table)->sj_inner_tables)
16311
18555
  {
16312
 
    TableList **end= table + tables->elements;
16313
 
    for (TableList **t2= table; t2!=end; t2++)
 
18556
    TABLE_LIST **end= table + tables->elements;
 
18557
    for (TABLE_LIST **t2= table; t2!=end; t2++)
16314
18558
    {
16315
18559
      if (!(*t2)->sj_inner_tables)
16316
18560
      {
16317
 
        TableList *tmp= *t2;
 
18561
        TABLE_LIST *tmp= *t2;
16318
18562
        *t2= *table;
16319
18563
        *table= tmp;
16320
18564
        break;
16321
18565
      }
16322
18566
    }
16323
18567
  }
16324
 
  assert(tables->elements >= 1);
 
18568
  DBUG_ASSERT(tables->elements >= 1);
16325
18569
  print_table_array(thd, str, table, table + tables->elements);
16326
18570
}
16327
18571
 
16352
18596
  if (key_name.length)
16353
18597
  {
16354
18598
    if (thd && !my_strnncoll(system_charset_info,
16355
 
                             (const unsigned char *)key_name.str, key_name.length, 
16356
 
                             (const unsigned char *)primary_key_name, 
 
18599
                             (const uchar *)key_name.str, key_name.length, 
 
18600
                             (const uchar *)primary_key_name, 
16357
18601
                             strlen(primary_key_name)))
16358
18602
      str->append(primary_key_name);
16359
18603
    else
16369
18613
  @param str   string where table should be printed
16370
18614
*/
16371
18615
 
16372
 
void TableList::print(THD *thd, String *str, enum_query_type query_type)
 
18616
void TABLE_LIST::print(THD *thd, String *str, enum_query_type query_type)
16373
18617
{
16374
18618
  if (nested_join)
16375
18619
  {
16417
18661
      {
16418
18662
        if (alias && alias[0])
16419
18663
        {
16420
 
          my_stpcpy(t_alias_buff, alias);
 
18664
          strmov(t_alias_buff, alias);
16421
18665
          my_casedn_str(files_charset_info, t_alias_buff);
16422
18666
          t_alias= t_alias_buff;
16423
18667
        }
16515
18759
  if (group_list.elements)
16516
18760
  {
16517
18761
    str->append(STRING_WITH_LEN(" group by "));
16518
 
    print_order(str, (order_st *) group_list.first, query_type);
 
18762
    print_order(str, (ORDER *) group_list.first, query_type);
16519
18763
    switch (olap)
16520
18764
    {
16521
18765
      case CUBE_TYPE:
16546
18790
  if (order_list.elements)
16547
18791
  {
16548
18792
    str->append(STRING_WITH_LEN(" order by "));
16549
 
    print_order(str, (order_st *) order_list.first, query_type);
 
18793
    print_order(str, (ORDER *) order_list.first, query_type);
16550
18794
  }
16551
18795
 
16552
18796
  // limit
16562
18806
  @param res            new select_result object
16563
18807
 
16564
18808
  @retval
16565
 
    false   OK
 
18809
    FALSE   OK
16566
18810
  @retval
16567
 
    true    error
 
18811
    TRUE    error
16568
18812
*/
16569
18813
 
16570
18814
bool JOIN::change_result(select_result *res)
16571
18815
{
 
18816
  DBUG_ENTER("JOIN::change_result");
16572
18817
  result= res;
16573
18818
  if (result->prepare(fields_list, select_lex->master_unit()) ||
16574
18819
                     result->prepare2())
16575
18820
  {
16576
 
    return(true);
 
18821
    DBUG_RETURN(TRUE);
16577
18822
  }
16578
 
  return(false);
 
18823
  DBUG_RETURN(FALSE);
16579
18824
}
16580
18825
 
16581
18826
/**