~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Brian Aker
  • Date: 2009-05-11 17:50:22 UTC
  • Revision ID: brian@gaz-20090511175022-y35q9ky6uh9ldcjt
Replacing Sun employee copyright headers (aka... anything done by a Sun
employee is copyright by Sun).

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>
 
26
#include "drizzled/server_includes.h"
 
27
#include "drizzled/sql_select.h"
 
28
#include "drizzled/sj_tmp_table.h"
 
29
#include "drizzled/table_map_iterator.h"
 
30
 
 
31
#include "mysys/my_bit.h"
 
32
#include "drizzled/error.h"
 
33
#include "drizzled/gettext.h"
 
34
#include "drizzled/util/test.h"
 
35
#include "drizzled/name_resolution_context_state.h"
 
36
#include "drizzled/nested_join.h"
 
37
#include "drizzled/probes.h"
 
38
#include "drizzled/show.h"
 
39
#include "drizzled/item/cache.h"
 
40
#include "drizzled/item/cmpfunc.h"
 
41
#include "drizzled/item/copy_string.h"
 
42
#include "drizzled/item/uint.h"
 
43
#include "drizzled/cached_item.h"
 
44
#include "drizzled/sql_base.h"
 
45
#include "drizzled/field/blob.h"
 
46
#include "drizzled/check_stack_overrun.h"
 
47
#include "drizzled/lock.h"
 
48
#include "drizzled/item/outer_ref.h"
 
49
#include "drizzled/index_hint.h"
 
50
 
 
51
#include <string>
 
52
#include <iostream>
 
53
 
 
54
using namespace std;
33
55
 
34
56
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
35
57
                              "MAYBE_REF","ALL","range","index",
42
64
static void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array);
43
65
static bool make_join_statistics(JOIN *join, TableList *leaves, COND *conds,
44
66
                                 DYNAMIC_ARRAY *keyuse);
45
 
static bool update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,
 
67
static bool update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,
46
68
                                JOIN_TAB *join_tab,
47
69
                                uint32_t tables, COND *conds,
48
70
                                COND_EQUAL *cond_equal,
49
 
                                table_map table_map, SELECT_LEX *select_lex,
 
71
                                table_map table_map, Select_Lex *select_lex,
50
72
                                st_sargable_param **sargables);
51
73
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
52
74
static void set_position(JOIN *join,uint32_t index,JOIN_TAB *table,KEYUSE *key);
54
76
                               table_map used_tables);
55
77
static bool choose_plan(JOIN *join,table_map join_tables);
56
78
 
57
 
static void best_access_path(JOIN *join, JOIN_TAB *s, THD *thd,
 
79
static void best_access_path(JOIN *join, JOIN_TAB *s, Session *session,
58
80
                             table_map remaining_tables, uint32_t idx,
59
81
                             double record_count, double read_time);
60
82
static void optimize_straight_join(JOIN *join, table_map join_tables);
66
88
                                             double read_time, uint32_t depth,
67
89
                                             uint32_t prune_level);
68
90
static uint32_t determine_search_depth(JOIN* join);
69
 
static int join_tab_cmp(const void* ptr1, const void* ptr2);
70
 
static int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
 
91
extern "C" int join_tab_cmp(const void* ptr1, const void* ptr2);
 
92
extern "C" int join_tab_cmp_straight(const void* ptr1, const void* ptr2);
71
93
/*
72
94
  TODO: 'find_best' is here only temporarily until 'greedy_search' is
73
95
  tested and approved.
77
99
static uint32_t cache_record_length(JOIN *join,uint32_t index);
78
100
static double prev_record_reads(JOIN *join, uint32_t idx, table_map found_ref);
79
101
static bool get_best_combination(JOIN *join);
80
 
static store_key *get_store_key(THD *thd,
 
102
static store_key *get_store_key(Session *session,
81
103
                                KEYUSE *keyuse, table_map used_tables,
82
104
                                KEY_PART_INFO *key_part, unsigned char *key_buff,
83
105
                                uint32_t maybe_null);
88
110
static bool only_eq_ref_tables(JOIN *join, order_st *order, table_map tables);
89
111
static void update_depend_map(JOIN *join);
90
112
static void update_depend_map(JOIN *join, order_st *order);
91
 
static order_st *remove_const(JOIN *join,order_st *first_order,COND *cond,
92
 
                           bool change_list, bool *simple_order);
 
113
static order_st *remove_constants(JOIN *join,order_st *first_order,COND *cond,
 
114
                                  bool change_list, bool *simple_order);
93
115
static int return_zero_rows(JOIN *join, select_result *res,TableList *tables,
94
116
                            List<Item> &fields, bool send_row,
95
117
                            uint64_t select_options, const char *info,
96
118
                            Item *having);
97
 
static COND *build_equal_items(THD *thd, COND *cond,
 
119
static COND *build_equal_items(Session *session, COND *cond,
98
120
                               COND_EQUAL *inherited,
99
121
                               List<TableList> *join_list,
100
122
                               COND_EQUAL **cond_equal_ref);
109
131
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
110
132
                                          uint32_t first_unused);
111
133
 
112
 
static 
 
134
static
113
135
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab);
114
 
static void restore_prev_sj_state(const table_map remaining_tables, 
 
136
static void restore_prev_sj_state(const table_map remaining_tables,
115
137
                                  const JOIN_TAB *tab);
116
138
 
117
139
static COND *optimize_cond(JOIN *join, COND *conds,
167
189
                          bool (*find_func) (Field *, void *), void *data);
168
190
static bool find_field_in_item_list (Field *field, void *data);
169
191
static bool find_field_in_order_list (Field *field, void *data);
170
 
static int create_sort_index(THD *thd, JOIN *join, order_st *order,
 
192
static int create_sort_index(Session *session, JOIN *join, order_st *order,
171
193
                             ha_rows filesort_limit, ha_rows select_limit,
172
194
                             bool is_order_by);
173
195
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
174
196
                             Item *having);
175
 
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
176
 
                                   ulong offset,Item *having);
177
 
static int remove_dup_with_hash_index(THD *thd,Table *table,
 
197
static int remove_dup_with_compare(Session *session, Table *entry, Field **field,
 
198
                                   uint32_t offset, Item *having);
 
199
static int remove_dup_with_hash_index(Session *session,Table *table,
178
200
                                      uint32_t field_count, Field **first_field,
179
 
 
180
 
                                      ulong key_length,Item *having);
181
 
static int join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count);
182
 
static ulong used_blob_length(CACHE_FIELD **ptr);
 
201
                                      uint32_t key_length, Item *having);
 
202
static int join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count);
 
203
static uint32_t used_blob_length(CACHE_FIELD **ptr);
183
204
static bool store_record_in_cache(JOIN_CACHE *cache);
184
205
static void reset_cache_read(JOIN_CACHE *cache);
185
206
static void reset_cache_write(JOIN_CACHE *cache);
186
207
static void read_cached_record(JOIN_TAB *tab);
187
208
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
188
 
static order_st *create_distinct_group(THD *thd, Item **ref_pointer_array,
 
209
static order_st *create_distinct_group(Session *session, Item **ref_pointer_array,
189
210
                                    order_st *order, List<Item> &fields,
190
211
                                    List<Item> &all_fields,
191
212
                                    bool *all_order_by_fields_used);
195
216
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
196
217
static bool alloc_group_fields(JOIN *join,order_st *group);
197
218
// Create list for using with tempory table
198
 
static bool change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
 
219
static bool change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
199
220
                                     List<Item> &new_list1,
200
221
                                     List<Item> &new_list2,
201
222
                                     uint32_t elements, List<Item> &items);
202
223
// Create list for using with tempory table
203
 
static bool change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
 
224
static bool change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
204
225
                                      List<Item> &new_list1,
205
226
                                      List<Item> &new_list2,
206
227
                                      uint32_t elements, List<Item> &items);
207
228
static void init_tmptable_sum_functions(Item_sum **func);
208
229
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
209
230
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
210
 
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
211
 
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
 
231
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab);
 
232
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr);
212
233
static bool init_sum_functions(Item_sum **func, Item_sum **end);
213
234
static bool update_sum_func(Item_sum **func);
214
235
void select_describe(JOIN *join, bool need_tmp_table,bool need_order,
216
237
static Item *remove_additional_cond(Item* conds);
217
238
static void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab);
218
239
static bool test_if_ref(Item_field *left_item,Item *right_item);
219
 
static bool replace_where_subcondition(JOIN *join, Item *old_cond, 
 
240
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
220
241
                                       Item *new_cond, bool fix_fields);
221
242
 
 
243
static bool eval_const_cond(COND *cond)
 
244
{
 
245
    return ((Item_func*) cond)->val_int() ? true : false;
 
246
}
 
247
 
 
248
 
222
249
/*
223
250
  This is used to mark equalities that were made from i-th IN-equality.
224
251
  We limit semi-join InsideOut optimization to handling max 64 inequalities,
236
263
  This handles SELECT with and without UNION.
237
264
*/
238
265
 
239
 
bool handle_select(THD *thd, LEX *lex, select_result *result,
240
 
                   ulong setup_tables_done_option)
 
266
bool handle_select(Session *session, LEX *lex, select_result *result,
 
267
                   uint64_t setup_tables_done_option)
241
268
{
242
269
  bool res;
243
 
  register SELECT_LEX *select_lex = &lex->select_lex;
 
270
  register Select_Lex *select_lex = &lex->select_lex;
244
271
  DRIZZLE_SELECT_START();
245
272
 
246
 
  if (select_lex->master_unit()->is_union() || 
 
273
  if (select_lex->master_unit()->is_union() ||
247
274
      select_lex->master_unit()->fake_select_lex)
248
 
    res= mysql_union(thd, lex, result, &lex->unit, setup_tables_done_option);
 
275
    res= mysql_union(session, lex, result, &lex->unit, setup_tables_done_option);
249
276
  else
250
277
  {
251
 
    SELECT_LEX_UNIT *unit= &lex->unit;
 
278
    Select_Lex_Unit *unit= &lex->unit;
252
279
    unit->set_limit(unit->global_parameters);
253
 
    thd->thd_marker= 0;
 
280
    session->session_marker= 0;
254
281
    /*
255
282
      'options' of mysql_select will be set in JOIN, as far as JOIN for
256
 
      every PS/SP execution new, we will not need reset this flag if 
 
283
      every PS/SP execution new, we will not need reset this flag if
257
284
      setup_tables_done_option changed for next rexecution
258
285
    */
259
 
    res= mysql_select(thd, &select_lex->ref_pointer_array,
 
286
    res= mysql_select(session, &select_lex->ref_pointer_array,
260
287
                      (TableList*) select_lex->table_list.first,
261
288
                      select_lex->with_wild, select_lex->item_list,
262
289
                      select_lex->where,
265
292
                      (order_st*) select_lex->order_list.first,
266
293
                      (order_st*) select_lex->group_list.first,
267
294
                      select_lex->having,
268
 
                      (order_st*) lex->proc_list.first,
269
 
                      select_lex->options | thd->options |
 
295
                      select_lex->options | session->options |
270
296
                      setup_tables_done_option,
271
297
                      result, unit, select_lex);
272
298
  }
273
 
  res|= thd->is_error();
 
299
  res|= session->is_error();
274
300
  if (unlikely(res))
275
301
    result->abort();
276
302
 
284
310
 
285
311
  SYNOPSIS
286
312
    fix_inner_refs()
287
 
    thd               Thread handle
 
313
    session               Thread handle
288
314
    all_fields        List of all fields used in select
289
315
    select            Current select
290
316
    ref_pointer_array Array of references to Items used in current select
321
347
*/
322
348
 
323
349
bool
324
 
fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
 
350
fix_inner_refs(Session *session, List<Item> &all_fields, Select_Lex *select,
325
351
                 Item **ref_pointer_array)
326
352
{
327
353
  Item_outer_ref *ref;
382
408
    ref->outer_ref= new_ref;
383
409
    ref->ref= &ref->outer_ref;
384
410
 
385
 
    if (!ref->fixed && ref->fix_fields(thd, 0))
 
411
    if (!ref->fixed && ref->fix_fields(session, 0))
386
412
      return true;
387
 
    thd->used_tables|= item->used_tables();
 
413
    session->used_tables|= item->used_tables();
388
414
  }
389
415
  return res;
390
416
}
391
417
 
392
 
#define MAGIC_IN_WHERE_TOP_LEVEL 10
393
418
/**
394
419
  Function to setup clauses without sum functions.
395
420
*/
396
 
inline int setup_without_group(THD *thd, Item **ref_pointer_array,
397
 
                               TableList *tables,
398
 
                               TableList *leaves,
399
 
                               List<Item> &fields,
400
 
                               List<Item> &all_fields,
401
 
                               COND **conds,
402
 
                               order_st *order,
403
 
                               order_st *group, bool *hidden_group_fields)
 
421
inline int setup_without_group(Session *session, Item **ref_pointer_array,
 
422
                               TableList *tables,
 
423
                               TableList *leaves,
 
424
                               List<Item> &fields,
 
425
                               List<Item> &all_fields,
 
426
                               COND **conds,
 
427
                               order_st *order,
 
428
                               order_st *group, bool *hidden_group_fields)
404
429
{
405
430
  int res;
406
 
  nesting_map save_allow_sum_func=thd->lex->allow_sum_func ;
407
 
 
408
 
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
409
 
  res= setup_conds(thd, tables, leaves, conds);
410
 
 
411
 
  thd->lex->allow_sum_func|= 1 << thd->lex->current_select->nest_level;
412
 
  res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
 
431
  nesting_map save_allow_sum_func=session->lex->allow_sum_func ;
 
432
 
 
433
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
 
434
  res= setup_conds(session, tables, leaves, conds);
 
435
 
 
436
  session->lex->allow_sum_func|= 1 << session->lex->current_select->nest_level;
 
437
  res= res || setup_order(session, ref_pointer_array, tables, fields, all_fields,
413
438
                          order);
414
 
  thd->lex->allow_sum_func&= ~(1 << thd->lex->current_select->nest_level);
415
 
  res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
 
439
  session->lex->allow_sum_func&= ~(1 << session->lex->current_select->nest_level);
 
440
  res= res || setup_group(session, ref_pointer_array, tables, fields, all_fields,
416
441
                          group, hidden_group_fields);
417
 
  thd->lex->allow_sum_func= save_allow_sum_func;
 
442
  session->lex->allow_sum_func= save_allow_sum_func;
418
443
  return(res);
419
444
}
420
445
 
441
466
              uint32_t wild_num, COND *conds_init, uint32_t og_num,
442
467
              order_st *order_init, order_st *group_init,
443
468
              Item *having_init,
444
 
              order_st *proc_param_init, SELECT_LEX *select_lex_arg,
445
 
              SELECT_LEX_UNIT *unit_arg)
 
469
              Select_Lex *select_lex_arg,
 
470
              Select_Lex_Unit *unit_arg)
446
471
{
447
472
  // to prevent double initialization on EXPLAIN
448
473
  if (optimized)
452
477
  order= order_init;
453
478
  group_list= group_init;
454
479
  having= having_init;
455
 
  proc_param= proc_param_init;
456
480
  tables_list= tables_init;
457
481
  select_lex= select_lex_arg;
458
482
  select_lex->join= this;
459
483
  join_list= &select_lex->top_join_list;
460
484
  union_part= unit_arg->is_union();
461
485
 
462
 
  thd->lex->current_select->is_item_list_lookup= 1;
 
486
  session->lex->current_select->is_item_list_lookup= 1;
463
487
  /*
464
488
    If we have already executed SELECT, then it have not sense to prevent
465
489
    its table from update (see unique_table())
466
490
  */
467
 
  if (thd->derived_tables_processing)
 
491
  if (session->derived_tables_processing)
468
492
    select_lex->exclude_from_table_unique_test= true;
469
493
 
470
494
  /* Check that all tables, fields, conds and order are ok */
471
495
 
472
496
  if (!(select_options & OPTION_SETUP_TABLES_DONE) &&
473
 
      setup_tables_and_check_access(thd, &select_lex->context, join_list,
 
497
      setup_tables_and_check_access(session, &select_lex->context, join_list,
474
498
                                    tables_list, &select_lex->leaf_tables,
475
499
                                    false))
476
500
      return(-1);
477
 
 
 
501
 
478
502
  TableList *table_ptr;
479
503
  for (table_ptr= select_lex->leaf_tables;
480
504
       table_ptr;
481
505
       table_ptr= table_ptr->next_leaf)
482
506
    tables++;
483
507
 
484
 
  if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
485
 
      select_lex->setup_ref_array(thd, og_num) ||
486
 
      setup_fields(thd, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
 
508
  if (setup_wild(session, tables_list, fields_list, &all_fields, wild_num) ||
 
509
      select_lex->setup_ref_array(session, og_num) ||
 
510
      setup_fields(session, (*rref_pointer_array), fields_list, MARK_COLUMNS_READ,
487
511
                   &all_fields, 1) ||
488
 
      setup_without_group(thd, (*rref_pointer_array), tables_list,
 
512
      setup_without_group(session, (*rref_pointer_array), tables_list,
489
513
                          select_lex->leaf_tables, fields_list,
490
514
                          all_fields, &conds, order, group_list,
491
515
                          &hidden_group_fields))
492
516
    return(-1);                         /* purecov: inspected */
493
517
 
494
518
  ref_pointer_array= *rref_pointer_array;
495
 
  
 
519
 
496
520
  if (having)
497
521
  {
498
 
    nesting_map save_allow_sum_func= thd->lex->allow_sum_func;
499
 
    thd->where="having clause";
500
 
    thd->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
 
522
    nesting_map save_allow_sum_func= session->lex->allow_sum_func;
 
523
    session->where="having clause";
 
524
    session->lex->allow_sum_func|= 1 << select_lex_arg->nest_level;
501
525
    select_lex->having_fix_field= 1;
502
526
    bool having_fix_rc= (!having->fixed &&
503
 
                         (having->fix_fields(thd, &having) ||
 
527
                         (having->fix_fields(session, &having) ||
504
528
                          having->check_cols(1)));
505
529
    select_lex->having_fix_field= 0;
506
 
    if (having_fix_rc || thd->is_error())
 
530
    if (having_fix_rc || session->is_error())
507
531
      return(-1);                               /* purecov: inspected */
508
 
    thd->lex->allow_sum_func= save_allow_sum_func;
 
532
    session->lex->allow_sum_func= save_allow_sum_func;
509
533
  }
510
534
 
511
535
  {
517
541
    */
518
542
    if ((subselect= select_lex->master_unit()->item))
519
543
    {
520
 
      bool do_semijoin= !test(thd->variables.optimizer_switch &
 
544
      bool do_semijoin= !test(session->variables.optimizer_switch &
521
545
                              OPTIMIZER_SWITCH_NO_SEMIJOIN);
522
546
      if (subselect->substype() == Item_subselect::IN_SUBS)
523
547
        in_subs= (Item_in_subselect*)subselect;
533
557
          5. Subquery predicate is at the AND-top-level of ON/WHERE clause
534
558
          6. No execution method was already chosen (by a prepared statement).
535
559
 
536
 
          (*). We are not in a subquery of a single table UPDATE/DELETE that 
 
560
          (*). We are not in a subquery of a single table UPDATE/DELETE that
537
561
               doesn't have a JOIN (TODO: We should handle this at some
538
562
               point by switching to multi-table UPDATE/DELETE)
539
563
 
540
564
          (**). We're not in a confluent table-less subquery, like
541
 
                "SELECT 1". 
 
565
                "SELECT 1".
542
566
      */
543
567
      if (in_subs &&                                                    // 1
544
568
          !select_lex->master_unit()->first_select()->next_select() &&  // 2
545
569
          !select_lex->group_list.elements && !order &&                 // 3
546
570
          !having && !select_lex->with_sum_func &&                      // 4
547
 
          thd->thd_marker &&                                            // 5
 
571
          session->session_marker &&                                            // 5
548
572
          select_lex->outer_select()->join &&                           // (*)
549
 
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**) 
 
573
          select_lex->master_unit()->first_select()->leaf_tables &&     // (**)
550
574
          do_semijoin &&
551
575
          in_subs->exec_method == Item_in_subselect::NOT_TRANSFORMED)   // 6
552
576
      {
553
577
        {
554
578
          if (!in_subs->left_expr->fixed &&
555
 
               in_subs->left_expr->fix_fields(thd, &in_subs->left_expr))
 
579
               in_subs->left_expr->fix_fields(session, &in_subs->left_expr))
556
580
          {
557
581
            return(-1);
558
582
          }
561
585
            column. E.g. in SELECT 1 IN (SELECT * ..) the right part is (SELECT * ...)
562
586
          */
563
587
          if (subselect->substype() == Item_subselect::IN_SUBS &&
564
 
             (select_lex->item_list.elements != 
 
588
             (select_lex->item_list.elements !=
565
589
              ((Item_in_subselect*)subselect)->left_expr->cols()))
566
590
          {
567
591
            my_error(ER_OPERAND_COLUMNS, MYF(0), ((Item_in_subselect*)subselect)->left_expr->cols());
570
594
        }
571
595
 
572
596
        /* Register the subquery for further processing */
573
 
        select_lex->outer_select()->join->sj_subselects.append(thd->mem_root, in_subs);
574
 
        in_subs->expr_join_nest= (TableList*)thd->thd_marker;
 
597
        select_lex->outer_select()->join->sj_subselects.append(session->mem_root, in_subs);
 
598
        in_subs->expr_join_nest= (TableList*)session->session_marker;
575
599
      }
576
600
      else
577
601
      {
578
 
        bool do_materialize= !test(thd->variables.optimizer_switch &
 
602
        bool do_materialize= !test(session->variables.optimizer_switch &
579
603
                                   OPTIMIZER_SWITCH_NO_MATERIALIZATION);
580
604
        /*
581
605
          Check if the subquery predicate can be executed via materialization.
606
630
          perform the whole transformation or only that part of it which wraps
607
631
          Item_in_subselect in an Item_in_optimizer.
608
632
        */
609
 
        if (do_materialize && 
 
633
        if (do_materialize &&
610
634
            in_subs  &&                                                   // 1
611
635
            !select_lex->master_unit()->first_select()->next_select() &&  // 2
612
636
            select_lex->master_unit()->first_select()->leaf_tables &&     // 3
613
 
            thd->lex->sql_command == SQLCOM_SELECT)                       // *
 
637
            session->lex->sql_command == SQLCOM_SELECT)                       // *
614
638
        {
615
639
          if (in_subs->is_top_level_item() &&                             // 4
616
640
              !in_subs->is_correlated &&                                  // 5
635
659
    {
636
660
      Item *item= *ord->item;
637
661
      if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM)
638
 
        item->split_sum_func(thd, ref_pointer_array, all_fields);
 
662
        item->split_sum_func(session, ref_pointer_array, all_fields);
639
663
    }
640
664
  }
641
665
 
642
666
  if (having && having->with_sum_func)
643
 
    having->split_sum_func2(thd, ref_pointer_array, all_fields,
644
 
                            &having, true);
 
667
    having->split_sum_func(session, ref_pointer_array, all_fields,
 
668
                           &having, true);
645
669
  if (select_lex->inner_sum_func_list)
646
670
  {
647
671
    Item_sum *end=select_lex->inner_sum_func_list;
648
 
    Item_sum *item_sum= end;  
 
672
    Item_sum *item_sum= end;
649
673
    do
650
 
    { 
 
674
    {
651
675
      item_sum= item_sum->next;
652
 
      item_sum->split_sum_func2(thd, ref_pointer_array,
653
 
                                all_fields, item_sum->ref_by, false);
 
676
      item_sum->split_sum_func(session, ref_pointer_array,
 
677
                               all_fields, item_sum->ref_by, false);
654
678
    } while (item_sum != end);
655
679
  }
656
680
 
657
681
  if (select_lex->inner_refs_list.elements &&
658
 
      fix_inner_refs(thd, all_fields, select_lex, ref_pointer_array))
 
682
      fix_inner_refs(session, all_fields, select_lex, ref_pointer_array))
659
683
    return(-1);
660
684
 
661
685
  /*
662
 
    Check if there are references to un-aggregated columns when computing 
 
686
    Check if there are references to un-aggregated columns when computing
663
687
    aggregate functions with implicit grouping (there is no GROUP BY).
664
688
 
665
689
    MODE_ONLY_FULL_GROUP_BY is enabled here by default
676
700
    for (order_st *group_tmp= group_list ; group_tmp ; group_tmp= group_tmp->next)
677
701
      send_group_parts++;
678
702
  }
679
 
  
 
703
 
680
704
  if (error)
681
705
    goto err;                                   /* purecov: inspected */
682
706
 
734
758
    TODO: We can remove the equalities that will be guaranteed to be true by the
735
759
    fact that subquery engine will be using index lookup. This must be done only
736
760
    for cases where there are no conversion errors of significance, e.g. 257
737
 
    that is searched in a byte. But this requires homogenization of the return 
 
761
    that is searched in a byte. But this requires homogenization of the return
738
762
    codes of all Field*::store() methods.
739
763
*/
740
764
 
765
789
  DESCRIPTION
766
790
    For index lookup-based subquery (i.e. one executed with
767
791
    subselect_uniquesubquery_engine or subselect_indexsubquery_engine),
768
 
    check its EXPLAIN output row should contain 
769
 
      "Using index" (TAB_INFO_FULL_SCAN_ON_NULL) 
 
792
    check its EXPLAIN output row should contain
 
793
      "Using index" (TAB_INFO_FULL_SCAN_ON_NULL)
770
794
      "Using Where" (TAB_INFO_USING_WHERE)
771
795
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
772
796
    and set appropriate flags in join_tab->packed_info.
775
799
static void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
776
800
{
777
801
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
778
 
  if (join_tab->table->covering_keys.is_set(join_tab->ref.key))
 
802
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
779
803
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
780
804
  if (where)
781
805
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
821
845
{
822
846
  if (join_tab->emb_sj_nest)
823
847
    return false;
824
 
  
 
848
 
825
849
  /* Check if this table is functionally dependent on the tables that
826
850
     are within the same outer join nest
827
851
  */
846
870
 
847
871
/*
848
872
  Setup the strategies to eliminate semi-join duplicates.
849
 
  
 
873
 
850
874
  SYNOPSIS
851
875
    setup_semijoin_dups_elimination()
852
876
      join           Join to process
853
 
      options        Join options (needed to see if join buffering will be 
 
877
      options        Join options (needed to see if join buffering will be
854
878
                     used or not)
855
879
      no_jbuf_after  Another bit of information re where join buffering will
856
880
                     be used.
864
888
    2. FirstMatch (pick only the 1st matching row combination of inner tables)
865
889
    3. InsideOut (scanning the sj-inner table in a way that groups duplicates
866
890
                  together and picking the 1st one)
867
 
    
 
891
 
868
892
    The join order has "duplicate-generating ranges", and every range is
869
893
    served by one strategy or a combination of FirstMatch with with some
870
894
    other strategy.
871
 
    
 
895
 
872
896
    "Duplicate-generating range" is defined as a range within the join order
873
897
    that contains all of the inner tables of a semi-join. All ranges must be
874
898
    disjoint, if tables of several semi-joins are interleaved, then the ranges
887
911
      +------+  +=========================+  +---+
888
912
        (1)                 (2)               (3)
889
913
 
890
 
       (1) - Prefix of OuterTables (those that participate in 
891
 
             IN-equality and/or are correlated with subquery) and outer 
 
914
       (1) - Prefix of OuterTables (those that participate in
 
915
             IN-equality and/or are correlated with subquery) and outer
892
916
             Noncorrelated Tables.
893
917
       (2) - The handled range. The range starts with the first sj-inner
894
 
             table, and covers all sj-inner and outer tables 
 
918
             table, and covers all sj-inner and outer tables
895
919
             Within the range,  Inner, Outer, outer Noncorrelated tables
896
920
             may follow in any order.
897
921
       (3) - The suffix of outer Noncorrelated tables.
898
 
    
 
922
 
899
923
    FirstMatch strategy
900
924
    ~~~~~~~~~~~~~~~~~~~
901
925
 
908
932
            non-correlated tables.
909
933
      (3) - The suffix of outer Noncorrelated tables.
910
934
 
911
 
    InsideOut strategy 
 
935
    InsideOut strategy
912
936
    ~~~~~~~~~~~~~~~~~~
913
937
 
914
938
     (ot|ct|nt) [ insideout_tbl (ot|nt|it)* it ]  (ot|nt)*
915
939
     +--------+   +===========+ +=============+   +------+
916
940
        (1)           (2)          (3)              (4)
917
 
     
 
941
 
918
942
      (1) - Prefix that may contain any outer tables. The prefix must contain
919
943
            all the non-trivially correlated outer tables. (non-trivially means
920
944
            that the correlation is not just through the IN-equality).
921
 
      
 
945
 
922
946
      (2) - Inner table for which the InsideOut scan is performed.
923
947
 
924
 
      (3) - The remainder of the duplicate-generating range. It is served by 
 
948
      (3) - The remainder of the duplicate-generating range. It is served by
925
949
            application of FirstMatch strategy, with the exception that
926
950
            outer IN-correlated tables are considered to be non-correlated.
927
951
 
929
953
 
930
954
    If several strategies are applicable, their relative priorities are:
931
955
      1. InsideOut
932
 
      2. FirstMatch 
 
956
      2. FirstMatch
933
957
      3. DuplicateWeedout
934
958
 
935
959
    This function walks over the join order and sets up the strategies by
936
960
    setting appropriate members in join_tab structures.
937
961
 
938
962
  RETURN
939
 
    false  OK 
 
963
    false  OK
940
964
    true   Out of memory error
941
965
*/
942
966
 
945
969
{
946
970
  table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
947
971
  struct {
948
 
    /* 
949
 
      0 - invalid (EOF marker), 
950
 
      1 - InsideOut, 
 
972
    /*
 
973
      0 - invalid (EOF marker),
 
974
      1 - InsideOut,
951
975
      2 - Temptable (maybe confluent),
952
976
      3 - Temptable with join buffering
953
977
    */
954
978
    uint32_t strategy;
955
979
    uint32_t start_idx; /* Left range bound */
956
980
    uint32_t end_idx;   /* Right range bound */
957
 
    /* 
958
 
      For Temptable strategy: Bitmap of all outer and correlated tables from 
 
981
    /*
 
982
      For Temptable strategy: Bitmap of all outer and correlated tables from
959
983
      all involved join nests.
960
984
    */
961
985
    table_map outer_tables;
1015
1039
          i <= no_jbuf_after && !dealing_with_jbuf)
1016
1040
      {
1017
1041
        /*
1018
 
          This table uses join buffering, which makes use of FirstMatch or 
1019
 
          InsideOut strategies impossible for the current and (we assume) 
 
1042
          This table uses join buffering, which makes use of FirstMatch or
 
1043
          InsideOut strategies impossible for the current and (we assume)
1020
1044
          preceding duplicate-producing ranges.
1021
1045
          That is, for the join order:
1022
1046
 
1032
1056
        dealing_with_jbuf= true;
1033
1057
        emb_insideout_nest= false;
1034
1058
 
1035
 
        /* 
 
1059
        /*
1036
1060
          Absorb all preceding duplicate-eliminating ranges. Their strategies
1037
 
          do not matter: 
 
1061
          do not matter:
1038
1062
        */
1039
1063
        for (int prev_range= 0; prev_range < cur_range; prev_range++)
1040
1064
        {
1041
 
          dups_ranges[cur_range].outer_tables |= 
 
1065
          dups_ranges[cur_range].outer_tables |=
1042
1066
            dups_ranges[prev_range].outer_tables;
1043
1067
        }
1044
1068
        dups_ranges[0].start_idx= 0; /* Will need to start from the 1st table */
1053
1077
           in the prefix), and all inner tables are in the join order prefix,
1054
1078
           or
1055
1079
        2. It's a DuplicateElimination range (possibly covering several
1056
 
           SJ-nests), and all inner, outer, and correlated tables of all 
 
1080
           SJ-nests), and all inner, outer, and correlated tables of all
1057
1081
           sj-nests are in the join order prefix.
1058
1082
      */
1059
1083
      bool end_of_range= false;
1060
 
      if (emb_insideout_nest && 
 
1084
      if (emb_insideout_nest &&
1061
1085
          bitmap_covers(cur_map, emb_insideout_nest->sj_inner_tables))
1062
1086
      {
1063
1087
        /* Save that this range is handled with InsideOut: */
1067
1091
      else if (bitmap_covers(cur_map, emb_outer_tables | emb_sj_map))
1068
1092
      {
1069
1093
        /*
1070
 
          This is a complete range to be handled with either DuplicateWeedout 
 
1094
          This is a complete range to be handled with either DuplicateWeedout
1071
1095
          or FirstMatch
1072
1096
        */
1073
1097
        dups_ranges[cur_range].strategy= dealing_with_jbuf? 3 : 2;
1074
 
        /* 
1075
 
          This will hold tables from within the range that need to be put 
 
1098
        /*
 
1099
          This will hold tables from within the range that need to be put
1076
1100
          into the join buffer before we can use the FirstMatch on its tail.
1077
1101
        */
1078
 
        dups_ranges[cur_range].outer_tables= emb_outer_tables & 
 
1102
        dups_ranges[cur_range].outer_tables= emb_outer_tables &
1079
1103
                                             ~range_start_map;
1080
1104
        end_of_range= true;
1081
1105
      }
1091
1115
    }
1092
1116
  }
1093
1117
 
1094
 
  THD *thd= join->thd;
 
1118
  Session *session= join->session;
1095
1119
  SJ_TMP_TABLE **next_sjtbl_ptr= &join->sj_tmp_tables;
1096
1120
  /*
1097
 
    Second pass: setup the chosen strategies    
 
1121
    Second pass: setup the chosen strategies
1098
1122
  */
1099
1123
  for (int j= 0; j < cur_range; j++)
1100
1124
  {
1108
1132
    else // DuplicateWeedout strategy
1109
1133
    {
1110
1134
      SJ_TMP_TABLE::TAB sjtabs[MAX_TABLES];
1111
 
      table_map cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
 
1135
      table_map weed_cur_map= join->const_table_map | PSEUDO_TABLE_BITS;
1112
1136
      uint32_t jt_rowid_offset= 0; // # tuple bytes are already occupied (w/o NULL bytes)
1113
1137
      uint32_t jt_null_bits= 0;    // # null bits in tuple bytes
1114
1138
      SJ_TMP_TABLE::TAB *last_tab= sjtabs;
1135
1159
          tab->table->prepare_for_position();
1136
1160
          tab->rowid_keep_flags= rowid_keep_flags;
1137
1161
        }
1138
 
        cur_map |= tab->table->map;
1139
 
        if (!tab->emb_sj_nest && bitmap_covers(cur_map, 
 
1162
        weed_cur_map |= tab->table->map;
 
1163
        if (!tab->emb_sj_nest && bitmap_covers(weed_cur_map,
1140
1164
                                               dups_ranges[j].outer_tables))
1141
1165
          last_outer_tab= tab;
1142
1166
      }
1145
1169
      {
1146
1170
        SJ_TMP_TABLE *sjtbl;
1147
1171
        uint32_t tabs_size= (last_tab - sjtabs) * sizeof(SJ_TMP_TABLE::TAB);
1148
 
        if (!(sjtbl= (SJ_TMP_TABLE*)thd->alloc(sizeof(SJ_TMP_TABLE))) ||
1149
 
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) thd->alloc(tabs_size)))
 
1172
        if (!(sjtbl= (SJ_TMP_TABLE*)session->alloc(sizeof(SJ_TMP_TABLE))) ||
 
1173
            !(sjtbl->tabs= (SJ_TMP_TABLE::TAB*) session->alloc(tabs_size)))
1150
1174
          return(true);
1151
1175
        memcpy(sjtbl->tabs, sjtabs, tabs_size);
1152
1176
        sjtbl->tabs_end= sjtbl->tabs + (last_tab - sjtabs);
1158
1182
        next_sjtbl_ptr= &(sjtbl->next);
1159
1183
        sjtbl->next= NULL;
1160
1184
 
1161
 
        sjtbl->tmp_table= 
1162
 
          create_duplicate_weedout_tmp_table(thd, 
1163
 
                                             sjtbl->rowid_len + 
 
1185
        sjtbl->tmp_table=
 
1186
          create_duplicate_weedout_tmp_table(session,
 
1187
                                             sjtbl->rowid_len +
1164
1188
                                             sjtbl->null_bytes,
1165
1189
                                             sjtbl);
1166
1190
 
1175
1199
    for (; tab < join->join_tab + dups_ranges[j].end_idx; tab++)
1176
1200
    {
1177
1201
      if (tab->emb_sj_nest)
1178
 
        tab->do_firstmatch= jump_to; 
 
1202
        tab->do_firstmatch= jump_to;
1179
1203
      else
1180
1204
        jump_to= tab;
1181
1205
    }
1186
1210
 
1187
1211
static void cleanup_sj_tmp_tables(JOIN *join)
1188
1212
{
1189
 
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl; 
 
1213
  for (SJ_TMP_TABLE *sj_tbl= join->sj_tmp_tables; sj_tbl;
1190
1214
       sj_tbl= sj_tbl->next)
1191
1215
  {
1192
1216
    if (sj_tbl->tmp_table)
1193
1217
    {
1194
 
      sj_tbl->tmp_table->free_tmp_table(join->thd);
 
1218
      sj_tbl->tmp_table->free_tmp_table(join->session);
1195
1219
    }
1196
1220
  }
1197
1221
  join->sj_tmp_tables= NULL;
1219
1243
    return(0);
1220
1244
  optimized= 1;
1221
1245
 
1222
 
  thd_proc_info(thd, "optimizing");
 
1246
  session->set_proc_info("optimizing");
1223
1247
  row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR :
1224
1248
              unit->select_limit_cnt);
1225
1249
  /* select_limit is used to decide if we are likely to scan the whole table */
1228
1252
    select_limit= HA_POS_ERROR;
1229
1253
  do_send_rows = (unit->select_limit_cnt) ? 1 : 0;
1230
1254
  // Ignore errors of execution if option IGNORE present
1231
 
  if (thd->lex->ignore)
1232
 
    thd->lex->current_select->no_error= 1;
 
1255
  if (session->lex->ignore)
 
1256
    session->lex->current_select->no_error= 1;
1233
1257
 
1234
1258
#ifdef HAVE_REF_TO_FIELDS                       // Not done yet
1235
1259
  /* Add HAVING to WHERE if possible */
1246
1270
        Item_cond_and can't be fixed after creation, so we do not check
1247
1271
        conds->fixed
1248
1272
      */
1249
 
      conds->fix_fields(thd, &conds);
1250
 
      conds->change_ref_to_fields(thd, tables_list);
 
1273
      conds->fix_fields(session, &conds);
 
1274
      conds->change_ref_to_fields(session, tables_list);
1251
1275
      conds->top_level_item();
1252
1276
      having= 0;
1253
1277
    }
1258
1282
  conds= simplify_joins(this, join_list, conds, true, false);
1259
1283
  build_bitmap_for_nested_joins(join_list, 0);
1260
1284
 
1261
 
  conds= optimize_cond(this, conds, join_list, &cond_value);   
1262
 
  if (thd->is_error())
 
1285
  conds= optimize_cond(this, conds, join_list, &cond_value);
 
1286
  if (session->is_error())
1263
1287
  {
1264
1288
    error= 1;
1265
1289
    return(1);
1267
1291
 
1268
1292
  {
1269
1293
    having= optimize_cond(this, having, join_list, &having_value);
1270
 
    if (thd->is_error())
 
1294
    if (session->is_error())
1271
1295
    {
1272
1296
      error= 1;
1273
1297
      return(1);
1277
1301
    if (select_lex->having)
1278
1302
      select_lex->having_value= having_value;
1279
1303
 
1280
 
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE || 
 
1304
    if (cond_value == Item::COND_FALSE || having_value == Item::COND_FALSE ||
1281
1305
        (!unit->select_limit_cnt && !(select_options & OPTION_FOUND_ROWS)))
1282
1306
    {                                           /* Impossible cond */
1283
1307
      zero_result_cause=  having_value == Item::COND_FALSE ?
1328
1352
        conjunctions.
1329
1353
        Preserve conditions for EXPLAIN.
1330
1354
      */
1331
 
      if (conds && !(thd->lex->describe & DESCRIBE_EXTENDED))
 
1355
      if (conds && !(session->lex->describe & DESCRIBE_EXTENDED))
1332
1356
      {
1333
1357
        COND *table_independent_conds=
1334
1358
          make_cond_for_table(conds, PSEUDO_TABLE_BITS, 0, 0);
1345
1369
  sort_by_table= get_sort_by_table(order, group_list, select_lex->leaf_tables);
1346
1370
 
1347
1371
  /* Calculate how to do the join */
1348
 
  thd_proc_info(thd, "statistics");
 
1372
  session->set_proc_info("statistics");
1349
1373
  if (make_join_statistics(this, select_lex->leaf_tables, conds, &keyuse) ||
1350
 
      thd->is_fatal_error)
 
1374
      session->is_fatal_error)
1351
1375
  {
1352
1376
    return(1);
1353
1377
  }
1354
1378
 
1355
1379
  /* Remove distinct if only const tables */
1356
1380
  select_distinct= select_distinct && (const_tables != tables);
1357
 
  thd_proc_info(thd, "preparing");
 
1381
  session->set_proc_info("preparing");
1358
1382
  if (result->initialize_tables(this))
1359
1383
  {
1360
1384
    return(1);                          // error == -1
1363
1387
      !(select_options & SELECT_DESCRIBE) &&
1364
1388
      (!conds ||
1365
1389
       !(conds->used_tables() & RAND_TABLE_BIT) ||
1366
 
       select_lex->master_unit() == &thd->lex->unit)) // upper level SELECT
 
1390
       select_lex->master_unit() == &session->lex->unit)) // upper level SELECT
1367
1391
  {
1368
1392
    zero_result_cause= "no matching row in const table";
1369
1393
    error= 0;
1370
1394
    return(0);
1371
1395
  }
1372
 
  if (!(thd->options & OPTION_BIG_SELECTS) &&
1373
 
      best_read > (double) thd->variables.max_join_size &&
 
1396
  if (!(session->options & OPTION_BIG_SELECTS) &&
 
1397
      best_read > (double) session->variables.max_join_size &&
1374
1398
      !(select_options & SELECT_DESCRIBE))
1375
1399
  {                                             /* purecov: inspected */
1376
1400
    my_message(ER_TOO_BIG_SELECT, ER(ER_TOO_BIG_SELECT), MYF(0));
1377
1401
    error= -1;
1378
1402
    return(1);
1379
1403
  }
1380
 
  if (const_tables && !thd->locked_tables &&
 
1404
  if (const_tables && !session->locked_tables &&
1381
1405
      !(select_options & SELECT_NO_UNLOCK))
1382
 
    mysql_unlock_some_tables(thd, table, const_tables);
 
1406
    mysql_unlock_some_tables(session, table, const_tables);
1383
1407
  if (!conds && outer_join)
1384
1408
  {
1385
1409
    /* Handle the case where we have an OUTER JOIN without a WHERE */
1392
1416
    error= -1;                                  /* purecov: inspected */
1393
1417
    return(1);
1394
1418
  }
1395
 
  
 
1419
 
1396
1420
  reset_nj_counters(join_list);
1397
1421
  make_outerjoin_info(this);
1398
1422
 
1411
1435
  /*
1412
1436
    Permorm the the optimization on fields evaluation mentioned above
1413
1437
    for all on expressions.
1414
 
  */ 
 
1438
  */
1415
1439
  for (JOIN_TAB *tab= join_tab + const_tables; tab < join_tab + tables ; tab++)
1416
1440
  {
1417
1441
    if (*tab->on_expr_ref)
1423
1447
    }
1424
1448
  }
1425
1449
 
1426
 
  if (conds &&!outer_join && const_table_map != found_const_table_map && 
 
1450
  if (conds &&!outer_join && const_table_map != found_const_table_map &&
1427
1451
      (select_options & SELECT_DESCRIBE) &&
1428
 
      select_lex->master_unit() == &thd->lex->unit) // upper level SELECT
 
1452
      select_lex->master_unit() == &session->lex->unit) // upper level SELECT
1429
1453
  {
1430
1454
    conds=new Item_int((int64_t) 0,1);  // Always false
1431
1455
  }
1441
1465
  /* Optimize distinct away if possible */
1442
1466
  {
1443
1467
    order_st *org_order= order;
1444
 
    order=remove_const(this, order,conds,1, &simple_order);
1445
 
    if (thd->is_error())
 
1468
    order=remove_constants(this, order,conds,1, &simple_order);
 
1469
    if (session->is_error())
1446
1470
    {
1447
1471
      error= 1;
1448
1472
      return(1);
1471
1495
      !tmp_table_param.sum_func_count &&
1472
1496
      (!join_tab[const_tables].select ||
1473
1497
       !join_tab[const_tables].select->quick ||
1474
 
       join_tab[const_tables].select->quick->get_type() != 
 
1498
       join_tab[const_tables].select->quick->get_type() !=
1475
1499
       QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
1476
1500
  {
1477
1501
    if (group_list &&
1497
1521
      if (!order || test_if_subpart(group_list, order))
1498
1522
          order= skip_sort_order ? 0 : group_list;
1499
1523
      /*
1500
 
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be 
 
1524
        If we have an IGNORE INDEX FOR GROUP BY(fields) clause, this must be
1501
1525
        rewritten to IGNORE INDEX FOR order_st BY(fields).
1502
1526
      */
1503
1527
      join_tab->table->keys_in_use_for_order_by=
1538
1562
    JOIN_TAB *tab= &join_tab[const_tables];
1539
1563
    bool all_order_fields_used;
1540
1564
    if (order)
1541
 
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1, 
 
1565
      skip_sort_order= test_if_skip_sort_order(tab, order, select_limit, 1,
1542
1566
        &tab->table->keys_in_use_for_order_by);
1543
 
    if ((group_list=create_distinct_group(thd, select_lex->ref_pointer_array,
 
1567
    if ((group_list=create_distinct_group(session, select_lex->ref_pointer_array,
1544
1568
                                          order, fields_list, all_fields,
1545
1569
                                          &all_order_fields_used)))
1546
1570
    {
1547
1571
      bool skip_group= (skip_sort_order &&
1548
 
        test_if_skip_sort_order(tab, group_list, select_limit, 1, 
 
1572
        test_if_skip_sort_order(tab, group_list, select_limit, 1,
1549
1573
                                &tab->table->keys_in_use_for_group_by) != 0);
1550
1574
      count_field_types(select_lex, &tmp_table_param, all_fields, 0);
1551
1575
      if ((skip_group && all_order_fields_used) ||
1572
1596
      else
1573
1597
        group_list= 0;
1574
1598
    }
1575
 
    else if (thd->is_fatal_error)                       // End of memory
 
1599
    else if (session->is_fatal_error)                   // End of memory
1576
1600
      return(1);
1577
1601
  }
1578
1602
  simple_group= 0;
1579
1603
  {
1580
1604
    order_st *old_group_list;
1581
 
    group_list= remove_const(this, (old_group_list= group_list), conds,
1582
 
                             rollup.state == ROLLUP::STATE_NONE,
1583
 
                             &simple_group);
1584
 
    if (thd->is_error())
 
1605
    group_list= remove_constants(this, (old_group_list= group_list), conds,
 
1606
                                 rollup.state == ROLLUP::STATE_NONE,
 
1607
                                 &simple_group);
 
1608
    if (session->is_error())
1585
1609
    {
1586
1610
      error= 1;
1587
1611
      return(1);
1628
1652
              test(select_options & OPTION_BUFFER_RESULT)));
1629
1653
 
1630
1654
  uint32_t no_jbuf_after= make_join_orderinfo(this);
1631
 
  uint64_t select_opts_for_readinfo= 
 
1655
  uint64_t select_opts_for_readinfo=
1632
1656
    (select_options & (SELECT_DESCRIBE | SELECT_NO_JOIN_CACHE)) | (0);
1633
1657
 
1634
1658
  sj_tmp_tables= NULL;
1664
1688
        error= 0;
1665
1689
        return(unit->item->
1666
1690
                    change_engine(new
1667
 
                                  subselect_uniquesubquery_engine(thd,
 
1691
                                  subselect_uniquesubquery_engine(session,
1668
1692
                                                                  join_tab,
1669
1693
                                                                  unit->item,
1670
1694
                                                                  where)));
1678
1702
        error= 0;
1679
1703
        return(unit->item->
1680
1704
                    change_engine(new
1681
 
                                  subselect_indexsubquery_engine(thd,
 
1705
                                  subselect_indexsubquery_engine(session,
1682
1706
                                                                 join_tab,
1683
1707
                                                                 unit->item,
1684
1708
                                                                 where,
1694
1718
      conds= remove_additional_cond(conds);
1695
1719
      save_index_subquery_explain_info(join_tab, conds);
1696
1720
      return(unit->item->
1697
 
                  change_engine(new subselect_indexsubquery_engine(thd,
 
1721
                  change_engine(new subselect_indexsubquery_engine(session,
1698
1722
                                                                   join_tab,
1699
1723
                                                                   unit->item,
1700
1724
                                                                   conds,
1728
1752
        (join_tab[const_tables].type != JT_REF_OR_NULL) &&
1729
1753
        ((order && simple_order) || (group_list && simple_group)))
1730
1754
    {
1731
 
      if (add_ref_to_table_cond(thd,&join_tab[const_tables])) {
 
1755
      if (add_ref_to_table_cond(session,&join_tab[const_tables])) {
1732
1756
        return(1);
1733
1757
      }
1734
1758
    }
1735
 
    
 
1759
 
1736
1760
    if (!(select_options & SELECT_BIG_RESULT) &&
1737
1761
        ((group_list &&
1738
1762
          (!simple_group ||
1739
1763
           !test_if_skip_sort_order(&join_tab[const_tables], group_list,
1740
 
                                    unit->select_limit_cnt, 0, 
 
1764
                                    unit->select_limit_cnt, 0,
1741
1765
                                    &join_tab[const_tables].table->
1742
1766
                                    keys_in_use_for_group_by))) ||
1743
1767
         select_distinct) &&
1789
1813
  /* Create a tmp table if distinct or if the sort is too complicated */
1790
1814
  if (need_tmp)
1791
1815
  {
1792
 
    thd_proc_info(thd, "Creating tmp table");
 
1816
    session->set_proc_info("Creating tmp table");
1793
1817
 
1794
1818
    init_items_ref_array();
1795
1819
 
1805
1829
    */
1806
1830
    ha_rows tmp_rows_limit= ((order == 0 || skip_sort_order) &&
1807
1831
                             !tmp_group &&
1808
 
                             !thd->lex->current_select->with_sum_func) ?
 
1832
                             !session->lex->current_select->with_sum_func) ?
1809
1833
                            select_limit : HA_POS_ERROR;
1810
1834
 
1811
1835
    if (!(exec_tmp_table1=
1812
 
          create_tmp_table(thd, &tmp_table_param, all_fields,
 
1836
          create_tmp_table(session, &tmp_table_param, all_fields,
1813
1837
                           tmp_group,
1814
1838
                           group_list ? 0 : select_distinct,
1815
1839
                           group_list && simple_group,
1826
1850
        temp table.
1827
1851
      - We are using DISTINCT without resolving the distinct as a GROUP BY
1828
1852
        on all columns.
1829
 
      
 
1853
 
1830
1854
      If having is not handled here, it will be checked before the row
1831
1855
      is sent to the client.
1832
 
    */    
1833
 
    if (tmp_having && 
 
1856
    */
 
1857
    if (tmp_having &&
1834
1858
        (sort_and_group || (exec_tmp_table1->distinct && !group_list)))
1835
1859
      having= tmp_having;
1836
1860
 
1837
1861
    /* if group or order on first table, sort first */
1838
1862
    if (group_list && simple_group)
1839
1863
    {
1840
 
      thd_proc_info(thd, "Sorting for group");
1841
 
      if (create_sort_index(thd, this, group_list,
 
1864
      session->set_proc_info("Sorting for group");
 
1865
      if (create_sort_index(session, this, group_list,
1842
1866
                            HA_POS_ERROR, HA_POS_ERROR, false) ||
1843
1867
          alloc_group_fields(this, group_list) ||
1844
1868
          make_sum_func_list(all_fields, fields_list, 1) ||
1845
 
          setup_sum_funcs(thd, sum_funcs))
 
1869
          setup_sum_funcs(session, sum_funcs))
1846
1870
      {
1847
1871
        return(1);
1848
1872
      }
1851
1875
    else
1852
1876
    {
1853
1877
      if (make_sum_func_list(all_fields, fields_list, 0) ||
1854
 
          setup_sum_funcs(thd, sum_funcs))
 
1878
          setup_sum_funcs(session, sum_funcs))
1855
1879
      {
1856
1880
        return(1);
1857
1881
      }
1858
1882
 
1859
1883
      if (!group_list && ! exec_tmp_table1->distinct && order && simple_order)
1860
1884
      {
1861
 
        thd_proc_info(thd, "Sorting for order");
1862
 
        if (create_sort_index(thd, this, order,
 
1885
        session->set_proc_info("Sorting for order");
 
1886
        if (create_sort_index(session, this, order,
1863
1887
                              HA_POS_ERROR, HA_POS_ERROR, true))
1864
1888
        {
1865
1889
          return(1);
1867
1891
        order=0;
1868
1892
      }
1869
1893
    }
1870
 
    
 
1894
 
1871
1895
    /*
1872
1896
      Optimize distinct when used on some of the tables
1873
1897
      SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b
1876
1900
 
1877
1901
    if (exec_tmp_table1->distinct)
1878
1902
    {
1879
 
      table_map used_tables= thd->used_tables;
 
1903
      table_map used_tables= session->used_tables;
1880
1904
      JOIN_TAB *last_join_tab= join_tab+tables-1;
1881
1905
      do
1882
1906
      {
1889
1913
      {
1890
1914
        /* Should always succeed */
1891
1915
        if (test_if_skip_sort_order(&join_tab[const_tables],
1892
 
                                    order, unit->select_limit_cnt, 0, 
 
1916
                                    order, unit->select_limit_cnt, 0,
1893
1917
                                    &join_tab[const_tables].table->
1894
1918
                                      keys_in_use_for_order_by))
1895
1919
          order=0;
1896
1920
      }
1897
1921
    }
1898
1922
 
1899
 
    /* 
1900
 
      If this join belongs to an uncacheable subquery save 
1901
 
      the original join 
 
1923
    /*
 
1924
      If this join belongs to an uncacheable subquery save
 
1925
      the original join
1902
1926
    */
1903
1927
    if (select_lex->uncacheable && !is_top_level_join() &&
1904
1928
        init_save_join_tab())
1964
1988
 
1965
1989
/**
1966
1990
   @brief Save the original join layout
1967
 
      
1968
 
   @details Saves the original join layout so it can be reused in 
 
1991
 
 
1992
   @details Saves the original join layout so it can be reused in
1969
1993
   re-execution and for EXPLAIN.
1970
 
             
 
1994
 
1971
1995
   @return Operation status
1972
1996
   @retval 0      success.
1973
1997
   @retval 1      error occurred.
1976
2000
bool
1977
2001
JOIN::init_save_join_tab()
1978
2002
{
1979
 
  if (!(tmp_join= (JOIN*)thd->alloc(sizeof(JOIN))))
 
2003
  if (!(tmp_join= (JOIN*)session->alloc(sizeof(JOIN))))
1980
2004
    return 1;                                  /* purecov: inspected */
1981
2005
  error= 0;                                    // Ensure that tmp_join.error= 0
1982
2006
  restore_tmp();
1989
2013
{
1990
2014
  if (!join_tab_save && select_lex->master_unit()->uncacheable)
1991
2015
  {
1992
 
    if (!(join_tab_save= (JOIN_TAB*)thd->memdup((unsigned char*) join_tab,
 
2016
    if (!(join_tab_save= (JOIN_TAB*)session->memdup((unsigned char*) join_tab,
1993
2017
                                                sizeof(JOIN_TAB) * tables)))
1994
2018
      return 1;
1995
2019
  }
2006
2030
    the query.  It's never shown in EXPLAIN!
2007
2031
 
2008
2032
  @todo
2009
 
    When can we have here thd->net.report_error not zero?
 
2033
    When can we have here session->net.report_error not zero?
2010
2034
*/
2011
 
void
2012
 
JOIN::exec()
 
2035
void JOIN::exec()
2013
2036
{
2014
2037
  List<Item> *columns_list= &fields_list;
2015
2038
  int      tmp_error;
2016
2039
 
2017
 
  thd_proc_info(thd, "executing");
 
2040
  session->set_proc_info("executing");
2018
2041
  error= 0;
2019
 
  (void) result->prepare2(); // Currently, this cannot fail.
2020
2042
 
2021
2043
  if (!tables_list && (tables || !select_lex->with_sum_func))
2022
 
  {                                           // Only test of functions
 
2044
  {                                           
 
2045
    /* Only test of functions */
2023
2046
    if (select_options & SELECT_DESCRIBE)
2024
 
      select_describe(this, false, false, false,
2025
 
                      (zero_result_cause?zero_result_cause:"No tables used"));
 
2047
      select_describe(this, false, false, false, (zero_result_cause?zero_result_cause:"No tables used"));
2026
2048
    else
2027
2049
    {
2028
 
      result->send_fields(*columns_list,
2029
 
                          Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
 
2050
      result->send_fields(*columns_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2030
2051
      /*
2031
2052
        We have to test for 'conds' here as the WHERE may not be constant
2032
2053
        even if we don't have any tables for prepared statements or if
2036
2057
          (!conds || conds->val_int()) &&
2037
2058
          (!having || having->val_int()))
2038
2059
      {
2039
 
        if (do_send_rows && result->send_data(fields_list))
2040
 
          error= 1;
2041
 
        else
2042
 
        {
2043
 
          error= (int) result->send_eof();
2044
 
          send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 :
2045
 
                         thd->sent_row_count);
2046
 
        }
 
2060
        if (do_send_rows && result->send_data(fields_list))
 
2061
          error= 1;
 
2062
        else
 
2063
        {
 
2064
          error= (int) result->send_eof();
 
2065
          send_records= ((select_options & OPTION_FOUND_ROWS) ? 1 : session->sent_row_count);
 
2066
        }
2047
2067
      }
2048
2068
      else
2049
2069
      {
2050
 
        error=(int) result->send_eof();
 
2070
        error= (int) result->send_eof();
2051
2071
        send_records= 0;
2052
2072
      }
2053
2073
    }
2054
2074
    /* Single select (without union) always returns 0 or 1 row */
2055
 
    thd->limit_found_rows= send_records;
2056
 
    thd->examined_row_count= 0;
 
2075
    session->limit_found_rows= send_records;
 
2076
    session->examined_row_count= 0;
2057
2077
    return;
2058
2078
  }
2059
2079
  /*
2062
2082
    It must be accumulated from all join iterations of all join parts.
2063
2083
  */
2064
2084
  if (tables)
2065
 
    thd->limit_found_rows= 0;
 
2085
    session->limit_found_rows= 0;
2066
2086
 
2067
2087
  if (zero_result_cause)
2068
2088
  {
2075
2095
    return;
2076
2096
  }
2077
2097
 
2078
 
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) &&
2079
 
      get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
 
2098
  if ((this->select_lex->options & OPTION_SCHEMA_TABLE) && get_schema_tables_result(this, PROCESSED_BY_JOIN_EXEC))
2080
2099
    return;
2081
2100
 
2082
2101
  if (select_options & SELECT_DESCRIBE)
2088
2107
    */
2089
2108
    if (!order && !no_order && (!skip_sort_order || !need_tmp))
2090
2109
    {
2091
 
      /*
2092
 
        Reset 'order' to 'group_list' and reinit variables describing
2093
 
        'order'
2094
 
      */
 
2110
      /* Reset 'order' to 'group_list' and reinit variables describing 'order' */
2095
2111
      order= group_list;
2096
2112
      simple_order= simple_group;
2097
2113
      skip_sort_order= 0;
2098
2114
    }
2099
 
    if (order && 
2100
 
        (order != group_list || !(select_options & SELECT_BIG_RESULT)) &&
2101
 
        (const_tables == tables ||
2102
 
         ((simple_order || skip_sort_order) &&
2103
 
          test_if_skip_sort_order(&join_tab[const_tables], order,
2104
 
                                  select_limit, 0, 
2105
 
                                  &join_tab[const_tables].table->
2106
 
                                    keys_in_use_for_query))))
2107
 
      order=0;
 
2115
    if (order && (order != group_list || !(select_options & SELECT_BIG_RESULT)))
 
2116
    {
 
2117
      if (const_tables == tables 
 
2118
        || ((simple_order || skip_sort_order) 
 
2119
          && test_if_skip_sort_order(&join_tab[const_tables], order, select_limit, 0, &join_tab[const_tables].table->keys_in_use_for_query)))
 
2120
      order= 0;
 
2121
    }
2108
2122
    having= tmp_having;
2109
 
    select_describe(this, need_tmp,
2110
 
                    order != 0 && !skip_sort_order,
2111
 
                    select_distinct,
2112
 
                    !tables ? "No tables used" : NULL);
 
2123
    select_describe(this, need_tmp, order != 0 && !skip_sort_order,  select_distinct, !tables ? "No tables used" : NULL);
2113
2124
    return;
2114
2125
  }
2115
2126
 
2140
2151
    curr_tmp_table= exec_tmp_table1;
2141
2152
 
2142
2153
    /* Copy data to the temporary table */
2143
 
    thd_proc_info(thd, "Copying to tmp table");
2144
 
    if (!curr_join->sort_and_group &&
2145
 
        curr_join->const_tables != curr_join->tables)
 
2154
    session->set_proc_info("Copying to tmp table");
 
2155
    if (! curr_join->sort_and_group && curr_join->const_tables != curr_join->tables)
2146
2156
      curr_join->join_tab[curr_join->const_tables].sorted= 0;
2147
2157
    if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2148
2158
    {
2150
2160
      return;
2151
2161
    }
2152
2162
    curr_tmp_table->file->info(HA_STATUS_VARIABLE);
2153
 
    
 
2163
 
2154
2164
    if (curr_join->having)
2155
2165
      curr_join->having= curr_join->tmp_having= 0; // Allready done
2156
 
    
 
2166
 
2157
2167
    /* Change sum_fields reference to calculated fields in tmp_table */
2158
2168
    curr_join->all_fields= *curr_all_fields;
2159
2169
    if (!items1)
2161
2171
      items1= items0 + all_fields.elements;
2162
2172
      if (sort_and_group || curr_tmp_table->group)
2163
2173
      {
2164
 
        if (change_to_use_tmp_fields(thd, items1,
2165
 
                                     tmp_fields_list1, tmp_all_fields1,
2166
 
                                     fields_list.elements, all_fields))
2167
 
          return;
 
2174
        if (change_to_use_tmp_fields(session, items1,
 
2175
                  tmp_fields_list1, tmp_all_fields1,
 
2176
                  fields_list.elements, all_fields))
 
2177
          return;
2168
2178
      }
2169
2179
      else
2170
2180
      {
2171
 
        if (change_refs_to_tmp_fields(thd, items1,
2172
 
                                      tmp_fields_list1, tmp_all_fields1,
2173
 
                                      fields_list.elements, all_fields))
2174
 
          return;
 
2181
        if (change_refs_to_tmp_fields(session, items1,
 
2182
                    tmp_fields_list1, tmp_all_fields1,
 
2183
                    fields_list.elements, all_fields))
 
2184
          return;
2175
2185
      }
2176
2186
      curr_join->tmp_all_fields1= tmp_all_fields1;
2177
2187
      curr_join->tmp_fields_list1= tmp_fields_list1;
2180
2190
    curr_all_fields= &tmp_all_fields1;
2181
2191
    curr_fields_list= &tmp_fields_list1;
2182
2192
    curr_join->set_items_ref_array(items1);
2183
 
    
 
2193
 
2184
2194
    if (sort_and_group || curr_tmp_table->group)
2185
2195
    {
2186
 
      curr_join->tmp_table_param.field_count+= 
2187
 
        curr_join->tmp_table_param.sum_func_count+
2188
 
        curr_join->tmp_table_param.func_count;
2189
 
      curr_join->tmp_table_param.sum_func_count= 
2190
 
        curr_join->tmp_table_param.func_count= 0;
 
2196
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count
 
2197
                                             + curr_join->tmp_table_param.func_count;
 
2198
      curr_join->tmp_table_param.sum_func_count= 0;
 
2199
      curr_join->tmp_table_param.func_count= 0;
2191
2200
    }
2192
2201
    else
2193
2202
    {
2194
 
      curr_join->tmp_table_param.field_count+= 
2195
 
        curr_join->tmp_table_param.func_count;
 
2203
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.func_count;
2196
2204
      curr_join->tmp_table_param.func_count= 0;
2197
2205
    }
2198
 
    
 
2206
 
2199
2207
    if (curr_tmp_table->group)
2200
2208
    {                                           // Already grouped
2201
2209
      if (!curr_join->order && !curr_join->no_order && !skip_sort_order)
2202
 
        curr_join->order= curr_join->group_list;  /* order by group */
 
2210
        curr_join->order= curr_join->group_list;  /* order by group */
2203
2211
      curr_join->group_list= 0;
2204
2212
    }
2205
 
    
 
2213
 
2206
2214
    /*
2207
2215
      If we have different sort & group then we must sort the data by group
2208
2216
      and copy it to another tmp table
2211
2219
      like SEC_TO_TIME(SUM(...)).
2212
2220
    */
2213
2221
 
2214
 
    if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
 
2222
    if ((curr_join->group_list && (!test_if_subpart(curr_join->group_list, curr_join->order) || curr_join->select_distinct)) 
 
2223
        || (curr_join->select_distinct && curr_join->tmp_table_param.using_indirect_summary_function))
2215
2224
    {                                   /* Must copy to another table */
2216
2225
      /* Free first data from old join */
2217
2226
      curr_join->join_free();
2218
2227
      if (make_simple_join(curr_join, curr_tmp_table))
2219
 
        return;
 
2228
        return;
2220
2229
      calc_group_buffer(curr_join, group_list);
2221
2230
      count_field_types(select_lex, &curr_join->tmp_table_param,
2222
2231
                        curr_join->tmp_all_fields1,
2223
2232
                        curr_join->select_distinct && !curr_join->group_list);
2224
 
      curr_join->tmp_table_param.hidden_field_count= 
2225
 
        (curr_join->tmp_all_fields1.elements-
2226
 
         curr_join->tmp_fields_list1.elements);
2227
 
      
2228
 
      
 
2233
      curr_join->tmp_table_param.hidden_field_count= curr_join->tmp_all_fields1.elements
 
2234
                                                   - curr_join->tmp_fields_list1.elements;
 
2235
 
2229
2236
      if (exec_tmp_table2)
2230
 
        curr_tmp_table= exec_tmp_table2;
 
2237
        curr_tmp_table= exec_tmp_table2;
2231
2238
      else
2232
2239
      {
2233
 
        /* group data to new table */
 
2240
        /* group data to new table */
2234
2241
 
2235
2242
        /*
2236
2243
          If the access method is loose index scan then all MIN/MAX
2240
2247
        if (curr_join->join_tab->is_using_loose_index_scan())
2241
2248
          curr_join->tmp_table_param.precomputed_group_by= true;
2242
2249
 
2243
 
        if (!(curr_tmp_table=
2244
 
              exec_tmp_table2= create_tmp_table(thd,
2245
 
                                                &curr_join->tmp_table_param,
2246
 
                                                *curr_all_fields,
2247
 
                                                (order_st*) 0,
2248
 
                                                curr_join->select_distinct && 
2249
 
                                                !curr_join->group_list,
2250
 
                                                1, curr_join->select_options,
2251
 
                                                HA_POS_ERROR,
2252
 
                                                (char *) "")))
2253
 
          return;
2254
 
        curr_join->exec_tmp_table2= exec_tmp_table2;
 
2250
        if (!(curr_tmp_table=
 
2251
              exec_tmp_table2= create_tmp_table(session,
 
2252
                                                &curr_join->tmp_table_param,
 
2253
                                                *curr_all_fields,
 
2254
                                                (order_st*) 0,
 
2255
                                                curr_join->select_distinct &&
 
2256
                                                !curr_join->group_list,
 
2257
                                                1, curr_join->select_options,
 
2258
                                                HA_POS_ERROR,
 
2259
                                                (char *) "")))
 
2260
          return;
 
2261
        curr_join->exec_tmp_table2= exec_tmp_table2;
2255
2262
      }
2256
2263
      if (curr_join->group_list)
2257
2264
      {
2258
 
        thd_proc_info(thd, "Creating sort index");
2259
 
        if (curr_join->join_tab == join_tab && save_join_tab())
2260
 
        {
2261
 
          return;
2262
 
        }
2263
 
        if (create_sort_index(thd, curr_join, curr_join->group_list,
2264
 
                              HA_POS_ERROR, HA_POS_ERROR, false) ||
2265
 
            make_group_fields(this, curr_join))
2266
 
        {
2267
 
          return;
2268
 
        }
 
2265
        session->set_proc_info("Creating sort index");
 
2266
        if (curr_join->join_tab == join_tab && save_join_tab())
 
2267
        {
 
2268
          return;
 
2269
        }
 
2270
        if (create_sort_index(session, curr_join, curr_join->group_list,
 
2271
                  HA_POS_ERROR, HA_POS_ERROR, false) ||
 
2272
            make_group_fields(this, curr_join))
 
2273
        {
 
2274
          return;
 
2275
        }
2269
2276
        sortorder= curr_join->sortorder;
2270
2277
      }
2271
 
      
2272
 
      thd_proc_info(thd, "Copying to group table");
 
2278
 
 
2279
      session->set_proc_info("Copying to group table");
2273
2280
      tmp_error= -1;
2274
2281
      if (curr_join != this)
2275
2282
      {
2276
 
        if (sum_funcs2)
2277
 
        {
2278
 
          curr_join->sum_funcs= sum_funcs2;
2279
 
          curr_join->sum_funcs_end= sum_funcs_end2; 
2280
 
        }
2281
 
        else
2282
 
        {
2283
 
          curr_join->alloc_func_list();
2284
 
          sum_funcs2= curr_join->sum_funcs;
2285
 
          sum_funcs_end2= curr_join->sum_funcs_end;
2286
 
        }
 
2283
        if (sum_funcs2)
 
2284
        {
 
2285
          curr_join->sum_funcs= sum_funcs2;
 
2286
          curr_join->sum_funcs_end= sum_funcs_end2;
 
2287
        }
 
2288
        else
 
2289
        {
 
2290
          curr_join->alloc_func_list();
 
2291
          sum_funcs2= curr_join->sum_funcs;
 
2292
          sum_funcs_end2= curr_join->sum_funcs_end;
 
2293
        }
2287
2294
      }
2288
 
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2289
 
                                        1, true))
 
2295
      if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list, 1, true))
2290
2296
        return;
2291
2297
      curr_join->group_list= 0;
2292
 
      if (!curr_join->sort_and_group &&
2293
 
          curr_join->const_tables != curr_join->tables)
 
2298
 
 
2299
      if (!curr_join->sort_and_group && (curr_join->const_tables != curr_join->tables))
2294
2300
        curr_join->join_tab[curr_join->const_tables].sorted= 0;
2295
 
      if (setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2296
 
          (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
 
2301
      
 
2302
      if (setup_sum_funcs(curr_join->session, curr_join->sum_funcs) 
 
2303
        || (tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table)))
2297
2304
      {
2298
 
        error= tmp_error;
2299
 
        return;
 
2305
        error= tmp_error;
 
2306
        return;
2300
2307
      }
2301
2308
      end_read_record(&curr_join->join_tab->read_record);
2302
2309
      curr_join->const_tables= curr_join->tables; // Mark free for cleanup()
2303
2310
      curr_join->join_tab[0].table= 0;           // Table is freed
2304
 
      
 
2311
 
2305
2312
      // No sum funcs anymore
2306
2313
      if (!items2)
2307
2314
      {
2308
 
        items2= items1 + all_fields.elements;
2309
 
        if (change_to_use_tmp_fields(thd, items2,
2310
 
                                     tmp_fields_list2, tmp_all_fields2, 
2311
 
                                     fields_list.elements, tmp_all_fields1))
2312
 
          return;
2313
 
        curr_join->tmp_fields_list2= tmp_fields_list2;
2314
 
        curr_join->tmp_all_fields2= tmp_all_fields2;
 
2315
        items2= items1 + all_fields.elements;
 
2316
        if (change_to_use_tmp_fields(session, items2,
 
2317
                  tmp_fields_list2, tmp_all_fields2,
 
2318
                  fields_list.elements, tmp_all_fields1))
 
2319
          return;
 
2320
        curr_join->tmp_fields_list2= tmp_fields_list2;
 
2321
        curr_join->tmp_all_fields2= tmp_all_fields2;
2315
2322
      }
2316
2323
      curr_fields_list= &curr_join->tmp_fields_list2;
2317
2324
      curr_all_fields= &curr_join->tmp_all_fields2;
2318
2325
      curr_join->set_items_ref_array(items2);
2319
 
      curr_join->tmp_table_param.field_count+= 
2320
 
        curr_join->tmp_table_param.sum_func_count;
 
2326
      curr_join->tmp_table_param.field_count+= curr_join->tmp_table_param.sum_func_count;
2321
2327
      curr_join->tmp_table_param.sum_func_count= 0;
2322
2328
    }
2323
2329
    if (curr_tmp_table->distinct)
2324
2330
      curr_join->select_distinct=0;             /* Each row is unique */
2325
 
    
 
2331
 
2326
2332
    curr_join->join_free();                     /* Free quick selects */
2327
2333
    if (curr_join->select_distinct && ! curr_join->group_list)
2328
2334
    {
2329
 
      thd_proc_info(thd, "Removing duplicates");
 
2335
      session->set_proc_info("Removing duplicates");
2330
2336
      if (curr_join->tmp_having)
2331
 
        curr_join->tmp_having->update_used_tables();
 
2337
        curr_join->tmp_having->update_used_tables();
 
2338
 
2332
2339
      if (remove_duplicates(curr_join, curr_tmp_table,
2333
2340
                            *curr_fields_list, curr_join->tmp_having))
2334
 
        return;
 
2341
        return;
 
2342
      
2335
2343
      curr_join->tmp_having=0;
2336
2344
      curr_join->select_distinct=0;
2337
2345
    }
2339
2347
    if (make_simple_join(curr_join, curr_tmp_table))
2340
2348
      return;
2341
2349
    calc_group_buffer(curr_join, curr_join->group_list);
2342
 
    count_field_types(select_lex, &curr_join->tmp_table_param, 
2343
 
                      *curr_all_fields, 0);
2344
 
    
 
2350
    count_field_types(select_lex, &curr_join->tmp_table_param, *curr_all_fields, 0);
 
2351
 
2345
2352
  }
2346
 
  
 
2353
 
2347
2354
  if (curr_join->group || curr_join->tmp_table_param.sum_func_count)
2348
2355
  {
2349
2356
    if (make_group_fields(this, curr_join))
2350
 
    {
2351
2357
      return;
2352
 
    }
2353
 
    if (!items3)
 
2358
 
 
2359
    if (! items3)
2354
2360
    {
2355
 
      if (!items0)
2356
 
        init_items_ref_array();
 
2361
      if (! items0)
 
2362
        init_items_ref_array();
2357
2363
      items3= ref_pointer_array + (all_fields.elements*4);
2358
 
      setup_copy_fields(thd, &curr_join->tmp_table_param,
 
2364
      setup_copy_fields(session, &curr_join->tmp_table_param,
2359
2365
                        items3, tmp_fields_list3, tmp_all_fields3,
2360
2366
                        curr_fields_list->elements, *curr_all_fields);
2361
2367
      tmp_table_param.save_copy_funcs= curr_join->tmp_table_param.copy_funcs;
2362
2368
      tmp_table_param.save_copy_field= curr_join->tmp_table_param.copy_field;
2363
 
      tmp_table_param.save_copy_field_end=
2364
 
        curr_join->tmp_table_param.copy_field_end;
 
2369
      tmp_table_param.save_copy_field_end= curr_join->tmp_table_param.copy_field_end;
2365
2370
      curr_join->tmp_all_fields3= tmp_all_fields3;
2366
2371
      curr_join->tmp_fields_list3= tmp_fields_list3;
2367
2372
    }
2369
2374
    {
2370
2375
      curr_join->tmp_table_param.copy_funcs= tmp_table_param.save_copy_funcs;
2371
2376
      curr_join->tmp_table_param.copy_field= tmp_table_param.save_copy_field;
2372
 
      curr_join->tmp_table_param.copy_field_end=
2373
 
        tmp_table_param.save_copy_field_end;
 
2377
      curr_join->tmp_table_param.copy_field_end= tmp_table_param.save_copy_field_end;
2374
2378
    }
2375
2379
    curr_fields_list= &tmp_fields_list3;
2376
2380
    curr_all_fields= &tmp_all_fields3;
2377
2381
    curr_join->set_items_ref_array(items3);
2378
2382
 
2379
2383
    if (curr_join->make_sum_func_list(*curr_all_fields, *curr_fields_list,
2380
 
                                      1, true) || 
2381
 
        setup_sum_funcs(curr_join->thd, curr_join->sum_funcs) ||
2382
 
        thd->is_fatal_error)
 
2384
                                      1, true) ||
 
2385
        setup_sum_funcs(curr_join->session, curr_join->sum_funcs) ||
 
2386
        session->is_fatal_error)
2383
2387
      return;
2384
2388
  }
2385
2389
  if (curr_join->group_list || curr_join->order)
2386
2390
  {
2387
 
    thd_proc_info(thd, "Sorting result");
 
2391
    session->set_proc_info("Sorting result");
2388
2392
    /* If we have already done the group, add HAVING to sorted table */
2389
 
    if (curr_join->tmp_having && ! curr_join->group_list && 
2390
 
        ! curr_join->sort_and_group)
 
2393
    if (curr_join->tmp_having && ! curr_join->group_list &&     ! curr_join->sort_and_group)
2391
2394
    {
2392
2395
      // Some tables may have been const
2393
2396
      curr_join->tmp_having->update_used_tables();
2395
2398
      table_map used_tables= (curr_join->const_table_map |
2396
2399
                              curr_table->table->map);
2397
2400
 
2398
 
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having,
2399
 
                                                 used_tables,
2400
 
                                                 used_tables, 0);
 
2401
      Item* sort_table_cond= make_cond_for_table(curr_join->tmp_having, used_tables, used_tables, 0);
2401
2402
      if (sort_table_cond)
2402
2403
      {
2403
 
        if (!curr_table->select)
2404
 
          if (!(curr_table->select= new SQL_SELECT))
2405
 
            return;
2406
 
        if (!curr_table->select->cond)
2407
 
          curr_table->select->cond= sort_table_cond;
2408
 
        else                                    // This should never happen
2409
 
        {
2410
 
          if (!(curr_table->select->cond=
2411
 
                new Item_cond_and(curr_table->select->cond,
2412
 
                                  sort_table_cond)))
2413
 
            return;
2414
 
          /*
2415
 
            Item_cond_and do not need fix_fields for execution, its parameters
2416
 
            are fixed or do not need fix_fields, too
2417
 
          */
2418
 
          curr_table->select->cond->quick_fix_field();
2419
 
        }
2420
 
        curr_table->select_cond= curr_table->select->cond;
2421
 
        curr_table->select_cond->top_level_item();
2422
 
        curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
2423
 
                                                   ~ (table_map) 0,
2424
 
                                                   ~used_tables, 0);
 
2404
        if (!curr_table->select)
 
2405
          if (!(curr_table->select= new SQL_SELECT))
 
2406
            return;
 
2407
        if (!curr_table->select->cond)
 
2408
          curr_table->select->cond= sort_table_cond;
 
2409
        else                                    // This should never happen
 
2410
        {
 
2411
          if (!(curr_table->select->cond=
 
2412
          new Item_cond_and(curr_table->select->cond,
 
2413
                sort_table_cond)))
 
2414
            return;
 
2415
          /*
 
2416
            Item_cond_and do not need fix_fields for execution, its parameters
 
2417
            are fixed or do not need fix_fields, too
 
2418
          */
 
2419
          curr_table->select->cond->quick_fix_field();
 
2420
        }
 
2421
        curr_table->select_cond= curr_table->select->cond;
 
2422
        curr_table->select_cond->top_level_item();
 
2423
        curr_join->tmp_having= make_cond_for_table(curr_join->tmp_having,
 
2424
                    ~ (table_map) 0,
 
2425
                    ~used_tables, 0);
2425
2426
      }
2426
2427
    }
2427
2428
    {
2428
2429
      if (group)
2429
 
        curr_join->select_limit= HA_POS_ERROR;
 
2430
        curr_join->select_limit= HA_POS_ERROR;
2430
2431
      else
2431
2432
      {
2432
 
        /*
2433
 
          We can abort sorting after thd->select_limit rows if we there is no
2434
 
          WHERE clause for any tables after the sorted one.
2435
 
        */
2436
 
        JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
2437
 
        JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
2438
 
        for (; curr_table < end_table ; curr_table++)
2439
 
        {
2440
 
          /*
2441
 
            table->keyuse is set in the case there was an original WHERE clause
2442
 
            on the table that was optimized away.
2443
 
          */
2444
 
          if (curr_table->select_cond ||
2445
 
              (curr_table->keyuse && !curr_table->first_inner))
2446
 
          {
2447
 
            /* We have to sort all rows */
2448
 
            curr_join->select_limit= HA_POS_ERROR;
2449
 
            break;
2450
 
          }
2451
 
        }
 
2433
        /*
 
2434
          We can abort sorting after session->select_limit rows if we there is no
 
2435
          WHERE clause for any tables after the sorted one.
 
2436
        */
 
2437
        JOIN_TAB *curr_table= &curr_join->join_tab[curr_join->const_tables+1];
 
2438
        JOIN_TAB *end_table= &curr_join->join_tab[curr_join->tables];
 
2439
        for (; curr_table < end_table ; curr_table++)
 
2440
        {
 
2441
          /*
 
2442
            table->keyuse is set in the case there was an original WHERE clause
 
2443
            on the table that was optimized away.
 
2444
          */
 
2445
          if (curr_table->select_cond ||
 
2446
              (curr_table->keyuse && !curr_table->first_inner))
 
2447
          {
 
2448
            /* We have to sort all rows */
 
2449
            curr_join->select_limit= HA_POS_ERROR;
 
2450
            break;
 
2451
          }
 
2452
        }
2452
2453
      }
2453
2454
      if (curr_join->join_tab == join_tab && save_join_tab())
2454
 
      {
2455
 
        return;
2456
 
      }
 
2455
        return;
2457
2456
      /*
2458
 
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
2459
 
        chose FILESORT to be faster than INDEX SCAN or there is no 
2460
 
        suitable index present.
2461
 
        Note, that create_sort_index calls test_if_skip_sort_order and may
2462
 
        finally replace sorting with index scan if there is a LIMIT clause in
2463
 
        the query. XXX: it's never shown in EXPLAIN!
2464
 
        OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
 
2457
        Here we sort rows for order_st BY/GROUP BY clause, if the optimiser
 
2458
        chose FILESORT to be faster than INDEX SCAN or there is no
 
2459
        suitable index present.
 
2460
        Note, that create_sort_index calls test_if_skip_sort_order and may
 
2461
        finally replace sorting with index scan if there is a LIMIT clause in
 
2462
        the query. XXX: it's never shown in EXPLAIN!
 
2463
        OPTION_FOUND_ROWS supersedes LIMIT and is taken into account.
2465
2464
      */
2466
 
      if (create_sort_index(thd, curr_join,
2467
 
                            curr_join->group_list ? 
 
2465
      if (create_sort_index(session, curr_join,
 
2466
                            curr_join->group_list ?
2468
2467
                            curr_join->group_list : curr_join->order,
2469
2468
                            curr_join->select_limit,
2470
2469
                            (select_options & OPTION_FOUND_ROWS ?
2471
2470
                             HA_POS_ERROR : unit->select_limit_cnt),
2472
2471
                            curr_join->group_list ? true : false))
2473
 
        return;
 
2472
        return;
 
2473
 
2474
2474
      sortorder= curr_join->sortorder;
2475
2475
      if (curr_join->const_tables != curr_join->tables &&
2476
2476
          !curr_join->join_tab[curr_join->const_tables].table->sort.io_cache)
2484
2484
      }
2485
2485
    }
2486
2486
  }
2487
 
  /* XXX: When can we have here thd->is_error() not zero? */
2488
 
  if (thd->is_error())
 
2487
  /* XXX: When can we have here session->is_error() not zero? */
 
2488
  if (session->is_error())
2489
2489
  {
2490
 
    error= thd->is_error();
 
2490
    error= session->is_error();
2491
2491
    return;
2492
2492
  }
2493
2493
  curr_join->having= curr_join->tmp_having;
2494
2494
  curr_join->fields= curr_fields_list;
2495
2495
 
2496
 
  {
2497
 
    thd_proc_info(thd, "Sending data");
2498
 
    result->send_fields(*curr_fields_list,
2499
 
                        Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
2500
 
    error= do_select(curr_join, curr_fields_list, NULL);
2501
 
    thd->limit_found_rows= curr_join->send_records;
2502
 
  }
 
2496
  session->set_proc_info("Sending data");
 
2497
  result->send_fields(*curr_fields_list,
 
2498
                      Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF);
 
2499
  error= do_select(curr_join, curr_fields_list, NULL);
 
2500
  session->limit_found_rows= curr_join->send_records;
2503
2501
 
2504
2502
  /* Accumulate the counts from all join iterations of all join parts. */
2505
 
  thd->examined_row_count+= curr_join->examined_rows;
 
2503
  session->examined_row_count+= curr_join->examined_rows;
2506
2504
 
2507
 
  /* 
 
2505
  /*
2508
2506
    With EXPLAIN EXTENDED we have to restore original ref_array
2509
2507
    for a derived table which is always materialized.
2510
2508
    Otherwise we would not be able to print the query  correctly.
2511
 
  */ 
2512
 
  if (items0 &&
2513
 
      (thd->lex->describe & DESCRIBE_EXTENDED) &&
2514
 
      select_lex->linkage == DERIVED_TABLE_TYPE)      
 
2509
  */
 
2510
  if (items0 && (session->lex->describe & DESCRIBE_EXTENDED) && select_lex->linkage == DERIVED_TABLE_TYPE)
2515
2511
    set_items_ref_array(items0);
2516
2512
 
2517
2513
  return;
2518
2514
}
2519
2515
 
2520
 
 
2521
2516
/**
2522
2517
  Clean up join.
2523
2518
 
2524
2519
  @return
2525
2520
    Return error that hold JOIN.
2526
2521
*/
2527
 
 
2528
 
int
2529
 
JOIN::destroy()
 
2522
int JOIN::destroy()
2530
2523
{
2531
2524
  select_lex->join= 0;
2532
2525
 
2536
2529
    {
2537
2530
      JOIN_TAB *tab, *end;
2538
2531
      for (tab= join_tab, end= tab+tables ; tab != end ; tab++)
2539
 
        tab->cleanup();
 
2532
        tab->cleanup();
2540
2533
    }
2541
2534
    tmp_join->tmp_join= 0;
2542
2535
    tmp_table_param.copy_field=0;
2546
2539
 
2547
2540
  cleanup(1);
2548
2541
  if (exec_tmp_table1)
2549
 
    exec_tmp_table1->free_tmp_table(thd);
 
2542
    exec_tmp_table1->free_tmp_table(session);
2550
2543
  if (exec_tmp_table2)
2551
 
    exec_tmp_table2->free_tmp_table(thd);
 
2544
    exec_tmp_table2->free_tmp_table(session);
2552
2545
  delete select;
2553
2546
  delete_dynamic(&keyuse);
2554
2547
  return(error);
2555
2548
}
2556
2549
 
2557
 
 
2558
 
 
2559
2550
/**
2560
2551
  An entry point to single-unit select (a select without UNION).
2561
2552
 
2562
 
  @param thd                  thread handler
 
2553
  @param session                  thread handler
2563
2554
  @param rref_pointer_array   a reference to ref_pointer_array of
2564
2555
                              the top-level select_lex for this query
2565
2556
  @param tables               list of all tables used in this query.
2566
2557
                              The tables have been pre-opened.
2567
 
  @param wild_num             number of wildcards used in the top level 
 
2558
  @param wild_num             number of wildcards used in the top level
2568
2559
                              select of this query.
2569
2560
                              For example statement
2570
2561
                              SELECT *, t1.*, catalog.t2.* FROM t0, t1, t2;
2580
2571
  @param order                linked list of order_st BY agruments
2581
2572
  @param group                linked list of GROUP BY arguments
2582
2573
  @param having               top level item of HAVING expression
2583
 
  @param proc_param           list of PROCEDUREs
2584
2574
  @param select_options       select options (BIG_RESULT, etc)
2585
2575
  @param result               an instance of result set handling class.
2586
2576
                              This object is responsible for send result
2587
2577
                              set rows to the client or inserting them
2588
2578
                              into a table.
2589
 
  @param select_lex           the only SELECT_LEX of this query
 
2579
  @param select_lex           the only Select_Lex of this query
2590
2580
  @param unit                 top-level UNIT of this query
2591
2581
                              UNIT is an artificial object created by the
2592
2582
                              parser for every SELECT clause.
2601
2591
*/
2602
2592
 
2603
2593
bool
2604
 
mysql_select(THD *thd, Item ***rref_pointer_array,
 
2594
mysql_select(Session *session, Item ***rref_pointer_array,
2605
2595
             TableList *tables, uint32_t wild_num, List<Item> &fields,
2606
2596
             COND *conds, uint32_t og_num,  order_st *order, order_st *group,
2607
 
             Item *having, order_st *proc_param, uint64_t select_options,
2608
 
             select_result *result, SELECT_LEX_UNIT *unit,
2609
 
             SELECT_LEX *select_lex)
 
2597
             Item *having, uint64_t select_options,
 
2598
             select_result *result, Select_Lex_Unit *unit,
 
2599
             Select_Lex *select_lex)
2610
2600
{
2611
2601
  bool err;
2612
2602
  bool free_join= 1;
2634
2624
      else
2635
2625
      {
2636
2626
        if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2637
 
                               conds, og_num, order, group, having, proc_param,
2638
 
                               select_lex, unit)))
 
2627
                               conds, og_num, order, group, having, select_lex, unit)))
2639
2628
        {
2640
2629
          goto err;
2641
2630
        }
2646
2635
  }
2647
2636
  else
2648
2637
  {
2649
 
    if (!(join= new JOIN(thd, fields, select_options, result)))
 
2638
    if (!(join= new JOIN(session, fields, select_options, result)))
2650
2639
        return(true);
2651
 
    thd_proc_info(thd, "init");
2652
 
    thd->used_tables=0;                         // Updated by setup_fields
 
2640
    session->set_proc_info("init");
 
2641
    session->used_tables=0;                         // Updated by setup_fields
2653
2642
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
2654
 
                           conds, og_num, order, group, having, proc_param,
 
2643
                           conds, og_num, order, group, having,
2655
2644
                           select_lex, unit)) == true)
2656
2645
    {
2657
2646
      goto err;
2658
2647
    }
2659
2648
  }
2660
2649
 
2661
 
  /* dump_TableList_graph(select_lex, select_lex->leaf_tables); */
2662
2650
  if (join->flatten_subqueries())
2663
2651
  {
2664
2652
    err= 1;
2665
2653
    goto err;
2666
2654
  }
2667
 
  /* dump_TableList_struct(select_lex, select_lex->leaf_tables); */
2668
2655
 
2669
2656
  if ((err= join->optimize()))
2670
2657
  {
2671
2658
    goto err;                                   // 1
2672
2659
  }
2673
2660
 
2674
 
  if (thd->lex->describe & DESCRIBE_EXTENDED)
 
2661
  if (session->lex->describe & DESCRIBE_EXTENDED)
2675
2662
  {
2676
2663
    join->conds_history= join->conds;
2677
2664
    join->having_history= (join->having?join->having:join->tmp_having);
2678
2665
  }
2679
2666
 
2680
 
  if (thd->is_error())
 
2667
  if (session->is_error())
2681
2668
    goto err;
2682
2669
 
2683
2670
  join->exec();
2684
2671
 
2685
 
  if (thd->lex->describe & DESCRIBE_EXTENDED)
 
2672
  if (session->lex->describe & DESCRIBE_EXTENDED)
2686
2673
  {
2687
2674
    select_lex->where= join->conds_history;
2688
2675
    select_lex->having= join->having_history;
2691
2678
err:
2692
2679
  if (free_join)
2693
2680
  {
2694
 
    thd_proc_info(thd, "end");
 
2681
    session->set_proc_info("end");
2695
2682
    err|= select_lex->cleanup();
2696
 
    return(err || thd->is_error());
 
2683
    return(err || session->is_error());
2697
2684
  }
2698
2685
  return(join->error);
2699
2686
}
2700
2687
 
2701
2688
 
2702
 
int subq_sj_candidate_cmp(Item_in_subselect* const *el1, 
 
2689
int subq_sj_candidate_cmp(Item_in_subselect* const *el1,
2703
2690
                          Item_in_subselect* const *el2)
2704
2691
{
2705
 
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 : 
 
2692
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
2706
2693
         ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
2707
2694
}
2708
2695
 
2713
2700
}
2714
2701
 
2715
2702
 
2716
 
static TableList *alloc_join_nest(THD *thd)
 
2703
static TableList *alloc_join_nest(Session *session)
2717
2704
{
2718
2705
  TableList *tbl;
2719
 
  if (!(tbl= (TableList*) thd->calloc(ALIGN_SIZE(sizeof(TableList))+
 
2706
  if (!(tbl= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
2720
2707
                                       sizeof(nested_join_st))))
2721
2708
    return NULL;
2722
 
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl + 
 
2709
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl +
2723
2710
                                    ALIGN_SIZE(sizeof(TableList)));
2724
2711
  return tbl;
2725
2712
}
2726
2713
 
2727
2714
 
2728
 
void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List<TableList> *tlist)
 
2715
void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
2729
2716
{
2730
2717
  List_iterator<TableList> it(*tlist);
2731
2718
  TableList *table;
2744
2731
 
2745
2732
  SYNOPSIS
2746
2733
    convert_subq_to_sj()
2747
 
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON 
 
2734
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON
2748
2735
                    clause
2749
2736
       subq_pred    Subquery predicate to be converted
2750
 
  
 
2737
 
2751
2738
  DESCRIPTION
2752
 
    Convert a subquery predicate into a TableList semi-join nest. All the 
 
2739
    Convert a subquery predicate into a TableList semi-join nest. All the
2753
2740
    prerequisites are already checked, so the conversion is always successfull.
2754
2741
 
2755
2742
    Prepared Statements: the transformation is permanent:
2756
2743
     - Changes in TableList structures are naturally permanent
2757
2744
     - Item tree changes are performed on statement MEM_ROOT:
2758
 
        = we activate statement MEM_ROOT 
 
2745
        = we activate statement MEM_ROOT
2759
2746
        = this function is called before the first fix_prepare_information
2760
2747
          call.
2761
2748
 
2769
2756
 
2770
2757
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
2771
2758
{
2772
 
  SELECT_LEX *parent_lex= parent_join->select_lex;
 
2759
  Select_Lex *parent_lex= parent_join->select_lex;
2773
2760
  TableList *emb_tbl_nest= NULL;
2774
2761
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
2775
 
  THD *thd= parent_join->thd;
 
2762
  Session *session= parent_join->session;
2776
2763
 
2777
2764
  /*
2778
2765
    1. Find out where to put the predicate into.
2808
2795
    }
2809
2796
    else if (!subq_pred->expr_join_nest->nested_join)
2810
2797
    {
2811
 
      TableList *outer_tbl= subq_pred->expr_join_nest;      
 
2798
      TableList *outer_tbl= subq_pred->expr_join_nest;
2812
2799
      TableList *wrap_nest;
2813
2800
      /*
2814
2801
        We're dealing with
2820
2807
          ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
2821
2808
                        |                      |
2822
2809
                        |<----- wrap_nest ---->|
2823
 
        
 
2810
 
2824
2811
        Q:  other subqueries may be pointing to this element. What to do?
2825
2812
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
2826
2813
            But we'll need to fix other pointers.
2829
2816
        A3: changes in the TableList::outer_join will make everything work
2830
2817
            automatically.
2831
2818
      */
2832
 
      if (!(wrap_nest= alloc_join_nest(parent_join->thd)))
 
2819
      if (!(wrap_nest= alloc_join_nest(parent_join->session)))
2833
2820
      {
2834
2821
        return(true);
2835
2822
      }
2864
2851
        }
2865
2852
      }
2866
2853
      /*
2867
 
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the 
 
2854
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the
2868
2855
        semi-join nest into it
2869
2856
      */
2870
2857
      emb_join_list= &wrap_nest->nested_join->join_list;
2874
2861
 
2875
2862
  TableList *sj_nest;
2876
2863
  nested_join_st *nested_join;
2877
 
  if (!(sj_nest= alloc_join_nest(parent_join->thd)))
 
2864
  if (!(sj_nest= alloc_join_nest(parent_join->session)))
2878
2865
  {
2879
2866
    return(true);
2880
2867
  }
2887
2874
  /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
2888
2875
  emb_join_list->push_back(sj_nest);
2889
2876
 
2890
 
  /* 
 
2877
  /*
2891
2878
    nested_join->used_tables and nested_join->not_null_tables are
2892
2879
    initialized in simplify_joins().
2893
2880
  */
2894
 
  
2895
 
  /* 
 
2881
 
 
2882
  /*
2896
2883
    2. Walk through subquery's top list and set 'embedding' to point to the
2897
2884
       sj-nest.
2898
2885
  */
2899
 
  st_select_lex *subq_lex= subq_pred->unit->first_select();
 
2886
  Select_Lex *subq_lex= subq_pred->unit->first_select();
2900
2887
  nested_join->join_list.empty();
2901
2888
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
2902
2889
  TableList *tl, *last_leaf;
2906
2893
    tl->join_list= &nested_join->join_list;
2907
2894
    nested_join->join_list.push_back(tl);
2908
2895
  }
2909
 
  
 
2896
 
2910
2897
  /*
2911
2898
    Reconnect the next_leaf chain.
2912
2899
    TODO: Do we have to put subquery's tables at the end of the chain?
2941
2928
  {
2942
2929
    tl->table->tablenr= table_no;
2943
2930
    tl->table->map= ((table_map)1) << table_no;
2944
 
    SELECT_LEX *old_sl= tl->select_lex;
2945
 
    tl->select_lex= parent_join->select_lex; 
 
2931
    Select_Lex *old_sl= tl->select_lex;
 
2932
    tl->select_lex= parent_join->select_lex;
2946
2933
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
2947
2934
      emb->select_lex= parent_join->select_lex;
2948
2935
  }
2949
2936
  parent_join->tables += subq_lex->join->tables;
2950
2937
 
2951
 
  /* 
 
2938
  /*
2952
2939
    Put the subquery's WHERE into semi-join's sj_on_expr
2953
2940
    Add the subquery-induced equalities too.
2954
2941
  */
2955
 
  SELECT_LEX *save_lex= thd->lex->current_select;
2956
 
  thd->lex->current_select=subq_lex;
 
2942
  Select_Lex *save_lex= session->lex->current_select;
 
2943
  session->lex->current_select=subq_lex;
2957
2944
  if (!subq_pred->left_expr->fixed &&
2958
 
       subq_pred->left_expr->fix_fields(thd, &subq_pred->left_expr))
 
2945
       subq_pred->left_expr->fix_fields(session, &subq_pred->left_expr))
2959
2946
    return(true);
2960
 
  thd->lex->current_select=save_lex;
 
2947
  session->lex->current_select=save_lex;
2961
2948
 
2962
2949
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
2963
2950
  sj_nest->nested_join->sj_depends_on=  subq_pred->used_tables() |
2975
2962
       (TODO: can we just create a list of pointers and hope the expressions
2976
2963
       will not substitute themselves on fix_fields()? or we need to wrap
2977
2964
       them into Item_direct_view_refs and store pointers to those. The
2978
 
       pointers to Item_direct_view_refs are guaranteed to be stable as 
2979
 
       Item_direct_view_refs doesn't substitute itself with anything in 
 
2965
       pointers to Item_direct_view_refs are guaranteed to be stable as
 
2966
       Item_direct_view_refs doesn't substitute itself with anything in
2980
2967
       Item_direct_view_ref::fix_fields.
2981
2968
  */
2982
2969
  sj_nest->sj_in_exprs= subq_pred->left_expr->cols();
2986
2973
  {
2987
2974
    nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr);
2988
2975
 
2989
 
    Item *item_eq= new Item_func_eq(subq_pred->left_expr, 
 
2976
    Item *item_eq= new Item_func_eq(subq_pred->left_expr,
2990
2977
                                    subq_lex->ref_pointer_array[0]);
2991
2978
    item_eq->name= (char*)subq_sj_cond_name;
2992
2979
    sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
2997
2984
    {
2998
2985
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
2999
2986
                                                element_index(i));
3000
 
      Item *item_eq= 
3001
 
        new Item_func_eq(subq_pred->left_expr->element_index(i), 
 
2987
      Item *item_eq=
 
2988
        new Item_func_eq(subq_pred->left_expr->element_index(i),
3002
2989
                         subq_lex->ref_pointer_array[i]);
3003
2990
      item_eq->name= (char*)subq_sj_cond_name + (i % 64);
3004
2991
      sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
3005
2992
    }
3006
2993
  }
3007
2994
  /* Fix the created equality and AND */
3008
 
  sj_nest->sj_on_expr->fix_fields(parent_join->thd, &sj_nest->sj_on_expr);
 
2995
  sj_nest->sj_on_expr->fix_fields(parent_join->session, &sj_nest->sj_on_expr);
3009
2996
 
3010
2997
  /*
3011
2998
    Walk through sj nest's WHERE and ON expressions and call
3021
3008
  /* Inject sj_on_expr into the parent's WHERE or ON */
3022
3009
  if (emb_tbl_nest)
3023
3010
  {
3024
 
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr, 
 
3011
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr,
3025
3012
                                     sj_nest->sj_on_expr);
3026
 
    emb_tbl_nest->on_expr->fix_fields(parent_join->thd, &emb_tbl_nest->on_expr);
 
3013
    emb_tbl_nest->on_expr->fix_fields(parent_join->session, &emb_tbl_nest->on_expr);
3027
3014
  }
3028
3015
  else
3029
3016
  {
3030
3017
    /* Inject into the WHERE */
3031
3018
    parent_join->conds= and_items(parent_join->conds, sj_nest->sj_on_expr);
3032
 
    parent_join->conds->fix_fields(parent_join->thd, &parent_join->conds);
 
3019
    parent_join->conds->fix_fields(parent_join->session, &parent_join->conds);
3033
3020
    parent_join->select_lex->where= parent_join->conds;
3034
3021
  }
3035
3022
 
3042
3029
 
3043
3030
  SYNOPSIS
3044
3031
    JOIN::flatten_subqueries()
3045
 
 
 
3032
 
3046
3033
  DESCRIPTION
3047
3034
    Convert candidate subquery predicates to semi-joins.
3048
3035
 
3049
 
  RETURN 
 
3036
  RETURN
3050
3037
    false  OK
3051
3038
    true   Error
3052
3039
*/
3060
3047
    return(false);
3061
3048
 
3062
3049
  /* 1. Fix children subqueries */
3063
 
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back(); 
 
3050
  for (in_subq= sj_subselects.front(), in_subq_end= sj_subselects.back();
3064
3051
       in_subq != in_subq_end; in_subq++)
3065
3052
  {
3066
3053
    JOIN *child_join= (*in_subq)->unit->first_select()->join;
3067
3054
    child_join->outer_tables = child_join->tables;
3068
3055
    if (child_join->flatten_subqueries())
3069
3056
      return(true);
3070
 
    (*in_subq)->sj_convert_priority= 
 
3057
    (*in_subq)->sj_convert_priority=
3071
3058
      (*in_subq)->is_correlated * MAX_TABLES + child_join->outer_tables;
3072
3059
  }
3073
 
 
3074
 
  //dump_TableList_struct(select_lex, select_lex->leaf_tables);
3075
 
  /* 
3076
 
    2. Pick which subqueries to convert:
3077
 
      sort the subquery array
3078
 
      - prefer correlated subqueries over uncorrelated;
3079
 
      - prefer subqueries that have greater number of outer tables;
3080
 
  */
3081
 
  sj_subselects.sort(subq_sj_candidate_cmp);
3082
 
  // #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
3083
 
  /* Replace all subqueries to be flattened with Item_int(1) */
3084
 
  for (in_subq= sj_subselects.front(); 
3085
 
       in_subq != in_subq_end && 
3086
 
       tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3087
 
       in_subq++)
 
3060
  
 
3061
  bool outer_join_disable_semi_join= false;
 
3062
  /*
 
3063
   * Temporary measure: disable semi-joins when they are together with outer
 
3064
   * joins.
 
3065
   *
 
3066
   * @see LP Bug #314911
 
3067
   */
 
3068
  for (TableList *tbl= select_lex->leaf_tables; tbl; tbl=tbl->next_leaf)
3088
3069
  {
3089
 
    if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
3090
 
      return(true);
 
3070
    TableList *embedding= tbl->embedding;
 
3071
    if (tbl->on_expr || (tbl->embedding && !(embedding->sj_on_expr && 
 
3072
                                            !embedding->embedding)))
 
3073
    {
 
3074
      in_subq= sj_subselects.front();
 
3075
      outer_join_disable_semi_join= true;
 
3076
    }
3091
3077
  }
3092
 
 
3093
 
  for (in_subq= sj_subselects.front(); 
3094
 
       in_subq != in_subq_end && 
3095
 
       tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
3096
 
       in_subq++)
 
3078
 
 
3079
  if (! outer_join_disable_semi_join)
3097
3080
  {
3098
 
    if (convert_subq_to_sj(this, *in_subq))
3099
 
      return(true);
 
3081
    /*
 
3082
      2. Pick which subqueries to convert:
 
3083
        sort the subquery array
 
3084
        - prefer correlated subqueries over uncorrelated;
 
3085
        - prefer subqueries that have greater number of outer tables;
 
3086
    */
 
3087
    sj_subselects.sort(subq_sj_candidate_cmp);
 
3088
    // #tables-in-parent-query + #tables-in-subquery < MAX_TABLES
 
3089
    /* Replace all subqueries to be flattened with Item_int(1) */
 
3090
    for (in_subq= sj_subselects.front();
 
3091
        in_subq != in_subq_end &&
 
3092
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
3093
        in_subq++)
 
3094
    {
 
3095
      if (replace_where_subcondition(this, *in_subq, new Item_int(1), false))
 
3096
        return(true);
 
3097
    }
 
3098
 
 
3099
    for (in_subq= sj_subselects.front();
 
3100
        in_subq != in_subq_end &&
 
3101
        tables + ((*in_subq)->sj_convert_priority % MAX_TABLES) < MAX_TABLES;
 
3102
        in_subq++)
 
3103
    {
 
3104
      if (convert_subq_to_sj(this, *in_subq))
 
3105
        return(true);
 
3106
    }
3100
3107
  }
3101
3108
 
3102
3109
  /* 3. Finalize those we didn't convert */
3118
3125
    if (replace_where_subcondition(this, *in_subq, substitute, do_fix_fields))
3119
3126
      return(true);
3120
3127
 
3121
 
    //if ((*in_subq)->fix_fields(thd, (*in_subq)->ref_ptr))
 
3128
    //if ((*in_subq)->fix_fields(session, (*in_subq)->ref_ptr))
3122
3129
    //  return(true);
3123
3130
  }
3124
3131
  sj_subselects.clear();
3125
3132
  return(false);
3126
3133
}
3127
3134
 
3128
 
 
3129
3135
/**
3130
3136
  Setup for execution all subqueries of a query, for which the optimizer
3131
3137
  chose hash semi-join.
3148
3154
  @retval false     success.
3149
3155
  @retval true      error occurred.
3150
3156
*/
3151
 
 
3152
3157
bool JOIN::setup_subquery_materialization()
3153
3158
{
3154
 
  for (SELECT_LEX_UNIT *un= select_lex->first_inner_unit(); un;
 
3159
  for (Select_Lex_Unit *un= select_lex->first_inner_unit(); un;
3155
3160
       un= un->next_unit())
3156
3161
  {
3157
 
    for (SELECT_LEX *sl= un->first_select(); sl; sl= sl->next_select())
 
3162
    for (Select_Lex *sl= un->first_select(); sl; sl= sl->next_select())
3158
3163
    {
3159
3164
      Item_subselect *subquery_predicate= sl->master_unit()->item;
3160
3165
      if (subquery_predicate &&
3247
3252
 
3248
3253
  DESCRIPTION
3249
3254
    Try to pull tables out of semi-join nests.
3250
 
     
 
3255
 
3251
3256
    PRECONDITIONS
3252
3257
    When this function is called, the join may have several semi-join nests
3253
3258
    (possibly within different semi-join nests), but it is guaranteed that
3254
3259
    one semi-join nest does not contain another.
3255
 
   
 
3260
 
3256
3261
    ACTION
3257
3262
    A table can be pulled out of the semi-join nest if
3258
3263
     - It is a constant table
3259
 
     - It is accessed 
 
3264
     - It is accessed
3260
3265
 
3261
3266
    POSTCONDITIONS
3262
3267
     * Pulled out tables have JOIN_TAB::emb_sj_nest == NULL (like the outer
3267
3272
    This operation is (and should be) performed at each PS execution since
3268
3273
    tables may become/cease to be constant across PS reexecutions.
3269
3274
 
3270
 
  RETURN 
 
3275
  RETURN
3271
3276
    0 - OK
3272
3277
    1 - Out of memory error
3273
3278
*/
3276
3281
{
3277
3282
  TableList *sj_nest;
3278
3283
  List_iterator<TableList> sj_list_it(join->select_lex->sj_nests);
3279
 
   
 
3284
 
3280
3285
  /* Try pulling out of the each of the semi-joins */
3281
3286
  while ((sj_nest= sj_list_it++))
3282
3287
  {
3283
3288
    /* Action #1: Mark the constant tables to be pulled out */
3284
3289
    table_map pulled_tables= 0;
3285
 
     
 
3290
 
3286
3291
    List_iterator<TableList> child_li(sj_nest->nested_join->join_list);
3287
3292
    TableList *tbl;
3288
3293
    while ((tbl= child_li++))
3296
3301
        }
3297
3302
      }
3298
3303
    }
3299
 
    
 
3304
 
3300
3305
    /*
3301
3306
      Action #2: Find which tables we can pull out based on
3302
3307
      update_ref_and_keys() data. Note that pulling one table out can allow
3303
3308
      us to pull out some other tables too.
3304
3309
    */
3305
3310
    bool pulled_a_table;
3306
 
    do 
 
3311
    do
3307
3312
    {
3308
3313
      pulled_a_table= false;
3309
3314
      child_li.rewind();
3311
3316
      {
3312
3317
        if (tbl->table && !(pulled_tables & tbl->table->map))
3313
3318
        {
3314
 
          if (find_eq_ref_candidate(tbl->table, 
3315
 
                                    sj_nest->nested_join->used_tables & 
 
3319
          if (find_eq_ref_candidate(tbl->table,
 
3320
                                    sj_nest->nested_join->used_tables &
3316
3321
                                    ~pulled_tables))
3317
3322
          {
3318
3323
            pulled_a_table= true;
3321
3326
        }
3322
3327
      }
3323
3328
    } while (pulled_a_table);
3324
 
 
 
3329
 
3325
3330
    child_li.rewind();
3326
3331
    if ((sj_nest)->nested_join->used_tables == pulled_tables)
3327
3332
    {
3335
3340
    else
3336
3341
    {
3337
3342
      /* Record the bitmap of inner tables, mark the inner tables */
3338
 
      table_map inner_tables=(sj_nest)->nested_join->used_tables & 
 
3343
      table_map inner_tables=(sj_nest)->nested_join->used_tables &
3339
3344
                             ~pulled_tables;
3340
3345
      (sj_nest)->sj_inner_tables= inner_tables;
3341
3346
      while ((tbl= child_li++))
3359
3364
*****************************************************************************/
3360
3365
 
3361
3366
 
3362
 
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
 
3367
static ha_rows get_quick_record_count(Session *session, SQL_SELECT *select,
3363
3368
                                      Table *table,
3364
3369
                                      const key_map *keys,ha_rows limit)
3365
3370
{
3366
3371
  int error;
3367
 
  if (check_stack_overrun(thd, STACK_MIN_SIZE, NULL))
 
3372
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
3368
3373
    return(0);                           // Fatal error flag is set
3369
3374
  if (select)
3370
3375
  {
3371
3376
    select->head=table;
3372
3377
    table->reginfo.impossible_range=0;
3373
 
    if ((error= select->test_quick_select(thd, *(key_map *)keys,(table_map) 0,
 
3378
    if ((error= select->test_quick_select(session, *(key_map *)keys,(table_map) 0,
3374
3379
                                          limit, 0, false)) == 1)
3375
3380
      return(select->quick->records);
3376
3381
    if (error == -1)
3394
3399
  Field *field;              /* field against which to check sargability */
3395
3400
  Item **arg_value;          /* values of potential keys for lookups     */
3396
3401
  uint32_t num_values;           /* number of values in the above array      */
3397
 
} SARGABLE_PARAM;  
 
3402
} SARGABLE_PARAM;
3398
3403
 
3399
3404
/**
3400
3405
  Calculate the best possible join and initialize the join structure.
3422
3427
  JOIN_TAB *stat_vector[MAX_TABLES+1];
3423
3428
 
3424
3429
  table_count=join->tables;
3425
 
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
3426
 
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
3427
 
  table_vector=(Table**) join->thd->alloc(sizeof(Table*)*(table_count*2));
 
3430
  stat=(JOIN_TAB*) join->session->calloc(sizeof(JOIN_TAB)*table_count);
 
3431
  stat_ref=(JOIN_TAB**) join->session->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
 
3432
  table_vector=(Table**) join->session->alloc(sizeof(Table*)*(table_count*2));
3428
3433
  if (!stat || !stat_ref || !table_vector)
3429
3434
    return(1);                          // Eom /* purecov: inspected */
3430
3435
 
3440
3445
  {
3441
3446
    TableList *embedding= tables->embedding;
3442
3447
    stat_vector[i]=s;
3443
 
    s->keys.init();
3444
 
    s->const_keys.init();
3445
 
    s->checked_keys.init();
3446
 
    s->needed_reg.init();
 
3448
    s->keys.reset();
 
3449
    s->const_keys.reset();
 
3450
    s->checked_keys.reset();
 
3451
    s->needed_reg.reset();
3447
3452
    table_vector[i]=s->table=table=tables->table;
3448
3453
    table->pos_in_table_list= tables;
3449
3454
    error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
3452
3457
        table->file->print_error(error, MYF(0));
3453
3458
        return(1);
3454
3459
    }
3455
 
    table->quick_keys.clear_all();
 
3460
    table->quick_keys.reset();
3456
3461
    table->reginfo.join_tab=s;
3457
3462
    table->reginfo.not_exists_optimize=0;
3458
3463
    memset(table->const_key_parts, 0,
3510
3515
 
3511
3516
  if (join->outer_join)
3512
3517
  {
3513
 
    /* 
 
3518
    /*
3514
3519
       Build transitive closure for relation 'to be dependent on'.
3515
3520
       This will speed up the plan search for many cases with outer joins,
3516
3521
       as well as allow us to catch illegal cross references/
3517
3522
       Warshall's algorithm is used to build the transitive closure.
3518
3523
       As we use bitmaps to represent the relation the complexity
3519
 
       of the algorithm is O((number of tables)^2). 
 
3524
       of the algorithm is O((number of tables)^2).
3520
3525
    */
3521
3526
    for (i= 0, s= stat ; i < table_count ; i++, s++)
3522
3527
    {
3543
3548
  }
3544
3549
 
3545
3550
  if (conds || outer_join)
3546
 
    if (update_ref_and_keys(join->thd, keyuse_array, stat, join->tables,
 
3551
    if (update_ref_and_keys(join->session, keyuse_array, stat, join->tables,
3547
3552
                            conds, join->cond_equal,
3548
3553
                            ~outer_join, join->select_lex, &sargables))
3549
3554
      return(1);
3585
3590
    {
3586
3591
      table=s->table;
3587
3592
 
3588
 
      /* 
 
3593
      /*
3589
3594
        If equi-join condition by a key is null rejecting and after a
3590
3595
        substitution of a const table the key value happens to be null
3591
3596
        then we can state that there are no matches for this equi-join.
3592
 
      */  
 
3597
      */
3593
3598
      if ((keyuse= s->keyuse) && *s->on_expr_ref && !s->embedding_map)
3594
3599
      {
3595
 
        /* 
 
3600
        /*
3596
3601
          When performing an outer join operation if there are no matching rows
3597
3602
          for the single row of the outer table all the inner tables are to be
3598
3603
          null complemented and thus considered as constant tables.
3599
 
          Here we apply this consideration to the case of outer join operations 
 
3604
          Here we apply this consideration to the case of outer join operations
3600
3605
          with a single inner table only because the case with nested tables
3601
3606
          would require a more thorough analysis.
3602
3607
          TODO. Apply single row substitution to null complemented inner tables
3603
 
          for nested outer join operations. 
3604
 
        */              
 
3608
          for nested outer join operations.
 
3609
        */
3605
3610
        while (keyuse->table == table)
3606
3611
        {
3607
3612
          if (!(keyuse->val->used_tables() & ~join->const_table_map) &&
3608
3613
              keyuse->val->is_null() && keyuse->null_rejecting)
3609
3614
          {
3610
3615
            s->type= JT_CONST;
3611
 
            mark_as_null_row(table);
 
3616
            table->mark_as_null_row();
3612
3617
            found_const_table_map|= table->map;
3613
3618
            join->const_table_map|= table->map;
3614
3619
            set_position(join,const_count++,s,(KEYUSE*) 0);
3649
3654
        {
3650
3655
          start_keyuse=keyuse;
3651
3656
          key=keyuse->key;
3652
 
          s->keys.set_bit(key);               // QQ: remove this ?
 
3657
          s->keys.set(key);               // QQ: remove this ?
3653
3658
 
3654
3659
          refs=0;
3655
 
          const_ref.clear_all();
3656
 
          eq_part.clear_all();
 
3660
          const_ref.reset();
 
3661
          eq_part.reset();
3657
3662
          do
3658
3663
          {
3659
3664
            if (keyuse->val->type() != Item::NULL_ITEM && !keyuse->optimize)
3660
3665
            {
3661
3666
              if (!((~found_const_table_map) & keyuse->used_tables))
3662
 
                const_ref.set_bit(keyuse->keypart);
 
3667
                const_ref.set(keyuse->keypart);
3663
3668
              else
3664
3669
                refs|=keyuse->used_tables;
3665
 
              eq_part.set_bit(keyuse->keypart);
 
3670
              eq_part.set(keyuse->keypart);
3666
3671
            }
3667
3672
            keyuse++;
3668
3673
          } while (keyuse->table == table && keyuse->key == key);
3669
3674
 
3670
 
          if (eq_part.is_prefix(table->key_info[key].key_parts) &&
 
3675
          if (is_keymap_prefix(eq_part, table->key_info[key].key_parts) &&
3671
3676
              !table->pos_in_table_list->embedding)
3672
3677
          {
3673
3678
            if ((table->key_info[key].flags & (HA_NOSAME))
3678
3683
                int tmp;
3679
3684
                ref_changed = 1;
3680
3685
                s->type= JT_CONST;
3681
 
                join->const_table_map|=table->map;
 
3686
                join->const_table_map|= table->map;
3682
3687
                set_position(join,const_count++,s,start_keyuse);
3683
3688
                if (create_ref_for_key(join, s, start_keyuse,
3684
3689
                                       found_const_table_map))
3697
3702
                found_ref|= refs;      // Table is const if all refs are const
3698
3703
            }
3699
3704
            else if (const_ref == eq_part)
3700
 
              s->const_keys.set_bit(key);
 
3705
              s->const_keys.set(key);
3701
3706
          }
3702
3707
        }
3703
3708
      }
3704
3709
    }
3705
3710
  } while (join->const_table_map & found_ref && ref_changed);
3706
 
 
3707
 
  /* 
 
3711
 
 
3712
  /*
3708
3713
    Update info on indexes that can be used for search lookups as
3709
 
    reading const tables may has added new sargable predicates. 
 
3714
    reading const tables may has added new sargable predicates.
3710
3715
  */
3711
3716
  if (const_count && sargables)
3712
3717
  {
3715
3720
      Field *field= sargables->field;
3716
3721
      JOIN_TAB *join_tab= field->table->reginfo.join_tab;
3717
3722
      key_map possible_keys= field->key_start;
3718
 
      possible_keys.intersect(field->table->keys_in_use_for_query);
 
3723
      possible_keys&= field->table->keys_in_use_for_query;
3719
3724
      bool is_const= 1;
3720
3725
      for (uint32_t j=0; j < sargables->num_values; j++)
3721
3726
        is_const&= sargables->arg_value[j]->const_item();
3722
3727
      if (is_const)
3723
 
        join_tab[0].const_keys.merge(possible_keys);
 
3728
        join_tab[0].const_keys|= possible_keys;
3724
3729
    }
3725
3730
  }
3726
3731
 
3757
3762
    */
3758
3763
    add_group_and_distinct_keys(join, s);
3759
3764
 
3760
 
    if (!s->const_keys.is_clear_all() &&
 
3765
    if (s->const_keys.any() &&
3761
3766
        !s->table->pos_in_table_list->embedding)
3762
3767
    {
3763
3768
      ha_rows records;
3768
3773
                          1, &error);
3769
3774
      if (!select)
3770
3775
        return(1);
3771
 
      records= get_quick_record_count(join->thd, select, s->table,
 
3776
      records= get_quick_record_count(join->session, select, s->table,
3772
3777
                                      &s->const_keys, join->row_limit);
3773
3778
      s->quick=select->quick;
3774
3779
      s->needed_reg=select->needed_reg;
3775
3780
      select->quick=0;
3776
3781
      if (records == 0 && s->table->reginfo.impossible_range)
3777
3782
      {
3778
 
        /*
3779
 
          Impossible WHERE or ON expression
3780
 
          In case of ON, we mark that the we match one empty NULL row.
3781
 
          In case of WHERE, don't set found_const_table_map to get the
3782
 
          caller to abort with a zero row result.
3783
 
        */
3784
 
        join->const_table_map|= s->table->map;
3785
 
        set_position(join,const_count++,s,(KEYUSE*) 0);
3786
 
        s->type= JT_CONST;
3787
 
        if (*s->on_expr_ref)
3788
 
        {
3789
 
          /* Generate empty row */
3790
 
          s->info= "Impossible ON condition";
3791
 
          found_const_table_map|= s->table->map;
3792
 
          s->type= JT_CONST;
3793
 
          mark_as_null_row(s->table);           // All fields are NULL
3794
 
        }
 
3783
        /*
 
3784
          Impossible WHERE or ON expression
 
3785
          In case of ON, we mark that the we match one empty NULL row.
 
3786
          In case of WHERE, don't set found_const_table_map to get the
 
3787
          caller to abort with a zero row result.
 
3788
        */
 
3789
        join->const_table_map|= s->table->map;
 
3790
        set_position(join,const_count++,s,(KEYUSE*) 0);
 
3791
        s->type= JT_CONST;
 
3792
        if (*s->on_expr_ref)
 
3793
        {
 
3794
          /* Generate empty row */
 
3795
          s->info= "Impossible ON condition";
 
3796
          found_const_table_map|= s->table->map;
 
3797
          s->type= JT_CONST;
 
3798
          s->table->mark_as_null_row();         // All fields are NULL
 
3799
        }
3795
3800
      }
3796
3801
      if (records != HA_POS_ERROR)
3797
3802
      {
3798
 
        s->found_records=records;
3799
 
        s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
 
3803
        s->found_records=records;
 
3804
        s->read_time= (ha_rows) (s->quick ? s->quick->read_time : 0.0);
3800
3805
      }
3801
3806
      delete select;
3802
3807
    }
3822
3827
    join->best_read=1.0;
3823
3828
  }
3824
3829
  /* Generate an execution plan from the found optimal join order. */
3825
 
  return(join->thd->killed || get_best_combination(join));
 
3830
  return(join->session->killed || get_best_combination(join));
3826
3831
}
3827
3832
 
3828
3833
 
3845
3850
    If true, the condition this struct represents will not be satisfied
3846
3851
    when val IS NULL.
3847
3852
  */
3848
 
  bool          null_rejecting; 
 
3853
  bool          null_rejecting;
3849
3854
  bool          *cond_guard; /* See KEYUSE::cond_guard */
3850
3855
  uint32_t          sj_pred_no; /* See KEYUSE::sj_pred_no */
3851
3856
} KEY_FIELD;
3860
3865
  that are internally transformed to something like:.
3861
3866
 
3862
3867
  @code
3863
 
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL 
 
3868
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
3864
3869
  @endcode
3865
3870
 
3866
3871
  KEY_FIELD::null_rejecting is processed as follows: @n
3895
3900
        /*
3896
3901
          NOTE: below const_item() call really works as "!used_tables()", i.e.
3897
3902
          it can return false where it is feasible to make it return true.
3898
 
          
 
3903
 
3899
3904
          The cause is as follows: Some of the tables are already known to be
3900
3905
          const tables (the detection code is in make_join_statistics(),
3901
 
          above the update_ref_and_keys() call), but we didn't propagate 
 
3906
          above the update_ref_and_keys() call), but we didn't propagate
3902
3907
          information about this: Table::const_table is not set to true, and
3903
3908
          Item::update_used_tables() hasn't been called for each item.
3904
3909
          The result of this is that we're missing some 'ref' accesses.
3922
3927
          }
3923
3928
        }
3924
3929
        else if (old->eq_func && new_fields->eq_func &&
3925
 
                 old->val->eq_by_collation(new_fields->val, 
 
3930
                 old->val->eq_by_collation(new_fields->val,
3926
3931
                                           old->field->binary(),
3927
3932
                                           old->field->charset()))
3928
3933
 
3936
3941
                                new_fields->null_rejecting);
3937
3942
        }
3938
3943
        else if (old->eq_func && new_fields->eq_func &&
3939
 
                 ((old->val->const_item() && old->val->is_null()) || 
 
3944
                 ((old->val->const_item() && old->val->is_null()) ||
3940
3945
                  new_fields->val->is_null()))
3941
3946
        {
3942
3947
          /* field = expression OR field IS NULL */
3948
3953
          */
3949
3954
          if (!old->val->used_tables() && old->val->is_null())
3950
3955
            old->val= new_fields->val;
3951
 
          /* The referred expression can be NULL: */ 
 
3956
          /* The referred expression can be NULL: */
3952
3957
          old->null_rejecting= 0;
3953
3958
        }
3954
3959
        else
4039
4044
    else
4040
4045
    {
4041
4046
      JOIN_TAB *stat=field->table->reginfo.join_tab;
4042
 
      key_map possible_keys=field->key_start;
4043
 
      possible_keys.intersect(field->table->keys_in_use_for_query);
4044
 
      stat[0].keys.merge(possible_keys);             // Add possible keys
 
4047
      key_map possible_keys= field->key_start;
 
4048
      possible_keys&= field->table->keys_in_use_for_query;
 
4049
      stat[0].keys|= possible_keys;             // Add possible keys
4045
4050
 
4046
4051
      /*
4047
4052
        Save the following cases:
4054
4059
         Field BETWEEN ...
4055
4060
         Field IN ...
4056
4061
      */
4057
 
      stat[0].key_dependent|=used_tables;
 
4062
      stat[0].key_dependent|= used_tables;
4058
4063
 
4059
4064
      bool is_const=1;
4060
4065
      for (uint32_t i=0; i<num_values; i++)
4063
4068
          break;
4064
4069
      }
4065
4070
      if (is_const)
4066
 
        stat[0].const_keys.merge(possible_keys);
 
4071
        stat[0].const_keys|= possible_keys;
4067
4072
      else if (!eq_func)
4068
4073
      {
4069
 
        /* 
4070
 
          Save info to be able check whether this predicate can be 
 
4074
        /*
 
4075
          Save info to be able check whether this predicate can be
4071
4076
          considered as sargable for range analisis after reading const tables.
4072
4077
          We do not save info about equalities as update_const_equal_items
4073
 
          will take care of updating info on keys from sargable equalities. 
 
4078
          will take care of updating info on keys from sargable equalities.
4074
4079
        */
4075
4080
        (*sargables)--;
4076
4081
        (*sargables)->field= field;
4084
4089
       */
4085
4090
      if (!eq_func)
4086
4091
      {
4087
 
        /* 
 
4092
        /*
4088
4093
          Additional optimization: if we're processing
4089
4094
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
4090
4095
          "t.key = c1".
4091
 
          TODO: This is a very limited fix. A more generic fix is possible. 
 
4096
          TODO: This is a very limited fix. A more generic fix is possible.
4092
4097
          There are 2 options:
4093
4098
          A) Make equality propagation code be able to handle BETWEEN
4094
4099
             (including cases like t1.key BETWEEN t2.key AND t3.key)
4135
4140
  (*key_fields)->level=         and_level;
4136
4141
  (*key_fields)->optimize=      exists_optimize;
4137
4142
  /*
4138
 
    If the condition has form "tbl.keypart = othertbl.field" and 
4139
 
    othertbl.field can be NULL, there will be no matches if othertbl.field 
 
4143
    If the condition has form "tbl.keypart = othertbl.field" and
 
4144
    othertbl.field can be NULL, there will be no matches if othertbl.field
4140
4145
    has NULL value.
4141
4146
    We use null_rejecting in add_not_null_conds() to add
4142
4147
    'othertbl.field IS NOT NULL' to tab->select_cond.
4146
4151
                                  ((*value)->type() == Item::FIELD_ITEM) &&
4147
4152
                                  ((Item_field*)*value)->field->maybe_null());
4148
4153
  (*key_fields)->cond_guard= NULL;
4149
 
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name && 
4150
 
                              cond->name < subq_sj_cond_name + 64)? 
 
4154
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name &&
 
4155
                              cond->name < subq_sj_cond_name + 64)?
4151
4156
                              cond->name - subq_sj_cond_name: UINT_MAX;
4152
4157
  (*key_fields)++;
4153
4158
}
4162
4167
    @param  field          Field used in comparision
4163
4168
    @param  eq_func        True if we used =, <=> or IS NULL
4164
4169
    @param  value          Value used for comparison with field
4165
 
                           Is NULL for BETWEEN and IN    
 
4170
                           Is NULL for BETWEEN and IN
4166
4171
    @param  usable_tables  Tables which can be used for key optimization
4167
4172
    @param  sargables      IN/OUT Array of found sargable candidates
4168
4173
 
4186
4191
                eq_func, val, num_values, usable_tables, sargables);
4187
4192
  Item_equal *item_equal= field_item->item_equal;
4188
4193
  if (item_equal)
4189
 
  { 
 
4194
  {
4190
4195
    /*
4191
4196
      Add to the set of possible key values every substitution of
4192
4197
      the field for an equal field included into item_equal
4243
4248
    return;
4244
4249
  }
4245
4250
 
4246
 
  /* 
 
4251
  /*
4247
4252
    Subquery optimization: Conditions that are pushed down into subqueries
4248
4253
    are wrapped into Item_func_trig_cond. We process the wrapped condition
4249
4254
    but need to set cond_guard for KEYUSE elements generated from it.
4254
4259
    {
4255
4260
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
4256
4261
      if (!join->group_list && !join->order &&
4257
 
          join->unit->item && 
 
4262
          join->unit->item &&
4258
4263
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
4259
4264
          !join->unit->is_union())
4260
4265
      {
4292
4297
                  cond_func->argument_count() != 2);
4293
4298
      add_key_equal_fields(key_fields, *and_level, cond_func,
4294
4299
                           (Item_field*) (cond_func->key_item()->real_item()),
4295
 
                           0, values, 
 
4300
                           0, values,
4296
4301
                           cond_func->argument_count()-1,
4297
4302
                           usable_tables, sargables);
4298
4303
    }
4308
4313
        {
4309
4314
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
4310
4315
          add_key_equal_fields(key_fields, *and_level, cond_func,
4311
 
                               field_item, 0, values, 1, usable_tables, 
 
4316
                               field_item, 0, values, 1, usable_tables,
4312
4317
                               sargables);
4313
4318
        }
4314
 
      }  
 
4319
      }
4315
4320
    }
4316
4321
    break;
4317
4322
  }
4333
4338
        cond_func->functype() != Item_func::LIKE_FUNC &&
4334
4339
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
4335
4340
    {
4336
 
      add_key_equal_fields(key_fields, *and_level, cond_func, 
 
4341
      add_key_equal_fields(key_fields, *and_level, cond_func,
4337
4342
                       (Item_field*) (cond_func->arguments()[1])->real_item(),
4338
4343
                           equal_func,
4339
4344
                           cond_func->arguments(),1,usable_tables,
4363
4368
    if (const_item)
4364
4369
    {
4365
4370
      /*
4366
 
        For each field field1 from item_equal consider the equality 
 
4371
        For each field field1 from item_equal consider the equality
4367
4372
        field1=const_item as a condition allowing an index access of the table
4368
4373
        with field1 by the keys value of field1.
4369
 
      */   
 
4374
      */
4370
4375
      while ((item= it++))
4371
4376
      {
4372
4377
        add_key_field(key_fields, *and_level, cond_func, item->field,
4373
4378
                      true, &const_item, 1, usable_tables, sargables);
4374
4379
      }
4375
4380
    }
4376
 
    else 
 
4381
    else
4377
4382
    {
4378
4383
      /*
4379
4384
        Consider all pairs of different fields included into item_equal.
4380
 
        For each of them (field1, field1) consider the equality 
 
4385
        For each of them (field1, field1) consider the equality
4381
4386
        field1=field2 as a condition allowing an index access of the table
4382
4387
        with field1 by the keys value of field2.
4383
 
      */   
 
4388
      */
4384
4389
      Item_equal_iterator fi(*item_equal);
4385
4390
      while ((item= fi++))
4386
4391
      {
4426
4431
  {
4427
4432
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
4428
4433
    {
4429
 
      if (!(form->keys_in_use_for_query.is_set(key)))
 
4434
      if (!(form->keys_in_use_for_query.test(key)))
4430
4435
        continue;
4431
4436
 
4432
 
      uint32_t key_parts= (uint) form->key_info[key].key_parts;
 
4437
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
4433
4438
      for (uint32_t part=0 ; part <  key_parts ; part++)
4434
4439
      {
4435
4440
        if (field->eq(form->key_info[key].key_part[part].field))
4474
4479
/*
4475
4480
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
4476
4481
 
4477
 
    This function populates KEY_FIELD array with entries generated from the 
4478
 
    ON condition of the given nested join, and does the same for nested joins 
 
4482
    This function populates KEY_FIELD array with entries generated from the
 
4483
    ON condition of the given nested join, and does the same for nested joins
4479
4484
    contained within this nested join.
4480
4485
 
4481
4486
  @param[in]      nested_join_table   Nested join pseudo-table to process
4485
4490
 
4486
4491
 
4487
4492
  @note
4488
 
    We can add accesses to the tables that are direct children of this nested 
 
4493
    We can add accesses to the tables that are direct children of this nested
4489
4494
    join (1), and are not inner tables w.r.t their neighbours (2).
4490
 
    
4491
 
    Example for #1 (outer brackets pair denotes nested join this function is 
 
4495
 
 
4496
    Example for #1 (outer brackets pair denotes nested join this function is
4492
4497
    invoked for):
4493
4498
    @code
4494
4499
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
4497
4502
    @code
4498
4503
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
4499
4504
    @endcode
4500
 
    In examples 1-2 for condition cond, we can add 'ref' access candidates to 
 
4505
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
4501
4506
    t1 only.
4502
4507
    Example #3:
4503
4508
    @code
4527
4532
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
4528
4533
        have_another= true;
4529
4534
        li2= li;
4530
 
        li= List_iterator<TableList>(table->nested_join->join_list); 
 
4535
        li= List_iterator<TableList>(table->nested_join->join_list);
4531
4536
      }
4532
4537
      else
4533
4538
        add_key_fields_for_nj(join, table, end, and_level, sargables);
4544
4549
 
4545
4550
/**
4546
4551
  Update keyuse array with all possible keys we can use to fetch rows.
4547
 
  
4548
 
  @param       thd 
 
4552
 
 
4553
  @param       session
4549
4554
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
4550
4555
  @param       join_tab       Array in tablenr_order
4551
4556
  @param       tables         Number of tables in join
4556
4561
                              clause)
4557
4562
  @param       select_lex     current SELECT
4558
4563
  @param[out]  sargables      Array of found sargable candidates
4559
 
      
 
4564
 
4560
4565
   @retval
4561
4566
     0  OK
4562
4567
   @retval
4564
4569
*/
4565
4570
 
4566
4571
static bool
4567
 
update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
4568
 
                    uint32_t tables, COND *cond,
4569
 
                    COND_EQUAL *cond_equal __attribute__((unused)),
4570
 
                    table_map normal_tables, SELECT_LEX *select_lex,
 
4572
update_ref_and_keys(Session *session, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
 
4573
                    uint32_t tables, COND *cond, COND_EQUAL *,
 
4574
                    table_map normal_tables, Select_Lex *select_lex,
4571
4575
                    SARGABLE_PARAM **sargables)
4572
4576
{
4573
4577
  uint  and_level,i,found_eq_constant;
4574
4578
  KEY_FIELD *key_fields, *end, *field;
4575
4579
  uint32_t sz;
4576
4580
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
4577
 
  
4578
 
  /* 
4579
 
    We use the same piece of memory to store both  KEY_FIELD 
 
4581
 
 
4582
  /*
 
4583
    We use the same piece of memory to store both  KEY_FIELD
4580
4584
    and SARGABLE_PARAM structure.
4581
4585
    KEY_FIELD values are placed at the beginning this memory
4582
4586
    while  SARGABLE_PARAM values are put at the end.
4583
4587
    All predicates that are used to fill arrays of KEY_FIELD
4584
4588
    and SARGABLE_PARAM structures have at most 2 arguments
4585
 
    except BETWEEN predicates that have 3 arguments and 
 
4589
    except BETWEEN predicates that have 3 arguments and
4586
4590
    IN predicates.
4587
 
    This any predicate if it's not BETWEEN/IN can be used 
 
4591
    This any predicate if it's not BETWEEN/IN can be used
4588
4592
    directly to fill at most 2 array elements, either of KEY_FIELD
4589
4593
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
4590
4594
    can be filled as this predicate is considered as
4593
4597
    it is considered as sargable only for its first argument.
4594
4598
    Multiple equality can add  elements that are filled after
4595
4599
    substitution of field arguments by equal fields. There
4596
 
    can be not more than select_lex->max_equal_elems such 
 
4600
    can be not more than select_lex->max_equal_elems such
4597
4601
    substitutions.
4598
 
  */ 
 
4602
  */
4599
4603
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
4600
 
      (((thd->lex->current_select->cond_count+1)*2 +
4601
 
        thd->lex->current_select->between_count)*m+1);
4602
 
  if (!(key_fields=(KEY_FIELD*) thd->alloc(sz)))
 
4604
      (((session->lex->current_select->cond_count+1)*2 +
 
4605
        session->lex->current_select->between_count)*m+1);
 
4606
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
4603
4607
    return true; /* purecov: inspected */
4604
4608
  and_level= 0;
4605
4609
  field= end= key_fields;
4606
 
  *sargables= (SARGABLE_PARAM *) key_fields + 
 
4610
  *sargables= (SARGABLE_PARAM *) key_fields +
4607
4611
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
4608
4612
  /* set a barrier for the array of SARGABLE_PARAM */
4609
 
  (*sargables)[0].field= 0; 
 
4613
  (*sargables)[0].field= 0;
4610
4614
 
4611
4615
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
4612
4616
    return true;
4633
4637
      In the future when we introduce conditional accesses
4634
4638
      for inner tables in outer joins these keys will be taken
4635
4639
      into account as well.
4636
 
    */ 
 
4640
    */
4637
4641
    if (*join_tab[i].on_expr_ref)
4638
 
      add_key_fields(join_tab->join, &end, &and_level, 
 
4642
      add_key_fields(join_tab->join, &end, &and_level,
4639
4643
                     *join_tab[i].on_expr_ref,
4640
4644
                     join_tab[i].table->map, sargables);
4641
4645
  }
4647
4651
    while ((table= li++))
4648
4652
    {
4649
4653
      if (table->nested_join)
4650
 
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level, 
 
4654
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
4651
4655
                              sargables);
4652
4656
    }
4653
4657
  }
4702
4706
      /* Save ptr to first use */
4703
4707
      if (!use->table->reginfo.join_tab->keyuse)
4704
4708
        use->table->reginfo.join_tab->keyuse=save_pos;
4705
 
      use->table->reginfo.join_tab->checked_keys.set_bit(use->key);
 
4709
      use->table->reginfo.join_tab->checked_keys.set(use->key);
4706
4710
      save_pos++;
4707
4711
    }
4708
 
    i=(uint) (save_pos-(KEYUSE*) keyuse->buffer);
 
4712
    i=(uint32_t) (save_pos-(KEYUSE*) keyuse->buffer);
4709
4713
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
4710
4714
    keyuse->elements=i;
4711
4715
  }
4804
4808
 
4805
4809
  /* Intersect the keys of all group fields. */
4806
4810
  cur_item= indexed_fields_it++;
4807
 
  possible_keys.merge(cur_item->field->part_of_key);
 
4811
  possible_keys|= cur_item->field->part_of_key;
4808
4812
  while ((cur_item= indexed_fields_it++))
4809
4813
  {
4810
 
    possible_keys.intersect(cur_item->field->part_of_key);
 
4814
    possible_keys&= cur_item->field->part_of_key;
4811
4815
  }
4812
4816
 
4813
 
  if (!possible_keys.is_clear_all())
4814
 
    join_tab->const_keys.merge(possible_keys);
 
4817
  if (possible_keys.any())
 
4818
    join_tab->const_keys|= possible_keys;
4815
4819
}
4816
4820
 
4817
4821
 
4860
4864
    Bitmap of bound IN-equalities.
4861
4865
*/
4862
4866
 
4863
 
uint64_t get_bound_sj_equalities(TableList *sj_nest, 
 
4867
uint64_t get_bound_sj_equalities(TableList *sj_nest,
4864
4868
                                  table_map remaining_tables)
4865
4869
{
4866
4870
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
4898
4902
  @param join             pointer to the structure providing all context info
4899
4903
                          for the query
4900
4904
  @param s                the table to be joined by the function
4901
 
  @param thd              thread for the connection that submitted the query
 
4905
  @param session              thread for the connection that submitted the query
4902
4906
  @param remaining_tables set of tables not included into the partial plan yet
4903
4907
  @param idx              the length of the partial plan
4904
4908
  @param record_count     estimate for the number of records returned by the
4912
4916
static void
4913
4917
best_access_path(JOIN      *join,
4914
4918
                 JOIN_TAB  *s,
4915
 
                 THD       *thd,
 
4919
                 Session       *session,
4916
4920
                 table_map remaining_tables,
4917
4921
                 uint32_t      idx,
4918
4922
                 double    record_count,
4919
 
                 double    read_time __attribute__((unused)))
 
4923
                 double)
4920
4924
{
4921
4925
  KEYUSE *best_key=         0;
4922
4926
  uint32_t best_max_key_part=   0;
4947
4951
        3. All correlation references from this sj-nest are bound
4948
4952
    */
4949
4953
    if (s->emb_sj_nest &&                                                 // (1)
4950
 
        s->emb_sj_nest->sj_in_exprs < 64 && 
 
4954
        s->emb_sj_nest->sj_in_exprs < 64 &&
4951
4955
        ((remaining_tables & s->emb_sj_nest->sj_inner_tables) ==           // (2)
4952
4956
         s->emb_sj_nest->sj_inner_tables) &&                               // (2)
4953
4957
        join->cur_emb_sj_nests == s->emb_sj_nest->sj_inner_tables &&       // (3)
4954
4958
        !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables)) // (4)
4955
4959
    {
4956
4960
      /* This table is an InsideOut scan candidate */
4957
 
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest, 
 
4961
      bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest,
4958
4962
                                                   remaining_tables);
4959
4963
      try_sj_inside_out= true;
4960
4964
    }
4982
4986
        uint32_t keypart= keyuse->keypart;
4983
4987
        table_map best_part_found_ref= 0;
4984
4988
        double best_prev_record_reads= DBL_MAX;
4985
 
        
 
4989
 
4986
4990
        do /* For each way to access the keypart */
4987
4991
        {
4988
4992
 
5047
5051
        /*
5048
5052
          Check if InsideOut scan is applicable:
5049
5053
          1. All IN-equalities are either "bound" or "handled"
5050
 
          2. Index keyparts are 
 
5054
          2. Index keyparts are
5051
5055
             ...
5052
5056
        */
5053
 
        if (try_sj_inside_out && 
5054
 
            table->covering_keys.is_set(key) &&
 
5057
        if (try_sj_inside_out &&
 
5058
            table->covering_keys.test(key) &&
5055
5059
            (handled_sj_equalities | bound_sj_equalities) ==     // (1)
5056
5060
            PREV_BITS(uint64_t, s->emb_sj_nest->sj_in_exprs)) // (1)
5057
5061
        {
5110
5114
                ReuseRangeEstimateForRef-1:
5111
5115
                We get here if we've found a ref(const) (c_i are constants):
5112
5116
                  "(keypart1=c1) AND ... AND (keypartN=cN)"   [ref_const_cond]
5113
 
                
5114
 
                If range optimizer was able to construct a "range" 
 
5117
 
 
5118
                If range optimizer was able to construct a "range"
5115
5119
                access on this index, then its condition "quick_cond" was
5116
5120
                eqivalent to ref_const_cond (*), and we can re-use E(#rows)
5117
5121
                from the range optimizer.
5118
 
                
5119
 
                Proof of (*): By properties of range and ref optimizers 
5120
 
                quick_cond will be equal or tighther than ref_const_cond. 
5121
 
                ref_const_cond already covers "smallest" possible interval - 
5122
 
                a singlepoint interval over all keyparts. Therefore, 
5123
 
                quick_cond is equivalent to ref_const_cond (if it was an 
 
5122
 
 
5123
                Proof of (*): By properties of range and ref optimizers
 
5124
                quick_cond will be equal or tighther than ref_const_cond.
 
5125
                ref_const_cond already covers "smallest" possible interval -
 
5126
                a singlepoint interval over all keyparts. Therefore,
 
5127
                quick_cond is equivalent to ref_const_cond (if it was an
5124
5128
                empty interval we wouldn't have got here).
5125
5129
              */
5126
 
              if (table->quick_keys.is_set(key))
 
5130
              if (table->quick_keys.test(key))
5127
5131
                records= (double) table->quick_rows[key];
5128
5132
              else
5129
5133
              {
5146
5150
              /*
5147
5151
                ReuseRangeEstimateForRef-2:  We get here if we could not reuse
5148
5152
                E(#rows) from range optimizer. Make another try:
5149
 
                
 
5153
 
5150
5154
                If range optimizer produced E(#rows) for a prefix of the ref
5151
5155
                access we're considering, and that E(#rows) is lower then our
5152
5156
                current estimate, make an adjustment. The criteria of when we
5153
5157
                can make an adjustment is a special case of the criteria used
5154
5158
                in ReuseRangeEstimateForRef-3.
5155
5159
              */
5156
 
              if (table->quick_keys.is_set(key) &&
 
5160
              if (table->quick_keys.test(key) &&
5157
5161
                  const_part & (1 << table->quick_key_parts[key]) &&
5158
5162
                  table->quick_n_ranges[key] == 1 &&
5159
5163
                  records > (double) table->quick_rows[key])
5163
5167
            }
5164
5168
            /* Limit the number of matched rows */
5165
5169
            tmp= records;
5166
 
            set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
5167
 
            if (table->covering_keys.is_set(key))
 
5170
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5171
            if (table->covering_keys.test(key))
5168
5172
            {
5169
5173
              /* we can use only index tree */
5170
5174
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5188
5192
            /*
5189
5193
              ReuseRangeEstimateForRef-3:
5190
5194
              We're now considering a ref[or_null] access via
5191
 
              (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR  
5192
 
              (same-as-above but with one cond replaced 
 
5195
              (t.keypart1=e1 AND ... AND t.keypartK=eK) [ OR
 
5196
              (same-as-above but with one cond replaced
5193
5197
               with "t.keypart_i IS NULL")]  (**)
5194
 
              
 
5198
 
5195
5199
              Try re-using E(#rows) from "range" optimizer:
5196
5200
              We can do so if "range" optimizer used the same intervals as
5197
 
              in (**). The intervals used by range optimizer may be not 
 
5201
              in (**). The intervals used by range optimizer may be not
5198
5202
              available at this point (as "range" access might have choosen to
5199
5203
              create quick select over another index), so we can't compare
5200
5204
              them to (**). We'll make indirect judgements instead.
5201
5205
              The sufficient conditions for re-use are:
5202
5206
              (C1) All e_i in (**) are constants, i.e. found_ref==false. (if
5203
5207
                   this is not satisfied we have no way to know which ranges
5204
 
                   will be actually scanned by 'ref' until we execute the 
 
5208
                   will be actually scanned by 'ref' until we execute the
5205
5209
                   join)
5206
5210
              (C2) max #key parts in 'range' access == K == max_key_part (this
5207
5211
                   is apparently a necessary requirement)
5208
5212
 
5209
 
              We also have a property that "range optimizer produces equal or 
 
5213
              We also have a property that "range optimizer produces equal or
5210
5214
              tighter set of scan intervals than ref(const) optimizer". Each
5211
 
              of the intervals in (**) are "tightest possible" intervals when 
5212
 
              one limits itself to using keyparts 1..K (which we do in #2).              
 
5215
              of the intervals in (**) are "tightest possible" intervals when
 
5216
              one limits itself to using keyparts 1..K (which we do in #2).
5213
5217
              From here it follows that range access used either one, or
5214
5218
              both of the (I1) and (I2) intervals:
5215
 
              
5216
 
               (t.keypart1=c1 AND ... AND t.keypartK=eK)  (I1) 
5217
 
               (same-as-above but with one cond replaced  
 
5219
 
 
5220
               (t.keypart1=c1 AND ... AND t.keypartK=eK)  (I1)
 
5221
               (same-as-above but with one cond replaced
5218
5222
                with "t.keypart_i IS NULL")               (I2)
5219
5223
 
5220
5224
              The remaining part is to exclude the situation where range
5224
5228
 
5225
5229
              (C3) "range optimizer used (have ref_or_null?2:1) intervals"
5226
5230
            */
5227
 
            if (table->quick_keys.is_set(key) && !found_ref &&          //(C1)
 
5231
            if (table->quick_keys.test(key) && !found_ref &&          //(C1)
5228
5232
                table->quick_key_parts[key] == max_key_part &&          //(C2)
5229
5233
                table->quick_n_ranges[key] == 1+((ref_or_null_part)?1:0)) //(C3)
5230
5234
            {
5235
5239
              /* Check if we have statistic about the distribution */
5236
5240
              if ((records= keyinfo->rec_per_key[max_key_part-1]))
5237
5241
              {
5238
 
                /* 
 
5242
                /*
5239
5243
                  Fix for the case where the index statistics is too
5240
 
                  optimistic: If 
 
5244
                  optimistic: If
5241
5245
                  (1) We're considering ref(const) and there is quick select
5242
 
                      on the same index, 
 
5246
                      on the same index,
5243
5247
                  (2) and that quick select uses more keyparts (i.e. it will
5244
5248
                      scan equal/smaller interval then this ref(const))
5245
5249
                  (3) and E(#rows) for quick select is higher then our
5246
5250
                      estimate,
5247
 
                  Then 
 
5251
                  Then
5248
5252
                    We'll use E(#rows) from quick select.
5249
5253
 
5250
5254
                  Q: Why do we choose to use 'ref'? Won't quick select be
5251
5255
                  cheaper in some cases ?
5252
5256
                  TODO: figure this out and adjust the plan choice if needed.
5253
5257
                */
5254
 
                if (!found_ref && table->quick_keys.is_set(key) &&    // (1)
 
5258
                if (!found_ref && table->quick_keys.test(key) &&    // (1)
5255
5259
                    table->quick_key_parts[key] > max_key_part &&     // (2)
5256
5260
                    records < (double)table->quick_rows[key])         // (3)
5257
5261
                  records= (double)table->quick_rows[key];
5294
5298
                    tmp= a;
5295
5299
                  set_if_bigger(tmp,1.0);
5296
5300
                }
5297
 
                records = (ulong) tmp;
 
5301
                records = (uint32_t) tmp;
5298
5302
              }
5299
5303
 
5300
5304
              if (ref_or_null_part)
5307
5311
              /*
5308
5312
                ReuseRangeEstimateForRef-4:  We get here if we could not reuse
5309
5313
                E(#rows) from range optimizer. Make another try:
5310
 
                
5311
 
                If range optimizer produced E(#rows) for a prefix of the ref 
 
5314
 
 
5315
                If range optimizer produced E(#rows) for a prefix of the ref
5312
5316
                access we're considering, and that E(#rows) is lower then our
5313
5317
                current estimate, make the adjustment.
5314
5318
 
5316
5320
                optimizer is the same as in ReuseRangeEstimateForRef-3,
5317
5321
                applied to first table->quick_key_parts[key] key parts.
5318
5322
              */
5319
 
              if (table->quick_keys.is_set(key) &&
 
5323
              if (table->quick_keys.test(key) &&
5320
5324
                  table->quick_key_parts[key] <= max_key_part &&
5321
5325
                  const_part & (1 << table->quick_key_parts[key]) &&
5322
5326
                  table->quick_n_ranges[key] == 1 + ((ref_or_null_part &
5328
5332
            }
5329
5333
 
5330
5334
            /* Limit the number of matched rows */
5331
 
            set_if_smaller(tmp, (double) thd->variables.max_seeks_for_key);
5332
 
            if (table->covering_keys.is_set(key))
 
5335
            set_if_smaller(tmp, (double) session->variables.max_seeks_for_key);
 
5336
            if (table->covering_keys.test(key))
5333
5337
            {
5334
5338
              /* we can use only index tree */
5335
5339
              tmp= record_count * table->file->index_only_read_time(key, tmp);
5378
5382
        (or index scan, or quick select), or 'ref' is more expensive than
5379
5383
        any of them.
5380
5384
    (2) This doesn't hold: the best way to perform table scan is to to perform
5381
 
        'range' access using index IDX, and the best way to perform 'ref' 
 
5385
        'range' access using index IDX, and the best way to perform 'ref'
5382
5386
        access is to use the same index IDX, with the same or more key parts.
5383
 
        (note: it is not clear how this rule is/should be extended to 
 
5387
        (note: it is not clear how this rule is/should be extended to
5384
5388
        index_merge quick selects)
5385
5389
    (3) See above note about InnoDB.
5386
5390
    (4) NOT ("FORCE INDEX(...)" is used for table and there is 'ref' access
5395
5399
      !(s->quick && best_key && s->quick->index == best_key->key &&      // (2)
5396
5400
        best_max_key_part >= s->table->quick_key_parts[best_key->key]) &&// (2)
5397
5401
      !((s->table->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) &&   // (3)
5398
 
        ! s->table->covering_keys.is_clear_all() && best_key && !s->quick) &&// (3)
 
5402
        ! s->table->covering_keys.none() && best_key && !s->quick) &&// (3)
5399
5403
      !(s->table->force_index && best_key && !s->quick))                 // (4)
5400
5404
  {                                             // Check full join
5401
5405
    ha_rows rnd_records= s->found_records;
5402
5406
    /*
5403
5407
      If there is a filtering condition on the table (i.e. ref analyzer found
5404
5408
      at least one "table.keyXpartY= exprZ", where exprZ refers only to tables
5405
 
      preceding this table in the join order we're now considering), then 
 
5409
      preceding this table in the join order we're now considering), then
5406
5410
      assume that 25% of the rows will be filtered out by this condition.
5407
5411
 
5408
5412
      This heuristic is supposed to force tables used in exprZ to be before
5429
5433
        For each record we:
5430
5434
        - read record range through 'quick'
5431
5435
        - skip rows which does not satisfy WHERE constraints
5432
 
        TODO: 
 
5436
        TODO:
5433
5437
        We take into account possible use of join cache for ALL/index
5434
 
        access (see first else-branch below), but we don't take it into 
 
5438
        access (see first else-branch below), but we don't take it into
5435
5439
        account here for range/index_merge access. Find out why this is so.
5436
5440
      */
5437
5441
      tmp= record_count *
5446
5450
      {
5447
5451
        /*
5448
5452
          For each record we have to:
5449
 
          - read the whole table record 
 
5453
          - read the whole table record
5450
5454
          - skip rows which does not satisfy join condition
5451
5455
        */
5452
5456
        tmp= record_count *
5458
5462
        /* We read the table as many times as join buffer becomes full. */
5459
5463
        tmp*= (1.0 + floor((double) cache_record_length(join,idx) *
5460
5464
                           record_count /
5461
 
                           (double) thd->variables.join_buff_size));
5462
 
        /* 
 
5465
                           (double) session->variables.join_buff_size));
 
5466
        /*
5463
5467
            We don't make full cartesian product between rows in the scanned
5464
5468
           table and existing records because we skip all rows from the
5465
 
           scanned table, which does not satisfy join condition when 
 
5469
           scanned table, which does not satisfy join condition when
5466
5470
           we read the table (see flush_cached_records for details). Here we
5467
5471
           take into account cost to read and skip these records.
5468
5472
        */
5536
5540
static bool
5537
5541
choose_plan(JOIN *join, table_map join_tables)
5538
5542
{
5539
 
  uint32_t search_depth= join->thd->variables.optimizer_search_depth;
5540
 
  uint32_t prune_level=  join->thd->variables.optimizer_prune_level;
 
5543
  uint32_t search_depth= join->session->variables.optimizer_search_depth;
 
5544
  uint32_t prune_level=  join->session->variables.optimizer_prune_level;
5541
5545
  bool straight_join= test(join->select_options & SELECT_STRAIGHT_JOIN);
5542
5546
 
5543
5547
  join->cur_embedding_map= 0;
5544
5548
  reset_nj_counters(join->join_list);
5545
5549
  /*
5546
5550
    if (SELECT_STRAIGHT_JOIN option is set)
5547
 
      reorder tables so dependent tables come after tables they depend 
5548
 
      on, otherwise keep tables in the order they were specified in the query 
 
5551
      reorder tables so dependent tables come after tables they depend
 
5552
      on, otherwise keep tables in the order they were specified in the query
5549
5553
    else
5550
5554
      Apply heuristic: pre-sort all access plans with respect to the number of
5551
5555
      records accessed.
5568
5572
      join->best_read= DBL_MAX;
5569
5573
      if (find_best(join, join_tables, join->const_tables, 1.0, 0.0))
5570
5574
        return(true);
5571
 
    } 
 
5575
    }
5572
5576
    else
5573
5577
    {
5574
5578
      if (search_depth == 0)
5579
5583
    }
5580
5584
  }
5581
5585
 
5582
 
  /* 
 
5586
  /*
5583
5587
    Store the cost of this query into a user variable
5584
5588
    Don't update last_query_cost for statements that are not "flat joins" :
5585
5589
    i.e. they have subqueries, unions or call stored procedures.
5586
5590
    TODO: calculate a correct cost for a query with subqueries and UNIONs.
5587
5591
  */
5588
 
  if (join->thd->lex->is_single_level_stmt())
5589
 
    join->thd->status_var.last_query_cost= join->best_read;
 
5592
  if (join->session->lex->is_single_level_stmt())
 
5593
    join->session->status_var.last_query_cost= join->best_read;
5590
5594
  return(false);
5591
5595
}
5592
5596
 
5607
5611
      a: dependent = 0x0 table->map = 0x1 found_records = 3 ptr = 0x907e6b0
5608
5612
      b: dependent = 0x0 table->map = 0x2 found_records = 3 ptr = 0x907e838
5609
5613
      c: dependent = 0x6 table->map = 0x10 found_records = 2 ptr = 0x907ecd0
5610
 
     
 
5614
 
5611
5615
  @retval
5612
5616
    1  if first is bigger
5613
5617
  @retval
5616
5620
    0  if equal
5617
5621
*/
5618
5622
 
5619
 
static int
5620
 
join_tab_cmp(const void* ptr1, const void* ptr2)
 
5623
int join_tab_cmp(const void* ptr1, const void* ptr2)
5621
5624
{
5622
5625
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
5623
5626
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
5625
5628
  if (jt1->dependent & jt2->table->map)
5626
5629
    return 1;
5627
5630
  if (jt2->dependent & jt1->table->map)
5628
 
    return -1;  
 
5631
    return -1;
5629
5632
  if (jt1->found_records > jt2->found_records)
5630
5633
    return 1;
5631
5634
  if (jt1->found_records < jt2->found_records)
5632
 
    return -1; 
 
5635
    return -1;
5633
5636
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
5634
5637
}
5635
5638
 
5638
5641
  Same as join_tab_cmp, but for use with SELECT_STRAIGHT_JOIN.
5639
5642
*/
5640
5643
 
5641
 
static int
5642
 
join_tab_cmp_straight(const void* ptr1, const void* ptr2)
 
5644
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
5643
5645
{
5644
5646
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
5645
5647
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
5734
5736
  uint32_t idx= join->const_tables;
5735
5737
  double    record_count= 1.0;
5736
5738
  double    read_time=    0.0;
5737
 
 
 
5739
 
5738
5740
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
5739
5741
  {
5740
5742
    /* Find the best access method from 's' to the current partial plan */
5741
5743
    advance_sj_state(join_tables, s);
5742
 
    best_access_path(join, s, join->thd, join_tables, idx,
 
5744
    best_access_path(join, s, join->session, join_tables, idx,
5743
5745
                     record_count, read_time);
5744
5746
    /* compute the cost of the new plan extended with 's' */
5745
5747
    record_count*= join->positions[idx].records_read;
5910
5912
    each table. The choice of a table order and an access path for each table
5911
5913
    constitutes a query execution plan (QEP) that fully specifies how to
5912
5914
    execute the query.
5913
 
   
 
5915
 
5914
5916
    The maximal size of the found plan is controlled by the parameter
5915
5917
    'search_depth'. When search_depth == N, the resulting plan is complete and
5916
5918
    can be used directly as a QEP. If search_depth < N, the found plan consists
6027
6029
                                 uint32_t      search_depth,
6028
6030
                                 uint32_t      prune_level)
6029
6031
{
6030
 
  THD *thd= join->thd;
6031
 
  if (thd->killed)  // Abort
 
6032
  Session *session= join->session;
 
6033
  if (session->killed)  // Abort
6032
6034
    return(true);
6033
6035
 
6034
 
  /* 
 
6036
  /*
6035
6037
     'join' is a partial plan with lower cost than the best plan so far,
6036
6038
     so continue expanding it further with the tables in 'remaining_tables'.
6037
6039
  */
6042
6044
  for (JOIN_TAB **pos= join->best_ref + idx ; (s= *pos) ; pos++)
6043
6045
  {
6044
6046
    table_map real_table_bit= s->table->map;
6045
 
    if ((remaining_tables & real_table_bit) && 
6046
 
        !(remaining_tables & s->dependent) && 
 
6047
    if ((remaining_tables & real_table_bit) &&
 
6048
        !(remaining_tables & s->dependent) &&
6047
6049
        (!idx || !check_interleaving_with_nj(join->positions[idx-1].table, s)))
6048
6050
    {
6049
6051
      double current_record_count, current_read_time;
6050
6052
      advance_sj_state(remaining_tables, s);
6051
6053
 
6052
6054
      /*
6053
 
        psergey-insideout-todo: 
6054
 
          when best_access_path() detects it could do an InsideOut scan or 
6055
 
          some other scan, have it return an insideout scan and a flag that 
6056
 
          requests to "fork" this loop iteration. (Q: how does that behave 
 
6055
        psergey-insideout-todo:
 
6056
          when best_access_path() detects it could do an InsideOut scan or
 
6057
          some other scan, have it return an insideout scan and a flag that
 
6058
          requests to "fork" this loop iteration. (Q: how does that behave
6057
6059
          when the depth is insufficient??)
6058
6060
      */
6059
6061
      /* Find the best access method from 's' to the current partial plan */
6060
 
      best_access_path(join, s, thd, remaining_tables, idx,
 
6062
      best_access_path(join, s, session, remaining_tables, idx,
6061
6063
                       record_count, read_time);
6062
6064
      /* Compute the cost of extending the plan with 's' */
6063
6065
      current_record_count= record_count * join->positions[idx].records_read;
6152
6154
find_best(JOIN *join,table_map rest_tables,uint32_t idx,double record_count,
6153
6155
          double read_time)
6154
6156
{
6155
 
  THD *thd= join->thd;
6156
 
  if (thd->killed)
 
6157
  Session *session= join->session;
 
6158
  if (session->killed)
6157
6159
    return(true);
6158
6160
  if (!rest_tables)
6159
6161
  {
6182
6184
    {
6183
6185
      double records, best;
6184
6186
      advance_sj_state(rest_tables, s);
6185
 
      best_access_path(join, s, thd, rest_tables, idx, record_count, 
 
6187
      best_access_path(join, s, session, rest_tables, idx, record_count,
6186
6188
                       read_time);
6187
6189
      records= join->positions[idx].records_read;
6188
6190
      best= join->positions[idx].read_time;
6223
6225
  Find how much space the prevous read not const tables takes in cache.
6224
6226
*/
6225
6227
 
6226
 
static void calc_used_field_length(THD *thd __attribute__((unused)),
6227
 
                                   JOIN_TAB *join_tab)
 
6228
static void calc_used_field_length(Session *, JOIN_TAB *join_tab)
6228
6229
{
6229
6230
  uint32_t null_fields,blobs,fields,rec_length;
6230
6231
  Field **f_ptr,*field;
6231
 
  MY_BITMAP *read_set= join_tab->table->read_set;;
6232
6232
 
6233
6233
  null_fields= blobs= fields= rec_length=0;
6234
6234
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
6235
6235
  {
6236
 
    if (bitmap_is_set(read_set, field->field_index))
 
6236
    if (field->isReadSet())
6237
6237
    {
6238
6238
      uint32_t flags=field->flags;
6239
6239
      fields++;
6250
6250
    rec_length+=sizeof(bool);
6251
6251
  if (blobs)
6252
6252
  {
6253
 
    uint32_t blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
 
6253
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
6254
6254
                             (join_tab->table->getRecordLength()- rec_length));
6255
 
    rec_length+=(uint) cmax((uint)4,blob_length);
 
6255
    rec_length+=(uint32_t) cmax((uint32_t)4,blob_length);
6256
6256
  }
6257
 
  join_tab->used_fields=fields;
6258
 
  join_tab->used_fieldlength=rec_length;
6259
 
  join_tab->used_blobs=blobs;
 
6257
  join_tab->used_fields= fields;
 
6258
  join_tab->used_fieldlength= rec_length;
 
6259
  join_tab->used_blobs= blobs;
6260
6260
}
6261
6261
 
6262
6262
 
6265
6265
{
6266
6266
  uint32_t length=0;
6267
6267
  JOIN_TAB **pos,**end;
6268
 
  THD *thd=join->thd;
 
6268
  Session *session=join->session;
6269
6269
 
6270
6270
  for (pos=join->best_ref+join->const_tables,end=join->best_ref+idx ;
6271
6271
       pos != end ;
6273
6273
  {
6274
6274
    JOIN_TAB *join_tab= *pos;
6275
6275
    if (!join_tab->used_fieldlength)            /* Not calced yet */
6276
 
      calc_used_field_length(thd, join_tab);
 
6276
      calc_used_field_length(session, join_tab);
6277
6277
    length+=join_tab->used_fieldlength;
6278
6278
  }
6279
6279
  return length;
6296
6296
    tables within that join order (specified in found_ref), find out how many
6297
6297
    distinct row combinations of subset tables will be in the result of the
6298
6298
    partial join order.
6299
 
     
 
6299
 
6300
6300
    This is used as follows: Suppose we have a table accessed with a ref-based
6301
6301
    method. The ref access depends on current rows of tables in found_ref.
6302
6302
    We want to count # of different ref accesses. We assume two ref accesses
6307
6307
 
6308
6308
    and a join order:
6309
6309
      t1,  ref access on t1.key=c1
6310
 
      t2,  ref access on t2.key=c2       
6311
 
      t3,  ref access on t3.key=t1.field 
6312
 
    
 
6310
      t2,  ref access on t2.key=c2
 
6311
      t3,  ref access on t3.key=t1.field
 
6312
 
6313
6313
    For t1: n_ref_scans = 1, n_distinct_ref_scans = 1
6314
6314
    For t2: n_ref_scans = records_read(t1), n_distinct_ref_scans=1
6315
6315
    For t3: n_ref_scans = records_read(t1)*records_read(t2)
6316
6316
            n_distinct_ref_scans = #records_read(t1)
6317
 
    
 
6317
 
6318
6318
    The reason for having this function (at least the latest version of it)
6319
 
    is that we need to account for buffering in join execution. 
6320
 
    
 
6319
    is that we need to account for buffering in join execution.
 
6320
 
6321
6321
    An edge-case example: if we have a non-first table in join accessed via
6322
6322
    ref(const) or ref(param) where there is a small number of different
6323
6323
    values of param, then the access will likely hit the disk cache and will
6324
6324
    not require any disk seeks.
6325
 
    
 
6325
 
6326
6326
    The proper solution would be to assume an LRU disk cache of some size,
6327
6327
    calculate probability of cache hits, etc. For now we just count
6328
6328
    identical ref accesses as one.
6329
6329
 
6330
 
  RETURN 
 
6330
  RETURN
6331
6331
    Expected number of row combinations
6332
6332
*/
6333
6333
 
6341
6341
    if (pos->table->table->map & found_ref)
6342
6342
    {
6343
6343
      found_ref|= pos->ref_depend_map;
6344
 
      /* 
6345
 
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table 
6346
 
        with no matching row we will get position[t2].records_read==0. 
6347
 
        Actually the size of output is one null-complemented row, therefore 
 
6344
      /*
 
6345
        For the case of "t1 LEFT JOIN t2 ON ..." where t2 is a const table
 
6346
        with no matching row we will get position[t2].records_read==0.
 
6347
        Actually the size of output is one null-complemented row, therefore
6348
6348
        we will use value of 1 whenever we get records_read==0.
6349
6349
 
6350
6350
        Note
6351
 
        - the above case can't occur if inner part of outer join has more 
 
6351
        - the above case can't occur if inner part of outer join has more
6352
6352
          than one table: table with no matches will not be marked as const.
6353
6353
 
6354
6354
        - Ideally we should add 1 to records_read for every possible null-
6377
6377
  JOIN_TAB *join_tab,*j;
6378
6378
  KEYUSE *keyuse;
6379
6379
  uint32_t table_count;
6380
 
  THD *thd=join->thd;
 
6380
  Session *session=join->session;
6381
6381
 
6382
6382
  table_count=join->tables;
6383
6383
  if (!(join->join_tab=join_tab=
6384
 
        (JOIN_TAB*) thd->alloc(sizeof(JOIN_TAB)*table_count)))
 
6384
        (JOIN_TAB*) session->alloc(sizeof(JOIN_TAB)*table_count)))
6385
6385
    return(true);
6386
6386
 
6387
6387
  join->full_join=0;
6404
6404
 
6405
6405
    if (j->type == JT_SYSTEM)
6406
6406
      continue;
6407
 
    if (j->keys.is_clear_all() || !(keyuse= join->best_positions[tablenr].key))
 
6407
    if (j->keys.none() || !(keyuse= join->best_positions[tablenr].key))
6408
6408
    {
6409
6409
      j->type=JT_ALL;
6410
6410
      if (tablenr != join->const_tables)
6425
6425
                               table_map used_tables)
6426
6426
{
6427
6427
  KEYUSE *keyuse=org_keyuse;
6428
 
  THD  *thd= join->thd;
 
6428
  Session  *session= join->session;
6429
6429
  uint32_t keyparts,length,key;
6430
6430
  Table *table;
6431
6431
  KEY *keyinfo;
6464
6464
  j->ref.key_parts=keyparts;
6465
6465
  j->ref.key_length=length;
6466
6466
  j->ref.key=(int) key;
6467
 
  if (!(j->ref.key_buff= (unsigned char*) thd->calloc(ALIGN_SIZE(length)*2)) ||
6468
 
      !(j->ref.key_copy= (store_key**) thd->alloc((sizeof(store_key*) *
 
6467
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
 
6468
      !(j->ref.key_copy= (store_key**) session->alloc((sizeof(store_key*) *
6469
6469
                                                   (keyparts+1)))) ||
6470
 
      !(j->ref.items=    (Item**) thd->alloc(sizeof(Item*)*keyparts)) ||
6471
 
      !(j->ref.cond_guards= (bool**) thd->alloc(sizeof(uint*)*keyparts)))
 
6470
      !(j->ref.items=    (Item**) session->alloc(sizeof(Item*)*keyparts)) ||
 
6471
      !(j->ref.cond_guards= (bool**) session->alloc(sizeof(uint*)*keyparts)))
6472
6472
  {
6473
6473
    return(true);
6474
6474
  }
6492
6492
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
6493
6493
      j->ref.items[i]=keyuse->val;              // Save for cond removal
6494
6494
      j->ref.cond_guards[i]= keyuse->cond_guard;
6495
 
      if (keyuse->null_rejecting) 
 
6495
      if (keyuse->null_rejecting)
6496
6496
        j->ref.null_rejecting |= 1 << i;
6497
6497
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
6498
6498
      if (!keyuse->used_tables &&
6499
6499
          !(join->select_options & SELECT_DESCRIBE))
6500
6500
      {                                 // Compare against constant
6501
 
        store_key_item tmp(thd, keyinfo->key_part[i].field,
 
6501
        store_key_item tmp(session, keyinfo->key_part[i].field,
6502
6502
                           key_buff + maybe_null,
6503
6503
                           maybe_null ?  key_buff : 0,
6504
6504
                           keyinfo->key_part[i].length, keyuse->val);
6505
 
        if (thd->is_fatal_error)
 
6505
        if (session->is_fatal_error)
6506
6506
          return(true);
6507
6507
        tmp.copy();
6508
6508
      }
6509
6509
      else
6510
 
        *ref_key++= get_store_key(thd,
 
6510
        *ref_key++= get_store_key(session,
6511
6511
                                  keyuse,join->const_table_map,
6512
6512
                                  &keyinfo->key_part[i],
6513
6513
                                  key_buff, maybe_null);
6550
6550
 
6551
6551
 
6552
6552
static store_key *
6553
 
get_store_key(THD *thd, KEYUSE *keyuse, table_map used_tables,
 
6553
get_store_key(Session *session, KEYUSE *keyuse, table_map used_tables,
6554
6554
              KEY_PART_INFO *key_part, unsigned char *key_buff, uint32_t maybe_null)
6555
6555
{
6556
6556
  if (!((~used_tables) & keyuse->used_tables))          // if const item
6557
6557
  {
6558
 
    return new store_key_const_item(thd,
 
6558
    return new store_key_const_item(session,
6559
6559
                                    key_part->field,
6560
6560
                                    key_buff + maybe_null,
6561
6561
                                    maybe_null ? key_buff : 0,
6566
6566
           (keyuse->val->type() == Item::REF_ITEM &&
6567
6567
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
6568
6568
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
6569
 
             Item_ref::DIRECT_REF && 
 
6569
             Item_ref::DIRECT_REF &&
6570
6570
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
6571
 
    return new store_key_field(thd,
 
6571
    return new store_key_field(session,
6572
6572
                               key_part->field,
6573
6573
                               key_buff + maybe_null,
6574
6574
                               maybe_null ? key_buff : 0,
6575
6575
                               key_part->length,
6576
6576
                               ((Item_field*) keyuse->val->real_item())->field,
6577
6577
                               keyuse->val->full_name());
6578
 
  return new store_key_item(thd,
 
6578
  return new store_key_item(session,
6579
6579
                            key_part->field,
6580
6580
                            key_buff + maybe_null,
6581
6581
                            maybe_null ? key_buff : 0,
6595
6595
{
6596
6596
  bool error;
6597
6597
  Table *table= field->table;
6598
 
  THD *thd= table->in_use;
6599
 
  ha_rows cuted_fields=thd->cuted_fields;
 
6598
  Session *session= table->in_use;
 
6599
  ha_rows cuted_fields=session->cuted_fields;
6600
6600
 
6601
6601
  /*
6602
6602
    we should restore old value of count_cuted_fields because
6603
 
    store_val_in_field can be called from mysql_insert 
 
6603
    store_val_in_field can be called from mysql_insert
6604
6604
    with select_insert, which make count_cuted_fields= 1
6605
6605
   */
6606
 
  enum_check_fields old_count_cuted_fields= thd->count_cuted_fields;
6607
 
  thd->count_cuted_fields= check_flag;
 
6606
  enum_check_fields old_count_cuted_fields= session->count_cuted_fields;
 
6607
  session->count_cuted_fields= check_flag;
6608
6608
  error= item->save_in_field(field, 1);
6609
 
  thd->count_cuted_fields= old_count_cuted_fields;
6610
 
  return error || cuted_fields != thd->cuted_fields;
 
6609
  session->count_cuted_fields= old_count_cuted_fields;
 
6610
  return error || cuted_fields != session->cuted_fields;
6611
6611
}
6612
6612
 
6613
6613
 
6623
6623
  */
6624
6624
  if (!join->table_reexec)
6625
6625
  {
6626
 
    if (!(join->table_reexec= (Table**) join->thd->alloc(sizeof(Table*))))
 
6626
    if (!(join->table_reexec= (Table**) join->session->alloc(sizeof(Table*))))
6627
6627
      return(true);                        /* purecov: inspected */
6628
6628
    if (join->tmp_join)
6629
6629
      join->tmp_join->table_reexec= join->table_reexec;
6631
6631
  if (!join->join_tab_reexec)
6632
6632
  {
6633
6633
    if (!(join->join_tab_reexec=
6634
 
          (JOIN_TAB*) join->thd->alloc(sizeof(JOIN_TAB))))
 
6634
          (JOIN_TAB*) join->session->alloc(sizeof(JOIN_TAB))))
6635
6635
      return(true);                        /* purecov: inspected */
6636
6636
    if (join->tmp_join)
6637
6637
      join->tmp_join->join_tab_reexec= join->join_tab_reexec;
6659
6659
  join_tab->select_cond=0;
6660
6660
  join_tab->quick=0;
6661
6661
  join_tab->type= JT_ALL;                       /* Map through all records */
6662
 
  join_tab->keys.init();
6663
 
  join_tab->keys.set_all();                     /* test everything in quick */
 
6662
  join_tab->keys.set();                     /* test everything in quick */
6664
6663
  join_tab->info=0;
6665
6664
  join_tab->on_expr_ref=0;
6666
6665
  join_tab->last_inner= 0;
6708
6707
    add "t1.field IS NOT NULL" to t1's table condition. @n
6709
6708
 
6710
6709
    Description of the optimization:
6711
 
    
 
6710
 
6712
6711
      We look through equalities choosen to perform ref/eq_ref access,
6713
6712
      pick equalities that have form "tbl.part_of_key = othertbl.field"
6714
6713
      (where othertbl is a non-const table and othertbl.field may be NULL)
6736
6735
      This optimization doesn't affect the choices that ref, range, or join
6737
6736
      optimizer make. This was intentional because this was added after 4.1
6738
6737
      was GA.
6739
 
      
 
6738
 
6740
6739
    Implementation overview
6741
6740
      1. update_ref_and_keys() accumulates info about null-rejecting
6742
6741
         predicates in in KEY_FIELD::null_rejecting
6751
6750
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
6752
6751
  {
6753
6752
    JOIN_TAB *tab=join->join_tab+i;
6754
 
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF || 
 
6753
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
6755
6754
         tab->type == JT_REF_OR_NULL) &&
6756
6755
        !tab->table->maybe_null)
6757
6756
    {
6775
6774
            return;
6776
6775
          /*
6777
6776
            We need to do full fix_fields() call here in order to have correct
6778
 
            notnull->const_item(). This is needed e.g. by test_quick_select 
6779
 
            when it is called from make_join_select after this function is 
 
6777
            notnull->const_item(). This is needed e.g. by test_quick_select
 
6778
            when it is called from make_join_select after this function is
6780
6779
            called.
6781
6780
          */
6782
 
          if (notnull->fix_fields(join->thd, &notnull))
 
6781
          if (notnull->fix_fields(join->session, &notnull))
6783
6782
            return;
6784
6783
          add_cond_and_fix(&referred_tab->select_cond, notnull);
6785
6784
        }
6840
6839
    corresponding first inner table through the field t0->on_expr_ref.
6841
6840
    Here ti are structures of the JOIN_TAB type.
6842
6841
 
6843
 
  EXAMPLE. For the query: 
 
6842
  EXAMPLE. For the query:
6844
6843
  @code
6845
6844
        SELECT * FROM t1
6846
6845
                      LEFT JOIN
6853
6852
    is selected, the following references will be set;
6854
6853
    t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2]
6855
6854
    t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2],
6856
 
    on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to 
 
6855
    on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to
6857
6856
    *t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref.
6858
6857
 
6859
6858
  @param join   reference to the info fully describing the query
6877
6876
 
6878
6877
    if (tbl->outer_join)
6879
6878
    {
6880
 
      /* 
 
6879
      /*
6881
6880
        Table tab is the only one inner table for outer join.
6882
6881
        (Like table t4 for the table reference t3 LEFT JOIN t4 ON t3.a=t4.a
6883
6882
        is in the query above.)
6887
6886
      tab->cond_equal= tbl->cond_equal;
6888
6887
      if (embedding)
6889
6888
        tab->first_upper= embedding->nested_join->first_nested;
6890
 
    }    
 
6889
    }
6891
6890
    for ( ; embedding ; embedding= embedding->embedding)
6892
6891
    {
6893
6892
      /* Ignore sj-nests: */
6896
6895
      nested_join_st *nested_join= embedding->nested_join;
6897
6896
      if (!nested_join->counter_)
6898
6897
      {
6899
 
        /* 
 
6898
        /*
6900
6899
          Table tab is the first inner table for nested_join.
6901
6900
          Save reference to it in the nested join structure.
6902
 
        */ 
 
6901
        */
6903
6902
        nested_join->first_nested= tab;
6904
6903
        tab->on_expr_ref= &embedding->on_expr;
6905
6904
        tab->cond_equal= tbl->cond_equal;
6906
6905
        if (embedding->embedding)
6907
6906
          tab->first_upper= embedding->embedding->nested_join->first_nested;
6908
6907
      }
6909
 
      if (!tab->first_inner)  
 
6908
      if (!tab->first_inner)
6910
6909
        tab->first_inner= nested_join->first_nested;
6911
6910
      if (++nested_join->counter_ < nested_join->join_list.elements)
6912
6911
        break;
6921
6920
static bool
6922
6921
make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
6923
6922
{
6924
 
  THD *thd= join->thd;
 
6923
  Session *session= join->session;
6925
6924
  if (select)
6926
6925
  {
6927
6926
    add_not_null_conds(join);
6928
6927
    table_map used_tables;
6929
6928
    if (cond)                /* Because of QUICK_GROUP_MIN_MAX_SELECT */
6930
 
    {                        /* there may be a select without a cond. */    
 
6929
    {                        /* there may be a select without a cond. */
6931
6930
      if (join->tables > 1)
6932
6931
        cond->update_used_tables();             // Tablenr may have changed
6933
6932
      if (join->const_tables == join->tables &&
6934
 
          thd->lex->current_select->master_unit() ==
6935
 
          &thd->lex->unit)              // not upper level SELECT
 
6933
          session->lex->current_select->master_unit() ==
 
6934
          &session->lex->unit)          // not upper level SELECT
6936
6935
        join->const_table_map|=RAND_TABLE_BIT;
6937
6936
      {                                         // Check const tables
6938
6937
        COND *const_cond=
6960
6959
            if (!cond_tab->select_cond)
6961
6960
              return(1);
6962
6961
            cond_tab->select_cond->quick_fix_field();
6963
 
          }       
 
6962
          }
6964
6963
        }
6965
6964
        if (const_cond && !const_cond->val_int())
6966
6965
        {
6977
6976
        first_inner is the X in queries like:
6978
6977
        SELECT * FROM t1 LEFT OUTER JOIN (t2 JOIN t3) ON X
6979
6978
      */
6980
 
      JOIN_TAB *first_inner_tab= tab->first_inner; 
 
6979
      JOIN_TAB *first_inner_tab= tab->first_inner;
6981
6980
      table_map current_map= tab->table->map;
6982
6981
      bool use_quick_range=0;
6983
6982
      COND *tmp;
6991
6990
      used_tables|=current_map;
6992
6991
 
6993
6992
      if (tab->type == JT_REF && tab->quick &&
6994
 
          (uint) tab->ref.key == tab->quick->index &&
 
6993
          (uint32_t) tab->ref.key == tab->quick->index &&
6995
6994
          tab->ref.key_length < tab->quick->max_used_key_length)
6996
6995
      {
6997
6996
        /* Range uses longer key;  Use this instead of ref on key */
7001
7000
        tab->ref.key= -1;
7002
7001
        tab->ref.key_parts=0;           // Don't use ref key.
7003
7002
        join->best_positions[i].records_read= rows2double(tab->quick->records);
7004
 
        /* 
 
7003
        /*
7005
7004
          We will use join cache here : prevent sorting of the first
7006
7005
          table only and sort at the end.
7007
7006
        */
7039
7038
          tab->type == JT_EQ_REF)
7040
7039
      {
7041
7040
        SQL_SELECT *sel= tab->select= ((SQL_SELECT*)
7042
 
                                       thd->memdup((unsigned char*) select,
 
7041
                                       session->memdup((unsigned char*) select,
7043
7042
                                                   sizeof(*select)));
7044
7043
        if (!sel)
7045
7044
          return(1);                    // End of memory
7048
7047
          add a match guard to the pushed down predicate.
7049
7048
          The guard will turn the predicate on only after
7050
7049
          the first match for outer tables is encountered.
7051
 
        */        
 
7050
        */
7052
7051
        if (cond && tmp)
7053
7052
        {
7054
7053
          /*
7061
7060
          /* Push condition to storage engine if this is enabled
7062
7061
             and the condition is not guarded */
7063
7062
          tab->table->file->pushed_cond= NULL;
7064
 
          if (thd->variables.engine_condition_pushdown)
 
7063
          if (session->variables.engine_condition_pushdown)
7065
7064
          {
7066
 
            COND *push_cond= 
 
7065
            COND *push_cond=
7067
7066
              make_cond_for_table(tmp, current_map, current_map, 0);
7068
7067
            if (push_cond)
7069
7068
            {
7081
7080
        {
7082
7081
          /* Use quick key read if it's a constant and it's not used
7083
7082
             with key reading */
7084
 
          if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
7085
 
              && (tab->type != JT_REF || (uint) tab->ref.key == tab->quick->index))
 
7083
          if (tab->needed_reg.none() && tab->type != JT_EQ_REF
 
7084
              && (tab->type != JT_REF || (uint32_t) tab->ref.key == tab->quick->index))
7086
7085
          {
7087
7086
            sel->quick=tab->quick;              // Use value from get_quick_...
7088
 
            sel->quick_keys.clear_all();
7089
 
            sel->needed_reg.clear_all();
 
7087
            sel->quick_keys.reset();
 
7088
            sel->needed_reg.reset();
7090
7089
          }
7091
7090
          else
7092
7091
          {
7094
7093
          }
7095
7094
          tab->quick=0;
7096
7095
        }
7097
 
        uint32_t ref_key=(uint) sel->head->reginfo.join_tab->ref.key+1;
 
7096
        uint32_t ref_key=(uint32_t) sel->head->reginfo.join_tab->ref.key+1;
7098
7097
        if (i == join->const_tables && ref_key)
7099
7098
        {
7100
 
          if (!tab->const_keys.is_clear_all() &&
 
7099
          if (tab->const_keys.any() &&
7101
7100
              tab->table->reginfo.impossible_range)
7102
7101
            return(1);
7103
7102
        }
7104
7103
        else if (tab->type == JT_ALL && ! use_quick_range)
7105
7104
        {
7106
 
          if (!tab->const_keys.is_clear_all() &&
 
7105
          if (tab->const_keys.any() &&
7107
7106
              tab->table->reginfo.impossible_range)
7108
7107
            return(1);                          // Impossible range
7109
7108
          /*
7113
7112
            the index if we are using limit and this is the first table
7114
7113
          */
7115
7114
 
7116
 
          if ((cond && (!tab->keys.is_subset(tab->const_keys) && i > 0)) ||
7117
 
              (!tab->const_keys.is_clear_all() && (i == join->const_tables) && (join->unit->select_limit_cnt < join->best_positions[i].records_read) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
 
7115
          if ((cond && (!((tab->keys & tab->const_keys) == tab->keys) && i > 0)) ||
 
7116
              (!tab->const_keys.none() && (i == join->const_tables) && (join->unit->select_limit_cnt < join->best_positions[i].records_read) && ((join->select_options & OPTION_FOUND_ROWS) == false)))
7118
7117
          {
7119
7118
            /* Join with outer join condition */
7120
7119
            COND *orig_cond=sel->cond;
7130
7129
            if (sel->cond && !sel->cond->fixed)
7131
7130
              sel->cond->quick_fix_field();
7132
7131
 
7133
 
            if (sel->test_quick_select(thd, tab->keys,
 
7132
            if (sel->test_quick_select(session, tab->keys,
7134
7133
                                       used_tables & ~ current_map,
7135
7134
                                       (join->select_options &
7136
7135
                                        OPTION_FOUND_ROWS ?
7144
7143
              */
7145
7144
              sel->cond=orig_cond;
7146
7145
              if (!*tab->on_expr_ref ||
7147
 
                  sel->test_quick_select(thd, tab->keys,
 
7146
                  sel->test_quick_select(session, tab->keys,
7148
7147
                                         used_tables & ~ current_map,
7149
7148
                                         (join->select_options &
7150
7149
                                          OPTION_FOUND_ROWS ?
7163
7162
          else
7164
7163
          {
7165
7164
            sel->needed_reg=tab->needed_reg;
7166
 
            sel->quick_keys.clear_all();
 
7165
            sel->quick_keys.reset();
7167
7166
          }
7168
 
          if (!sel->quick_keys.is_subset(tab->checked_keys) ||
7169
 
              !sel->needed_reg.is_subset(tab->checked_keys))
 
7167
          if (!((tab->checked_keys & sel->quick_keys) == sel->quick_keys) ||
 
7168
              !((tab->checked_keys & sel->needed_reg) == sel->needed_reg))
7170
7169
          {
7171
 
            tab->keys=sel->quick_keys;
7172
 
            tab->keys.merge(sel->needed_reg);
7173
 
            tab->use_quick= (!sel->needed_reg.is_clear_all() &&
7174
 
                             (select->quick_keys.is_clear_all() ||
 
7170
            tab->keys= sel->quick_keys;
 
7171
            tab->keys|= sel->needed_reg;
 
7172
            tab->use_quick= (!sel->needed_reg.none() &&
 
7173
                             (select->quick_keys.none() ||
7175
7174
                              (select->quick &&
7176
7175
                               (select->quick->records >= 100L)))) ?
7177
7176
              2 : 1;
7186
7185
                                         current_map, 0)))
7187
7186
            {
7188
7187
              tab->cache.select=(SQL_SELECT*)
7189
 
                thd->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
 
7188
                session->memdup((unsigned char*) sel, sizeof(SQL_SELECT));
7190
7189
              tab->cache.select->cond=tmp;
7191
7190
              tab->cache.select->read_tables=join->const_table_map;
7192
7191
            }
7193
7192
          }
7194
7193
        }
7195
7194
      }
7196
 
      
7197
 
      /* 
 
7195
 
 
7196
      /*
7198
7197
        Push down conditions from all on expressions.
7199
7198
        Each of these conditions are guarded by a variable
7200
7199
        that turns if off just before null complemented row for
7201
7200
        outer joins is formed. Thus, the condition from an
7202
7201
        'on expression' are guaranteed not to be checked for
7203
7202
        the null complemented row.
7204
 
      */ 
 
7203
      */
7205
7204
 
7206
7205
      /* First push down constant conditions from on expressions */
7207
7206
      for (JOIN_TAB *join_tab= join->join_tab+join->const_tables;
7210
7209
        if (*join_tab->on_expr_ref)
7211
7210
        {
7212
7211
          JOIN_TAB *cond_tab= join_tab->first_inner;
7213
 
          COND *tmp= make_cond_for_table(*join_tab->on_expr_ref,
7214
 
                                         join->const_table_map,
7215
 
                                         (table_map) 0, 0);
 
7212
          tmp= make_cond_for_table(*join_tab->on_expr_ref,
 
7213
                                   join->const_table_map,
 
7214
                                   (table_map) 0, 0);
7216
7215
          if (!tmp)
7217
7216
            continue;
7218
7217
          tmp= new Item_func_trig_cond(tmp, &cond_tab->not_null_compl);
7224
7223
          if (!cond_tab->select_cond)
7225
7224
            return(1);
7226
7225
          cond_tab->select_cond->quick_fix_field();
7227
 
        }       
 
7226
        }
7228
7227
      }
7229
7228
 
7230
7229
      /* Push down non-constant conditions from on expressions */
7231
7230
      JOIN_TAB *last_tab= tab;
7232
7231
      while (first_inner_tab && first_inner_tab->last_inner == last_tab)
7233
 
      {  
7234
 
        /* 
 
7232
      {
 
7233
        /*
7235
7234
          Table tab is the last inner table of an outer join.
7236
7235
          An on expression is always attached to it.
7237
 
        */     
 
7236
        */
7238
7237
        COND *on_expr= *first_inner_tab->on_expr_ref;
7239
7238
 
7240
7239
        table_map used_tables2= (join->const_table_map |
7256
7255
                                                     tmp_cond,
7257
7256
                                                     first_inner_tab)))
7258
7257
              return(1);
7259
 
            /* 
7260
 
              Now add the guard turning the predicate off for 
 
7258
            /*
 
7259
              Now add the guard turning the predicate off for
7261
7260
              the null complemented row.
7262
 
            */ 
 
7261
            */
7263
7262
            tmp_cond= new Item_func_trig_cond(tmp_cond,
7264
7263
                                              &first_inner_tab->
7265
7264
                                              not_null_compl);
7272
7271
            if (!cond_tab->select_cond)
7273
7272
              return(1);
7274
7273
            cond_tab->select_cond->quick_fix_field();
7275
 
          }              
 
7274
          }
7276
7275
        }
7277
 
        first_inner_tab= first_inner_tab->first_upper;       
 
7276
        first_inner_tab= first_inner_tab->first_upper;
7278
7277
      }
7279
7278
    }
7280
7279
  }
7282
7281
}
7283
7282
 
7284
7283
 
7285
 
/* 
 
7284
/*
7286
7285
  Check if given expression uses only table fields covered by the given index
7287
7286
 
7288
7287
  SYNOPSIS
7295
7294
  DESCRIPTION
7296
7295
    Check if given expression only uses fields covered by index #keyno in the
7297
7296
    table tbl. The expression can use any fields in any other tables.
7298
 
    
7299
 
    The expression is guaranteed not to be AND or OR - those constructs are 
 
7297
 
 
7298
    The expression is guaranteed not to be AND or OR - those constructs are
7300
7299
    handled outside of this function.
7301
7300
 
7302
7301
  RETURN
7304
7303
    false  No
7305
7304
*/
7306
7305
 
7307
 
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, 
 
7306
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno,
7308
7307
                            bool other_tbls_ok)
7309
7308
{
7310
7309
  if (item->const_item())
7311
7310
    return true;
7312
7311
 
7313
 
  /* 
7314
 
    Don't push down the triggered conditions. Nested outer joins execution 
 
7312
  /*
 
7313
    Don't push down the triggered conditions. Nested outer joins execution
7315
7314
    code may need to evaluate a condition several times (both triggered and
7316
7315
    untriggered), and there is no way to put thi
7317
7316
    TODO: Consider cloning the triggered condition and using the copies for:
7318
7317
      1. push the first copy down, to have most restrictive index condition
7319
7318
         possible
7320
 
      2. Put the second copy into tab->select_cond. 
 
7319
      2. Put the second copy into tab->select_cond.
7321
7320
  */
7322
 
  if (item->type() == Item::FUNC_ITEM && 
 
7321
  if (item->type() == Item::FUNC_ITEM &&
7323
7322
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
7324
7323
    return false;
7325
7324
 
7345
7344
    {
7346
7345
      /* This is a function, apply condition recursively to arguments */
7347
7346
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
7348
 
      Item *item;
7349
 
      while ((item=li++))
 
7347
      Item *list_item;
 
7348
      while ((list_item=li++))
7350
7349
      {
7351
7350
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
7352
7351
          return false;
7356
7355
  case Item::FIELD_ITEM:
7357
7356
    {
7358
7357
      Item_field *item_field= (Item_field*)item;
7359
 
      if (item_field->field->table != tbl) 
 
7358
      if (item_field->field->table != tbl)
7360
7359
        return true;
7361
 
      return item_field->field->part_of_key.is_set(keyno);
 
7360
      return item_field->field->part_of_key.test(keyno);
7362
7361
    }
7363
7362
  case Item::REF_ITEM:
7364
7363
    return uses_index_fields_only(item->real_item(), tbl, keyno,
7383
7382
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
7384
7383
 
7385
7384
  DESCRIPTION
7386
 
    Get a part of the condition that can be checked when for the given table 
 
7385
    Get a part of the condition that can be checked when for the given table
7387
7386
    we have values only of fields covered by some index. The condition may
7388
 
    refer to other tables, it is assumed that we have values of all of their 
 
7387
    refer to other tables, it is assumed that we have values of all of their
7389
7388
    fields.
7390
7389
 
7391
7390
    Example:
7392
7391
      make_cond_for_index(
7393
7392
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
7394
 
          t2, keyno(t2.key1)) 
 
7393
          t2, keyno(t2.key1))
7395
7394
      will return
7396
7395
        "cond(t1.field) AND cond(t2.key2)"
7397
7396
 
7542
7541
{
7543
7542
  Item *idx_cond;
7544
7543
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
7545
 
      tab->join->thd->variables.engine_condition_pushdown)
 
7544
      tab->join->session->variables.engine_condition_pushdown)
7546
7545
  {
7547
7546
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
7548
7547
                                  other_tbls_ok);
7550
7549
    if (idx_cond)
7551
7550
    {
7552
7551
      tab->pre_idx_push_select_cond= tab->select_cond;
7553
 
      Item *idx_remainder_cond= 
 
7552
      Item *idx_remainder_cond=
7554
7553
        tab->table->file->idx_cond_push(keyno, idx_cond);
7555
7554
 
7556
7555
      /*
7557
7556
        Disable eq_ref's "lookup cache" if we've pushed down an index
7558
 
        condition. 
 
7557
        condition.
7559
7558
        TODO: This check happens to work on current ICP implementations, but
7560
 
        there may exist a compliant implementation that will not work 
 
7559
        there may exist a compliant implementation that will not work
7561
7560
        correctly with it. Sort this out when we stabilize the condition
7562
7561
        pushdown APIs.
7563
7562
      */
7574
7573
        {
7575
7574
          tab->select_cond= new Item_cond_and(row_cond, idx_remainder_cond);
7576
7575
          tab->select_cond->quick_fix_field();
7577
 
          ((Item_cond_and*)tab->select_cond)->used_tables_cache= 
 
7576
          ((Item_cond_and*)tab->select_cond)->used_tables_cache=
7578
7577
            row_cond->used_tables() | idx_remainder_cond->used_tables();
7579
7578
        }
7580
7579
      }
7592
7591
 
7593
7592
 
7594
7593
    /*
7595
 
      Determine if the set is already ordered for order_st BY, so it can 
 
7594
      Determine if the set is already ordered for order_st BY, so it can
7596
7595
      disable join cache because it will change the ordering of the results.
7597
 
      Code handles sort table that is at any location (not only first after 
 
7596
      Code handles sort table that is at any location (not only first after
7598
7597
      the const tables) despite the fact that it's currently prohibited.
7599
7598
      We must disable join cache if the first non-const table alone is
7600
7599
      ordered. If there is a temp table the ordering is done as a last
7610
7609
  {
7611
7610
    JOIN_TAB *tab=join->join_tab+i;
7612
7611
    Table *table=tab->table;
7613
 
    if ((table == join->sort_by_table && 
 
7612
    if ((table == join->sort_by_table &&
7614
7613
         (!join->order || join->skip_sort_order)) ||
7615
7614
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
7616
7615
    {
7627
7626
  SYNOPSIS
7628
7627
    make_join_readinfo()
7629
7628
      join           Join being processed
7630
 
      options        Join's options (checking for SELECT_DESCRIBE, 
 
7629
      options        Join's options (checking for SELECT_DESCRIBE,
7631
7630
                     SELECT_NO_JOIN_CACHE)
7632
7631
      no_jbuf_after  Don't use join buffering after table with this number.
7633
7632
 
7638
7637
      - increment counters
7639
7638
      - etc
7640
7639
 
7641
 
  RETURN 
 
7640
  RETURN
7642
7641
    false - OK
7643
7642
    true  - Out of memory
7644
7643
*/
7658
7657
    tab->read_record.table= table;
7659
7658
    tab->read_record.file=table->file;
7660
7659
    tab->next_select=sub_select;                /* normal select */
7661
 
    /* 
7662
 
      TODO: don't always instruct first table's ref/range access method to 
 
7660
    /*
 
7661
      TODO: don't always instruct first table's ref/range access method to
7663
7662
      produce sorted output.
7664
7663
    */
7665
7664
    tab->sorted= sorted;
7666
7665
    sorted= 0;                                  // only first must be sorted
7667
7666
    if (tab->insideout_match_tab)
7668
7667
    {
7669
 
      if (!(tab->insideout_buf= (unsigned char*)join->thd->alloc(tab->table->key_info
 
7668
      if (!(tab->insideout_buf= (unsigned char*)join->session->alloc(tab->table->key_info
7670
7669
                                                         [tab->index].
7671
7670
                                                         key_length)))
7672
7671
        return true;
7681
7680
      table->status=STATUS_NO_RECORD;
7682
7681
      tab->read_first_record= join_read_const;
7683
7682
      tab->read_record.read_record= join_no_more_records;
7684
 
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7683
      if (table->covering_keys.test(tab->ref.key) &&
7685
7684
          !table->no_keyread)
7686
7685
      {
7687
7686
        table->key_read=1;
7699
7698
      tab->quick=0;
7700
7699
      tab->read_first_record= join_read_key;
7701
7700
      tab->read_record.read_record= join_no_more_records;
7702
 
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7701
      if (table->covering_keys.test(tab->ref.key) &&
7703
7702
          !table->no_keyread)
7704
7703
      {
7705
7704
        table->key_read=1;
7718
7717
      }
7719
7718
      delete tab->quick;
7720
7719
      tab->quick=0;
7721
 
      if (table->covering_keys.is_set(tab->ref.key) &&
 
7720
      if (table->covering_keys.test(tab->ref.key) &&
7722
7721
          !table->no_keyread)
7723
7722
      {
7724
7723
        table->key_read=1;
7729
7728
      if (tab->type == JT_REF)
7730
7729
      {
7731
7730
        tab->read_first_record= join_read_always_key;
7732
 
        tab->read_record.read_record= tab->insideout_match_tab? 
 
7731
        tab->read_record.read_record= tab->insideout_match_tab?
7733
7732
           join_read_next_same_diff : join_read_next_same;
7734
7733
      }
7735
7734
      else
7750
7749
          !tab->insideout_match_tab)
7751
7750
      {
7752
7751
        if ((options & SELECT_DESCRIBE) ||
7753
 
            !join_init_cache(join->thd,join->join_tab+join->const_tables,
 
7752
            !join_init_cache(join->session,join->join_tab+join->const_tables,
7754
7753
                             i-join->const_tables))
7755
7754
        {
7756
7755
          using_join_cache= true;
7760
7759
      /* These init changes read_record */
7761
7760
      if (tab->use_quick == 2)
7762
7761
      {
7763
 
        join->thd->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
 
7762
        join->session->server_status|=SERVER_QUERY_NO_GOOD_INDEX_USED;
7764
7763
        tab->read_first_record= join_init_quick_read_record;
7765
7764
        if (statistics)
7766
 
          status_var_increment(join->thd->status_var.select_range_check_count);
 
7765
          status_var_increment(join->session->status_var.select_range_check_count);
7767
7766
      }
7768
7767
      else
7769
7768
      {
7773
7772
          if (tab->select && tab->select->quick)
7774
7773
          {
7775
7774
            if (statistics)
7776
 
              status_var_increment(join->thd->status_var.select_range_count);
 
7775
              status_var_increment(join->session->status_var.select_range_count);
7777
7776
          }
7778
7777
          else
7779
7778
          {
7780
 
            join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7779
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
7781
7780
            if (statistics)
7782
 
              status_var_increment(join->thd->status_var.select_scan_count);
 
7781
              status_var_increment(join->session->status_var.select_scan_count);
7783
7782
          }
7784
7783
        }
7785
7784
        else
7787
7786
          if (tab->select && tab->select->quick)
7788
7787
          {
7789
7788
            if (statistics)
7790
 
              status_var_increment(join->thd->status_var.select_full_range_join_count);
 
7789
              status_var_increment(join->session->status_var.select_full_range_join_count);
7791
7790
          }
7792
7791
          else
7793
7792
          {
7794
 
            join->thd->server_status|=SERVER_QUERY_NO_INDEX_USED;
 
7793
            join->session->server_status|=SERVER_QUERY_NO_INDEX_USED;
7795
7794
            if (statistics)
7796
 
              status_var_increment(join->thd->status_var.select_full_join_count);
 
7795
              status_var_increment(join->session->status_var.select_full_join_count);
7797
7796
          }
7798
7797
        }
7799
7798
        if (!table->no_keyread)
7800
7799
        {
7801
7800
          if (tab->select && tab->select->quick &&
7802
7801
              tab->select->quick->index != MAX_KEY && //not index_merge
7803
 
              table->covering_keys.is_set(tab->select->quick->index))
 
7802
              table->covering_keys.test(tab->select->quick->index))
7804
7803
          {
7805
7804
            table->key_read=1;
7806
7805
            table->file->extra(HA_EXTRA_KEYREAD);
7807
7806
          }
7808
 
          else if (!table->covering_keys.is_clear_all() &&
 
7807
          else if (!table->covering_keys.none() &&
7809
7808
                   !(tab->select && tab->select->quick))
7810
7809
          {                                     // Only read index tree
7811
7810
            if (!tab->insideout_match_tab)
7949
7948
 
7950
7949
void JOIN::join_free()
7951
7950
{
7952
 
  SELECT_LEX_UNIT *tmp_unit;
7953
 
  SELECT_LEX *sl;
 
7951
  Select_Lex_Unit *tmp_unit;
 
7952
  Select_Lex *sl;
7954
7953
  /*
7955
7954
    Optimization: if not EXPLAIN and we are done with the JOIN,
7956
7955
    free all tables.
7957
7956
  */
7958
 
  bool full= (!select_lex->uncacheable && !thd->lex->describe);
 
7957
  bool full= (!select_lex->uncacheable && !session->lex->describe);
7959
7958
  bool can_unlock= full;
7960
7959
 
7961
7960
  cleanup(full);
7985
7984
    We are not using tables anymore
7986
7985
    Unlock all tables. We may be in an INSERT .... SELECT statement.
7987
7986
  */
7988
 
  if (can_unlock && lock && thd->lock &&
 
7987
  if (can_unlock && lock && session->lock &&
7989
7988
      !(select_options & SELECT_NO_UNLOCK) &&
7990
7989
      !select_lex->subquery_in_having &&
7991
 
      (select_lex == (thd->lex->unit.fake_select_lex ?
7992
 
                      thd->lex->unit.fake_select_lex : &thd->lex->select_lex)))
 
7990
      (select_lex == (session->lex->unit.fake_select_lex ?
 
7991
                      session->lex->unit.fake_select_lex : &session->lex->select_lex)))
7993
7992
  {
7994
7993
    /*
7995
7994
      TODO: unlock tables even if the join isn't top level select in the
7996
7995
      tree.
7997
7996
    */
7998
 
    mysql_unlock_read_tables(thd, lock);           // Don't free join->lock
 
7997
    mysql_unlock_read_tables(session, lock);           // Don't free join->lock
7999
7998
    lock= 0;
8000
7999
  }
8001
8000
 
8236
8235
*/
8237
8236
 
8238
8237
static order_st *
8239
 
remove_const(JOIN *join,order_st *first_order, COND *cond,
8240
 
             bool change_list, bool *simple_order)
 
8238
remove_constants(JOIN *join,order_st *first_order, COND *cond,
 
8239
                 bool change_list, bool *simple_order)
8241
8240
{
8242
8241
  if (join->tables == join->const_tables)
8243
8242
    return change_list ? 0 : first_order;               // No need to sort
8314
8313
  if (send_row)
8315
8314
  {
8316
8315
    for (TableList *table= tables; table; table= table->next_leaf)
8317
 
      mark_as_null_row(table->table);           // All fields are NULL
 
8316
      table->table->mark_as_null_row();         // All fields are NULL
8318
8317
    if (having && having->val_int() == 0)
8319
8318
      send_row=0;
8320
8319
  }
8332
8331
    result->send_eof();                         // Should be safe
8333
8332
  }
8334
8333
  /* Update results for FOUND_ROWS */
8335
 
  join->thd->limit_found_rows= join->thd->examined_row_count= 0;
 
8334
  join->session->limit_found_rows= join->session->examined_row_count= 0;
8336
8335
  return(0);
8337
8336
}
8338
8337
 
8341
8340
*/
8342
8341
static void clear_tables(JOIN *join)
8343
8342
{
8344
 
  /* 
 
8343
  /*
8345
8344
    must clear only the non-const tables, as const tables
8346
8345
    are not re-calculated.
8347
8346
  */
8348
8347
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
8349
 
    mark_as_null_row(join->table[i]);           // All fields are NULL
 
8348
    join->table[i]->mark_as_null_row();         // All fields are NULL
8350
8349
}
8351
8350
 
8352
8351
/*****************************************************************************
8362
8361
public:
8363
8362
  static void *operator new(size_t size)
8364
8363
  {
8365
 
    return (void*) sql_alloc((uint) size);
 
8364
    return (void*) sql_alloc((uint32_t) size);
8366
8365
  }
8367
 
  static void operator delete(void *ptr __attribute__((unused)),
8368
 
                              size_t size __attribute__((unused)))
 
8366
  static void operator delete(void *, size_t)
8369
8367
  { TRASH(ptr, size); }
8370
8368
 
8371
8369
  Item *and_level;
8420
8418
  return item;
8421
8419
}
8422
8420
 
8423
 
  
 
8421
 
8424
8422
/**
8425
8423
  Check whether an equality can be used to build multiple equalities.
8426
8424
 
8447
8445
    the check_equality will be called for the following equality
8448
8446
    predicates a=b, b=c, b=2 and f=e.
8449
8447
    - For a=b it will be called with *cond_equal=(0,[]) and will transform
8450
 
      *cond_equal into (0,[Item_equal(a,b)]). 
 
8448
      *cond_equal into (0,[Item_equal(a,b)]).
8451
8449
    - For b=c it will be called with *cond_equal=(0,[Item_equal(a,b)])
8452
8450
      and will transform *cond_equal into CE=(0,[Item_equal(a,b,c)]).
8453
8451
    - For b=2 it will be called with *cond_equal=(ptr(CE),[])
8460
8458
    the Field::eq_def method) are placed to the same multiple equalities.
8461
8459
    Because of this some equality predicates are not eliminated and
8462
8460
    can be used in the constant propagation procedure.
8463
 
    We could weeken the equlity test as soon as at least one of the 
8464
 
    equal fields is to be equal to a constant. It would require a 
 
8461
    We could weeken the equlity test as soon as at least one of the
 
8462
    equal fields is to be equal to a constant. It would require a
8465
8463
    more complicated implementation: we would have to store, in
8466
8464
    general case, its own constant for each fields from the multiple
8467
8465
    equality. But at the same time it would allow us to get rid
8479
8477
    containing just field1 and field2 is added to the existing
8480
8478
    multiple equalities.
8481
8479
    If the function processes the predicate of the form field1=const,
8482
 
    it looks for a multiple equality containing field1. If found, the 
 
8480
    it looks for a multiple equality containing field1. If found, the
8483
8481
    function checks the constant of the multiple equality. If the value
8484
8482
    is unknown, it is setup to const. Otherwise the value is compared with
8485
8483
    const and the evaluation of the equality predicate is performed.
8506
8504
static bool check_simple_equality(Item *left_item, Item *right_item,
8507
8505
                                  Item *item, COND_EQUAL *cond_equal)
8508
8506
{
8509
 
  if (left_item->type() == Item::REF_ITEM &&
8510
 
      ((Item_ref*)left_item)->ref_type() == Item_ref::VIEW_REF)
8511
 
  {
8512
 
    if (((Item_ref*)left_item)->depended_from)
8513
 
      return false;
8514
 
    left_item= left_item->real_item();
8515
 
  }
8516
 
  if (right_item->type() == Item::REF_ITEM &&
8517
 
      ((Item_ref*)right_item)->ref_type() == Item_ref::VIEW_REF)
8518
 
  {
8519
 
    if (((Item_ref*)right_item)->depended_from)
8520
 
      return false;
8521
 
    right_item= right_item->real_item();
8522
 
  }
8523
8507
  if (left_item->type() == Item::FIELD_ITEM &&
8524
8508
      right_item->type() == Item::FIELD_ITEM &&
8525
8509
      !((Item_field*)left_item)->depended_from &&
8537
8521
    bool left_copyfl, right_copyfl;
8538
8522
    Item_equal *left_item_equal=
8539
8523
               find_item_equal(cond_equal, left_field, &left_copyfl);
8540
 
    Item_equal *right_item_equal= 
 
8524
    Item_equal *right_item_equal=
8541
8525
               find_item_equal(cond_equal, right_field, &right_copyfl);
8542
8526
 
8543
8527
    /* As (NULL=NULL) != true we can't just remove the predicate f=f */
8544
8528
    if (left_field->eq(right_field)) /* f = f */
8545
 
      return (!(left_field->maybe_null() && !left_item_equal)); 
 
8529
      return (!(left_field->maybe_null() && !left_item_equal));
8546
8530
 
8547
8531
    if (left_item_equal && left_item_equal == right_item_equal)
8548
8532
    {
8549
 
      /* 
 
8533
      /*
8550
8534
        The equality predicate is inference of one of the existing
8551
8535
        multiple equalities, i.e the condition is already covered
8552
8536
        by upper level equalities
8553
8537
      */
8554
8538
       return true;
8555
8539
    }
8556
 
    
8557
 
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name && 
 
8540
 
 
8541
    bool copy_item_name= test(item && item->name >= subq_sj_cond_name &&
8558
8542
                              item->name < subq_sj_cond_name + 64);
8559
8543
    /* Copy the found multiple equalities at the current level if needed */
8560
8544
    if (left_copyfl)
8575
8559
    }
8576
8560
 
8577
8561
    if (left_item_equal)
8578
 
    { 
 
8562
    {
8579
8563
      /* left item was found in the current or one of the upper levels */
8580
8564
      if (! right_item_equal)
8581
8565
        left_item_equal->add((Item_field *) right_item);
8590
8574
      }
8591
8575
    }
8592
8576
    else
8593
 
    { 
 
8577
    {
8594
8578
      /* left item was not found neither the current nor in upper levels  */
8595
8579
      if (right_item_equal)
8596
8580
      {
8598
8582
        if (copy_item_name)
8599
8583
          right_item_equal->name = item->name;
8600
8584
      }
8601
 
      else 
 
8585
      else
8602
8586
      {
8603
8587
        /* None of the fields was found in multiple equalities */
8604
8588
        Item_equal *item_equal= new Item_equal((Item_field *) left_item,
8646
8630
          eq_item->set_cmp_func();
8647
8631
          eq_item->quick_fix_field();
8648
8632
          item= eq_item;
8649
 
        }  
 
8633
        }
8650
8634
        if ((cs != ((Item_func *) item)->compare_collation()) ||
8651
8635
            !cs->coll->propagate(cs, 0, 0))
8652
8636
          return false;
8661
8645
      }
8662
8646
      if (item_equal)
8663
8647
      {
8664
 
        /* 
 
8648
        /*
8665
8649
          The flag cond_false will be set to 1 after this, if item_equal
8666
8650
          already contains a constant and its value is  not equal to
8667
8651
          the value of const_item.
8692
8676
    simple equality nor a row equality the item for this predicate is added
8693
8677
    to eq_list.
8694
8678
 
8695
 
  @param thd        thread handle
 
8679
  @param session        thread handle
8696
8680
  @param left_row   left term of the row equality to be processed
8697
8681
  @param right_row  right term of the row equality to be processed
8698
8682
  @param cond_equal multiple equalities that must hold together with the
8705
8689
  @retval
8706
8690
    false   otherwise
8707
8691
*/
8708
 
 
8709
 
static bool check_row_equality(THD *thd, Item *left_row, Item_row *right_row,
 
8692
 
 
8693
static bool check_row_equality(Session *session, Item *left_row, Item_row *right_row,
8710
8694
                               COND_EQUAL *cond_equal, List<Item>* eq_list)
8711
 
 
8695
{
8712
8696
  uint32_t n= left_row->cols();
8713
8697
  for (uint32_t i= 0 ; i < n; i++)
8714
8698
  {
8718
8702
    if (left_item->type() == Item::ROW_ITEM &&
8719
8703
        right_item->type() == Item::ROW_ITEM)
8720
8704
    {
8721
 
      is_converted= check_row_equality(thd, 
 
8705
      is_converted= check_row_equality(session,
8722
8706
                                       (Item_row *) left_item,
8723
8707
                                       (Item_row *) right_item,
8724
8708
                                       cond_equal, eq_list);
8725
8709
      if (!is_converted)
8726
 
        thd->lex->current_select->cond_count++;      
 
8710
        session->lex->current_select->cond_count++;
8727
8711
    }
8728
8712
    else
8729
 
    { 
 
8713
    {
8730
8714
      is_converted= check_simple_equality(left_item, right_item, 0, cond_equal);
8731
 
      thd->lex->current_select->cond_count++;
8732
 
    }  
8733
 
 
 
8715
      session->lex->current_select->cond_count++;
 
8716
    }
 
8717
 
8734
8718
    if (!is_converted)
8735
8719
    {
8736
8720
      Item_func_eq *eq_item;
8759
8743
    equalities which are treated in the same way as original equality
8760
8744
    predicates.
8761
8745
 
8762
 
  @param thd        thread handle
 
8746
  @param session        thread handle
8763
8747
  @param item       predicate to process
8764
8748
  @param cond_equal multiple equalities that must hold together with the
8765
8749
                    predicate
8775
8759
           or, if the procedure fails by a fatal error.
8776
8760
*/
8777
8761
 
8778
 
static bool check_equality(THD *thd, Item *item, COND_EQUAL *cond_equal,
 
8762
static bool check_equality(Session *session, Item *item, COND_EQUAL *cond_equal,
8779
8763
                           List<Item> *eq_list)
8780
8764
{
8781
8765
  if (item->type() == Item::FUNC_ITEM &&
8787
8771
    if (left_item->type() == Item::ROW_ITEM &&
8788
8772
        right_item->type() == Item::ROW_ITEM)
8789
8773
    {
8790
 
      thd->lex->current_select->cond_count--;
8791
 
      return check_row_equality(thd,
 
8774
      session->lex->current_select->cond_count--;
 
8775
      return check_row_equality(session,
8792
8776
                                (Item_row *) left_item,
8793
8777
                                (Item_row *) right_item,
8794
8778
                                cond_equal, eq_list);
8795
8779
    }
8796
 
    else 
 
8780
    else
8797
8781
      return check_simple_equality(left_item, right_item, item, cond_equal);
8798
 
  } 
 
8782
  }
8799
8783
  return false;
8800
8784
}
8801
8785
 
8802
 
                          
 
8786
 
8803
8787
/**
8804
8788
  Replace all equality predicates in a condition by multiple equality items.
8805
8789
 
8806
8790
    At each 'and' level the function detects items for equality predicates
8807
8791
    and replaced them by a set of multiple equality items of class Item_equal,
8808
 
    taking into account inherited equalities from upper levels. 
 
8792
    taking into account inherited equalities from upper levels.
8809
8793
    If an equality predicate is used not in a conjunction it's just
8810
8794
    replaced by a multiple equality predicate.
8811
8795
    For each 'and' level the function set a pointer to the inherited
8812
8796
    multiple equalities in the cond_equal field of the associated
8813
 
    object of the type Item_cond_and.   
 
8797
    object of the type Item_cond_and.
8814
8798
    The function also traverses the cond tree and and for each field reference
8815
8799
    sets a pointer to the multiple equality item containing the field, if there
8816
8800
    is any. If this multiple equality equates fields to a constant the
8817
 
    function replaces the field reference by the constant in the cases 
 
8801
    function replaces the field reference by the constant in the cases
8818
8802
    when the field is not of a string type or when the field reference is
8819
8803
    just an argument of a comparison predicate.
8820
 
    The function also determines the maximum number of members in 
 
8804
    The function also determines the maximum number of members in
8821
8805
    equality lists of each Item_cond_and object assigning it to
8822
 
    thd->lex->current_select->max_equal_elems.
 
8806
    session->lex->current_select->max_equal_elems.
8823
8807
 
8824
8808
  @note
8825
8809
    Multiple equality predicate =(f1,..fn) is equivalent to the conjuction of
8831
8815
    in a conjuction for a minimal set of multiple equality predicates.
8832
8816
    This set can be considered as a canonical representation of the
8833
8817
    sub-conjunction of the equality predicates.
8834
 
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by 
 
8818
    E.g. (t1.a=t2.b AND t2.b>5 AND t1.a=t3.c) is replaced by
8835
8819
    (=(t1.a,t2.b,t3.c) AND t2.b>5), not by
8836
8820
    (=(t1.a,t2.b) AND =(t1.a,t3.c) AND t2.b>5);
8837
8821
    while (t1.a=t2.b AND t2.b>5 AND t3.c=t4.d) is replaced by
8842
8826
    The function performs the substitution in a recursive descent by
8843
8827
    the condtion tree, passing to the next AND level a chain of multiple
8844
8828
    equality predicates which have been built at the upper levels.
8845
 
    The Item_equal items built at the level are attached to other 
 
8829
    The Item_equal items built at the level are attached to other
8846
8830
    non-equality conjucts as a sublist. The pointer to the inherited
8847
8831
    multiple equalities is saved in the and condition object (Item_cond_and).
8848
 
    This chain allows us for any field reference occurence easyly to find a 
 
8832
    This chain allows us for any field reference occurence easyly to find a
8849
8833
    multiple equality that must be held for this occurence.
8850
8834
    For each AND level we do the following:
8851
8835
    - scan it for all equality predicate (=) items
8852
8836
    - join them into disjoint Item_equal() groups
8853
 
    - process the included OR conditions recursively to do the same for 
8854
 
      lower AND levels. 
 
8837
    - process the included OR conditions recursively to do the same for
 
8838
      lower AND levels.
8855
8839
 
8856
8840
    We need to do things in this order as lower AND levels need to know about
8857
8841
    all possible Item_equal objects in upper levels.
8858
8842
 
8859
 
  @param thd        thread handle
 
8843
  @param session        thread handle
8860
8844
  @param cond       condition(expression) where to make replacement
8861
8845
  @param inherited  path to all inherited multiple equality items
8862
8846
 
8864
8848
    pointer to the transformed condition
8865
8849
*/
8866
8850
 
8867
 
static COND *build_equal_items_for_cond(THD *thd, COND *cond,
 
8851
static COND *build_equal_items_for_cond(Session *session, COND *cond,
8868
8852
                                        COND_EQUAL *inherited)
8869
8853
{
8870
8854
  Item_equal *item_equal;
8877
8861
    bool and_level= ((Item_cond*) cond)->functype() ==
8878
8862
      Item_func::COND_AND_FUNC;
8879
8863
    List<Item> *args= ((Item_cond*) cond)->argument_list();
8880
 
    
 
8864
 
8881
8865
    List_iterator<Item> li(*args);
8882
8866
    Item *item;
8883
8867
 
8886
8870
      /*
8887
8871
         Retrieve all conjucts of this level detecting the equality
8888
8872
         that are subject to substitution by multiple equality items and
8889
 
         removing each such predicate from the conjunction after having 
 
8873
         removing each such predicate from the conjunction after having
8890
8874
         found/created a multiple equality whose inference the predicate is.
8891
 
     */      
 
8875
     */
8892
8876
      while ((item= li++))
8893
8877
      {
8894
8878
        /*
8896
8880
          structure here because it's restored before each
8897
8881
          re-execution of any prepared statement/stored procedure.
8898
8882
        */
8899
 
        if (check_equality(thd, item, &cond_equal, &eq_list))
 
8883
        if (check_equality(session, item, &cond_equal, &eq_list))
8900
8884
          li.remove();
8901
8885
      }
8902
8886
 
8905
8889
      {
8906
8890
        item_equal->fix_length_and_dec();
8907
8891
        item_equal->update_used_tables();
8908
 
        set_if_bigger(thd->lex->current_select->max_equal_elems,
8909
 
                      item_equal->members());  
 
8892
        set_if_bigger(session->lex->current_select->max_equal_elems,
 
8893
                      item_equal->members());
8910
8894
      }
8911
8895
 
8912
8896
      ((Item_cond_and*)cond)->cond_equal= cond_equal;
8918
8902
    */
8919
8903
    li.rewind();
8920
8904
    while ((item= li++))
8921
 
    { 
 
8905
    {
8922
8906
      Item *new_item;
8923
 
      if ((new_item= build_equal_items_for_cond(thd, item, inherited)) != item)
 
8907
      if ((new_item= build_equal_items_for_cond(session, item, inherited)) != item)
8924
8908
      {
8925
8909
        /* This replacement happens only for standalone equalities */
8926
8910
        /*
8948
8932
      (b=5) and (a=c) are standalone equalities.
8949
8933
      In general we can't leave alone standalone eqalities:
8950
8934
      for WHERE a=b AND c=d AND (b=c OR d=5)
8951
 
      b=c is replaced by =(a,b,c,d).  
 
8935
      b=c is replaced by =(a,b,c,d).
8952
8936
     */
8953
 
    if (check_equality(thd, cond, &cond_equal, &eq_list))
 
8937
    if (check_equality(session, cond, &cond_equal, &eq_list))
8954
8938
    {
8955
8939
      int n= cond_equal.current_level.elements + eq_list.elements;
8956
8940
      if (n == 0)
8964
8948
        }
8965
8949
        else
8966
8950
          item_equal= (Item_equal *) eq_list.pop();
8967
 
        set_if_bigger(thd->lex->current_select->max_equal_elems,
8968
 
                      item_equal->members());  
 
8951
        set_if_bigger(session->lex->current_select->max_equal_elems,
 
8952
                      item_equal->members());
8969
8953
        return item_equal;
8970
8954
      }
8971
8955
      else
8972
8956
      {
8973
 
        /* 
 
8957
        /*
8974
8958
          Here a new AND level must be created. It can happen only
8975
8959
          when a row equality is processed as a standalone predicate.
8976
8960
        */
8982
8966
        {
8983
8967
          item_equal->fix_length_and_dec();
8984
8968
          item_equal->update_used_tables();
8985
 
          set_if_bigger(thd->lex->current_select->max_equal_elems,
8986
 
                        item_equal->members());  
 
8969
          set_if_bigger(session->lex->current_select->max_equal_elems,
 
8970
                        item_equal->members());
8987
8971
        }
8988
8972
        and_cond->cond_equal= cond_equal;
8989
8973
        args->concat((List<Item> *)&cond_equal.current_level);
8990
 
        
 
8974
 
8991
8975
        return and_cond;
8992
8976
      }
8993
8977
    }
8994
 
    /* 
 
8978
    /*
8995
8979
      For each field reference in cond, not from equal item predicates,
8996
8980
      set a pointer to the multiple equality it belongs to (if there is any)
8997
8981
      as soon the field is not of a string type or the field reference is
8998
 
      an argument of a comparison predicate. 
8999
 
    */ 
 
8982
      an argument of a comparison predicate.
 
8983
    */
9000
8984
    unsigned char *is_subst_valid= (unsigned char *) 1;
9001
8985
    cond= cond->compile(&Item::subst_argument_checker,
9002
 
                        &is_subst_valid, 
 
8986
                        &is_subst_valid,
9003
8987
                        &Item::equal_fields_propagator,
9004
8988
                        (unsigned char *) inherited);
9005
8989
    cond->update_used_tables();
9053
9037
      SELECT * FROM (t1,t2) LEFT JOIN (t3,t4) ON t2.a=t4.a AND t3.a=t4.a
9054
9038
        WHERE t1.a=t2.a
9055
9039
    @endcode
9056
 
    that is equivalent to:   
 
9040
    that is equivalent to:
9057
9041
    @code
9058
9042
      SELECT * FROM (t2 LEFT JOIN (t3,t4)ON t2.a=t4.a AND t3.a=t4.a), t1
9059
9043
        WHERE t1.a=t2.a
9060
9044
    @endcode
9061
9045
    Thus, applying equalities from the where condition we basically
9062
9046
    can get more freedom in performing join operations.
9063
 
    Althogh we don't use this property now, it probably makes sense to use 
9064
 
    it in the future.    
9065
 
  @param thd                  Thread handler
 
9047
    Althogh we don't use this property now, it probably makes sense to use
 
9048
    it in the future.
 
9049
  @param session                      Thread handler
9066
9050
  @param cond                condition to build the multiple equalities for
9067
9051
  @param inherited           path to all inherited multiple equality items
9068
9052
  @param join_list           list of join tables to which the condition
9073
9057
  @return
9074
9058
    pointer to the transformed condition containing multiple equalities
9075
9059
*/
9076
 
   
9077
 
static COND *build_equal_items(THD *thd, COND *cond,
 
9060
 
 
9061
static COND *build_equal_items(Session *session, COND *cond,
9078
9062
                               COND_EQUAL *inherited,
9079
9063
                               List<TableList> *join_list,
9080
9064
                               COND_EQUAL **cond_equal_ref)
9081
9065
{
9082
9066
  COND_EQUAL *cond_equal= 0;
9083
9067
 
9084
 
  if (cond) 
 
9068
  if (cond)
9085
9069
  {
9086
 
    cond= build_equal_items_for_cond(thd, cond, inherited);
 
9070
    cond= build_equal_items_for_cond(session, cond, inherited);
9087
9071
    cond->update_used_tables();
9088
9072
    if (cond->type() == Item::COND_ITEM &&
9089
9073
        ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
9117
9101
          We can modify table->on_expr because its old value will
9118
9102
          be restored before re-execution of PS/SP.
9119
9103
        */
9120
 
        table->on_expr= build_equal_items(thd, table->on_expr, inherited,
 
9104
        table->on_expr= build_equal_items(session, table->on_expr, inherited,
9121
9105
                                          nested_join_list,
9122
9106
                                          &table->cond_equal);
9123
9107
      }
9125
9109
  }
9126
9110
 
9127
9111
  return cond;
9128
 
}    
 
9112
}
9129
9113
 
9130
9114
 
9131
9115
/**
9132
9116
  Compare field items by table order in the execution plan.
9133
9117
 
9134
9118
    field1 considered as better than field2 if the table containing
9135
 
    field1 is accessed earlier than the table containing field2.   
 
9119
    field1 is accessed earlier than the table containing field2.
9136
9120
    The function finds out what of two fields is better according
9137
9121
    this criteria.
9138
9122
 
9155
9139
  int cmp= 0;
9156
9140
  bool outer_ref= 0;
9157
9141
  if (field2->used_tables() & OUTER_REF_TABLE_BIT)
9158
 
  {  
 
9142
  {
9159
9143
    outer_ref= 1;
9160
9144
    cmp= -1;
9161
9145
  }
9218
9202
  List<Item> eq_list;
9219
9203
  Item_func_eq *eq_item= 0;
9220
9204
  if (((Item *) item_equal)->const_item() && !item_equal->val_int())
9221
 
    return new Item_int((int64_t) 0,1); 
 
9205
    return new Item_int((int64_t) 0,1);
9222
9206
  Item *item_const= item_equal->get_const();
9223
9207
  Item_equal_iterator it(*item_equal);
9224
9208
  Item *head;
9235
9219
    Item_equal *upper= item_field->find_item_equal(upper_levels);
9236
9220
    Item_field *item= item_field;
9237
9221
    if (upper)
9238
 
    { 
 
9222
    {
9239
9223
      if (item_const && upper->get_const())
9240
9224
        item= 0;
9241
9225
      else
9279
9263
 
9280
9264
  cond->quick_fix_field();
9281
9265
  cond->update_used_tables();
9282
 
   
 
9266
 
9283
9267
  return cond;
9284
9268
}
9285
9269
 
9292
9276
    multiple equality predicate it sorts the field references in it
9293
9277
    according to the order of tables specified by the table_join_idx
9294
9278
    parameter. Then it eliminates the multiple equality predicate it
9295
 
    replacing it by the conjunction of simple equality predicates 
 
9279
    replacing it by the conjunction of simple equality predicates
9296
9280
    equating every field from the multiple equality to the first
9297
9281
    field in it, or to the constant, if there is any.
9298
9282
    After this the function retrieves all other conjuncted
9329
9313
      cond_equal= &((Item_cond_and *) cond)->cond_equal;
9330
9314
      cond_list->disjoin((List<Item> *) &cond_equal->current_level);
9331
9315
 
9332
 
      List_iterator_fast<Item_equal> it(cond_equal->current_level);      
 
9316
      List_iterator_fast<Item_equal> it(cond_equal->current_level);
9333
9317
      while ((item_equal= it++))
9334
9318
      {
9335
9319
        item_equal->sort(&compare_fields_by_table_order, table_join_idx);
9336
9320
      }
9337
9321
    }
9338
 
    
 
9322
 
9339
9323
    List_iterator<Item> li(*cond_list);
9340
9324
    Item *item;
9341
9325
    while ((item= li++))
9368
9352
      cond= new Item_int((int32_t)cond->val_bool());
9369
9353
 
9370
9354
  }
9371
 
  else if (cond->type() == Item::FUNC_ITEM && 
 
9355
  else if (cond->type() == Item::FUNC_ITEM &&
9372
9356
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
9373
9357
  {
9374
9358
    item_equal= (Item_equal *) cond;
9403
9387
 
9404
9388
  if (cond->type() == Item::COND_ITEM)
9405
9389
  {
9406
 
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list(); 
 
9390
    List<Item> *cond_list= ((Item_cond*) cond)->argument_list();
9407
9391
    List_iterator_fast<Item> li(*cond_list);
9408
9392
    Item *item;
9409
9393
    while ((item= li++))
9410
9394
      update_const_equal_items(item, tab);
9411
9395
  }
9412
 
  else if (cond->type() == Item::FUNC_ITEM && 
 
9396
  else if (cond->type() == Item::FUNC_ITEM &&
9413
9397
           ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
9414
9398
  {
9415
9399
    Item_equal *item_equal= (Item_equal *) cond;
9425
9409
        Field *field= item_field->field;
9426
9410
        JOIN_TAB *stat= field->table->reginfo.join_tab;
9427
9411
        key_map possible_keys= field->key_start;
9428
 
        possible_keys.intersect(field->table->keys_in_use_for_query);
9429
 
        stat[0].const_keys.merge(possible_keys);
 
9412
        possible_keys&= field->table->keys_in_use_for_query;
 
9413
        stat[0].const_keys|= possible_keys;
9430
9414
 
9431
9415
        /*
9432
 
          For each field in the multiple equality (for which we know that it 
9433
 
          is a constant) we have to find its corresponding key part, and set 
 
9416
          For each field in the multiple equality (for which we know that it
 
9417
          is a constant) we have to find its corresponding key part, and set
9434
9418
          that key part in const_key_parts.
9435
 
        */  
9436
 
        if (!possible_keys.is_clear_all())
 
9419
        */
 
9420
        if (possible_keys.any())
9437
9421
        {
9438
 
          Table *tab= field->table;
 
9422
          Table *field_tab= field->table;
9439
9423
          KEYUSE *use;
9440
 
          for (use= stat->keyuse; use && use->table == tab; use++)
9441
 
            if (possible_keys.is_set(use->key) && 
9442
 
                tab->key_info[use->key].key_part[use->keypart].field ==
 
9424
          for (use= stat->keyuse; use && use->table == field_tab; use++)
 
9425
            if (possible_keys.test(use->key) &&
 
9426
                field_tab->key_info[use->key].key_part[use->keypart].field ==
9443
9427
                field)
9444
 
              tab->const_key_parts[use->key]|= use->keypart_map;
 
9428
              field_tab->const_key_parts[use->key]|= use->keypart_map;
9445
9429
        }
9446
9430
      }
9447
9431
    }
9455
9439
*/
9456
9440
 
9457
9441
static void
9458
 
change_cond_ref_to_const(THD *thd, I_List<COND_CMP> *save_list,
 
9442
change_cond_ref_to_const(Session *session, I_List<COND_CMP> *save_list,
9459
9443
                         Item *and_father, Item *cond,
9460
9444
                         Item *field, Item *value)
9461
9445
{
9466
9450
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
9467
9451
    Item *item;
9468
9452
    while ((item=li++))
9469
 
      change_cond_ref_to_const(thd, save_list,and_level ? cond : item, item,
 
9453
      change_cond_ref_to_const(session, save_list,and_level ? cond : item, item,
9470
9454
                               field, value);
9471
9455
    return;
9472
9456
  }
9487
9471
  {
9488
9472
    Item *tmp=value->clone_item();
9489
9473
    tmp->collation.set(right_item->collation);
9490
 
    
 
9474
 
9491
9475
    if (tmp)
9492
9476
    {
9493
 
      thd->change_item_tree(args + 1, tmp);
 
9477
      session->change_item_tree(args + 1, tmp);
9494
9478
      func->update_used_tables();
9495
9479
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
9496
9480
          && and_father != cond && !left_item->const_item())
9511
9495
  {
9512
9496
    Item *tmp= value->clone_item();
9513
9497
    tmp->collation.set(left_item->collation);
9514
 
    
 
9498
 
9515
9499
    if (tmp)
9516
9500
    {
9517
 
      thd->change_item_tree(args, tmp);
 
9501
      session->change_item_tree(args, tmp);
9518
9502
      value= tmp;
9519
9503
      func->update_used_tables();
9520
9504
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC)
9521
9505
          && and_father != cond && !right_item->const_item())
9522
9506
      {
9523
9507
        args[0]= args[1];                       // For easy check
9524
 
        thd->change_item_tree(args + 1, value);
 
9508
        session->change_item_tree(args + 1, value);
9525
9509
        cond->marker=1;
9526
9510
        COND_CMP *tmp2;
9527
9511
        if ((tmp2=new COND_CMP(and_father,func)))
9565
9549
}
9566
9550
 
9567
9551
static void
9568
 
propagate_cond_constants(THD *thd, I_List<COND_CMP> *save_list,
 
9552
propagate_cond_constants(Session *session, I_List<COND_CMP> *save_list,
9569
9553
                         COND *and_father, COND *cond)
9570
9554
{
9571
9555
  if (cond->type() == Item::COND_ITEM)
9577
9561
    I_List<COND_CMP> save;
9578
9562
    while ((item=li++))
9579
9563
    {
9580
 
      propagate_cond_constants(thd, &save,and_level ? cond : item, item);
 
9564
      propagate_cond_constants(session, &save,and_level ? cond : item, item);
9581
9565
    }
9582
9566
    if (and_level)
9583
9567
    {                                           // Handle other found items
9587
9571
      {
9588
9572
        Item **args= cond_cmp->cmp_func->arguments();
9589
9573
        if (!args[0]->const_item())
9590
 
          change_cond_ref_to_const(thd, &save,cond_cmp->and_level,
 
9574
          change_cond_ref_to_const(session, &save,cond_cmp->and_level,
9591
9575
                                   cond_cmp->and_level, args[0], args[1]);
9592
9576
      }
9593
9577
    }
9607
9591
      {
9608
9592
        if (right_const)
9609
9593
        {
9610
 
          resolve_const_item(thd, &args[1], args[0]);
 
9594
          resolve_const_item(session, &args[1], args[0]);
9611
9595
          func->update_used_tables();
9612
 
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
 
9596
          change_cond_ref_to_const(session, save_list, and_father, and_father,
9613
9597
                                   args[0], args[1]);
9614
9598
        }
9615
9599
        else if (left_const)
9616
9600
        {
9617
 
          resolve_const_item(thd, &args[0], args[1]);
 
9601
          resolve_const_item(session, &args[0], args[1]);
9618
9602
          func->update_used_tables();
9619
 
          change_cond_ref_to_const(thd, save_list, and_father, and_father,
 
9603
          change_cond_ref_to_const(session, save_list, and_father, and_father,
9620
9604
                                   args[1], args[0]);
9621
9605
        }
9622
9606
      }
9634
9618
    It also moves the on expressions for the converted outer joins
9635
9619
    and from inner joins to conds.
9636
9620
    The function also calculates some attributes for nested joins:
9637
 
    - used_tables    
 
9621
    - used_tables
9638
9622
    - not_null_tables
9639
9623
    - dep_tables.
9640
9624
    - on_expr_dep_tables
9657
9641
    or the on expression for an embedding nested join contains a conjunctive
9658
9642
    predicate rejecting null values for some attribute of the inner tables.
9659
9643
 
9660
 
    E.g. in the query:    
 
9644
    E.g. in the query:
9661
9645
    @code
9662
9646
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5
9663
9647
    @endcode
9675
9659
    Similarly the following query:
9676
9660
    @code
9677
9661
      SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b
9678
 
        WHERE t2.c < 5  
 
9662
        WHERE t2.c < 5
9679
9663
    @endcode
9680
9664
    is converted to:
9681
9665
    @code
9682
 
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b 
 
9666
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b
9683
9667
 
9684
9668
    @endcode
9685
9669
 
9689
9673
                       LEFT JOIN t3 ON t3.b=t2.b
9690
9674
        WHERE t3 IS NOT NULL =>
9691
9675
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3
9692
 
        WHERE t3 IS NOT NULL AND t3.b=t2.b => 
 
9676
        WHERE t3 IS NOT NULL AND t3.b=t2.b =>
9693
9677
      SELECT * FROM t1, t2, t3
9694
9678
        WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a
9695
9679
  @endcode
9700
9684
    @code
9701
9685
      SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
9702
9686
    @endcode
9703
 
    finally is converted to: 
 
9687
    finally is converted to:
9704
9688
    @code
9705
9689
      SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b
9706
9690
 
9713
9697
      SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b.
9714
9698
    @endcode
9715
9699
 
9716
 
    The benefit of this simplification procedure is that it might return 
 
9700
    The benefit of this simplification procedure is that it might return
9717
9701
    a query for which the optimizer can evaluate execution plan with more
9718
9702
    join orders. With a left join operation the optimizer does not
9719
9703
    consider any plan where one of the inner tables is before some of outer
9733
9717
  EXAMPLES
9734
9718
    Here is an example of a join query with invalid cross references:
9735
9719
    @code
9736
 
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b 
 
9720
      SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b
9737
9721
    @endcode
9738
9722
 
9739
9723
  @param join        reference to the query info
9755
9739
  TableList *prev_table= 0;
9756
9740
  List_iterator<TableList> li(*join_list);
9757
9741
 
9758
 
  /* 
 
9742
  /*
9759
9743
    Try to simplify join operations from join_list.
9760
 
    The most outer join operation is checked for conversion first. 
 
9744
    The most outer join operation is checked for conversion first.
9761
9745
  */
9762
9746
  while ((table= li++))
9763
9747
  {
9766
9750
 
9767
9751
    if ((nested_join= table->nested_join))
9768
9752
    {
9769
 
      /* 
 
9753
      /*
9770
9754
         If the element of join_list is a nested join apply
9771
9755
         the procedure to its nested join list first.
9772
9756
      */
9773
9757
      if (table->on_expr)
9774
9758
      {
9775
9759
        Item *expr= table->on_expr;
9776
 
        /* 
9777
 
           If an on expression E is attached to the table, 
 
9760
        /*
 
9761
           If an on expression E is attached to the table,
9778
9762
           check all null rejected predicates in this expression.
9779
9763
           If such a predicate over an attribute belonging to
9780
9764
           an inner table of an embedded outer join is found,
9781
9765
           the outer join is converted to an inner join and
9782
 
           the corresponding on expression is added to E. 
9783
 
        */ 
 
9766
           the corresponding on expression is added to E.
 
9767
        */
9784
9768
        expr= simplify_joins(join, &nested_join->join_list,
9785
9769
                             expr, false, in_sj || table->sj_on_expr);
9786
9770
 
9789
9773
          assert(expr);
9790
9774
 
9791
9775
          table->on_expr= expr;
9792
 
          table->prep_on_expr= expr->copy_andor_structure(join->thd);
 
9776
          table->prep_on_expr= expr->copy_andor_structure(join->session);
9793
9777
        }
9794
9778
      }
9795
9779
      nested_join->used_tables= (table_map) 0;
9796
9780
      nested_join->not_null_tables=(table_map) 0;
9797
 
      conds= simplify_joins(join, &nested_join->join_list, conds, top, 
 
9781
      conds= simplify_joins(join, &nested_join->join_list, conds, top,
9798
9782
                            in_sj || table->sj_on_expr);
9799
9783
      used_tables= nested_join->used_tables;
9800
 
      not_null_tables= nested_join->not_null_tables;  
 
9784
      not_null_tables= nested_join->not_null_tables;
9801
9785
    }
9802
9786
    else
9803
9787
    {
9807
9791
      if (conds)
9808
9792
        not_null_tables= conds->not_null_tables();
9809
9793
    }
9810
 
      
 
9794
 
9811
9795
    if (table->embedding)
9812
9796
    {
9813
9797
      table->embedding->nested_join->used_tables|= used_tables;
9816
9800
 
9817
9801
    if (!table->outer_join || (used_tables & not_null_tables))
9818
9802
    {
9819
 
      /* 
 
9803
      /*
9820
9804
        For some of the inner tables there are conjunctive predicates
9821
9805
        that reject nulls => the outer join can be replaced by an inner join.
9822
9806
      */
9830
9814
          conds->top_level_item();
9831
9815
          /* conds is always a new item as both cond and on_expr existed */
9832
9816
          assert(!conds->fixed);
9833
 
          conds->fix_fields(join->thd, &conds);
 
9817
          conds->fix_fields(join->session, &conds);
9834
9818
        }
9835
9819
        else
9836
 
          conds= table->on_expr; 
 
9820
          conds= table->on_expr;
9837
9821
        table->prep_on_expr= table->on_expr= 0;
9838
9822
      }
9839
9823
    }
9840
 
    
 
9824
 
9841
9825
    if (!top)
9842
9826
      continue;
9843
9827
 
9844
 
    /* 
 
9828
    /*
9845
9829
      Only inner tables of non-convertible outer joins
9846
9830
      remain with on_expr.
9847
 
    */ 
 
9831
    */
9848
9832
    if (table->on_expr)
9849
9833
    {
9850
 
      table->dep_tables|= table->on_expr->used_tables(); 
 
9834
      table->dep_tables|= table->on_expr->used_tables();
9851
9835
      if (table->embedding)
9852
9836
      {
9853
 
        table->dep_tables&= ~table->embedding->nested_join->used_tables;   
 
9837
        table->dep_tables&= ~table->embedding->nested_join->used_tables;
9854
9838
        /*
9855
9839
           Embedding table depends on tables used
9856
 
           in embedded on expressions. 
 
9840
           in embedded on expressions.
9857
9841
        */
9858
9842
        table->embedding->on_expr_dep_tables|= table->on_expr->used_tables();
9859
9843
      }
9872
9856
        table_map prev_used_tables= prev_table->nested_join ?
9873
9857
                                    prev_table->nested_join->used_tables :
9874
9858
                                    prev_table->table->map;
9875
 
        /* 
 
9859
        /*
9876
9860
          If on expression contains only references to inner tables
9877
9861
          we still make the inner tables dependent on the outer tables.
9878
9862
          It would be enough to set dependency only on one outer table
9879
9863
          for them. Yet this is really a rare case.
9880
 
        */  
 
9864
        */
9881
9865
        if (!(prev_table->on_expr->used_tables() & ~prev_used_tables))
9882
9866
          prev_table->dep_tables|= used_tables;
9883
9867
      }
9884
9868
    }
9885
9869
    prev_table= table;
9886
9870
  }
9887
 
    
9888
 
  /* 
 
9871
 
 
9872
  /*
9889
9873
    Flatten nested joins that can be flattened.
9890
9874
    no ON expression and not a semi-join => can be flattened.
9891
9875
  */
9896
9880
    if (table->sj_on_expr && !in_sj)
9897
9881
    {
9898
9882
       /*
9899
 
         If this is a semi-join that is not contained within another semi-join, 
 
9883
         If this is a semi-join that is not contained within another semi-join,
9900
9884
         leave it intact (otherwise it is flattened)
9901
9885
       */
9902
9886
      join->select_lex->sj_nests.push_back(table);
9909
9893
      {
9910
9894
        tbl->embedding= table->embedding;
9911
9895
        tbl->join_list= table->join_list;
9912
 
      }      
 
9896
      }
9913
9897
      li.replace(nested_join->join_list);
9914
9898
    }
9915
9899
  }
9916
 
  return(conds); 
 
9900
  return(conds);
9917
9901
}
9918
9902
 
9919
9903
 
9937
9921
    First unused bit in nested_join_map after the call.
9938
9922
*/
9939
9923
 
9940
 
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list, 
 
9924
static uint32_t build_bitmap_for_nested_joins(List<TableList> *join_list,
9941
9925
                                          uint32_t first_unused)
9942
9926
{
9943
9927
  List_iterator<TableList> li(*join_list);
9950
9934
      /*
9951
9935
        It is guaranteed by simplify_joins() function that a nested join
9952
9936
        that has only one child is either
9953
 
         - a single-table view (the child is the underlying table), or 
 
9937
         - a single-table view (the child is the underlying table), or
9954
9938
         - a single-table semi-join nest
9955
9939
 
9956
 
        We don't assign bits to such sj-nests because 
9957
 
        1. it is redundant (a "sequence" of one table cannot be interleaved 
 
9940
        We don't assign bits to such sj-nests because
 
9941
        1. it is redundant (a "sequence" of one table cannot be interleaved
9958
9942
            with anything)
9959
9943
        2. we could run out bits in nested_join_map otherwise.
9960
9944
      */
10003
9987
  Check interleaving with an inner tables of an outer join for
10004
9988
  extension table.
10005
9989
 
10006
 
    Check if table next_tab can be added to current partial join order, and 
 
9990
    Check if table next_tab can be added to current partial join order, and
10007
9991
    if yes, record that it has been added.
10008
9992
 
10009
9993
    The function assumes that both current partial join order and its
10010
9994
    extension with next_tab are valid wrt table dependencies.
10011
9995
 
10012
9996
  @verbatim
10013
 
     IMPLEMENTATION 
 
9997
     IMPLEMENTATION
10014
9998
       LIMITATIONS ON JOIN order_st
10015
9999
         The nested [outer] joins executioner algorithm imposes these limitations
10016
10000
         on join order:
10017
 
         1. "Outer tables first" -  any "outer" table must be before any 
 
10001
         1. "Outer tables first" -  any "outer" table must be before any
10018
10002
             corresponding "inner" table.
10019
10003
         2. "No interleaving" - tables inside a nested join must form a continuous
10020
 
            sequence in join order (i.e. the sequence must not be interrupted by 
 
10004
            sequence in join order (i.e. the sequence must not be interrupted by
10021
10005
            tables that are outside of this nested join).
10022
10006
 
10023
10007
         #1 is checked elsewhere, this function checks #2 provided that #1 has
10024
10008
         been already checked.
10025
10009
 
10026
10010
       WHY NEED NON-INTERLEAVING
10027
 
         Consider an example: 
 
10011
         Consider an example:
10028
10012
 
10029
10013
           select * from t0 join t1 left join (t2 join t3) on cond1
10030
10014
 
10048
10032
         The limitations on join order can be rephrased as follows: for valid
10049
10033
         join order one must be able to:
10050
10034
           1. write down the used tables in the join order on one line.
10051
 
           2. for each nested join, put one '(' and one ')' on the said line        
 
10035
           2. for each nested join, put one '(' and one ')' on the said line
10052
10036
           3. write "LEFT JOIN" and "ON (...)" where appropriate
10053
10037
           4. get a query equivalent to the query we're trying to execute.
10054
10038
 
10055
10039
         Calls to check_interleaving_with_nj() are equivalent to writing the
10056
 
         above described line from left to right. 
10057
 
         A single check_interleaving_with_nj(A,B) call is equivalent to writing 
 
10040
         above described line from left to right.
 
10041
         A single check_interleaving_with_nj(A,B) call is equivalent to writing
10058
10042
         table B and appropriate brackets on condition that table A and
10059
10043
         appropriate brackets is the last what was written. Graphically the
10060
10044
         transition is as follows:
10067
10051
                                                      position.
10068
10052
 
10069
10053
         Notes about the position:
10070
 
           The caller guarantees that there is no more then one X-bracket by 
10071
 
           checking "!(remaining_tables & s->dependent)" before calling this 
 
10054
           The caller guarantees that there is no more then one X-bracket by
 
10055
           checking "!(remaining_tables & s->dependent)" before calling this
10072
10056
           function. X-bracket may have a pair in Y-bracket.
10073
10057
 
10074
10058
         When "writing" we store/update this auxilary info about the current
10099
10083
 
10100
10084
  if (join->cur_embedding_map & ~next_tab->embedding_map)
10101
10085
  {
10102
 
    /* 
 
10086
    /*
10103
10087
      next_tab is outside of the "pair of brackets" we're currently in.
10104
10088
      Cannot add it.
10105
10089
    */
10106
10090
    return true;
10107
10091
  }
10108
 
   
 
10092
 
10109
10093
  /*
10110
10094
    Do update counters for "pairs of brackets" that we've left (marked as
10111
10095
    X,Y,Z in the above picture)
10115
10099
    next_emb->nested_join->counter_++;
10116
10100
    if (next_emb->nested_join->counter_ == 1)
10117
10101
    {
10118
 
      /* 
 
10102
      /*
10119
10103
        next_emb is the first table inside a nested join we've "entered". In
10120
10104
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
10121
10105
        X bracket might have Y pair bracket.
10122
10106
      */
10123
10107
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
10124
10108
    }
10125
 
    
 
10109
 
10126
10110
    if (next_emb->nested_join->join_list.elements !=
10127
10111
        next_emb->nested_join->counter_)
10128
10112
      break;
10141
10125
  Nested joins perspective: Remove the last table from the join order.
10142
10126
 
10143
10127
    Remove the last table from the partial join order and update the nested
10144
 
    joins counters and join->cur_embedding_map. It is ok to call this 
10145
 
    function for the first table in join order (for which 
 
10128
    joins counters and join->cur_embedding_map. It is ok to call this
 
10129
    function for the first table in join order (for which
10146
10130
    check_interleaving_with_nj has not been called)
10147
10131
 
10148
10132
  @param last  join table to remove, it is assumed to be the last in current
10160
10144
      if (!(--last_emb->nested_join->counter_))
10161
10145
        join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
10162
10146
      else if (last_emb->nested_join->join_list.elements-1 ==
10163
 
               last_emb->nested_join->counter_) 
 
10147
               last_emb->nested_join->counter_)
10164
10148
        join->cur_embedding_map|= last_emb->nested_join->nj_map;
10165
10149
      else
10166
10150
        break;
10171
10155
 
10172
10156
 
10173
10157
 
10174
 
static 
 
10158
static
10175
10159
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
10176
10160
{
10177
10161
  TableList *emb_sj_nest;
10189
10173
  we assume remaining_tables doesnt contain @tab.
10190
10174
*/
10191
10175
 
10192
 
static void restore_prev_sj_state(const table_map remaining_tables, 
 
10176
static void restore_prev_sj_state(const table_map remaining_tables,
10193
10177
                                  const JOIN_TAB *tab)
10194
10178
{
10195
10179
  TableList *emb_sj_nest;
10196
10180
  if ((emb_sj_nest= tab->emb_sj_nest))
10197
10181
  {
10198
10182
    /* If we're removing the last SJ-inner table, remove the sj-nest */
10199
 
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) == 
 
10183
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) ==
10200
10184
        (emb_sj_nest->sj_inner_tables & ~tab->table->map))
10201
10185
    {
10202
10186
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
10209
10193
optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list,
10210
10194
              Item::cond_result *cond_value)
10211
10195
{
10212
 
  THD *thd= join->thd;
 
10196
  Session *session= join->session;
10213
10197
 
10214
10198
  if (!conds)
10215
10199
    *cond_value= Item::COND_TRUE;
10216
10200
  else
10217
10201
  {
10218
 
    /* 
 
10202
    /*
10219
10203
      Build all multiple equality predicates and eliminate equality
10220
10204
      predicates that can be inferred from these multiple equalities.
10221
10205
      For each reference of a field included into a multiple equality
10222
10206
      that occurs in a function set a pointer to the multiple equality
10223
10207
      predicate. Substitute a constant instead of this field if the
10224
10208
      multiple equality contains a constant.
10225
 
    */ 
10226
 
    conds= build_equal_items(join->thd, conds, NULL, join_list,
 
10209
    */
 
10210
    conds= build_equal_items(join->session, conds, NULL, join_list,
10227
10211
                             &join->cond_equal);
10228
10212
 
10229
10213
    /* change field = field to field = const for each found field = const */
10230
 
    propagate_cond_constants(thd, (I_List<COND_CMP> *) 0, conds, conds);
 
10214
    propagate_cond_constants(session, (I_List<COND_CMP> *) 0, conds, conds);
10231
10215
    /*
10232
10216
      Remove all instances of item == item
10233
10217
      Remove all and-levels where CONST item != CONST item
10234
10218
    */
10235
 
    conds= remove_eq_conds(thd, conds, cond_value) ;
 
10219
    conds= remove_eq_conds(session, conds, cond_value) ;
10236
10220
  }
10237
10221
  return(conds);
10238
10222
}
10250
10234
*/
10251
10235
 
10252
10236
COND *
10253
 
remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value)
 
10237
remove_eq_conds(Session *session, COND *cond, Item::cond_result *cond_value)
10254
10238
{
10255
10239
  if (cond->type() == Item::COND_ITEM)
10256
10240
  {
10257
 
    bool and_level= ((Item_cond*) cond)->functype()
10258
 
      == Item_func::COND_AND_FUNC;
 
10241
    bool and_level= (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC);
 
10242
 
10259
10243
    List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
10260
10244
    Item::cond_result tmp_cond_value;
10261
 
    bool should_fix_fields=0;
 
10245
    bool should_fix_fields= false;
10262
10246
 
10263
 
    *cond_value=Item::COND_UNDEF;
 
10247
    *cond_value= Item::COND_UNDEF;
10264
10248
    Item *item;
10265
 
    while ((item=li++))
 
10249
    while ((item= li++))
10266
10250
    {
10267
 
      Item *new_item=remove_eq_conds(thd, item, &tmp_cond_value);
10268
 
      if (!new_item)
10269
 
        li.remove();
 
10251
      Item *new_item= remove_eq_conds(session, item, &tmp_cond_value);
 
10252
      if (! new_item)
 
10253
              li.remove();
10270
10254
      else if (item != new_item)
10271
10255
      {
10272
 
        li.replace(new_item);
10273
 
        should_fix_fields=1;
 
10256
        li.replace(new_item);
 
10257
        should_fix_fields= true;
10274
10258
      }
10275
10259
      if (*cond_value == Item::COND_UNDEF)
10276
 
        *cond_value=tmp_cond_value;
10277
 
      switch (tmp_cond_value) {
10278
 
      case Item::COND_OK:                       // Not true or false
10279
 
        if (and_level || *cond_value == Item::COND_FALSE)
10280
 
          *cond_value=tmp_cond_value;
10281
 
        break;
10282
 
      case Item::COND_FALSE:
10283
 
        if (and_level)
10284
 
        {
10285
 
          *cond_value=tmp_cond_value;
10286
 
          return (COND*) 0;                     // Always false
10287
 
        }
10288
 
        break;
10289
 
      case Item::COND_TRUE:
10290
 
        if (!and_level)
10291
 
        {
10292
 
          *cond_value= tmp_cond_value;
10293
 
          return (COND*) 0;                     // Always true
10294
 
        }
10295
 
        break;
10296
 
      case Item::COND_UNDEF:                    // Impossible
10297
 
        break; /* purecov: deadcode */
 
10260
              *cond_value= tmp_cond_value;
 
10261
 
 
10262
      switch (tmp_cond_value) 
 
10263
      {
 
10264
        case Item::COND_OK:                     /* Not true or false */
 
10265
          if (and_level || (*cond_value == Item::COND_FALSE))
 
10266
            *cond_value= tmp_cond_value;
 
10267
          break;
 
10268
        case Item::COND_FALSE:
 
10269
          if (and_level)
 
10270
          {
 
10271
            *cond_value= tmp_cond_value;
 
10272
            return (COND *) NULL;                       /* Always false */
 
10273
          }
 
10274
          break;
 
10275
        case Item::COND_TRUE:
 
10276
          if (! and_level)
 
10277
          {
 
10278
            *cond_value= tmp_cond_value;
 
10279
            return (COND *) NULL;                       /* Always true */
 
10280
          }
 
10281
          break;
 
10282
        case Item::COND_UNDEF:                  /* Impossible */
 
10283
          break; /* purecov: deadcode */
10298
10284
      }
10299
10285
    }
 
10286
 
10300
10287
    if (should_fix_fields)
10301
10288
      cond->update_used_tables();
10302
10289
 
10303
 
    if (!((Item_cond*) cond)->argument_list()->elements ||
10304
 
        *cond_value != Item::COND_OK)
10305
 
      return (COND*) 0;
 
10290
    if (! ((Item_cond*) cond)->argument_list()->elements || *cond_value != Item::COND_OK)
 
10291
      return (COND*) NULL;
 
10292
 
10306
10293
    if (((Item_cond*) cond)->argument_list()->elements == 1)
10307
 
    {                                           // Remove list
 
10294
    {                                           
 
10295
      /* Argument list contains only one element, so reduce it so a single item, then remove list */
10308
10296
      item= ((Item_cond*) cond)->argument_list()->head();
10309
10297
      ((Item_cond*) cond)->argument_list()->empty();
10310
10298
      return item;
10311
10299
    }
10312
10300
  }
10313
 
  else if (cond->type() == Item::FUNC_ITEM &&
10314
 
           ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
 
10301
  else if (cond->type() == Item::FUNC_ITEM && ((Item_func*) cond)->functype() == Item_func::ISNULL_FUNC)
10315
10302
  {
10316
10303
    /*
10317
10304
      Handles this special case for some ODBC applications:
10323
10310
      SELECT * from table_name where auto_increment_column = LAST_INSERT_ID
10324
10311
    */
10325
10312
 
10326
 
    Item_func_isnull *func=(Item_func_isnull*) cond;
 
10313
    Item_func_isnull *func= (Item_func_isnull*) cond;
10327
10314
    Item **args= func->arguments();
10328
10315
    if (args[0]->type() == Item::FIELD_ITEM)
10329
10316
    {
10330
 
      Field *field=((Item_field*) args[0])->field;
10331
 
      if (field->flags & AUTO_INCREMENT_FLAG && !field->table->maybe_null &&
10332
 
          (thd->options & OPTION_AUTO_IS_NULL) &&
10333
 
          (thd->first_successful_insert_id_in_prev_stmt > 0 &&
10334
 
           thd->substitute_null_with_insert_id))
 
10317
      Field *field= ((Item_field*) args[0])->field;
 
10318
      if (field->flags & AUTO_INCREMENT_FLAG 
 
10319
          && ! field->table->maybe_null 
 
10320
          && session->options & OPTION_AUTO_IS_NULL
 
10321
          && (
 
10322
            session->first_successful_insert_id_in_prev_stmt > 0 
 
10323
            && session->substitute_null_with_insert_id
 
10324
            )
 
10325
          )
10335
10326
      {
10336
 
        COND *new_cond;
10337
 
        if ((new_cond= new Item_func_eq(args[0],
10338
 
                                        new Item_int("last_insert_id()",
10339
 
                                                     thd->read_first_successful_insert_id_in_prev_stmt(),
10340
 
                                                     MY_INT64_NUM_DECIMAL_DIGITS))))
10341
 
        {
10342
 
          cond=new_cond;
 
10327
        COND *new_cond;
 
10328
        if ((new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()",
 
10329
                                                          session->read_first_successful_insert_id_in_prev_stmt(),
 
10330
                                                          MY_INT64_NUM_DECIMAL_DIGITS))))
 
10331
        {
 
10332
          cond= new_cond;
10343
10333
          /*
10344
10334
            Item_func_eq can't be fixed after creation so we do not check
10345
10335
            cond->fixed, also it do not need tables so we use 0 as second
10346
10336
            argument.
10347
10337
          */
10348
 
          cond->fix_fields(thd, &cond);
10349
 
        }
 
10338
          cond->fix_fields(session, &cond);
 
10339
        }
10350
10340
        /*
10351
10341
          IS NULL should be mapped to LAST_INSERT_ID only for first row, so
10352
10342
          clear for next row
10353
10343
        */
10354
 
        thd->substitute_null_with_insert_id= false;
 
10344
        session->substitute_null_with_insert_id= false;
10355
10345
      }
 
10346
#ifdef NOTDEFINED
10356
10347
      /* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
10357
 
      else if (((field->type() == DRIZZLE_TYPE_NEWDATE) ||
10358
 
                (field->type() == DRIZZLE_TYPE_DATETIME)) &&
10359
 
                (field->flags & NOT_NULL_FLAG) &&
10360
 
               !field->table->maybe_null)
 
10348
      else if (
 
10349
          ((field->type() == DRIZZLE_TYPE_DATE) || (field->type() == DRIZZLE_TYPE_DATETIME)) 
 
10350
          && (field->flags & NOT_NULL_FLAG) 
 
10351
          && ! field->table->maybe_null)
10361
10352
      {
10362
 
        COND *new_cond;
10363
 
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
10364
 
        {
10365
 
          cond=new_cond;
 
10353
        COND *new_cond;
 
10354
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
 
10355
        {
 
10356
          cond= new_cond;
10366
10357
          /*
10367
10358
            Item_func_eq can't be fixed after creation so we do not check
10368
10359
            cond->fixed, also it do not need tables so we use 0 as second
10369
10360
            argument.
10370
10361
          */
10371
 
          cond->fix_fields(thd, &cond);
10372
 
        }
 
10362
          cond->fix_fields(session, &cond);
 
10363
        }
10373
10364
      }
 
10365
#endif /* NOTDEFINED */
10374
10366
    }
10375
10367
    if (cond->const_item())
10376
10368
    {
10377
10369
      *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10378
 
      return (COND*) 0;
 
10370
      return (COND *) NULL;
10379
10371
    }
10380
10372
  }
10381
10373
  else if (cond->const_item() && !cond->is_expensive())
10391
10383
  */
10392
10384
  {
10393
10385
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
10394
 
    return (COND*) 0;
 
10386
    return (COND *) NULL;
10395
10387
  }
10396
10388
  else if ((*cond_value= cond->eq_cmp_result()) != Item::COND_OK)
10397
 
  {                                             // boolan compare function
 
10389
  {                                             
 
10390
    /* boolan compare function */
10398
10391
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
10399
10392
    Item *right_item= ((Item_func*) cond)->arguments()[1];
10400
10393
    if (left_item->eq(right_item,1))
10401
10394
    {
10402
 
      if (!left_item->maybe_null ||
10403
 
          ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
10404
 
        return (COND*) 0;                       // Compare of identical items
 
10395
      if (!left_item->maybe_null || ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
 
10396
              return (COND*) NULL;                      /* Comparison of identical items */
10405
10397
    }
10406
10398
  }
10407
 
  *cond_value=Item::COND_OK;
10408
 
  return cond;                                  // Point at next and level
 
10399
  *cond_value= Item::COND_OK;
 
10400
  return cond;                                  /* Point at next and return into recursion */
10409
10401
}
10410
10402
 
10411
 
/* 
 
10403
/*
10412
10404
  Check if equality can be used in removing components of GROUP BY/DISTINCT
10413
 
  
 
10405
 
10414
10406
  SYNOPSIS
10415
10407
    test_if_equality_guarantees_uniqueness()
10416
10408
      l          the left comparison argument (a field if any)
10417
10409
      r          the right comparison argument (a const of any)
10418
 
  
10419
 
  DESCRIPTION    
10420
 
    Checks if an equality predicate can be used to take away 
10421
 
    DISTINCT/GROUP BY because it is known to be true for exactly one 
 
10410
 
 
10411
  DESCRIPTION
 
10412
    Checks if an equality predicate can be used to take away
 
10413
    DISTINCT/GROUP BY because it is known to be true for exactly one
10422
10414
    distinct value (e.g. <expr> == <const>).
10423
 
    Arguments must be of the same type because e.g. 
10424
 
    <string_field> = <int_const> may match more than 1 distinct value from 
10425
 
    the column. 
10426
 
    We must take into consideration and the optimization done for various 
 
10415
    Arguments must be of the same type because e.g.
 
10416
    <string_field> = <int_const> may match more than 1 distinct value from
 
10417
    the column.
 
10418
    We must take into consideration and the optimization done for various
10427
10419
    string constants when compared to dates etc (see Item_int_with_ref) as
10428
10420
    well as the collation of the arguments.
10429
 
  
10430
 
  RETURN VALUE  
 
10421
 
 
10422
  RETURN VALUE
10431
10423
    true    can be used
10432
10424
    false   cannot be used
10433
10425
*/
10518
10510
Next_select_func setup_end_select_func(JOIN *join)
10519
10511
{
10520
10512
  Table *table= join->tmp_table;
10521
 
  TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param;
 
10513
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
10522
10514
  Next_select_func end_select;
10523
10515
 
10524
10516
  /* Set up select_end */
10525
10517
  if (table)
10526
10518
  {
10527
 
    if (table->group && tmp_tbl->sum_func_count && 
 
10519
    if (table->group && tmp_tbl->sum_func_count &&
10528
10520
        !tmp_tbl->precomputed_group_by)
10529
10521
    {
10530
10522
      if (table->s->keys)
10548
10540
        /*
10549
10541
          A preceding call to create_tmp_table in the case when loose
10550
10542
          index scan is used guarantees that
10551
 
          TMP_TABLE_PARAM::items_to_copy has enough space for the group
 
10543
          Tmp_Table_Param::items_to_copy has enough space for the group
10552
10544
          by functions. It is OK here to use memcpy since we copy
10553
10545
          Item_sum pointers into an array of Item pointers.
10554
10546
        */
10588
10580
  int rc= 0;
10589
10581
  enum_nested_loop_state error= NESTED_LOOP_OK;
10590
10582
  JOIN_TAB *join_tab= NULL;
10591
 
  
 
10583
 
10592
10584
  join->tmp_table= table;                       /* Save for easy recursion */
10593
10585
  join->fields= fields;
10594
10586
 
10595
10587
  if (table)
10596
10588
  {
10597
10589
    table->file->extra(HA_EXTRA_WRITE_CACHE);
10598
 
    empty_record(table);
 
10590
    table->emptyRecord();
10599
10591
    if (table->group && join->tmp_table_param.sum_func_count &&
10600
10592
        table->s->keys && !table->file->inited)
10601
10593
      table->file->ha_index_init(0, 0);
10627
10619
        so we don't touch it here.
10628
10620
      */
10629
10621
      join->examined_rows++;
10630
 
      join->thd->row_count++;
 
10622
      join->session->row_count++;
10631
10623
      assert(join->examined_rows <= 1);
10632
10624
    }
10633
10625
    else if (join->send_row_on_empty_set())
10681
10673
    if (new_errno)
10682
10674
      table->file->print_error(new_errno,MYF(0));
10683
10675
  }
10684
 
  return(join->thd->is_error() ? -1 : rc);
 
10676
  return(join->session->is_error() ? -1 : rc);
10685
10677
}
10686
10678
 
10687
10679
 
10697
10689
      rc= sub_select(join,join_tab,end_of_records);
10698
10690
    return rc;
10699
10691
  }
10700
 
  if (join->thd->killed)                // If aborted by user
 
10692
  if (join->session->killed)            // If aborted by user
10701
10693
  {
10702
 
    join->thd->send_kill_message();
 
10694
    join->session->send_kill_message();
10703
10695
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
10704
10696
  }
10705
10697
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
10717
10709
/**
10718
10710
  Retrieve records ends with a given beginning from the result of a join.
10719
10711
 
10720
 
    For a given partial join record consisting of records from the tables 
 
10712
    For a given partial join record consisting of records from the tables
10721
10713
    preceding the table join_tab in the execution plan, the function
10722
10714
    retrieves all matching full records from the result set and
10723
 
    send them to the result set stream. 
 
10715
    send them to the result set stream.
10724
10716
 
10725
10717
  @note
10726
10718
    The function effectively implements the  final (n-k) nested loops
10760
10752
    first row with t3.a=t1.a has been encountered.
10761
10753
    Thus, the second predicate P2 is supplied with a guarded value that are
10762
10754
    stored in the field 'found' of the first inner table for the outer join
10763
 
    (table t2). When the first row with t3.a=t1.a for the  current row 
 
10755
    (table t2). When the first row with t3.a=t1.a for the  current row
10764
10756
    of table t1  appears, the value becomes true. For now on the predicate
10765
10757
    is evaluated immediately after the row of table t2 has been read.
10766
10758
    When the first row with t3.a=t1.a has been encountered all
10768
10760
    Only when all of them are true the row is sent to the output stream.
10769
10761
    If not, the function returns to the lowest nest level that has a false
10770
10762
    attached condition.
10771
 
    The predicates from on expressions are also pushed down. If in the 
 
10763
    The predicates from on expressions are also pushed down. If in the
10772
10764
    the above example the on expression were (t3.a=t1.a AND t2.a=t1.a),
10773
10765
    then t1.a=t2.a would be pushed down to table t2, and without any
10774
10766
    guard.
10778
10770
    is complemented by nulls  for t2 and t3. Then the pushed down predicates
10779
10771
    are checked for the composed row almost in the same way as it had
10780
10772
    been done for the first row with a match. The only difference is
10781
 
    the predicates from on expressions are not checked. 
 
10773
    the predicates from on expressions are not checked.
10782
10774
 
10783
10775
  @par
10784
10776
  @b IMPLEMENTATION
10794
10786
    and a pointer to a guarding boolean variable.
10795
10787
    When the value of the guard variable is true the value of the object
10796
10788
    is the same as the value of the predicate, otherwise it's just returns
10797
 
    true. 
10798
 
    To carry out a return to a nested loop level of join table t the pointer 
 
10789
    true.
 
10790
    To carry out a return to a nested loop level of join table t the pointer
10799
10791
    to t is remembered in the field 'return_tab' of the join structure.
10800
10792
    Consider the following query:
10801
10793
    @code
10812
10804
    t5.a=t3.a is found, the pushed down predicate t4.b=2 OR t4.b IS NULL
10813
10805
    becomes 'activated', as well the predicate t4.a=t2.a. But
10814
10806
    the predicate (t2.b=5 OR t2.b IS NULL) can not be checked until
10815
 
    t4.a=t2.a becomes true. 
 
10807
    t4.a=t2.a becomes true.
10816
10808
    In order not to re-evaluate the predicates that were already evaluated
10817
10809
    as attached pushed down predicates, a pointer to the the first
10818
10810
    most inner unmatched table is maintained in join_tab->first_unmatched.
10819
10811
    Thus, when the first row from t5 with t5.a=t3.a is found
10820
 
    this pointer for t5 is changed from t4 to t2.             
 
10812
    this pointer for t5 is changed from t4 to t2.
10821
10813
 
10822
10814
    @par
10823
10815
    @b STRUCTURE @b NOTES
10828
10820
  @param join      pointer to the structure providing all context info for
10829
10821
                   the query
10830
10822
  @param join_tab  the first next table of the execution plan to be retrieved
10831
 
  @param end_records  true when we need to perform final steps of retrival   
 
10823
  @param end_records  true when we need to perform final steps of retrival
10832
10824
 
10833
10825
  @return
10834
10826
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
10877
10869
      /* Set first_unmatched for the last inner table of this group */
10878
10870
      join_tab->last_inner->first_unmatched= join_tab;
10879
10871
    }
10880
 
    join->thd->row_count= 0;
 
10872
    join->session->row_count= 0;
10881
10873
 
10882
10874
    error= (*join_tab->read_first_record)(join_tab);
10883
10875
    rc= evaluate_join_record(join, join_tab, error);
10884
10876
  }
10885
 
  
10886
 
  /* 
10887
 
    Note: psergey has added the 2nd part of the following condition; the 
 
10877
 
 
10878
  /*
 
10879
    Note: psergey has added the 2nd part of the following condition; the
10888
10880
    change should probably be made in 5.1, too.
10889
10881
  */
10890
10882
  while (rc == NESTED_LOOP_OK && join->return_tab >= join_tab)
10910
10902
 
10911
10903
  SYNPOSIS
10912
10904
    do_sj_dups_weedout()
10913
 
      
 
10905
 
10914
10906
  RETURN
10915
10907
    -1  Error
10916
10908
    1   The row combination is a duplicate (discard it)
10917
10909
    0   The row combination is not a duplicate (continue)
10918
10910
*/
10919
10911
 
10920
 
int do_sj_dups_weedout(THD *thd, SJ_TMP_TABLE *sjtbl) 
 
10912
int do_sj_dups_weedout(Session *session, SJ_TMP_TABLE *sjtbl)
10921
10913
{
10922
10914
  int error;
10923
10915
  SJ_TMP_TABLE::TAB *tab= sjtbl->tabs;
10924
10916
  SJ_TMP_TABLE::TAB *tab_end= sjtbl->tabs_end;
10925
10917
  unsigned char *ptr= sjtbl->tmp_table->record[0] + 1;
10926
10918
  unsigned char *nulls_ptr= ptr;
10927
 
  
 
10919
 
10928
10920
  /* Put the the rowids tuple into table->record[0]: */
10929
10921
 
10930
 
  // 1. Store the length 
 
10922
  // 1. Store the length
10931
10923
  if (((Field_varstring*)(sjtbl->tmp_table->field[0]))->length_bytes == 1)
10932
10924
  {
10933
10925
    *ptr= (unsigned char)(sjtbl->rowid_len + sjtbl->null_bytes);
10939
10931
    ptr += 2;
10940
10932
  }
10941
10933
 
10942
 
  // 2. Zero the null bytes 
 
10934
  // 2. Zero the null bytes
10943
10935
  if (sjtbl->null_bytes)
10944
10936
  {
10945
10937
    memset(ptr, 0, sjtbl->null_bytes);
10946
 
    ptr += sjtbl->null_bytes; 
 
10938
    ptr += sjtbl->null_bytes;
10947
10939
  }
10948
10940
 
10949
10941
  // 3. Put the rowids
10970
10962
  {
10971
10963
    /* create_myisam_from_heap will generate error if needed */
10972
10964
    if (sjtbl->tmp_table->file->is_fatal_error(error, HA_CHECK_DUP) &&
10973
 
        create_myisam_from_heap(thd, sjtbl->tmp_table, sjtbl->start_recinfo, 
 
10965
        create_myisam_from_heap(session, sjtbl->tmp_table, sjtbl->start_recinfo,
10974
10966
                                &sjtbl->recinfo, error, 1))
10975
10967
      return -1;
10976
10968
    //return (error == HA_ERR_FOUND_DUPP_KEY || error== HA_ERR_FOUND_DUPP_UNIQUE) ? 1: -1;
11007
10999
  ha_rows found_records=join->found_records;
11008
11000
  COND *select_cond= join_tab->select_cond;
11009
11001
 
11010
 
  if (error > 0 || (join->thd->is_error()))     // Fatal error
 
11002
  if (error > 0 || (join->session->is_error()))     // Fatal error
11011
11003
    return NESTED_LOOP_ERROR;
11012
11004
  if (error < 0)
11013
11005
    return NESTED_LOOP_NO_MORE_ROWS;
11014
 
  if (join->thd->killed)                        // Aborted by user
 
11006
  if (join->session->killed)                    // Aborted by user
11015
11007
  {
11016
 
    join->thd->send_kill_message();
 
11008
    join->session->send_kill_message();
11017
11009
    return NESTED_LOOP_KILLED;               /* purecov: inspected */
11018
11010
  }
11019
11011
  if (!select_cond || select_cond->val_int())
11076
11068
    join_tab->found_match= true;
11077
11069
    if (join_tab->check_weed_out_table)
11078
11070
    {
11079
 
      int res= do_sj_dups_weedout(join->thd, join_tab->check_weed_out_table);
 
11071
      int res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table);
11080
11072
      if (res == -1)
11081
11073
        return NESTED_LOOP_ERROR;
11082
11074
      if (res == 1)
11084
11076
    }
11085
11077
    else if (join_tab->do_firstmatch)
11086
11078
    {
11087
 
      /* 
11088
 
        We should return to the join_tab->do_firstmatch after we have 
 
11079
      /*
 
11080
        We should return to the join_tab->do_firstmatch after we have
11089
11081
        enumerated all the suffixes for current prefix row combination
11090
11082
      */
11091
11083
      return_tab= join_tab->do_firstmatch;
11097
11089
      (See above join->return_tab= tab).
11098
11090
    */
11099
11091
    join->examined_rows++;
11100
 
    join->thd->row_count++;
 
11092
    join->session->row_count++;
11101
11093
 
11102
11094
    if (found)
11103
11095
    {
11129
11121
      with the beginning coinciding with the current partial join.
11130
11122
    */
11131
11123
    join->examined_rows++;
11132
 
    join->thd->row_count++;
 
11124
    join->session->row_count++;
11133
11125
    join_tab->read_record.file->unlock_row();
11134
11126
  }
11135
11127
  return NESTED_LOOP_OK;
11160
11152
    join_tab->found= 1;
11161
11153
    join_tab->not_null_compl= 0;
11162
11154
    /* The outer row is complemented by nulls for each inner tables */
11163
 
    restore_record(join_tab->table,s->default_values);  // Make empty record
11164
 
    mark_as_null_row(join_tab->table);       // For group by without error
 
11155
    join_tab->table->restoreRecordAsDefault();  // Make empty record
 
11156
    join_tab->table->mark_as_null_row();       // For group by without error
11165
11157
    select_cond= join_tab->select_cond;
11166
11158
    /* Check all attached conditions for inner table rows. */
11167
11159
    if (select_cond && !select_cond->val_int())
11239
11231
  info= &join_tab->read_record;
11240
11232
  do
11241
11233
  {
11242
 
    if (join->thd->killed)
 
11234
    if (join->session->killed)
11243
11235
    {
11244
 
      join->thd->send_kill_message();
 
11236
      join->session->send_kill_message();
11245
11237
      return NESTED_LOOP_KILLED; // Aborted by user /* purecov: inspected */
11246
11238
    }
11247
11239
    SQL_SELECT *select=join_tab->select;
11256
11248
        if (!select || !select->skip_record())
11257
11249
        {
11258
11250
          int res= 0;
11259
 
          if (!join_tab->check_weed_out_table || 
11260
 
              !(res= do_sj_dups_weedout(join->thd, join_tab->check_weed_out_table)))
 
11251
          if (!join_tab->check_weed_out_table ||
 
11252
              !(res= do_sj_dups_weedout(join->session, join_tab->check_weed_out_table)))
11261
11253
          {
11262
11254
            rc= (join_tab->next_select)(join,join_tab+1,0);
11263
11255
            if (rc != NESTED_LOOP_OK && rc != NESTED_LOOP_NO_MORE_ROWS)
11304
11296
  table->const_table=1;
11305
11297
  table->null_row=0;
11306
11298
  table->status=STATUS_NO_RECORD;
11307
 
  
 
11299
 
11308
11300
  if (tab->type == JT_SYSTEM)
11309
11301
  {
11310
11302
    if ((error=join_read_system(tab)))
11319
11311
  }
11320
11312
  else
11321
11313
  {
11322
 
    if (!table->key_read && table->covering_keys.is_set(tab->ref.key) &&
 
11314
    if (!table->key_read && table->covering_keys.test(tab->ref.key) &&
11323
11315
        !table->no_keyread &&
11324
11316
        (int) table->reginfo.lock_type <= (int) TL_READ_HIGH_PRIORITY)
11325
11317
    {
11346
11338
  if (*tab->on_expr_ref && !table->null_row)
11347
11339
  {
11348
11340
    if ((table->null_row= test((*tab->on_expr_ref)->val_int() == 0)))
11349
 
      mark_as_null_row(table);  
 
11341
      table->mark_as_null_row();
11350
11342
  }
11351
11343
  if (!table->null_row)
11352
11344
    table->maybe_null=0;
11387
11379
    {
11388
11380
      if (error != HA_ERR_END_OF_FILE)
11389
11381
        return table->report_error(error);
11390
 
      mark_as_null_row(tab->table);
11391
 
      empty_record(table);                      // Make empty record
 
11382
      tab->table->mark_as_null_row();
 
11383
      table->emptyRecord();                     // Make empty record
11392
11384
      return -1;
11393
11385
    }
11394
 
    store_record(table,record[1]);
 
11386
    table->storeRecord();
11395
11387
  }
11396
11388
  else if (!table->status)                      // Only happens with left join
11397
 
    restore_record(table,record[1]);                    // restore old record
 
11389
    table->restoreRecord();                     // restore old record
11398
11390
  table->null_row=0;
11399
11391
  return table->status ? -1 : 0;
11400
11392
}
11421
11413
  if (table->status & STATUS_GARBAGE)           // If first read
11422
11414
  {
11423
11415
    table->status= 0;
11424
 
    if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
11416
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
11425
11417
      error=HA_ERR_KEY_NOT_FOUND;
11426
11418
    else
11427
11419
    {
11433
11425
    if (error)
11434
11426
    {
11435
11427
      table->status= STATUS_NOT_FOUND;
11436
 
      mark_as_null_row(tab->table);
11437
 
      empty_record(table);
 
11428
      tab->table->mark_as_null_row();
 
11429
      table->emptyRecord();
11438
11430
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
11439
11431
        return table->report_error(error);
11440
11432
      return -1;
11441
11433
    }
11442
 
    store_record(table,record[1]);
 
11434
    table->storeRecord();
11443
11435
  }
11444
11436
  else if (!(table->status & ~STATUS_NULL_ROW)) // Only happens with left join
11445
11437
  {
11446
11438
    table->status=0;
11447
 
    restore_record(table,record[1]);                    // restore old record
 
11439
    table->restoreRecord();                     // restore old record
11448
11440
  }
11449
11441
  table->null_row=0;
11450
11442
  return table->status ? -1 : 0;
11464
11456
 
11465
11457
  RETURN
11466
11458
    0  - Ok
11467
 
   -1  - Row not found 
 
11459
   -1  - Row not found
11468
11460
    1  - Error
11469
11461
*/
11470
11462
 
11509
11501
 
11510
11502
  DESCRIPTION
11511
11503
    This is "read_fist" function for the "ref" access method.
11512
 
   
 
11504
 
11513
11505
    The functon must leave the index initialized when it returns.
11514
11506
    ref_or_null access implementation depends on that.
11515
11507
 
11516
11508
  RETURN
11517
11509
    0  - Ok
11518
 
   -1  - Row not found 
 
11510
   -1  - Row not found
11519
11511
    1  - Error
11520
11512
*/
11521
11513
 
11528
11520
  /* Initialize the index first */
11529
11521
  if (!table->file->inited)
11530
11522
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11531
 
 
 
11523
 
11532
11524
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
11533
11525
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
11534
11526
  {
11536
11528
        return -1;
11537
11529
  }
11538
11530
 
11539
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
11531
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
11540
11532
    return -1;
11541
11533
  if ((error=table->file->index_read_map(table->record[0],
11542
11534
                                         tab->ref.key_buff,
11547
11539
      return table->report_error(error);
11548
11540
    return -1; /* purecov: inspected */
11549
11541
  }
 
11542
 
11550
11543
  return 0;
11551
11544
}
11552
11545
 
11553
11546
 
11554
11547
/**
11555
 
  This function is used when optimizing away order_st BY in 
 
11548
  This function is used when optimizing away order_st BY in
11556
11549
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
11557
11550
*/
11558
 
  
 
11551
 
11559
11552
static int
11560
11553
join_read_last_key(JOIN_TAB *tab)
11561
11554
{
11564
11557
 
11565
11558
  if (!table->file->inited)
11566
11559
    table->file->ha_index_init(tab->ref.key, tab->sorted);
11567
 
  if (cp_buffer_from_ref(tab->join->thd, &tab->ref))
 
11560
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
11568
11561
    return -1;
11569
11562
  if ((error=table->file->index_read_last_map(table->record[0],
11570
11563
                                              tab->ref.key_buff,
11580
11573
 
11581
11574
        /* ARGSUSED */
11582
11575
static int
11583
 
join_no_more_records(READ_RECORD *info __attribute__((unused)))
 
11576
join_no_more_records(READ_RECORD *)
11584
11577
{
11585
11578
  return -1;
11586
11579
}
11593
11586
  if (tab->insideout_match_tab->found_match)
11594
11587
  {
11595
11588
    KEY *key= tab->table->key_info + tab->index;
11596
 
    do 
 
11589
    do
11597
11590
    {
11598
11591
      int error;
11599
11592
      /* Save index tuple from record to the buffer */
11608
11601
        table->status= STATUS_GARBAGE;
11609
11602
        return -1;
11610
11603
      }
11611
 
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
 
11604
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
11612
11605
                      tab->insideout_buf, key->key_length));
11613
11606
    tab->insideout_match_tab->found_match= 0;
11614
11607
    return 0;
11633
11626
    table->status= STATUS_GARBAGE;
11634
11627
    return -1;
11635
11628
  }
 
11629
 
11636
11630
  return 0;
11637
11631
}
11638
11632
 
11652
11646
    table->status=STATUS_NOT_FOUND;
11653
11647
    error= -1;
11654
11648
  }
 
11649
 
11655
11650
  return error;
11656
11651
}
11657
11652
 
11679
11674
{
11680
11675
  delete tab->select->quick;
11681
11676
  tab->select->quick=0;
11682
 
  return tab->select->test_quick_select(tab->join->thd, tab->keys,
 
11677
  return tab->select->test_quick_select(tab->join->session, tab->keys,
11683
11678
                                        (table_map) 0, HA_POS_ERROR, 0,
11684
11679
                                        false);
11685
11680
}
11690
11685
{
11691
11686
  if (tab->select && tab->select->quick && tab->select->quick->reset())
11692
11687
    return 1;
11693
 
  init_read_record(&tab->read_record, tab->join->thd, tab->table,
 
11688
  init_read_record(&tab->read_record, tab->join->session, tab->table,
11694
11689
                   tab->select,1,1);
11695
11690
  return (*tab->read_record.read_record)(&tab->read_record);
11696
11691
}
11701
11696
{
11702
11697
  int error;
11703
11698
  Table *table=tab->table;
11704
 
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
 
11699
  if (!table->key_read && table->covering_keys.test(tab->index) &&
11705
11700
      !table->no_keyread)
11706
11701
  {
11707
11702
    table->key_read=1;
11732
11727
      table->report_error(error);
11733
11728
    return -1;
11734
11729
  }
 
11730
 
11735
11731
  return 0;
11736
11732
}
11737
11733
 
11743
11739
  if (tab->insideout_match_tab->found_match)
11744
11740
  {
11745
11741
    KEY *key= tab->table->key_info + tab->index;
11746
 
    do 
 
11742
    do
11747
11743
    {
11748
11744
      int error;
11749
11745
      /* Save index tuple from record to the buffer */
11751
11747
 
11752
11748
      if ((error=info->file->index_next(info->record)))
11753
11749
        return info->table->report_error(error);
11754
 
      
11755
 
    } while (!key_cmp(tab->table->key_info[tab->index].key_part, 
 
11750
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
11756
11751
                      tab->insideout_buf, key->key_length));
11757
11752
    tab->insideout_match_tab->found_match= 0;
11758
11753
    return 0;
11777
11772
{
11778
11773
  Table *table=tab->table;
11779
11774
  int error;
11780
 
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
 
11775
  if (!table->key_read && table->covering_keys.test(tab->index) &&
11781
11776
      !table->no_keyread)
11782
11777
  {
11783
11778
    table->key_read=1;
11793
11788
    table->file->ha_index_init(tab->index, 1);
11794
11789
  if ((error= tab->table->file->index_last(tab->table->record[0])))
11795
11790
    return table->report_error(error);
 
11791
 
11796
11792
  return 0;
11797
11793
}
11798
11794
 
11803
11799
  int error;
11804
11800
  if ((error= info->file->index_prev(info->record)))
11805
11801
    return info->table->report_error(error);
 
11802
 
11806
11803
  return 0;
11807
11804
}
11808
11805
 
11869
11866
 
11870
11867
/* ARGSUSED */
11871
11868
static enum_nested_loop_state
11872
 
end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
11873
 
         bool end_of_records)
 
11869
end_send(JOIN *join, JOIN_TAB *,
 
11870
         bool end_of_records)
11874
11871
{
11875
11872
  if (!end_of_records)
11876
11873
  {
11910
11907
            join->send_records= table->file->stats.records;
11911
11908
          }
11912
11909
        }
11913
 
        else 
 
11910
        else
11914
11911
        {
11915
11912
          join->do_send_rows= 0;
11916
11913
          if (join->unit->fake_select_lex)
11934
11931
}
11935
11932
 
11936
11933
 
11937
 
        /* ARGSUSED */
 
11934
/* ARGSUSED */
11938
11935
enum_nested_loop_state
11939
 
end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
11940
 
               bool end_of_records)
 
11936
end_send_group(JOIN *join, JOIN_TAB *, bool end_of_records)
11941
11937
{
11942
11938
  int idx= -1;
11943
11939
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
11945
11941
  if (!join->first_record || end_of_records ||
11946
11942
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
11947
11943
  {
11948
 
    if (join->first_record || 
 
11944
    if (join->first_record ||
11949
11945
        (end_of_records && !join->group && !join->group_optimized_away))
11950
11946
    {
11951
11947
      if (idx < (int) join->send_group_parts)
11972
11968
          }
11973
11969
          if (join->rollup.state != ROLLUP::STATE_NONE && error <= 0)
11974
11970
          {
11975
 
            if (join->rollup_send_data((uint) (idx+1)))
 
11971
            if (join->rollup_send_data((uint32_t) (idx+1)))
11976
11972
              error= 1;
11977
11973
          }
11978
11974
        }
12027
12023
}
12028
12024
 
12029
12025
 
12030
 
        /* ARGSUSED */
 
12026
/* ARGSUSED */
12031
12027
enum_nested_loop_state
12032
 
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12033
 
          bool end_of_records)
 
12028
end_write(JOIN *join, JOIN_TAB *,
 
12029
          bool end_of_records)
12034
12030
{
12035
12031
  Table *table=join->tmp_table;
12036
12032
 
12037
 
  if (join->thd->killed)                        // Aborted by user
 
12033
  if (join->session->killed)                    // Aborted by user
12038
12034
  {
12039
 
    join->thd->send_kill_message();
 
12035
    join->session->send_kill_message();
12040
12036
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12041
12037
  }
12042
12038
  if (!end_of_records)
12043
12039
  {
12044
12040
    copy_fields(&join->tmp_table_param);
12045
12041
    copy_funcs(join->tmp_table_param.items_to_copy);
12046
 
#ifdef TO_BE_DELETED
12047
 
    if (!table->uniques)                        // If not unique handling
12048
 
    {
12049
 
      /* Copy null values from group to row */
12050
 
      order_st   *group;
12051
 
      for (group=table->group ; group ; group=group->next)
12052
 
      {
12053
 
        Item *item= *group->item;
12054
 
        if (item->maybe_null)
12055
 
        {
12056
 
          Field *field=item->get_tmp_table_field();
12057
 
          field->ptr[-1]= (unsigned char) (field->is_null() ? 1 : 0);
12058
 
        }
12059
 
      }
12060
 
    }
12061
 
#endif
12062
12042
    if (!join->having || join->having->val_int())
12063
12043
    {
12064
12044
      int error;
12067
12047
      {
12068
12048
        if (!table->file->is_fatal_error(error, HA_CHECK_DUP))
12069
12049
          goto end;
12070
 
        if (create_myisam_from_heap(join->thd, table,
 
12050
        if (create_myisam_from_heap(join->session, table,
12071
12051
                                    join->tmp_table_param.start_recinfo,
12072
12052
                                    &join->tmp_table_param.recinfo,
12073
12053
                                    error, 1))
12093
12073
/** Group by searching after group record and updating it if possible. */
12094
12074
 
12095
12075
static enum_nested_loop_state
12096
 
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12097
 
           bool end_of_records)
 
12076
end_update(JOIN *join, JOIN_TAB *,
 
12077
           bool end_of_records)
12098
12078
{
12099
12079
  Table *table=join->tmp_table;
12100
12080
  order_st   *group;
12102
12082
 
12103
12083
  if (end_of_records)
12104
12084
    return(NESTED_LOOP_OK);
12105
 
  if (join->thd->killed)                        // Aborted by user
 
12085
  if (join->session->killed)                    // Aborted by user
12106
12086
  {
12107
 
    join->thd->send_kill_message();
 
12087
    join->session->send_kill_message();
12108
12088
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12109
12089
  }
12110
12090
 
12124
12104
                                   HA_WHOLE_KEY,
12125
12105
                                   HA_READ_KEY_EXACT))
12126
12106
  {                                             /* Update old record */
12127
 
    restore_record(table,record[1]);
 
12107
    table->restoreRecord();
12128
12108
    update_tmptable_sum_func(join->sum_funcs,table);
12129
12109
    if ((error=table->file->ha_update_row(table->record[1],
12130
12110
                                          table->record[0])))
12152
12132
  copy_funcs(join->tmp_table_param.items_to_copy);
12153
12133
  if ((error=table->file->ha_write_row(table->record[0])))
12154
12134
  {
12155
 
    if (create_myisam_from_heap(join->thd, table,
 
12135
    if (create_myisam_from_heap(join->session, table,
12156
12136
                                join->tmp_table_param.start_recinfo,
12157
12137
                                &join->tmp_table_param.recinfo,
12158
12138
                                error, 0))
12169
12149
/** Like end_update, but this is done with unique constraints instead of keys.  */
12170
12150
 
12171
12151
static enum_nested_loop_state
12172
 
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12173
 
                  bool end_of_records)
 
12152
end_unique_update(JOIN *join, JOIN_TAB *,
 
12153
                  bool end_of_records)
12174
12154
{
12175
12155
  Table *table=join->tmp_table;
12176
12156
  int     error;
12177
12157
 
12178
12158
  if (end_of_records)
12179
12159
    return(NESTED_LOOP_OK);
12180
 
  if (join->thd->killed)                        // Aborted by user
 
12160
  if (join->session->killed)                    // Aborted by user
12181
12161
  {
12182
 
    join->thd->send_kill_message();
 
12162
    join->session->send_kill_message();
12183
12163
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12184
12164
  }
12185
12165
 
12201
12181
      table->file->print_error(error,MYF(0));   /* purecov: inspected */
12202
12182
      return(NESTED_LOOP_ERROR);            /* purecov: inspected */
12203
12183
    }
12204
 
    restore_record(table,record[1]);
 
12184
    table->restoreRecord();
12205
12185
    update_tmptable_sum_func(join->sum_funcs,table);
12206
12186
    if ((error=table->file->ha_update_row(table->record[1],
12207
12187
                                          table->record[0])))
12214
12194
}
12215
12195
 
12216
12196
 
12217
 
        /* ARGSUSED */
 
12197
/* ARGSUSED */
12218
12198
enum_nested_loop_state
12219
 
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
12220
 
                bool end_of_records)
 
12199
end_write_group(JOIN *join, JOIN_TAB *,
 
12200
                bool end_of_records)
12221
12201
{
12222
12202
  Table *table=join->tmp_table;
12223
12203
  int     idx= -1;
12224
12204
 
12225
 
  if (join->thd->killed)
 
12205
  if (join->session->killed)
12226
12206
  {                                             // Aborted by user
12227
 
    join->thd->send_kill_message();
 
12207
    join->session->send_kill_message();
12228
12208
    return(NESTED_LOOP_KILLED);             /* purecov: inspected */
12229
12209
  }
12230
12210
  if (!join->first_record || end_of_records ||
12245
12225
        if (!join->having || join->having->val_int())
12246
12226
        {
12247
12227
          int error= table->file->ha_write_row(table->record[0]);
12248
 
          if (error && create_myisam_from_heap(join->thd, table,
 
12228
          if (error && create_myisam_from_heap(join->session, table,
12249
12229
                                               join->tmp_table_param.start_recinfo,
12250
12230
                                                &join->tmp_table_param.recinfo,
12251
12231
                                               error, 0))
12253
12233
        }
12254
12234
        if (join->rollup.state != ROLLUP::STATE_NONE)
12255
12235
        {
12256
 
          if (join->rollup_write_data((uint) (idx+1), table))
 
12236
          if (join->rollup_write_data((uint32_t) (idx+1), table))
12257
12237
            return(NESTED_LOOP_ERROR);
12258
12238
        }
12259
12239
        if (end_of_records)
12343
12323
 
12344
12324
   @note Because of current requirements for semijoin flattening, we do not
12345
12325
   need to recurse here, hence this function will only examine the top-level
12346
 
   AND conditions. (see JOIN::prepare, comment above the line 
 
12326
   AND conditions. (see JOIN::prepare, comment above the line
12347
12327
   'if (do_materialize)'
12348
 
   
 
12328
 
12349
12329
   @param join The top-level query.
12350
12330
   @param old_cond The expression to be replaced.
12351
12331
   @param new_cond The expression to be substituted.
12352
 
   @param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for
 
12332
   @param do_fix_fields If true, Item::fix_fields(Session*, Item**) is called for
12353
12333
   the new expression.
12354
12334
   @return <code>true</code> if there was an error, <code>false</code> if
12355
12335
   successful.
12356
12336
*/
12357
 
static bool replace_where_subcondition(JOIN *join, Item *old_cond, 
 
12337
static bool replace_where_subcondition(JOIN *join, Item *old_cond,
12358
12338
                                       Item *new_cond, bool do_fix_fields)
12359
12339
{
12360
12340
  if (join->conds == old_cond) {
12361
12341
    join->conds= new_cond;
12362
12342
    if (do_fix_fields)
12363
 
      new_cond->fix_fields(join->thd, &join->conds);
 
12343
      new_cond->fix_fields(join->session, &join->conds);
12364
12344
    return false;
12365
12345
  }
12366
 
  
 
12346
 
12367
12347
  if (join->conds->type() == Item::COND_ITEM) {
12368
12348
    List_iterator<Item> li(*((Item_cond*)join->conds)->argument_list());
12369
12349
    Item *item;
12370
12350
    while ((item= li++))
12371
 
      if (item == old_cond) 
 
12351
      if (item == old_cond)
12372
12352
      {
12373
12353
        li.replace(new_cond);
12374
12354
        if (do_fix_fields)
12375
 
          new_cond->fix_fields(join->thd, li.ref());
 
12355
          new_cond->fix_fields(join->session, li.ref());
12376
12356
        return false;
12377
12357
      }
12378
12358
  }
12382
12362
 
12383
12363
/*
12384
12364
  Extract a condition that can be checked after reading given table
12385
 
  
 
12365
 
12386
12366
  SYNOPSIS
12387
12367
    make_cond_for_table()
12388
12368
      cond         Condition to analyze
12389
12369
      tables       Tables for which "current field values" are available
12390
 
      used_table   Table that we're extracting the condition for (may 
 
12370
      used_table   Table that we're extracting the condition for (may
12391
12371
                   also include PSEUDO_TABLE_BITS
12392
12372
 
12393
12373
  DESCRIPTION
12397
12377
 
12398
12378
    The function assumes that
12399
12379
      - Constant parts of the condition has already been checked.
12400
 
      - Condition that could be checked for tables in 'tables' has already 
 
12380
      - Condition that could be checked for tables in 'tables' has already
12401
12381
        been checked.
12402
 
        
 
12382
 
12403
12383
    The function takes into account that some parts of the condition are
12404
12384
    guaranteed to be true by employed 'ref' access methods (the code that
12405
12385
    does this is located at the end, search down for "EQ_FUNC").
12406
12386
 
12407
12387
 
12408
 
  SEE ALSO 
 
12388
  SEE ALSO
12409
12389
    make_cond_for_info_schema uses similar algorithm
12410
12390
 
12411
12391
  RETURN
12500
12480
  if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK)
12501
12481
    return cond;                                // Not boolean op
12502
12482
 
12503
 
  /* 
 
12483
  /*
12504
12484
    Remove equalities that are guaranteed to be true by use of 'ref' access
12505
12485
    method
12506
12486
  */
12595
12575
      These are already skipped in the order_st BY by const_expression_in_where()
12596
12576
    */
12597
12577
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
12598
 
      key_part++; 
 
12578
      key_part++;
12599
12579
 
12600
12580
    if (key_part == key_part_end)
12601
12581
    {
12602
 
      /* 
 
12582
      /*
12603
12583
        We are at the end of the key. Check if the engine has the primary
12604
12584
        key as a suffix to the secondary keys. If it has continue to check
12605
12585
        the primary key as a suffix.
12614
12594
        const_key_parts=table->const_key_parts[table->s->primary_key];
12615
12595
 
12616
12596
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
12617
 
          key_part++; 
 
12597
          key_part++;
12618
12598
        /*
12619
12599
         The primary and secondary key parts were all const (i.e. there's
12620
12600
         one row).  The sorting doesn't matter.
12638
12618
    key_part++;
12639
12619
  }
12640
12620
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
12641
 
    (uint) (key_part - table->key_info[idx].key_part);
 
12621
    (uint32_t) (key_part - table->key_info[idx].key_part);
12642
12622
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
12643
12623
                         HA_READ_PREV))
12644
12624
    reverse= 0;                                 // Index can't be used
12662
12642
    0   no sub key
12663
12643
*/
12664
12644
 
12665
 
inline bool 
 
12645
inline bool
12666
12646
is_subkey(KEY_PART_INFO *key_part, KEY_PART_INFO *ref_key_part,
12667
12647
          KEY_PART_INFO *ref_key_part_end)
12668
12648
{
12697
12677
 
12698
12678
  for (nr= 0 ; nr < table->s->keys ; nr++)
12699
12679
  {
12700
 
    if (usable_keys->is_set(nr) &&
 
12680
    if (usable_keys->test(nr) &&
12701
12681
        table->key_info[nr].key_length < min_length &&
12702
12682
        table->key_info[nr].key_parts >= ref_key_parts &&
12703
12683
        is_subkey(table->key_info[nr].key_part, ref_key_part,
12730
12710
    of the table are referenced by a list : either the select list
12731
12711
    through find_field_in_item_list or GROUP BY list through
12732
12712
    find_field_in_order_list.
12733
 
    If the above holds and the key parts cannot contain NULLs then we 
 
12713
    If the above holds and the key parts cannot contain NULLs then we
12734
12714
    can safely remove the GROUP BY/DISTINCT,
12735
12715
    as no result set can be more distinct than an unique key.
12736
12716
 
12761
12741
           key_part < key_part_end;
12762
12742
           key_part++)
12763
12743
      {
12764
 
        if (key_part->field->maybe_null() || 
 
12744
        if (key_part->field->maybe_null() ||
12765
12745
            !find_func(key_part->field, data))
12766
12746
          break;
12767
12747
      }
12858
12838
  The index must cover all fields in <order>, or it will not be considered.
12859
12839
 
12860
12840
  @todo
12861
 
    - sergeyp: Results of all index merge selects actually are ordered 
 
12841
    - sergeyp: Results of all index merge selects actually are ordered
12862
12842
    by clustered PK values.
12863
12843
 
12864
12844
  @retval
12891
12871
    Item *item= (*tmp_order->item)->real_item();
12892
12872
    if (item->type() != Item::FIELD_ITEM)
12893
12873
    {
12894
 
      usable_keys.clear_all();
 
12874
      usable_keys.reset();
12895
12875
      return(0);
12896
12876
    }
12897
 
    usable_keys.intersect(((Item_field*) item)->field->part_of_sortkey);
12898
 
    if (usable_keys.is_clear_all())
 
12877
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
 
12878
    if (usable_keys.none())
12899
12879
      return(0);                                        // No usable keys
12900
12880
  }
12901
12881
 
12912
12892
  {
12913
12893
    int quick_type= select->quick->get_type();
12914
12894
    save_quick= select->quick;
12915
 
    /* 
12916
 
      assume results are not ordered when index merge is used 
12917
 
      TODO: sergeyp: Results of all index merge selects actually are ordered 
 
12895
    /*
 
12896
      assume results are not ordered when index merge is used
 
12897
      TODO: sergeyp: Results of all index merge selects actually are ordered
12918
12898
      by clustered PK values.
12919
12899
    */
12920
 
  
12921
 
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE || 
12922
 
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || 
 
12900
 
 
12901
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
12902
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
12923
12903
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
12924
12904
      return(0);
12925
12905
    ref_key=       select->quick->index;
12931
12911
    /*
12932
12912
      We come here when there is a REF key.
12933
12913
    */
12934
 
    if (!usable_keys.is_set(ref_key))
 
12914
    if (! usable_keys.test(ref_key))
12935
12915
    {
12936
12916
      /*
12937
12917
        We come here when ref_key is not among usable_keys
12941
12921
        If using index only read, only consider other possible index only
12942
12922
        keys
12943
12923
      */
12944
 
      if (table->covering_keys.is_set(ref_key))
12945
 
        usable_keys.intersect(table->covering_keys);
 
12924
      if (table->covering_keys.test(ref_key))
 
12925
        usable_keys&= table->covering_keys;
12946
12926
      if (tab->pre_idx_push_select_cond)
12947
12927
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
12948
12928
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
12952
12932
        if (tab->ref.key >= 0)
12953
12933
        {
12954
12934
          /*
12955
 
            We'll use ref access method on key new_ref_key. In general case 
 
12935
            We'll use ref access method on key new_ref_key. In general case
12956
12936
            the index search tuple for new_ref_key will be different (e.g.
12957
12937
            when one index is defined as (part1, part2, ...) and another as
12958
 
            (part1, part2(N), ...) and the WHERE clause contains 
12959
 
            "part1 = const1 AND part2=const2". 
 
12938
            (part1, part2(N), ...) and the WHERE clause contains
 
12939
            "part1 = const1 AND part2=const2".
12960
12940
            So we build tab->ref from scratch here.
12961
12941
          */
12962
12942
          KEYUSE *keyuse= tab->keyuse;
12963
12943
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
12964
12944
            keyuse++;
12965
12945
 
12966
 
          if (create_ref_for_key(tab->join, tab, keyuse, 
 
12946
          if (create_ref_for_key(tab->join, tab, keyuse,
12967
12947
                                 tab->join->const_table_map))
12968
12948
            return(0);
12969
12949
        }
12978
12958
            parameres are set correctly by the range optimizer.
12979
12959
           */
12980
12960
          key_map new_ref_key_map;
12981
 
          new_ref_key_map.clear_all();  // Force the creation of quick select
12982
 
          new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
 
12961
          new_ref_key_map.reset();  // Force the creation of quick select
 
12962
          new_ref_key_map.set(new_ref_key); // only for new_ref_key.
12983
12963
 
12984
 
          if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0,
 
12964
          if (select->test_quick_select(tab->join->session, new_ref_key_map, 0,
12985
12965
                                        (tab->join->select_options &
12986
12966
                                         OPTION_FOUND_ROWS) ?
12987
12967
                                        HA_POS_ERROR :
12994
12974
      }
12995
12975
    }
12996
12976
    /* Check if we get the rows in requested sorted order by using the key */
12997
 
    if (usable_keys.is_set(ref_key) &&
 
12977
    if (usable_keys.test(ref_key) &&
12998
12978
        (order_direction= test_if_order_by_key(order,table,ref_key,
12999
12979
                                               &used_key_parts)))
13000
12980
      goto check_reverse_order;
13027
13007
    */
13028
13008
    if (select_limit >= table_records)
13029
13009
    {
13030
 
      /* 
13031
 
        filesort() and join cache are usually faster than reading in 
 
13010
      /*
 
13011
        filesort() and join cache are usually faster than reading in
13032
13012
        index order and not using join cache
13033
13013
        */
13034
13014
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
13035
13015
        return(0);
13036
13016
      keys= *table->file->keys_to_use_for_scanning();
13037
 
      keys.merge(table->covering_keys);
 
13017
      keys|= table->covering_keys;
13038
13018
 
13039
13019
      /*
13040
 
        We are adding here also the index specified in FORCE INDEX clause, 
 
13020
        We are adding here also the index specified in FORCE INDEX clause,
13041
13021
        if any.
13042
13022
        This is to allow users to use index in order_st BY.
13043
13023
      */
13044
 
      if (table->force_index) 
13045
 
        keys.merge(group ? table->keys_in_use_for_group_by :
 
13024
      if (table->force_index)
 
13025
        keys|= (group ? table->keys_in_use_for_group_by :
13046
13026
                           table->keys_in_use_for_order_by);
13047
 
      keys.intersect(usable_keys);
 
13027
      keys&= usable_keys;
13048
13028
    }
13049
13029
    else
13050
13030
      keys= usable_keys;
13056
13036
    for (nr=0; nr < table->s->keys ; nr++)
13057
13037
    {
13058
13038
      int direction;
13059
 
      if (keys.is_set(nr) &&
 
13039
      if (keys.test(nr) &&
13060
13040
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
13061
13041
      {
13062
 
        bool is_covering= table->covering_keys.is_set(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
13063
 
        
13064
 
        /* 
 
13042
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
 
13043
 
 
13044
        /*
13065
13045
          Don't use an index scan with order_st BY without limit.
13066
13046
          For GROUP BY without limit always use index scan
13067
 
          if there is a suitable index. 
 
13047
          if there is a suitable index.
13068
13048
          Why we hold to this asymmetry hardly can be explained
13069
13049
          rationally. It's easy to demonstrate that using
13070
13050
          temporary table + filesort could be cheaper for grouping
13071
13051
          queries too.
13072
 
        */ 
 
13052
        */
13073
13053
        if (is_covering ||
13074
 
            select_limit != HA_POS_ERROR || 
 
13054
            select_limit != HA_POS_ERROR ||
13075
13055
            (ref_key < 0 && (group || table->force_index)))
13076
 
        { 
 
13056
        {
13077
13057
          double rec_per_key;
13078
13058
          double index_scan_time;
13079
13059
          KEY *keyinfo= tab->table->key_info+nr;
13082
13062
          if (group)
13083
13063
          {
13084
13064
            rec_per_key= keyinfo->rec_per_key[used_key_parts-1];
13085
 
            set_if_bigger(rec_per_key, 1);
 
13065
            set_if_bigger(rec_per_key, 1.0);
13086
13066
            /*
13087
13067
              With a grouping query each group containing on average
13088
13068
              rec_per_key records produces only one row that will
13089
13069
              be included into the result set.
13090
 
            */  
 
13070
            */
13091
13071
            if (select_limit > table_records/rec_per_key)
13092
13072
                select_limit= table_records;
13093
13073
            else
13094
13074
              select_limit= (ha_rows) (select_limit*rec_per_key);
13095
13075
          }
13096
 
          /* 
 
13076
          /*
13097
13077
            If tab=tk is not the last joined table tn then to get first
13098
13078
            L records from the result set we can expect to retrieve
13099
13079
            only L/fanout(tk,tn) where fanout(tk,tn) says how many
13108
13088
          /*
13109
13089
            We assume that each of the tested indexes is not correlated
13110
13090
            with ref_key. Thus, to select first N records we have to scan
13111
 
            N/selectivity(ref_key) index entries. 
 
13091
            N/selectivity(ref_key) index entries.
13112
13092
            selectivity(ref_key) = #scanned_records/#table_records =
13113
13093
            table->quick_condition_rows/table_records.
13114
13094
            In any case we can't select more than #table_records.
13115
 
            N/(table->quick_condition_rows/table_records) > table_records 
 
13095
            N/(table->quick_condition_rows/table_records) > table_records
13116
13096
            <=> N > table->quick_condition_rows.
13117
 
          */ 
 
13097
          */
13118
13098
          if (select_limit > table->quick_condition_rows)
13119
13099
            select_limit= table_records;
13120
13100
          else
13122
13102
                                     (double) table_records /
13123
13103
                                      table->quick_condition_rows);
13124
13104
          rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1];
13125
 
          set_if_bigger(rec_per_key, 1);
 
13105
          set_if_bigger(rec_per_key, 1.0);
13126
13106
          /*
13127
13107
            Here we take into account the fact that rows are
13128
13108
            accessed in sequences rec_per_key records in each.
13131
13111
            in a sequence we'll touch not more pages than the
13132
13112
            table file contains.
13133
13113
            TODO. Use the formula for a disk sweep sequential access
13134
 
            to calculate the cost of accessing data rows for one 
 
13114
            to calculate the cost of accessing data rows for one
13135
13115
            index entry.
13136
13116
          */
13137
13117
          index_scan_time= select_limit/rec_per_key *
13142
13122
            ha_rows quick_records= table_records;
13143
13123
            if (is_best_covering && !is_covering)
13144
13124
              continue;
13145
 
            if (table->quick_keys.is_set(nr))
 
13125
            if (table->quick_keys.test(nr))
13146
13126
              quick_records= table->quick_rows[nr];
13147
13127
            if (best_key < 0 ||
13148
13128
                (select_limit <= cmin(quick_records,best_records) ?
13153
13133
              best_key_parts= keyinfo->key_parts;
13154
13134
              best_records= quick_records;
13155
13135
              is_best_covering= is_covering;
13156
 
              best_key_direction= direction; 
 
13136
              best_key_direction= direction;
13157
13137
            }
13158
 
          }   
13159
 
        }      
 
13138
          }
 
13139
        }
13160
13140
      }
13161
13141
    }
13162
13142
    if (best_key >= 0)
13163
13143
    {
13164
13144
      bool quick_created= false;
13165
 
      if (table->quick_keys.is_set(best_key) && best_key != ref_key)
 
13145
      if (table->quick_keys.test(best_key) && best_key != ref_key)
13166
13146
      {
13167
 
        key_map map;
13168
 
        map.clear_all();       // Force the creation of quick select
13169
 
        map.set_bit(best_key); // only best_key.
13170
 
        quick_created=         
13171
 
          select->test_quick_select(join->thd, map, 0,
 
13147
        key_map test_map;
 
13148
        test_map.reset();       // Force the creation of quick select
 
13149
        test_map.set(best_key); // only best_key.
 
13150
        quick_created=
 
13151
          select->test_quick_select(join->session, test_map, 0,
13172
13152
                                    join->select_options & OPTION_FOUND_ROWS ?
13173
13153
                                    HA_POS_ERROR :
13174
13154
                                    join->unit->select_limit_cnt,
13187
13167
            delete select->quick;
13188
13168
            select->quick= 0;
13189
13169
          }
13190
 
          if (table->covering_keys.is_set(best_key))
 
13170
          if (table->covering_keys.test(best_key))
13191
13171
          {
13192
13172
            table->key_read=1;
13193
13173
            table->file->extra(HA_EXTRA_KEYREAD);
13197
13177
          {
13198
13178
            tab->ref.key= -1;
13199
13179
            tab->ref.key_parts= 0;
13200
 
            if (select_limit < table_records) 
 
13180
            if (select_limit < table_records)
13201
13181
              tab->limit= select_limit;
13202
13182
          }
13203
13183
        }
13223
13203
      order_direction= best_key_direction;
13224
13204
    }
13225
13205
    else
13226
 
      return(0); 
13227
 
  } 
 
13206
      return(0);
 
13207
  }
13228
13208
 
13229
 
check_reverse_order:                  
 
13209
check_reverse_order:
13230
13210
  if (order_direction == -1)            // If order_st BY ... DESC
13231
13211
  {
13232
13212
    if (select && select->quick)
13249
13229
          select->quick= save_quick;
13250
13230
          return(0);                   // Use filesort
13251
13231
        }
13252
 
            
 
13232
 
13253
13233
        /* order_st BY range_key DESC */
13254
13234
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
13255
13235
                                    used_key_parts, &error);
13263
13243
        select->quick=tmp;
13264
13244
      }
13265
13245
    }
13266
 
    else if (tab->type != JT_NEXT && 
 
13246
    else if (tab->type != JT_NEXT &&
13267
13247
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
13268
13248
    {
13269
13249
      /*
13287
13267
 
13288
13268
  SYNOPSIS
13289
13269
   create_sort_index()
13290
 
     thd                Thread handler
 
13270
     session            Thread handler
13291
13271
     tab                Table to sort (in join structure)
13292
13272
     order              How table should be sorted
13293
13273
     filesort_limit     Max number of rows that needs to be sorted
13294
13274
     select_limit       Max number of rows in final output
13295
13275
                        Used to decide if we should use index or not
13296
13276
     is_order_by        true if we are sorting on order_st BY, false if GROUP BY
13297
 
                        Used to decide if we should use index or not     
 
13277
                        Used to decide if we should use index or not
13298
13278
 
13299
13279
 
13300
13280
  IMPLEMENTATION
13312
13292
*/
13313
13293
 
13314
13294
static int
13315
 
create_sort_index(THD *thd, JOIN *join, order_st *order,
 
13295
create_sort_index(Session *session, JOIN *join, order_st *order,
13316
13296
                  ha_rows filesort_limit, ha_rows select_limit,
13317
13297
                  bool is_order_by)
13318
13298
{
13334
13314
    is going to be used as it is applied now only for one table queries
13335
13315
    with covering indexes.
13336
13316
  */
13337
 
  if ((order != join->group_list || 
 
13317
  if ((order != join->group_list ||
13338
13318
       !(join->select_options & SELECT_BIG_RESULT) ||
13339
13319
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
13340
 
      test_if_skip_sort_order(tab,order,select_limit,0, 
 
13320
      test_if_skip_sort_order(tab,order,select_limit,0,
13341
13321
                              is_order_by ?  &table->keys_in_use_for_order_by :
13342
13322
                              &table->keys_in_use_for_group_by))
13343
13323
    return(0);
13344
13324
  for (order_st *ord= join->order; ord; ord= ord->next)
13345
13325
    length++;
13346
 
  if (!(join->sortorder= 
 
13326
  if (!(join->sortorder=
13347
13327
        make_unireg_sortorder(order, &length, join->sortorder)))
13348
13328
    goto err;                           /* purecov: inspected */
13349
13329
 
13350
 
  table->sort.io_cache=(IO_CACHE*) my_malloc(sizeof(IO_CACHE),
13351
 
                                             MYF(MY_WME | MY_ZEROFILL));
 
13330
  table->sort.io_cache= new IO_CACHE;
 
13331
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
13352
13332
  table->status=0;                              // May be wrong if quick_select
13353
13333
 
13354
13334
  // If table has a range, move it to select
13358
13338
    {
13359
13339
      select->quick=tab->quick;
13360
13340
      tab->quick=0;
13361
 
      /* 
 
13341
      /*
13362
13342
        We can only use 'Only index' if quick key is same as ref_key
13363
13343
        and in index_merge 'Only index' cannot be used
13364
13344
      */
13365
 
      if (table->key_read && ((uint) tab->ref.key != select->quick->index))
 
13345
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
13366
13346
      {
13367
13347
        table->key_read=0;
13368
13348
        table->file->extra(HA_EXTRA_NO_KEYREAD);
13376
13356
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
13377
13357
        field, quick will contain an empty record set.
13378
13358
      */
13379
 
      if (!(select->quick= (get_quick_select_for_ref(thd, table, &tab->ref, 
 
13359
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
13380
13360
                                                     tab->found_records))))
13381
13361
        goto err;
13382
13362
    }
13389
13369
 
13390
13370
  if (table->s->tmp_table)
13391
13371
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
13392
 
  table->sort.found_records=filesort(thd, table,join->sortorder, length,
 
13372
  table->sort.found_records=filesort(session, table,join->sortorder, length,
13393
13373
                                     select, filesort_limit, 0,
13394
13374
                                     &examined_rows);
13395
13375
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
13439
13419
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
13440
13420
{
13441
13421
  int error;
13442
 
  ulong reclength,offset;
 
13422
  uint32_t reclength,offset;
13443
13423
  uint32_t field_count;
13444
 
  THD *thd= join->thd;
 
13424
  Session *session= join->session;
13445
13425
 
13446
13426
  entry->reginfo.lock_type=TL_WRITE;
13447
13427
 
13455
13435
      field_count++;
13456
13436
  }
13457
13437
 
13458
 
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having) 
 
13438
  if (!field_count && !(join->select_options & OPTION_FOUND_ROWS) && !having)
13459
13439
  {                    // only const items with no OPTION_FOUND_ROWS
13460
13440
    join->unit->select_limit_cnt= 1;            // Only send first row
13461
13441
    return(0);
13462
13442
  }
13463
13443
  Field **first_field=entry->field+entry->s->fields - field_count;
13464
 
  offset= (field_count ? 
 
13444
  offset= (field_count ?
13465
13445
           entry->field[entry->s->fields - field_count]->
13466
13446
           offset(entry->record[0]) : 0);
13467
 
  reclength=entry->s->reclength-offset;
 
13447
  reclength= entry->s->reclength-offset;
13468
13448
 
13469
13449
  free_io_cache(entry);                         // Safety
13470
13450
  entry->file->info(HA_STATUS_VARIABLE);
13471
 
  if (entry->s->db_type() == heap_hton ||
 
13451
  if (entry->s->db_type() == heap_engine ||
13472
13452
      (!entry->s->blob_fields &&
13473
13453
       ((ALIGN_SIZE(reclength) + HASH_OVERHEAD) * entry->file->stats.records <
13474
 
        thd->variables.sortbuff_size)))
13475
 
    error=remove_dup_with_hash_index(join->thd, entry,
 
13454
        session->variables.sortbuff_size)))
 
13455
    error= remove_dup_with_hash_index(join->session, entry,
13476
13456
                                     field_count, first_field,
13477
13457
                                     reclength, having);
13478
13458
  else
13479
 
    error=remove_dup_with_compare(join->thd, entry, first_field, offset,
 
13459
    error= remove_dup_with_compare(join->session, entry, first_field, offset,
13480
13460
                                  having);
13481
13461
 
13482
13462
  free_blobs(first_field);
13484
13464
}
13485
13465
 
13486
13466
 
13487
 
static int remove_dup_with_compare(THD *thd, Table *table, Field **first_field,
13488
 
                                   ulong offset, Item *having)
 
13467
static int remove_dup_with_compare(Session *session, Table *table, Field **first_field,
 
13468
                                   uint32_t offset, Item *having)
13489
13469
{
13490
13470
  handler *file=table->file;
13491
13471
  char *org_record,*new_record;
13492
13472
  unsigned char *record;
13493
13473
  int error;
13494
 
  ulong reclength= table->s->reclength-offset;
 
13474
  uint32_t reclength= table->s->reclength-offset;
13495
13475
 
13496
13476
  org_record=(char*) (record=table->record[0])+offset;
13497
13477
  new_record=(char*) table->record[1]+offset;
13500
13480
  error=file->rnd_next(record);
13501
13481
  for (;;)
13502
13482
  {
13503
 
    if (thd->killed)
 
13483
    if (session->killed)
13504
13484
    {
13505
 
      thd->send_kill_message();
 
13485
      session->send_kill_message();
13506
13486
      error=0;
13507
13487
      goto err;
13508
13488
    }
13575
13555
    Note that this will not work on tables with blobs!
13576
13556
*/
13577
13557
 
13578
 
static int remove_dup_with_hash_index(THD *thd, Table *table,
 
13558
static int remove_dup_with_hash_index(Session *session, Table *table,
13579
13559
                                      uint32_t field_count,
13580
13560
                                      Field **first_field,
13581
 
                                      ulong key_length,
 
13561
                                      uint32_t key_length,
13582
13562
                                      Item *having)
13583
13563
{
13584
13564
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
13585
13565
  int error;
13586
13566
  handler *file= table->file;
13587
 
  ulong extra_length= ALIGN_SIZE(key_length)-key_length;
 
13567
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
13588
13568
  uint32_t *field_lengths,*field_length;
13589
13569
  HASH hash;
13590
13570
 
13591
13571
  if (!my_multi_malloc(MYF(MY_WME),
13592
13572
                       &key_buffer,
13593
 
                       (uint) ((key_length + extra_length) *
 
13573
                       (uint32_t) ((key_length + extra_length) *
13594
13574
                               (long) file->stats.records),
13595
13575
                       &field_lengths,
13596
 
                       (uint) (field_count*sizeof(*field_lengths)),
 
13576
                       (uint32_t) (field_count*sizeof(*field_lengths)),
13597
13577
                       NULL))
13598
13578
    return(1);
13599
13579
 
13600
13580
  {
13601
13581
    Field **ptr;
13602
 
    ulong total_length= 0;
 
13582
    uint32_t total_length= 0;
13603
13583
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
13604
13584
    {
13605
13585
      uint32_t length= (*ptr)->sort_length();
13611
13591
    extra_length= ALIGN_SIZE(key_length)-key_length;
13612
13592
  }
13613
13593
 
13614
 
  if (hash_init(&hash, &my_charset_bin, (uint) file->stats.records, 0, 
 
13594
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
13615
13595
                key_length, (hash_get_key) 0, 0, 0))
13616
13596
  {
13617
13597
    free((char*) key_buffer);
13623
13603
  for (;;)
13624
13604
  {
13625
13605
    unsigned char *org_key_pos;
13626
 
    if (thd->killed)
 
13606
    if (session->killed)
13627
13607
    {
13628
 
      thd->send_kill_message();
 
13608
      session->send_kill_message();
13629
13609
      error=0;
13630
13610
      goto err;
13631
13611
    }
13726
13706
******************************************************************************/
13727
13707
 
13728
13708
static int
13729
 
join_init_cache(THD *thd,JOIN_TAB *tables,uint32_t table_count)
 
13709
join_init_cache(Session *session,JOIN_TAB *tables,uint32_t table_count)
13730
13710
{
13731
13711
  register unsigned int i;
13732
13712
  unsigned int length, blobs;
13742
13722
  for (i=0 ; i < table_count ; i++,join_tab++)
13743
13723
  {
13744
13724
    if (!join_tab->used_fieldlength)            /* Not calced yet */
13745
 
      calc_used_field_length(thd, join_tab);
 
13725
      calc_used_field_length(session, join_tab);
13746
13726
    cache->fields+=join_tab->used_fields;
13747
13727
    blobs+=join_tab->used_blobs;
13748
13728
 
13771
13751
  {
13772
13752
    uint32_t null_fields=0, used_fields;
13773
13753
    Field **f_ptr,*field;
13774
 
    MY_BITMAP *read_set= tables[i].table->read_set;
13775
13754
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
13776
13755
         used_fields ;
13777
13756
         f_ptr++)
13778
13757
    {
13779
13758
      field= *f_ptr;
13780
 
      if (bitmap_is_set(read_set, field->field_index))
 
13759
      if (field->isReadSet())
13781
13760
      {
13782
13761
        used_fields--;
13783
13762
        length+=field->fill_cache_field(copy);
13834
13813
 
13835
13814
  cache->length=length+blobs*sizeof(char*);
13836
13815
  cache->blobs=blobs;
13837
 
  *blob_ptr=0;                                  /* End sequentel */
13838
 
  size=cmax(thd->variables.join_buff_size, (ulong)cache->length);
13839
 
  if (!(cache->buff=(unsigned char*) my_malloc(size,MYF(0))))
13840
 
    return(1);                          /* Don't use cache */ /* purecov: inspected */
 
13816
  *blob_ptr= NULL;                                      /* End sequentel */
 
13817
  size= max((size_t)session->variables.join_buff_size,
 
13818
            (size_t)cache->length);
 
13819
  if (!(cache->buff=(unsigned char*) malloc(size)))
 
13820
    return 1;                           /* Don't use cache */ /* purecov: inspected */
13841
13821
  cache->end=cache->buff+size;
13842
13822
  reset_cache_write(cache);
13843
 
  return(0);
 
13823
  return 0;
13844
13824
}
13845
13825
 
13846
13826
 
13847
 
static ulong
13848
 
used_blob_length(CACHE_FIELD **ptr)
 
13827
static uint32_t used_blob_length(CACHE_FIELD **ptr)
13849
13828
{
13850
13829
  uint32_t length,blob_length;
13851
13830
  for (length=0 ; *ptr ; ptr++)
13871
13850
 
13872
13851
  length=cache->length;
13873
13852
  if (cache->blobs)
13874
 
    length+=used_blob_length(cache->blob_ptr);
 
13853
    length+= used_blob_length(cache->blob_ptr);
13875
13854
  if ((last_record= (length + cache->length > (size_t) (cache->end - pos))))
13876
13855
    cache->ptr_record=cache->records;
13877
13856
  /*
13884
13863
    {
13885
13864
      if (last_record)
13886
13865
      {
13887
 
        copy->blob_field->get_image(pos, copy->length+sizeof(char*), 
 
13866
        copy->blob_field->get_image(pos, copy->length+sizeof(char*),
13888
13867
                                    copy->blob_field->charset());
13889
13868
        pos+=copy->length+sizeof(char*);
13890
13869
      }
13908
13887
        for (str=copy->str,end= str+copy->length;
13909
13888
             end > str && end[-1] == ' ' ;
13910
13889
             end--) ;
13911
 
        length=(uint) (end-str);
 
13890
        length=(uint32_t) (end-str);
13912
13891
        memcpy(pos+2, str, length);
13913
13892
        int2store(pos, length);
13914
13893
        pos+= length+2;
13996
13975
  SYNOPSIS
13997
13976
    cmp_buffer_with_ref()
13998
13977
      tab  Join tab of the accessed table
13999
 
 
14000
 
  DESCRIPTION 
14001
 
    Used by eq_ref access method: create the index lookup key and check if 
 
13978
 
 
13979
  DESCRIPTION
 
13980
    Used by eq_ref access method: create the index lookup key and check if
14002
13981
    we've used this key at previous lookup (If yes, we don't need to repeat
14003
13982
    the lookup - the record has been already fetched)
14004
13983
 
14005
 
  RETURN 
 
13984
  RETURN
14006
13985
    true   No cached record for the key, or failed to create the key (due to
14007
13986
           out-of-domain error)
14008
 
    false  The created key is the same as the previous one (and the record 
 
13987
    false  The created key is the same as the previous one (and the record
14009
13988
           is already in table->record)
14010
13989
*/
14011
13990
 
14021
14000
      memcpy(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length);
14022
14001
    }
14023
14002
  }
14024
 
  else 
 
14003
  else
14025
14004
    no_prev_key= true;
14026
 
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->thd, &tab->ref)) ||
 
14005
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->session, &tab->ref)) ||
14027
14006
      no_prev_key)
14028
14007
    return 1;
14029
14008
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
14032
14011
 
14033
14012
 
14034
14013
bool
14035
 
cp_buffer_from_ref(THD *thd, TABLE_REF *ref)
 
14014
cp_buffer_from_ref(Session *session, TABLE_REF *ref)
14036
14015
{
14037
 
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
14038
 
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
 
14016
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
 
14017
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
14039
14018
  bool result= 0;
14040
14019
 
14041
14020
  for (store_key **copy=ref->key_copy ; *copy ; copy++)
14046
14025
      break;
14047
14026
    }
14048
14027
  }
14049
 
  thd->count_cuted_fields= save_count_cuted_fields;
 
14028
  session->count_cuted_fields= save_count_cuted_fields;
14050
14029
  return result;
14051
14030
}
14052
14031
 
14071
14050
 
14072
14051
  ref_pointer_array and all_fields are updated.
14073
14052
 
14074
 
  @param[in] thd                     Pointer to current thread structure
 
14053
  @param[in] session                 Pointer to current thread structure
14075
14054
  @param[in,out] ref_pointer_array  All select, group and order by fields
14076
14055
  @param[in] tables                 List of tables to search in (usually
14077
14056
    FROM clause)
14089
14068
*/
14090
14069
 
14091
14070
static bool
14092
 
find_order_in_list(THD *thd, Item **ref_pointer_array, TableList *tables,
 
14071
find_order_in_list(Session *session, Item **ref_pointer_array, TableList *tables,
14093
14072
                   order_st *order, List<Item> &fields, List<Item> &all_fields,
14094
14073
                   bool is_group_field)
14095
14074
{
14106
14085
  */
14107
14086
  if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item())
14108
14087
  {                                             /* Order by position */
14109
 
    uint32_t count= (uint) order_item->val_int();
 
14088
    uint32_t count= (uint32_t) order_item->val_int();
14110
14089
    if (!count || count > fields.elements)
14111
14090
    {
14112
14091
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
14113
 
               order_item->full_name(), thd->where);
 
14092
               order_item->full_name(), session->where);
14114
14093
      return true;
14115
14094
    }
14116
14095
    order->item= ref_pointer_array + count - 1;
14136
14115
      for this name (in case if we would perform lookup in all tables).
14137
14116
    */
14138
14117
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
14139
 
        order_item->fix_fields(thd, order->item))
 
14118
        order_item->fix_fields(session, order->item))
14140
14119
      return true;
14141
14120
 
14142
14121
    /* Lookup the current GROUP field in the FROM clause. */
14145
14124
    if ((is_group_field && order_item_type == Item::FIELD_ITEM) ||
14146
14125
        order_item_type == Item::REF_ITEM)
14147
14126
    {
14148
 
      from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables,
 
14127
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
14149
14128
                                       NULL, &view_ref, IGNORE_ERRORS, true,
14150
14129
                                       false);
14151
14130
      if (!from_field)
14185
14164
        warning so the user knows that the field from the FROM clause
14186
14165
        overshadows the column reference from the SELECT list.
14187
14166
      */
14188
 
      push_warning_printf(thd, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
 
14167
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
14189
14168
                          ER(ER_NON_UNIQ_ERROR),
14190
14169
                          ((Item_ident*) order_item)->field_name,
14191
 
                          current_thd->where);
 
14170
                          current_session->where);
14192
14171
    }
14193
14172
  }
14194
14173
 
14205
14184
    arguments for which fix_fields already was called.
14206
14185
  */
14207
14186
  if (!order_item->fixed &&
14208
 
      (order_item->fix_fields(thd, order->item) ||
 
14187
      (order_item->fix_fields(session, order->item) ||
14209
14188
       (order_item= *order->item)->check_cols(1) ||
14210
 
       thd->is_fatal_error))
 
14189
       session->is_fatal_error))
14211
14190
    return true; /* Wrong field. */
14212
14191
 
14213
14192
  uint32_t el= all_fields.elements;
14225
14204
  the field list.
14226
14205
*/
14227
14206
 
14228
 
int setup_order(THD *thd, Item **ref_pointer_array, TableList *tables,
 
14207
int setup_order(Session *session, Item **ref_pointer_array, TableList *tables,
14229
14208
                List<Item> &fields, List<Item> &all_fields, order_st *order)
14230
14209
{
14231
 
  thd->where="order clause";
 
14210
  session->where="order clause";
14232
14211
  for (; order; order=order->next)
14233
14212
  {
14234
 
    if (find_order_in_list(thd, ref_pointer_array, tables, order, fields,
 
14213
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
14235
14214
                           all_fields, false))
14236
14215
      return 1;
14237
14216
  }
14242
14221
/**
14243
14222
  Intitialize the GROUP BY list.
14244
14223
 
14245
 
  @param thd                    Thread handler
 
14224
  @param session                        Thread handler
14246
14225
  @param ref_pointer_array      We store references to all fields that was
14247
14226
                               not in 'fields' here.
14248
14227
  @param fields         All fields in the select part. Any item in
14266
14245
*/
14267
14246
 
14268
14247
int
14269
 
setup_group(THD *thd, Item **ref_pointer_array, TableList *tables,
 
14248
setup_group(Session *session, Item **ref_pointer_array, TableList *tables,
14270
14249
            List<Item> &fields, List<Item> &all_fields, order_st *order,
14271
14250
            bool *hidden_group_fields)
14272
14251
{
14278
14257
 
14279
14258
  uint32_t org_fields=all_fields.elements;
14280
14259
 
14281
 
  thd->where="group statement";
 
14260
  session->where="group statement";
14282
14261
  for (ord= order; ord; ord= ord->next)
14283
14262
  {
14284
 
    if (find_order_in_list(thd, ref_pointer_array, tables, ord, fields,
 
14263
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
14285
14264
                           all_fields, true))
14286
14265
      return 1;
14287
14266
    (*ord->item)->marker= UNDEF_POS;            /* Mark found */
14312
14291
    Item_field *field;
14313
14292
    int cur_pos_in_select_list= 0;
14314
14293
    List_iterator<Item> li(fields);
14315
 
    List_iterator<Item_field> naf_it(thd->lex->current_select->non_agg_fields);
 
14294
    List_iterator<Item_field> naf_it(session->lex->current_select->non_agg_fields);
14316
14295
 
14317
14296
    field= naf_it++;
14318
14297
    while (field && (item=li++))
14363
14342
*/
14364
14343
 
14365
14344
static order_st *
14366
 
create_distinct_group(THD *thd, Item **ref_pointer_array,
 
14345
create_distinct_group(Session *session, Item **ref_pointer_array,
14367
14346
                      order_st *order_list, List<Item> &fields,
14368
 
                      List<Item> &all_fields __attribute__((unused)),
14369
 
                      bool *all_order_by_fields_used)
 
14347
                      List<Item> &, bool *all_order_by_fields_used)
14370
14348
{
14371
14349
  List_iterator<Item> li(fields);
14372
14350
  Item *item;
14381
14359
  {
14382
14360
    if (order->in_field_list)
14383
14361
    {
14384
 
      order_st *ord=(order_st*) thd->memdup((char*) order,sizeof(order_st));
 
14362
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
14385
14363
      if (!ord)
14386
14364
        return 0;
14387
14365
      *prev=ord;
14397
14375
  {
14398
14376
    if (!item->const_item() && !item->with_sum_func && !item->marker)
14399
14377
    {
14400
 
      /* 
14401
 
        Don't put duplicate columns from the SELECT list into the 
 
14378
      /*
 
14379
        Don't put duplicate columns from the SELECT list into the
14402
14380
        GROUP BY list.
14403
14381
      */
14404
14382
      order_st *ord_iter;
14405
14383
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
14406
14384
        if ((*ord_iter->item)->eq(item, 1))
14407
14385
          goto next_item;
14408
 
      
14409
 
      order_st *ord=(order_st*) thd->calloc(sizeof(order_st));
 
14386
 
 
14387
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
14410
14388
      if (!ord)
14411
14389
        return 0;
14412
14390
 
14433
14411
*/
14434
14412
 
14435
14413
void
14436
 
count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, 
 
14414
count_field_types(Select_Lex *select_lex, Tmp_Table_Param *param,
14437
14415
                  List<Item> &fields, bool reset_with_sum_func)
14438
14416
{
14439
14417
  List_iterator<Item> li(fields);
14557
14535
        key_length+= field->pack_length();
14558
14536
    }
14559
14537
    else
14560
 
    { 
 
14538
    {
14561
14539
      switch (group_item->result_type()) {
14562
14540
      case REAL_RESULT:
14563
14541
        key_length+= sizeof(double);
14566
14544
        key_length+= sizeof(int64_t);
14567
14545
        break;
14568
14546
      case DECIMAL_RESULT:
14569
 
        key_length+= my_decimal_get_binary_size(group_item->max_length - 
 
14547
        key_length+= my_decimal_get_binary_size(group_item->max_length -
14570
14548
                                                (group_item->decimals ? 1 : 0),
14571
14549
                                                group_item->decimals);
14572
14550
        break;
14575
14553
        enum enum_field_types type= group_item->field_type();
14576
14554
        /*
14577
14555
          As items represented as DATE/TIME fields in the group buffer
14578
 
          have STRING_RESULT result type, we increase the length 
 
14556
          have STRING_RESULT result type, we increase the length
14579
14557
          by 8 as maximum pack length of such fields.
14580
14558
        */
14581
 
        if (type == DRIZZLE_TYPE_TIME ||
14582
 
            type == DRIZZLE_TYPE_NEWDATE ||
 
14559
        if (type == DRIZZLE_TYPE_DATE ||
14583
14560
            type == DRIZZLE_TYPE_DATETIME ||
14584
14561
            type == DRIZZLE_TYPE_TIMESTAMP)
14585
14562
        {
14656
14633
  {
14657
14634
    for (; group ; group=group->next)
14658
14635
    {
14659
 
      Cached_item *tmp=new_Cached_item(join->thd, *group->item, false);
 
14636
      Cached_item *tmp=new_Cached_item(join->session, *group->item, false);
14660
14637
      if (!tmp || join->group_fields.push_front(tmp))
14661
14638
        return true;
14662
14639
    }
14672
14649
  @details Test if a list of items that typically represents a result
14673
14650
  row has changed. If the value of some item changed, update the cached
14674
14651
  value for this item.
14675
 
  
 
14652
 
14676
14653
  @param list list of <item, cached_value> pairs stored as Cached_item.
14677
14654
 
14678
14655
  @return -1 if no item changed
14703
14680
  Change old item_field to use a new field with points at saved fieldvalue
14704
14681
  This function is only called before use of send_fields.
14705
14682
 
14706
 
  @param thd                   THD pointer
 
14683
  @param session                   Session pointer
14707
14684
  @param param                 temporary table parameters
14708
14685
  @param ref_pointer_array     array of pointers to top elements of filed list
14709
14686
  @param res_selected_fields   new list of items of select item list
14724
14701
*/
14725
14702
 
14726
14703
bool
14727
 
setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
 
14704
setup_copy_fields(Session *session, Tmp_Table_Param *param,
14728
14705
                  Item **ref_pointer_array,
14729
14706
                  List<Item> &res_selected_fields, List<Item> &res_all_fields,
14730
14707
                  uint32_t elements, List<Item> &all_fields)
14738
14715
  List<Item> extra_funcs;
14739
14716
  uint32_t i, border= all_fields.elements - elements;
14740
14717
 
14741
 
  if (param->field_count && 
 
14718
  if (param->field_count &&
14742
14719
      !(copy=param->copy_field= new Copy_field[param->field_count]))
14743
14720
    goto err2;
14744
14721
 
14751
14728
    if (real_pos->type() == Item::FIELD_ITEM)
14752
14729
    {
14753
14730
      Item_field *item;
14754
 
      if (!(item= new Item_field(thd, ((Item_field*) real_pos))))
 
14731
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
14755
14732
        goto err;
14756
14733
      if (pos->type() == Item::REF_ITEM)
14757
14734
      {
14767
14744
        if (!(pos= new Item_copy_string(pos)))
14768
14745
          goto err;
14769
14746
       /*
14770
 
         Item_copy_string::copy for function can call 
 
14747
         Item_copy_string::copy for function can call
14771
14748
         Item_copy_string::val_int for blob via Item_ref.
14772
14749
         But if Item_copy_string::copy for blob isn't called before,
14773
14750
         it's value will be wrong
14774
 
         so let's insert Item_copy_string for blobs in the beginning of 
 
14751
         so let's insert Item_copy_string for blobs in the beginning of
14775
14752
         copy_funcs
14776
 
         (to see full test case look at having.test, BUG #4358) 
 
14753
         (to see full test case look at having.test, BUG #4358)
14777
14754
       */
14778
14755
        if (param->copy_funcs.push_front(pos))
14779
14756
          goto err;
14780
14757
      }
14781
14758
      else
14782
14759
      {
14783
 
        /* 
14784
 
           set up save buffer and change result_field to point at 
 
14760
        /*
 
14761
           set up save buffer and change result_field to point at
14785
14762
           saved value
14786
14763
        */
14787
14764
        field= item->field;
14788
 
        item->result_field=field->new_field(thd->mem_root,field->table, 1);
 
14765
        item->result_field=field->new_field(session->mem_root,field->table, 1);
14789
14766
        /*
14790
14767
          We need to allocate one extra byte for null handling and
14791
14768
          another extra byte to not get warnings from purify in
14861
14838
*/
14862
14839
 
14863
14840
void
14864
 
copy_fields(TMP_TABLE_PARAM *param)
 
14841
copy_fields(Tmp_Table_Param *param)
14865
14842
{
14866
14843
  Copy_field *ptr=param->copy_field;
14867
14844
  Copy_field *end=param->copy_field_end;
14919
14896
  }
14920
14897
 
14921
14898
  /* This must use calloc() as rollup_make_fields depends on this */
14922
 
  sum_funcs= (Item_sum**) thd->calloc(sizeof(Item_sum**) * (func_count+1) +
 
14899
  sum_funcs= (Item_sum**) session->calloc(sizeof(Item_sum**) * (func_count+1) +
14923
14900
                                      sizeof(Item_sum***) * (group_parts+1));
14924
14901
  sum_funcs_end= (Item_sum***) (sum_funcs+func_count+1);
14925
14902
  return(sum_funcs == 0);
14980
14957
  Change all funcs and sum_funcs to fields in tmp table, and create
14981
14958
  new list of all items.
14982
14959
 
14983
 
  @param thd                   THD pointer
 
14960
  @param session                   Session pointer
14984
14961
  @param ref_pointer_array     array of pointers to top elements of filed list
14985
14962
  @param res_selected_fields   new list of items of select item list
14986
14963
  @param res_all_fields        new list of all items
14994
14971
*/
14995
14972
 
14996
14973
static bool
14997
 
change_to_use_tmp_fields(THD *thd, Item **ref_pointer_array,
 
14974
change_to_use_tmp_fields(Session *session, Item **ref_pointer_array,
14998
14975
                         List<Item> &res_selected_fields,
14999
14976
                         List<Item> &res_all_fields,
15000
14977
                         uint32_t elements, List<Item> &all_fields)
15018
14995
    {
15019
14996
      if (item->type() == Item::FIELD_ITEM)
15020
14997
      {
15021
 
        item_field= item->get_tmp_table_item(thd);
 
14998
        item_field= item->get_tmp_table_item(session);
15022
14999
      }
15023
15000
      else if ((field= item->get_tmp_table_field()))
15024
15001
      {
15060
15037
  Change all sum_func refs to fields to point at fields in tmp table.
15061
15038
  Change all funcs to be fields in tmp table.
15062
15039
 
15063
 
  @param thd                   THD pointer
 
15040
  @param session                   Session pointer
15064
15041
  @param ref_pointer_array     array of pointers to top elements of filed list
15065
15042
  @param res_selected_fields   new list of items of select item list
15066
15043
  @param res_all_fields        new list of all items
15074
15051
*/
15075
15052
 
15076
15053
static bool
15077
 
change_refs_to_tmp_fields(THD *thd, Item **ref_pointer_array,
 
15054
change_refs_to_tmp_fields(Session *session, Item **ref_pointer_array,
15078
15055
                          List<Item> &res_selected_fields,
15079
15056
                          List<Item> &res_all_fields, uint32_t elements,
15080
15057
                          List<Item> &all_fields)
15087
15064
  uint32_t i, border= all_fields.elements - elements;
15088
15065
  for (i= 0; (item= it++); i++)
15089
15066
  {
15090
 
    res_all_fields.push_back(new_item= item->get_tmp_table_item(thd));
 
15067
    res_all_fields.push_back(new_item= item->get_tmp_table_item(session));
15091
15068
    ref_pointer_array[((i < border)? all_fields.elements-i-1 : i-border)]=
15092
15069
      new_item;
15093
15070
  }
15097
15074
    itr++;
15098
15075
  itr.sublist(res_selected_fields, elements);
15099
15076
 
15100
 
  return thd->is_fatal_error;
 
15077
  return session->is_fatal_error;
15101
15078
}
15102
15079
 
15103
15080
 
15110
15087
/**
15111
15088
  Call ::setup for all sum functions.
15112
15089
 
15113
 
  @param thd           thread handler
 
15090
  @param session           thread handler
15114
15091
  @param func_ptr      sum function list
15115
15092
 
15116
15093
  @retval
15119
15096
    true   error
15120
15097
*/
15121
15098
 
15122
 
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr)
 
15099
static bool setup_sum_funcs(Session *session, Item_sum **func_ptr)
15123
15100
{
15124
15101
  Item_sum *func;
15125
15102
  while ((func= *(func_ptr++)))
15126
15103
  {
15127
 
    if (func->setup(thd))
 
15104
    if (func->setup(session))
15128
15105
      return(true);
15129
15106
  }
15130
15107
  return(false);
15143
15120
/** Update record 0 in tmp_table from record 1. */
15144
15121
 
15145
15122
static void
15146
 
update_tmptable_sum_func(Item_sum **func_ptr,
15147
 
                         Table *tmp_table __attribute__((unused)))
 
15123
update_tmptable_sum_func(Item_sum **func_ptr, Table *)
15148
15124
{
15149
15125
  Item_sum *func;
15150
15126
  while ((func= *(func_ptr++)))
15207
15183
  currenct select for the table.
15208
15184
*/
15209
15185
 
15210
 
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab)
 
15186
static bool add_ref_to_table_cond(Session *session, JOIN_TAB *join_tab)
15211
15187
{
15212
15188
  if (!join_tab->ref.key_parts)
15213
15189
    return(false);
15225
15201
    Item *value=join_tab->ref.items[i];
15226
15202
    cond->add(new Item_func_equal(new Item_field(field), value));
15227
15203
  }
15228
 
  if (thd->is_fatal_error)
 
15204
  if (session->is_fatal_error)
15229
15205
    return(true);
15230
15206
 
15231
15207
  if (!cond->fixed)
15232
 
    cond->fix_fields(thd, (Item**)&cond);
 
15208
    cond->fix_fields(session, (Item**)&cond);
15233
15209
  if (join_tab->select)
15234
15210
  {
15235
15211
    error=(int) cond->add(join_tab->select->cond);
15246
15222
/**
15247
15223
  Free joins of subselect of this select.
15248
15224
 
15249
 
  @param thd      THD pointer
15250
 
  @param select   pointer to st_select_lex which subselects joins we will free
 
15225
  @param session      Session pointer
 
15226
  @param select   pointer to Select_Lex which subselects joins we will free
15251
15227
*/
15252
15228
 
15253
 
void free_underlaid_joins(THD *thd __attribute__((unused)),
15254
 
                          SELECT_LEX *select)
 
15229
void free_underlaid_joins(Session *, Select_Lex *select)
15255
15230
{
15256
 
  for (SELECT_LEX_UNIT *unit= select->first_inner_unit();
 
15231
  for (Select_Lex_Unit *unit= select->first_inner_unit();
15257
15232
       unit;
15258
15233
       unit= unit->next_unit())
15259
15234
    unit->cleanup();
15275
15250
  @b EXAMPLES
15276
15251
    @code
15277
15252
      SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP
15278
 
      SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP 
 
15253
      SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP
15279
15254
  @endcode
15280
15255
 
15281
15256
  @b IMPLEMENTATION
15288
15263
    This substitution is needed GROUP BY queries with ROLLUP if
15289
15264
    SELECT list contains expressions over group by attributes.
15290
15265
 
15291
 
  @param thd                  reference to the context
 
15266
  @param session                  reference to the context
15292
15267
  @param expr                 expression to make replacement
15293
15268
  @param group_list           list of references to group by items
15294
15269
  @param changed        out:  returns 1 if item contains a replaced field item
15295
15270
 
15296
15271
  @todo
15297
15272
    - TODO: Some functions are not null-preserving. For those functions
15298
 
    updating of the maybe_null attribute is an overkill. 
 
15273
    updating of the maybe_null attribute is an overkill.
15299
15274
 
15300
15275
  @retval
15301
15276
    0   if ok
15303
15278
    1   on error
15304
15279
*/
15305
15280
 
15306
 
static bool change_group_ref(THD *thd, Item_func *expr, order_st *group_list,
 
15281
static bool change_group_ref(Session *session, Item_func *expr, order_st *group_list,
15307
15282
                             bool *changed)
15308
15283
{
15309
15284
  if (expr->arg_count)
15310
15285
  {
15311
 
    Name_resolution_context *context= &thd->lex->current_select->context;
 
15286
    Name_resolution_context *context= &session->lex->current_select->context;
15312
15287
    Item **arg,**arg_end;
15313
15288
    bool arg_changed= false;
15314
15289
    for (arg= expr->arguments(),
15327
15302
            if (!(new_item= new Item_ref(context, group_tmp->item, 0,
15328
15303
                                        item->name)))
15329
15304
              return 1;                                 // fatal_error is set
15330
 
            thd->change_item_tree(arg, new_item);
 
15305
            session->change_item_tree(arg, new_item);
15331
15306
            arg_changed= true;
15332
15307
          }
15333
15308
        }
15334
15309
      }
15335
15310
      else if (item->type() == Item::FUNC_ITEM)
15336
15311
      {
15337
 
        if (change_group_ref(thd, (Item_func *) item, group_list, &arg_changed))
 
15312
        if (change_group_ref(session, (Item_func *) item, group_list, &arg_changed))
15338
15313
          return 1;
15339
15314
      }
15340
15315
    }
15364
15339
  */
15365
15340
  tmp_table_param.group_parts= send_group_parts;
15366
15341
 
15367
 
  if (!(rollup.null_items= (Item_null_result**) thd->alloc((sizeof(Item*) +
 
15342
  if (!(rollup.null_items= (Item_null_result**) session->alloc((sizeof(Item*) +
15368
15343
                                                sizeof(Item**) +
15369
15344
                                                sizeof(List<Item>) +
15370
15345
                                                ref_pointer_array_size)
15371
15346
                                                * send_group_parts )))
15372
15347
    return 1;
15373
 
  
 
15348
 
15374
15349
  rollup.fields= (List<Item>*) (rollup.null_items + send_group_parts);
15375
15350
  rollup.ref_pointer_arrays= (Item***) (rollup.fields + send_group_parts);
15376
15351
  ref_array= (Item**) (rollup.ref_pointer_arrays+send_group_parts);
15381
15356
  */
15382
15357
  for (i= 0 ; i < send_group_parts ; i++)
15383
15358
  {
15384
 
    rollup.null_items[i]= new (thd->mem_root) Item_null_result();
 
15359
    rollup.null_items[i]= new (session->mem_root) Item_null_result();
15385
15360
    List<Item> *rollup_fields= &rollup.fields[i];
15386
15361
    rollup_fields->empty();
15387
15362
    rollup.ref_pointer_arrays[i]= ref_array;
15419
15394
            ROLLUP is used together with DISTINCT in the SELECT list.
15420
15395
            Usually when creating temporary tables for a intermidiate
15421
15396
            result we do not include fields for constant expressions.
15422
 
          */           
 
15397
          */
15423
15398
          Item* new_item= new Item_func_rollup_const(item);
15424
15399
          if (!new_item)
15425
15400
            return 1;
15426
 
          new_item->fix_fields(thd, (Item **) 0);
15427
 
          thd->change_item_tree(it.ref(), new_item);
 
15401
          new_item->fix_fields(session, (Item **) 0);
 
15402
          session->change_item_tree(it.ref(), new_item);
15428
15403
          for (order_st *tmp= group_tmp; tmp; tmp= tmp->next)
15429
 
          { 
 
15404
          {
15430
15405
            if (*tmp->item == item)
15431
 
              thd->change_item_tree(tmp->item, new_item);
 
15406
              session->change_item_tree(tmp->item, new_item);
15432
15407
          }
15433
15408
        }
15434
15409
      }
15436
15411
    if (item->type() == Item::FUNC_ITEM && !found_in_group)
15437
15412
    {
15438
15413
      bool changed= false;
15439
 
      if (change_group_ref(thd, (Item_func *) item, group_list, &changed))
 
15414
      if (change_group_ref(session, (Item_func *) item, group_list, &changed))
15440
15415
        return 1;
15441
15416
      /*
15442
15417
        We have to prevent creation of a field in a temporary table for
15443
15418
        an expression that contains GROUP BY attributes.
15444
15419
        Marking the expression item as 'with_sum_func' will ensure this.
15445
 
      */ 
 
15420
      */
15446
15421
      if (changed)
15447
15422
        item->with_sum_func= 1;
15448
15423
    }
15449
15424
  }
15450
15425
  return 0;
15451
15426
}
15452
 
  
 
15427
 
15453
15428
 
15454
15429
/**
15455
15430
  Fill up rollup structures with pointers to fields to use.
15529
15504
      if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item() &&
15530
15505
          (!((Item_sum*) item)->depended_from() ||
15531
15506
           ((Item_sum *)item)->depended_from() == select_lex))
15532
 
          
 
15507
 
15533
15508
      {
15534
15509
        /*
15535
15510
          This is a top level summary function that must be replaced with
15539
15514
          sub select.  Fortunately it's not common to have rollup in
15540
15515
          sub selects.
15541
15516
        */
15542
 
        item= item->copy_or_same(thd);
 
15517
        item= item->copy_or_same(session);
15543
15518
        ((Item_sum*) item)->make_unique();
15544
15519
        *(*func)= (Item_sum*) item;
15545
15520
        (*func)++;
15546
15521
      }
15547
 
      else 
 
15522
      else
15548
15523
      {
15549
15524
        /* Check if this is something that is part of this group by */
15550
15525
        order_st *group_tmp;
15557
15532
              This is an element that is used by the GROUP BY and should be
15558
15533
              set to NULL in this level
15559
15534
            */
15560
 
            Item_null_result *null_item= new (thd->mem_root) Item_null_result();
 
15535
            Item_null_result *null_item= new (session->mem_root) Item_null_result();
15561
15536
            if (!null_item)
15562
15537
              return 1;
15563
15538
            item->maybe_null= 1;                // Value will be null sometimes
15663
15638
      copy_sum_funcs(sum_funcs_end[i+1], sum_funcs_end[i]);
15664
15639
      if ((write_error= table_arg->file->ha_write_row(table_arg->record[0])))
15665
15640
      {
15666
 
        if (create_myisam_from_heap(thd, table_arg, 
 
15641
        if (create_myisam_from_heap(session, table_arg,
15667
15642
                                    tmp_table_param.start_recinfo,
15668
15643
                                    &tmp_table_param.recinfo,
15669
15644
                                    write_error, 0))
15670
 
          return 1;                  
 
15645
          return 1;
15671
15646
      }
15672
15647
    }
15673
15648
  }
15705
15680
{
15706
15681
  List<Item> field_list;
15707
15682
  List<Item> item_list;
15708
 
  THD *thd=join->thd;
 
15683
  Session *session=join->session;
15709
15684
  select_result *result=join->result;
15710
15685
  Item *item_null= new Item_null();
15711
15686
  const CHARSET_INFO * const cs= system_charset_info;
15712
15687
  int quick_type;
15713
15688
  /* Don't log this into the slow query log */
15714
 
  thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
15689
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
15715
15690
  join->unit->offset_limit_cnt= 0;
15716
15691
 
15717
 
  /* 
 
15692
  /*
15718
15693
    NOTE: the number/types of items pushed into item_list must be in sync with
15719
 
    EXPLAIN column types as they're "defined" in THD::send_explain_fields()
 
15694
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
15720
15695
  */
15721
15696
  if (message)
15722
15697
  {
15726
15701
                                        strlen(join->select_lex->type), cs));
15727
15702
    for (uint32_t i=0 ; i < 7; i++)
15728
15703
      item_list.push_back(item_null);
15729
 
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
15704
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
15730
15705
      item_list.push_back(item_null);
15731
 
  
 
15706
 
15732
15707
    item_list.push_back(new Item_string(message,strlen(message),cs));
15733
15708
    if (result->send_data(item_list))
15734
15709
      join->error= 1;
15735
15710
  }
15736
15711
  else if (join->select_lex == join->unit->fake_select_lex)
15737
15712
  {
15738
 
    /* 
 
15713
    /*
15739
15714
      here we assume that the query will return at least two rows, so we
15740
15715
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
15741
15716
      and no filesort will be actually done, but executing all selects in
15752
15727
                                        cs));
15753
15728
    /* table */
15754
15729
    {
15755
 
      SELECT_LEX *sl= join->unit->first_select();
 
15730
      Select_Lex *sl= join->unit->first_select();
15756
15731
      uint32_t len= 6, lastop= 0;
15757
15732
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
15758
15733
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
15786
15761
    /* ref */
15787
15762
    item_list.push_back(item_null);
15788
15763
    /* in_rows */
15789
 
    if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
15764
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
15790
15765
      item_list.push_back(item_null);
15791
15766
    /* rows */
15792
15767
    item_list.push_back(item_null);
15808
15783
      JOIN_TAB *tab=join->join_tab+i;
15809
15784
      Table *table=tab->table;
15810
15785
      TableList *table_list= tab->table->pos_in_table_list;
15811
 
      char buff[512]; 
 
15786
      char buff[512];
15812
15787
      char buff1[512], buff2[512], buff3[512];
15813
15788
      char keylen_str_buf[64];
15814
15789
      String extra(buff, sizeof(buff),cs);
15851
15826
      }
15852
15827
      else
15853
15828
      {
15854
 
        TableList *real_table= table->pos_in_table_list; 
 
15829
        TableList *real_table= table->pos_in_table_list;
15855
15830
        item_list.push_back(new Item_string(real_table->alias,
15856
15831
                                            strlen(real_table->alias),
15857
15832
                                            cs));
15861
15836
                                          strlen(join_type_str[tab->type]),
15862
15837
                                          cs));
15863
15838
      /* Build "possible_keys" value and add it to item_list */
15864
 
      if (!tab->keys.is_clear_all())
 
15839
      if (tab->keys.any())
15865
15840
      {
15866
15841
        uint32_t j;
15867
15842
        for (j=0 ; j < table->s->keys ; j++)
15868
15843
        {
15869
 
          if (tab->keys.is_set(j))
 
15844
          if (tab->keys.test(j))
15870
15845
          {
15871
15846
            if (tmp1.length())
15872
15847
              tmp1.append(',');
15873
 
            tmp1.append(table->key_info[j].name, 
 
15848
            tmp1.append(table->key_info[j].name,
15874
15849
                        strlen(table->key_info[j].name),
15875
15850
                        system_charset_info);
15876
15851
          }
15889
15864
        item_list.push_back(new Item_string(key_info->name,
15890
15865
                                            strlen(key_info->name),
15891
15866
                                            system_charset_info));
15892
 
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) - 
 
15867
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
15893
15868
                keylen_str_buf;
15894
15869
        item_list.push_back(new Item_string(keylen_str_buf, length,
15895
15870
                                            system_charset_info));
15908
15883
        register uint32_t length;
15909
15884
        item_list.push_back(new Item_string(key_info->name,
15910
15885
                                            strlen(key_info->name),cs));
15911
 
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) - 
 
15886
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
15912
15887
                keylen_str_buf;
15913
 
        item_list.push_back(new Item_string(keylen_str_buf, 
 
15888
        item_list.push_back(new Item_string(keylen_str_buf,
15914
15889
                                            length,
15915
15890
                                            system_charset_info));
15916
15891
        item_list.push_back(item_null);
15933
15908
            f_idx= table_list->schema_table->idx_field1;
15934
15909
            tmp_buff= table_list->schema_table->fields_info[f_idx].field_name;
15935
15910
            tmp2.append(tmp_buff, strlen(tmp_buff), cs);
15936
 
          }          
 
15911
          }
15937
15912
          if (table_list->has_table_lookup_value)
15938
15913
          {
15939
15914
            if (table_list->has_db_lookup_value)
15952
15927
        item_list.push_back(item_null);
15953
15928
        item_list.push_back(item_null);
15954
15929
      }
15955
 
      
 
15930
 
15956
15931
      /* Add "rows" field to item_list. */
15957
15932
      if (table_list->schema_table)
15958
15933
      {
15959
15934
        /* in_rows */
15960
 
        if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
15935
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
15961
15936
          item_list.push_back(item_null);
15962
15937
        /* rows */
15963
15938
        item_list.push_back(item_null);
15968
15943
        if (tab->select && tab->select->quick)
15969
15944
          examined_rows= rows2double(tab->select->quick->records);
15970
15945
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
15971
 
          examined_rows= rows2double(tab->limit ? tab->limit : 
 
15946
          examined_rows= rows2double(tab->limit ? tab->limit :
15972
15947
                                     tab->table->file->records());
15973
15948
        else
15974
 
          examined_rows= join->best_positions[i].records_read; 
15975
 
 
15976
 
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows, 
 
15949
          examined_rows= join->best_positions[i].records_read;
 
15950
 
 
15951
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
15977
15952
                                         MY_INT64_NUM_DECIMAL_DIGITS));
15978
15953
 
15979
15954
        /* Add "filtered" field to item_list. */
15980
 
        if (join->thd->lex->describe & DESCRIBE_EXTENDED)
 
15955
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
15981
15956
        {
15982
 
          float f= 0.0; 
 
15957
          float f= 0.0;
15983
15958
          if (examined_rows)
15984
15959
            f= (float) (100.0 * join->best_positions[i].records_read /
15985
15960
                        examined_rows);
15990
15965
      /* Build "Extra" field and add it to item_list. */
15991
15966
      bool key_read=table->key_read;
15992
15967
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
15993
 
          table->covering_keys.is_set(tab->index))
 
15968
          table->covering_keys.test(tab->index))
15994
15969
        key_read=1;
15995
15970
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
15996
15971
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
15997
15972
        key_read=1;
15998
 
        
 
15973
 
15999
15974
      if (tab->info)
16000
15975
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
16001
15976
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
16028
16003
            table->file->pushed_idx_cond)
16029
16004
          extra.append(STRING_WITH_LEN("; Using index condition"));
16030
16005
 
16031
 
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION || 
 
16006
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
16032
16007
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
16033
16008
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
16034
16009
        {
16039
16014
        {
16040
16015
          if (tab->use_quick == 2)
16041
16016
          {
16042
 
            /* 4 bits per 1 hex digit + terminating '\0' */
16043
 
            char buf[MAX_KEY / 4 + 1];
 
16017
            /*
 
16018
             * To print out the bitset in tab->keys, we go through
 
16019
             * it 32 bits at a time. We need to do this to ensure
 
16020
             * that the to_ulong() method will not throw an
 
16021
             * out_of_range exception at runtime which would happen
 
16022
             * if the bitset we were working with was larger than 64
 
16023
             * bits on a 64-bit platform (for example).
 
16024
             */
 
16025
            stringstream s, w;
 
16026
            string str;
 
16027
            w << tab->keys;
 
16028
            w >> str;
 
16029
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
 
16030
            {
 
16031
              bitset<32> tmp(str, pos, 32);
 
16032
              if (tmp.any())
 
16033
                s << uppercase << hex << tmp.to_ulong();
 
16034
            }
16044
16035
            extra.append(STRING_WITH_LEN("; Range checked for each "
16045
16036
                                         "record (index map: 0x"));
16046
 
            extra.append(tab->keys.print(buf));
 
16037
            extra.append(s.str().c_str());
16047
16038
            extra.append(')');
16048
16039
          }
16049
16040
          else if (tab->select->cond)
16050
16041
          {
16051
16042
            const COND *pushed_cond= tab->table->file->pushed_cond;
16052
16043
 
16053
 
            if (thd->variables.engine_condition_pushdown && pushed_cond)
 
16044
            if (session->variables.engine_condition_pushdown && pushed_cond)
16054
16045
            {
16055
16046
              extra.append(STRING_WITH_LEN("; Using where with pushed "
16056
16047
                                           "condition"));
16057
 
              if (thd->lex->describe & DESCRIBE_EXTENDED)
 
16048
              if (session->lex->describe & DESCRIBE_EXTENDED)
16058
16049
              {
16059
16050
                extra.append(STRING_WITH_LEN(": "));
16060
16051
                ((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
16073
16064
        }
16074
16065
        if (table->reginfo.not_exists_optimize)
16075
16066
          extra.append(STRING_WITH_LEN("; Not exists"));
16076
 
          
 
16067
 
16077
16068
        if (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE &&
16078
16069
            !(((QUICK_RANGE_SELECT*)(tab->select->quick))->mrr_flags &
16079
16070
             HA_MRR_USE_DEFAULT_IMPL))
16109
16100
          need_order=0;
16110
16101
          extra.append(STRING_WITH_LEN("; Using filesort"));
16111
16102
        }
16112
 
        if (distinct & test_all_bits(used_tables,thd->used_tables))
 
16103
        if (distinct & test_all_bits(used_tables,session->used_tables))
16113
16104
          extra.append(STRING_WITH_LEN("; Distinct"));
16114
16105
 
16115
16106
        if (tab->insideout_match_tab)
16167
16158
        join->error= 1;
16168
16159
    }
16169
16160
  }
16170
 
  for (SELECT_LEX_UNIT *unit= join->select_lex->first_inner_unit();
 
16161
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
16171
16162
       unit;
16172
16163
       unit= unit->next_unit())
16173
16164
  {
16174
 
    if (mysql_explain_union(thd, unit, result))
 
16165
    if (mysql_explain_union(session, unit, result))
16175
16166
      return;
16176
16167
  }
16177
16168
  return;
16178
16169
}
16179
16170
 
16180
16171
 
16181
 
bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result)
 
16172
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
16182
16173
{
16183
 
  bool res= 0;
16184
 
  SELECT_LEX *first= unit->first_select();
 
16174
  bool res= false;
 
16175
  Select_Lex *first= unit->first_select();
16185
16176
 
16186
 
  for (SELECT_LEX *sl= first;
 
16177
  for (Select_Lex *sl= first;
16187
16178
       sl;
16188
16179
       sl= sl->next_select())
16189
16180
  {
16190
16181
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
16191
16182
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
16192
 
    sl->type= (((&thd->lex->select_lex)==sl)?
16193
 
               (sl->first_inner_unit() || sl->next_select() ? 
 
16183
    sl->type= (((&session->lex->select_lex)==sl)?
 
16184
               (sl->first_inner_unit() || sl->next_select() ?
16194
16185
                "PRIMARY" : "SIMPLE"):
16195
16186
               ((sl == first)?
16196
16187
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
16210
16201
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
16211
16202
    unit->fake_select_lex->type= "UNION RESULT";
16212
16203
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
16213
 
    if (!(res= unit->prepare(thd, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
16204
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
16214
16205
      res= unit->exec();
16215
16206
    res|= unit->cleanup();
16216
16207
  }
16217
16208
  else
16218
16209
  {
16219
 
    thd->lex->current_select= first;
 
16210
    session->lex->current_select= first;
16220
16211
    unit->set_limit(unit->global_parameters);
16221
 
    res= mysql_select(thd, &first->ref_pointer_array,
 
16212
    res= mysql_select(session, &first->ref_pointer_array,
16222
16213
                        (TableList*) first->table_list.first,
16223
16214
                        first->with_wild, first->item_list,
16224
16215
                        first->where,
16227
16218
                        (order_st*) first->order_list.first,
16228
16219
                        (order_st*) first->group_list.first,
16229
16220
                        first->having,
16230
 
                        (order_st*) thd->lex->proc_list.first,
16231
 
                        first->options | thd->options | SELECT_DESCRIBE,
 
16221
                        first->options | session->options | SELECT_DESCRIBE,
16232
16222
                        result, unit, first);
16233
16223
  }
16234
 
  return(res || thd->is_error());
 
16224
  return(res || session->is_error());
16235
16225
}
16236
16226
 
16237
16227
 
16238
 
static void print_table_array(THD *thd, String *str, TableList **table, 
 
16228
static void print_table_array(Session *session, String *str, TableList **table,
16239
16229
                              TableList **end)
16240
16230
{
16241
 
  (*table)->print(thd, str, QT_ORDINARY);
 
16231
  (*table)->print(session, str, QT_ORDINARY);
16242
16232
 
16243
16233
  for (TableList **tbl= table + 1; tbl < end; tbl++)
16244
16234
  {
16254
16244
      str->append(STRING_WITH_LEN(" semi join "));
16255
16245
    else
16256
16246
      str->append(STRING_WITH_LEN(" join "));
16257
 
    curr->print(thd, str, QT_ORDINARY);
 
16247
    curr->print(session, str, QT_ORDINARY);
16258
16248
    if (curr->on_expr)
16259
16249
    {
16260
16250
      str->append(STRING_WITH_LEN(" on("));
16267
16257
 
16268
16258
/**
16269
16259
  Print joins from the FROM clause.
16270
 
  @param thd     thread handler
 
16260
  @param session     thread handler
16271
16261
  @param str     string where table should be printed
16272
16262
  @param tables  list of tables in join
16273
16263
  @query_type    type of the query is being generated
16274
16264
*/
16275
16265
 
16276
 
static void print_join(THD *thd,
16277
 
                       String *str,
16278
 
                       List<TableList> *tables,
16279
 
                       enum_query_type query_type __attribute__((unused)))
 
16266
static void print_join(Session *session, String *str,
 
16267
                       List<TableList> *tables, enum_query_type)
16280
16268
{
16281
16269
  /* List is reversed => we should reverse it before using */
16282
16270
  List_iterator_fast<TableList> ti(*tables);
16283
 
  TableList **table= (TableList **)thd->alloc(sizeof(TableList*) *
 
16271
  TableList **table= (TableList **)session->alloc(sizeof(TableList*) *
16284
16272
                                                tables->elements);
16285
16273
  if (table == 0)
16286
16274
    return;  // out of memory
16287
16275
 
16288
16276
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
16289
16277
    *t= ti++;
16290
 
  
16291
 
  /* 
 
16278
 
 
16279
  /*
16292
16280
    If the first table is a semi-join nest, swap it with something that is
16293
16281
    not a semi-join nest.
16294
16282
  */
16307
16295
    }
16308
16296
  }
16309
16297
  assert(tables->elements >= 1);
16310
 
  print_table_array(thd, str, table, table + tables->elements);
16311
 
}
16312
 
 
16313
 
 
16314
 
/**
16315
 
  @brief Print an index hint
16316
 
 
16317
 
  @details Prints out the USE|FORCE|IGNORE index hint.
16318
 
 
16319
 
  @param      thd         the current thread
16320
 
  @param[out] str         appends the index hint here
16321
 
  @param      hint        what the hint is (as string : "USE INDEX"|
16322
 
                          "FORCE INDEX"|"IGNORE INDEX")
16323
 
  @param      hint_length the length of the string in 'hint'
16324
 
  @param      indexes     a list of index names for the hint
16325
 
*/
16326
 
 
16327
 
void 
16328
 
Index_hint::print(THD *thd, String *str)
16329
 
{
16330
 
  switch (type)
16331
 
  {
16332
 
    case INDEX_HINT_IGNORE: str->append(STRING_WITH_LEN("IGNORE INDEX")); break;
16333
 
    case INDEX_HINT_USE:    str->append(STRING_WITH_LEN("USE INDEX")); break;
16334
 
    case INDEX_HINT_FORCE:  str->append(STRING_WITH_LEN("FORCE INDEX")); break;
16335
 
  }
16336
 
  str->append (STRING_WITH_LEN(" ("));
16337
 
  if (key_name.length)
16338
 
  {
16339
 
    if (thd && !my_strnncoll(system_charset_info,
16340
 
                             (const unsigned char *)key_name.str, key_name.length, 
16341
 
                             (const unsigned char *)primary_key_name, 
16342
 
                             strlen(primary_key_name)))
16343
 
      str->append(primary_key_name);
16344
 
    else
16345
 
      append_identifier(thd, str, key_name.str, key_name.length);
16346
 
  }
16347
 
  str->append(')');
16348
 
}
16349
 
 
 
16298
  print_table_array(session, str, table, table + tables->elements);
 
16299
}
16350
16300
 
16351
16301
/**
16352
16302
  Print table as it should be in join list.
16353
16303
 
16354
16304
  @param str   string where table should be printed
16355
16305
*/
16356
 
 
16357
 
void TableList::print(THD *thd, String *str, enum_query_type query_type)
 
16306
void TableList::print(Session *session, String *str, enum_query_type query_type)
16358
16307
{
16359
16308
  if (nested_join)
16360
16309
  {
16361
16310
    str->append('(');
16362
 
    print_join(thd, str, &nested_join->join_list, query_type);
 
16311
    print_join(session, str, &nested_join->join_list, query_type);
16363
16312
    str->append(')');
16364
16313
  }
16365
16314
  else
16377
16326
    {
16378
16327
      // A normal table
16379
16328
      {
16380
 
        append_identifier(thd, str, db, db_length);
 
16329
        str->append_identifier(db, db_length);
16381
16330
        str->append('.');
16382
16331
      }
16383
16332
      if (schema_table)
16384
16333
      {
16385
 
        append_identifier(thd, str, schema_table_name,
16386
 
                          strlen(schema_table_name));
 
16334
        str->append_identifier(schema_table_name, strlen(schema_table_name));
16387
16335
        cmp_name= schema_table_name;
16388
16336
      }
16389
16337
      else
16390
16338
      {
16391
 
        append_identifier(thd, str, table_name, table_name_length);
 
16339
        str->append_identifier(table_name, table_name_length);
16392
16340
        cmp_name= table_name;
16393
16341
      }
16394
16342
    }
16395
16343
    if (my_strcasecmp(table_alias_charset, cmp_name, alias))
16396
16344
    {
16397
 
      char t_alias_buff[MAX_ALIAS_NAME];
16398
 
      const char *t_alias= alias;
16399
16345
 
16400
 
      str->append(' ');
16401
 
      if (lower_case_table_names== 1)
 
16346
      if (alias && alias[0])
16402
16347
      {
16403
 
        if (alias && alias[0])
16404
 
        {
16405
 
          my_stpcpy(t_alias_buff, alias);
16406
 
          my_casedn_str(files_charset_info, t_alias_buff);
16407
 
          t_alias= t_alias_buff;
16408
 
        }
 
16348
        str->append(' ');
 
16349
 
 
16350
        string t_alias(alias);
 
16351
        if (lower_case_table_names== 1)
 
16352
          transform(t_alias.begin(), t_alias.end(),
 
16353
                    t_alias.begin(), ::tolower);
 
16354
 
 
16355
        str->append_identifier(t_alias.c_str(), t_alias.length());
16409
16356
      }
16410
16357
 
16411
 
      append_identifier(thd, str, t_alias, strlen(t_alias));
16412
16358
    }
16413
16359
 
16414
16360
    if (index_hints)
16419
16365
      while ((hint= it++))
16420
16366
      {
16421
16367
        str->append (STRING_WITH_LEN(" "));
16422
 
        hint->print (thd, str);
 
16368
        hint->print (session, str);
16423
16369
      }
16424
16370
    }
16425
16371
  }
16426
16372
}
16427
16373
 
16428
16374
 
16429
 
void st_select_lex::print(THD *thd, String *str, enum_query_type query_type)
 
16375
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
16430
16376
{
16431
 
  /* QQ: thd may not be set for sub queries, but this should be fixed */
16432
 
  if (!thd)
16433
 
    thd= current_thd;
 
16377
  /* QQ: session may not be set for sub queries, but this should be fixed */
 
16378
  if (!session)
 
16379
    session= current_session;
16434
16380
 
16435
16381
  str->append(STRING_WITH_LEN("select "));
16436
16382
 
16437
16383
  /* First add options */
16438
16384
  if (options & SELECT_STRAIGHT_JOIN)
16439
16385
    str->append(STRING_WITH_LEN("straight_join "));
16440
 
  if ((thd->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
16441
 
      (this == &thd->lex->select_lex))
 
16386
  if ((session->lex->lock_option == TL_READ_HIGH_PRIORITY) &&
 
16387
      (this == &session->lex->select_lex))
16442
16388
    str->append(STRING_WITH_LEN("high_priority "));
16443
16389
  if (options & SELECT_DISTINCT)
16444
16390
    str->append(STRING_WITH_LEN("distinct "));
16472
16418
  {
16473
16419
    str->append(STRING_WITH_LEN(" from "));
16474
16420
    /* go through join tree */
16475
 
    print_join(thd, str, &top_join_list, query_type);
 
16421
    print_join(session, str, &top_join_list, query_type);
16476
16422
  }
16477
16423
  else if (where)
16478
16424
  {
16479
16425
    /*
16480
 
      "SELECT 1 FROM DUAL WHERE 2" should not be printed as 
 
16426
      "SELECT 1 FROM DUAL WHERE 2" should not be printed as
16481
16427
      "SELECT 1 WHERE 2": the 1st syntax is valid, but the 2nd is not.
16482
16428
    */
16483
16429
    str->append(STRING_WITH_LEN(" from DUAL "));
16535
16481
  }
16536
16482
 
16537
16483
  // limit
16538
 
  print_limit(thd, str, query_type);
 
16484
  print_limit(session, str, query_type);
16539
16485
 
16540
16486
  // PROCEDURE unsupported here
16541
16487
}
16555
16501
bool JOIN::change_result(select_result *res)
16556
16502
{
16557
16503
  result= res;
16558
 
  if (result->prepare(fields_list, select_lex->master_unit()) ||
16559
 
                     result->prepare2())
 
16504
  if (result->prepare(fields_list, select_lex->master_unit()))
16560
16505
  {
16561
16506
    return(true);
16562
16507
  }