~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: devananda
  • Date: 2009-07-01 17:38:47 UTC
  • mto: (1093.1.7 captain)
  • mto: This revision was merged to the branch mainline in revision 1095.
  • Revision ID: devananda.vdv@gmail.com-20090701173847-3n3mbtessg5ff35e
refactored function/benchmark into plugin/benchmark

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
/**
17
17
  @file
22
22
  @defgroup Query_Optimizer  Query Optimizer
23
23
  @{
24
24
*/
25
 
#include "config.h"
26
 
 
27
 
#include <string>
28
 
#include <iostream>
29
 
#include <algorithm>
30
 
#include <vector>
31
 
 
 
25
#include "drizzled/server_includes.h"
32
26
#include "drizzled/sql_select.h" /* include join.h */
 
27
#include "drizzled/sj_tmp_table.h"
 
28
#include "drizzled/table_map_iterator.h"
33
29
 
34
30
#include "drizzled/error.h"
35
31
#include "drizzled/gettext.h"
38
34
#include "drizzled/nested_join.h"
39
35
#include "drizzled/probes.h"
40
36
#include "drizzled/show.h"
 
37
#include "drizzled/info_schema.h"
41
38
#include "drizzled/item/cache.h"
42
39
#include "drizzled/item/cmpfunc.h"
43
40
#include "drizzled/item/copy_string.h"
49
46
#include "drizzled/lock.h"
50
47
#include "drizzled/item/outer_ref.h"
51
48
#include "drizzled/index_hint.h"
52
 
#include "drizzled/records.h"
53
 
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
55
 
 
56
 
#include "drizzled/sql_union.h"
57
 
#include "drizzled/optimizer/key_field.h"
58
 
#include "drizzled/optimizer/position.h"
59
 
#include "drizzled/optimizer/sargable_param.h"
60
 
#include "drizzled/optimizer/key_use.h"
61
 
#include "drizzled/optimizer/range.h"
62
 
#include "drizzled/optimizer/quick_range_select.h"
63
 
#include "drizzled/optimizer/quick_ror_intersect_select.h"
64
 
 
65
 
#include "drizzled/filesort.h"
 
49
 
 
50
#include <drizzled/sql_union.h>
 
51
 
 
52
#include <string>
 
53
#include <iostream>
66
54
 
67
55
using namespace std;
68
56
 
69
 
namespace drizzled
70
 
{
 
57
const char *join_type_str[]={ "UNKNOWN","system","const","eq_ref","ref",
 
58
                              "MAYBE_REF","ALL","range","index",
 
59
                              "ref_or_null","unique_subquery","index_subquery",
 
60
                              "index_merge"
 
61
};
71
62
 
72
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
 
63
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
73
64
static COND *build_equal_items(Session *session, COND *cond,
74
65
                               COND_EQUAL *inherited,
75
66
                               List<TableList> *join_list,
76
67
                               COND_EQUAL **cond_equal_ref);
77
68
 
78
69
static Item* part_of_refkey(Table *form,Field *field);
79
 
static bool cmp_buffer_with_ref(JoinTable *tab);
 
70
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
80
71
static void change_cond_ref_to_const(Session *session,
81
72
                                     vector<COND_CMP>& save_list,
82
73
                                     Item *and_father,
84
75
                                     Item *field,
85
76
                                     Item *value);
86
77
static bool copy_blobs(Field **ptr);
87
 
 
88
78
static bool eval_const_cond(COND *cond)
89
79
{
90
80
    return ((Item_func*) cond)->val_int() ? true : false;
117
107
{
118
108
  bool res;
119
109
  register Select_Lex *select_lex= &lex->select_lex;
120
 
  DRIZZLE_SELECT_START(session->getQueryString()->c_str());
 
110
  DRIZZLE_SELECT_START();
121
111
 
122
112
  if (select_lex->master_unit()->is_union() ||
123
113
      select_lex->master_unit()->fake_select_lex)
124
 
  {
125
114
    res= drizzle_union(session, lex, result, &lex->unit,
126
115
                       setup_tables_done_option);
127
 
  }
128
116
  else
129
117
  {
130
118
    Select_Lex_Unit *unit= &lex->unit;
135
123
      every PS/SP execution new, we will not need reset this flag if
136
124
      setup_tables_done_option changed for next rexecution
137
125
    */
138
 
    res= mysql_select(session,
139
 
                      &select_lex->ref_pointer_array,
 
126
    res= mysql_select(session, &select_lex->ref_pointer_array,
140
127
                      (TableList*) select_lex->table_list.first,
141
 
                      select_lex->with_wild,
142
 
                      select_lex->item_list,
 
128
                      select_lex->with_wild, select_lex->item_list,
143
129
                      select_lex->where,
144
130
                      select_lex->order_list.elements +
145
131
                      select_lex->group_list.elements,
146
 
                      (Order*) select_lex->order_list.first,
147
 
                      (Order*) select_lex->group_list.first,
 
132
                      (order_st*) select_lex->order_list.first,
 
133
                      (order_st*) select_lex->group_list.first,
148
134
                      select_lex->having,
149
135
                      select_lex->options | session->options |
150
136
                      setup_tables_done_option,
154
140
  if (unlikely(res))
155
141
    result->abort();
156
142
 
157
 
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
158
 
  return res;
 
143
  DRIZZLE_SELECT_END();
 
144
  return(res);
159
145
}
160
146
 
161
147
/*
291
277
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
292
278
    and set appropriate flags in join_tab->packed_info.
293
279
*/
294
 
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
 
280
void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
295
281
{
296
282
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
297
283
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
311
297
/**
312
298
  An entry point to single-unit select (a select without UNION).
313
299
 
314
 
  @param session                  thread Cursor
 
300
  @param session                  thread handler
315
301
  @param rref_pointer_array   a reference to ref_pointer_array of
316
302
                              the top-level select_lex for this query
317
303
  @param tables               list of all tables used in this query.
327
313
                              for a, b and c in this list.
328
314
  @param conds                top level item of an expression representing
329
315
                              WHERE clause of the top level select
330
 
  @param og_num               total number of ORDER BY and GROUP BY clauses
 
316
  @param og_num               total number of order_st BY and GROUP BY clauses
331
317
                              arguments
332
 
  @param order                linked list of ORDER BY agruments
 
318
  @param order                linked list of order_st BY agruments
333
319
  @param group                linked list of GROUP BY arguments
334
320
  @param having               top level item of HAVING expression
335
321
  @param select_options       select options (BIG_RESULT, etc)
352
338
*/
353
339
bool mysql_select(Session *session,
354
340
                  Item ***rref_pointer_array,
355
 
                  TableList *tables, 
 
341
                        TableList *tables, 
356
342
                  uint32_t wild_num, 
357
343
                  List<Item> &fields,
358
 
                  COND *conds, 
 
344
                        COND *conds, 
359
345
                  uint32_t og_num,  
360
 
                  Order *order,
361
 
                  Order *group,
362
 
                  Item *having, 
 
346
                  order_st *order, 
 
347
                  order_st *group,
 
348
                        Item *having, 
363
349
                  uint64_t select_options,
364
 
                  select_result *result, 
 
350
                        select_result *result, 
365
351
                  Select_Lex_Unit *unit,
366
 
                  Select_Lex *select_lex)
 
352
                        Select_Lex *select_lex)
367
353
{
368
354
  bool err;
369
355
  bool free_join= 1;
370
356
 
371
357
  select_lex->context.resolve_in_select_list= true;
372
 
  Join *join;
 
358
  JOIN *join;
373
359
  if (select_lex->join != 0)
374
360
  {
375
361
    join= select_lex->join;
402
388
  }
403
389
  else
404
390
  {
405
 
    if (!(join= new Join(session, fields, select_options, result)))
 
391
    if (!(join= new JOIN(session, fields, select_options, result)))
406
392
      return(true);
407
393
    session->set_proc_info("init");
408
394
    session->used_tables=0;                         // Updated by setup_fields
414
400
    }
415
401
  }
416
402
 
417
 
  err= join->optimize();
418
 
  if (err)
419
 
  {
420
 
    goto err; // 1
 
403
  if (join->flatten_subqueries())
 
404
  {
 
405
    err= 1;
 
406
    goto err;
 
407
  }
 
408
 
 
409
  if ((err= join->optimize()))
 
410
  {
 
411
    goto err;                                   // 1
421
412
  }
422
413
 
423
414
  if (session->lex->describe & DESCRIBE_EXTENDED)
447
438
  return(join->error);
448
439
}
449
440
 
 
441
int subq_sj_candidate_cmp(Item_in_subselect* const *el1,
 
442
                          Item_in_subselect* const *el2)
 
443
{
 
444
  return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 :
 
445
         ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1);
 
446
}
 
447
 
450
448
inline Item *and_items(Item* cond, Item *item)
451
449
{
452
450
  return (cond? (new Item_cond_and(cond, item)) : item);
453
451
}
454
452
 
 
453
static TableList *alloc_join_nest(Session *session)
 
454
{
 
455
  TableList *tbl;
 
456
  if (!(tbl= (TableList*) session->calloc(ALIGN_SIZE(sizeof(TableList))+
 
457
                                       sizeof(nested_join_st))))
 
458
    return NULL;
 
459
  tbl->nested_join= (nested_join_st*) ((unsigned char*)tbl +
 
460
                                    ALIGN_SIZE(sizeof(TableList)));
 
461
  return tbl;
 
462
}
 
463
 
 
464
void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
465
{
 
466
  List_iterator<TableList> it(*tlist);
 
467
  TableList *table;
 
468
  while ((table= it++))
 
469
  {
 
470
    if (table->on_expr)
 
471
      table->on_expr->fix_after_pullout(new_parent, &table->on_expr);
 
472
    if (table->nested_join)
 
473
      fix_list_after_tbl_changes(new_parent, &table->nested_join->join_list);
 
474
  }
 
475
}
 
476
 
 
477
/*
 
478
  Convert a subquery predicate into a TableList semi-join nest
 
479
 
 
480
  SYNOPSIS
 
481
    convert_subq_to_sj()
 
482
       parent_join  Parent join, the one that has subq_pred in its WHERE/ON
 
483
                    clause
 
484
       subq_pred    Subquery predicate to be converted
 
485
 
 
486
  DESCRIPTION
 
487
    Convert a subquery predicate into a TableList semi-join nest. All the
 
488
    prerequisites are already checked, so the conversion is always successfull.
 
489
 
 
490
    Prepared Statements: the transformation is permanent:
 
491
     - Changes in TableList structures are naturally permanent
 
492
     - Item tree changes are performed on statement MEM_ROOT:
 
493
        = we activate statement MEM_ROOT
 
494
        = this function is called before the first fix_prepare_information
 
495
          call.
 
496
 
 
497
    This is intended because the criteria for subquery-to-sj conversion remain
 
498
    constant for the lifetime of the Prepared Statement.
 
499
 
 
500
  RETURN
 
501
    false  OK
 
502
    true   Out of memory error
 
503
*/
 
504
bool convert_subq_to_sj(JOIN *parent_join, Item_in_subselect *subq_pred)
 
505
{
 
506
  Select_Lex *parent_lex= parent_join->select_lex;
 
507
  TableList *emb_tbl_nest= NULL;
 
508
  List<TableList> *emb_join_list= &parent_lex->top_join_list;
 
509
  Session *session= parent_join->session;
 
510
 
 
511
  /*
 
512
    1. Find out where to put the predicate into.
 
513
     Note: for "t1 LEFT JOIN t2" this will be t2, a leaf.
 
514
  */
 
515
  if ((void*)subq_pred->expr_join_nest != (void*)1)
 
516
  {
 
517
    if (subq_pred->expr_join_nest->nested_join)
 
518
    {
 
519
      /*
 
520
        We're dealing with
 
521
 
 
522
          ... [LEFT] JOIN  ( ... ) ON (subquery AND whatever) ...
 
523
 
 
524
        The sj-nest will be inserted into the brackets nest.
 
525
      */
 
526
      emb_tbl_nest=  subq_pred->expr_join_nest;
 
527
      emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
528
    }
 
529
    else if (!subq_pred->expr_join_nest->outer_join)
 
530
    {
 
531
      /*
 
532
        We're dealing with
 
533
 
 
534
          ... INNER JOIN tblX ON (subquery AND whatever) ...
 
535
 
 
536
        The sj-nest will be tblX's "sibling", i.e. another child of its
 
537
        parent. This is ok because tblX is joined as an inner join.
 
538
      */
 
539
      emb_tbl_nest= subq_pred->expr_join_nest->embedding;
 
540
      if (emb_tbl_nest)
 
541
        emb_join_list= &emb_tbl_nest->nested_join->join_list;
 
542
    }
 
543
    else if (!subq_pred->expr_join_nest->nested_join)
 
544
    {
 
545
      TableList *outer_tbl= subq_pred->expr_join_nest;
 
546
      TableList *wrap_nest;
 
547
      /*
 
548
        We're dealing with
 
549
 
 
550
          ... LEFT JOIN tbl ON (on_expr AND subq_pred) ...
 
551
 
 
552
        we'll need to convert it into:
 
553
 
 
554
          ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ...
 
555
                        |                      |
 
556
                        |<----- wrap_nest ---->|
 
557
 
 
558
        Q:  other subqueries may be pointing to this element. What to do?
 
559
        A1: simple solution: copy *subq_pred->expr_join_nest= *parent_nest.
 
560
            But we'll need to fix other pointers.
 
561
        A2: Another way: have TableList::next_ptr so the following
 
562
            subqueries know the table has been nested.
 
563
        A3: changes in the TableList::outer_join will make everything work
 
564
            automatically.
 
565
      */
 
566
      if (!(wrap_nest= alloc_join_nest(parent_join->session)))
 
567
      {
 
568
        return(true);
 
569
      }
 
570
      wrap_nest->embedding= outer_tbl->embedding;
 
571
      wrap_nest->join_list= outer_tbl->join_list;
 
572
      wrap_nest->alias= (char*) "(sj-wrap)";
 
573
 
 
574
      wrap_nest->nested_join->join_list.empty();
 
575
      wrap_nest->nested_join->join_list.push_back(outer_tbl);
 
576
 
 
577
      outer_tbl->embedding= wrap_nest;
 
578
      outer_tbl->join_list= &wrap_nest->nested_join->join_list;
 
579
 
 
580
      /*
 
581
        wrap_nest will take place of outer_tbl, so move the outer join flag
 
582
        and on_expr
 
583
      */
 
584
      wrap_nest->outer_join= outer_tbl->outer_join;
 
585
      outer_tbl->outer_join= 0;
 
586
 
 
587
      wrap_nest->on_expr= outer_tbl->on_expr;
 
588
      outer_tbl->on_expr= NULL;
 
589
 
 
590
      List_iterator<TableList> li(*wrap_nest->join_list);
 
591
      TableList *tbl;
 
592
      while ((tbl= li++))
 
593
      {
 
594
        if (tbl == outer_tbl)
 
595
        {
 
596
          li.replace(wrap_nest);
 
597
          break;
 
598
        }
 
599
      }
 
600
      /*
 
601
        Ok now wrap_nest 'contains' outer_tbl and we're ready to add the
 
602
        semi-join nest into it
 
603
      */
 
604
      emb_join_list= &wrap_nest->nested_join->join_list;
 
605
      emb_tbl_nest=  wrap_nest;
 
606
    }
 
607
  }
 
608
 
 
609
  TableList *sj_nest;
 
610
  nested_join_st *nested_join;
 
611
  if (!(sj_nest= alloc_join_nest(parent_join->session)))
 
612
  {
 
613
    return(true);
 
614
  }
 
615
  nested_join= sj_nest->nested_join;
 
616
 
 
617
  sj_nest->join_list= emb_join_list;
 
618
  sj_nest->embedding= emb_tbl_nest;
 
619
  sj_nest->alias= (char*) "(sj-nest)";
 
620
  /* Nests do not participate in those 'chains', so: */
 
621
  /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/
 
622
  emb_join_list->push_back(sj_nest);
 
623
 
 
624
  /*
 
625
    nested_join->used_tables and nested_join->not_null_tables are
 
626
    initialized in simplify_joins().
 
627
  */
 
628
 
 
629
  /*
 
630
    2. Walk through subquery's top list and set 'embedding' to point to the
 
631
       sj-nest.
 
632
  */
 
633
  Select_Lex *subq_lex= subq_pred->unit->first_select();
 
634
  nested_join->join_list.empty();
 
635
  List_iterator_fast<TableList> li(subq_lex->top_join_list);
 
636
  TableList *tl, *last_leaf;
 
637
  while ((tl= li++))
 
638
  {
 
639
    tl->embedding= sj_nest;
 
640
    tl->join_list= &nested_join->join_list;
 
641
    nested_join->join_list.push_back(tl);
 
642
  }
 
643
 
 
644
  /*
 
645
    Reconnect the next_leaf chain.
 
646
    TODO: Do we have to put subquery's tables at the end of the chain?
 
647
          Inserting them at the beginning would be a bit faster.
 
648
    NOTE: We actually insert them at the front! That's because the order is
 
649
          reversed in this list.
 
650
  */
 
651
  for (tl= parent_lex->leaf_tables; tl->next_leaf; tl= tl->next_leaf) {};
 
652
  tl->next_leaf= subq_lex->leaf_tables;
 
653
  last_leaf= tl;
 
654
 
 
655
  /*
 
656
    Same as above for next_local chain
 
657
    (a theory: a next_local chain always starts with ::leaf_tables
 
658
     because view's tables are inserted after the view)
 
659
  */
 
660
  for (tl= parent_lex->leaf_tables; tl->next_local; tl= tl->next_local) {};
 
661
  tl->next_local= subq_lex->leaf_tables;
 
662
 
 
663
  /* A theory: no need to re-connect the next_global chain */
 
664
 
 
665
  /* 3. Remove the original subquery predicate from the WHERE/ON */
 
666
 
 
667
  // The subqueries were replaced for Item_int(1) earlier
 
668
  subq_pred->exec_method= Item_in_subselect::SEMI_JOIN; // for subsequent executions
 
669
  /*TODO: also reset the 'with_subselect' there. */
 
670
 
 
671
  /* n. Adjust the parent_join->tables counter */
 
672
  uint32_t table_no= parent_join->tables;
 
673
  /* n. Walk through child's tables and adjust table->map */
 
674
  for (tl= subq_lex->leaf_tables; tl; tl= tl->next_leaf, table_no++)
 
675
  {
 
676
    tl->table->tablenr= table_no;
 
677
    tl->table->map= ((table_map)1) << table_no;
 
678
    Select_Lex *old_sl= tl->select_lex;
 
679
    tl->select_lex= parent_join->select_lex;
 
680
    for(TableList *emb= tl->embedding; emb && emb->select_lex == old_sl; emb= emb->embedding)
 
681
      emb->select_lex= parent_join->select_lex;
 
682
  }
 
683
  parent_join->tables += subq_lex->join->tables;
 
684
 
 
685
  /*
 
686
    Put the subquery's WHERE into semi-join's sj_on_expr
 
687
    Add the subquery-induced equalities too.
 
688
  */
 
689
  Select_Lex *save_lex= session->lex->current_select;
 
690
  session->lex->current_select=subq_lex;
 
691
  if (!subq_pred->left_expr->fixed &&
 
692
       subq_pred->left_expr->fix_fields(session, &subq_pred->left_expr))
 
693
    return(true);
 
694
  session->lex->current_select=save_lex;
 
695
 
 
696
  sj_nest->nested_join->sj_corr_tables= subq_pred->used_tables();
 
697
  sj_nest->nested_join->sj_depends_on=  subq_pred->used_tables() |
 
698
                                        subq_pred->left_expr->used_tables();
 
699
  sj_nest->sj_on_expr= subq_lex->where;
 
700
 
 
701
  /*
 
702
    Create the IN-equalities and inject them into semi-join's ON expression.
 
703
    Additionally, for InsideOut strategy
 
704
     - Record the number of IN-equalities.
 
705
     - Create list of pointers to (oe1, ..., ieN). We'll need the list to
 
706
       see which of the expressions are bound and which are not (for those
 
707
       we'll produce a distinct stream of (ie_i1,...ie_ik).
 
708
 
 
709
       (TODO: can we just create a list of pointers and hope the expressions
 
710
       will not substitute themselves on fix_fields()? or we need to wrap
 
711
       them into Item_direct_view_refs and store pointers to those. The
 
712
       pointers to Item_direct_view_refs are guaranteed to be stable as
 
713
       Item_direct_view_refs doesn't substitute itself with anything in
 
714
       Item_direct_view_ref::fix_fields.
 
715
  */
 
716
  sj_nest->sj_in_exprs= subq_pred->left_expr->cols();
 
717
  sj_nest->nested_join->sj_outer_expr_list.empty();
 
718
 
 
719
  if (subq_pred->left_expr->cols() == 1)
 
720
  {
 
721
    nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr);
 
722
 
 
723
    Item *item_eq= new Item_func_eq(subq_pred->left_expr,
 
724
                                    subq_lex->ref_pointer_array[0]);
 
725
    item_eq->name= (char*)subq_sj_cond_name;
 
726
    sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
727
  }
 
728
  else
 
729
  {
 
730
    for (uint32_t i= 0; i < subq_pred->left_expr->cols(); i++)
 
731
    {
 
732
      nested_join->sj_outer_expr_list.push_back(subq_pred->left_expr->
 
733
                                                element_index(i));
 
734
      Item *item_eq=
 
735
        new Item_func_eq(subq_pred->left_expr->element_index(i),
 
736
                         subq_lex->ref_pointer_array[i]);
 
737
      item_eq->name= (char*)subq_sj_cond_name + (i % 64);
 
738
      sj_nest->sj_on_expr= and_items(sj_nest->sj_on_expr, item_eq);
 
739
    }
 
740
  }
 
741
  /* Fix the created equality and AND */
 
742
  sj_nest->sj_on_expr->fix_fields(parent_join->session, &sj_nest->sj_on_expr);
 
743
 
 
744
  /*
 
745
    Walk through sj nest's WHERE and ON expressions and call
 
746
    item->fix_table_changes() for all items.
 
747
  */
 
748
  sj_nest->sj_on_expr->fix_after_pullout(parent_lex, &sj_nest->sj_on_expr);
 
749
  fix_list_after_tbl_changes(parent_lex, &sj_nest->nested_join->join_list);
 
750
 
 
751
 
 
752
  /* Unlink the child select_lex so it doesn't show up in EXPLAIN: */
 
753
  subq_lex->master_unit()->exclude_level();
 
754
 
 
755
  /* Inject sj_on_expr into the parent's WHERE or ON */
 
756
  if (emb_tbl_nest)
 
757
  {
 
758
    emb_tbl_nest->on_expr= and_items(emb_tbl_nest->on_expr,
 
759
                                     sj_nest->sj_on_expr);
 
760
    emb_tbl_nest->on_expr->fix_fields(parent_join->session, &emb_tbl_nest->on_expr);
 
761
  }
 
762
  else
 
763
  {
 
764
    /* Inject into the WHERE */
 
765
    parent_join->conds= and_items(parent_join->conds, sj_nest->sj_on_expr);
 
766
    parent_join->conds->fix_fields(parent_join->session, &parent_join->conds);
 
767
    parent_join->select_lex->where= parent_join->conds;
 
768
  }
 
769
 
 
770
  return(false);
 
771
}
 
772
 
 
773
/*
 
774
  Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
775
 
 
776
  SYNOPSIS
 
777
    find_eq_ref_candidate()
 
778
      table             Table to be checked
 
779
      sj_inner_tables   Bitmap of inner tables. eq_ref(inner_table) doesn't
 
780
                        count.
 
781
 
 
782
  DESCRIPTION
 
783
    Check if table's KEYUSE elements have an eq_ref(outer_tables) candidate
 
784
 
 
785
  TODO
 
786
    Check again if it is feasible to factor common parts with constant table
 
787
    search
 
788
 
 
789
  RETURN
 
790
    true  - There exists an eq_ref(outer-tables) candidate
 
791
    false - Otherwise
 
792
*/
 
793
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
 
794
{
 
795
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
 
796
  uint32_t key;
 
797
 
 
798
  if (keyuse)
 
799
  {
 
800
    while (1) /* For each key */
 
801
    {
 
802
      key= keyuse->key;
 
803
      KEY *keyinfo= table->key_info + key;
 
804
      key_part_map bound_parts= 0;
 
805
      if ((keyinfo->flags & HA_NOSAME) == HA_NOSAME)
 
806
      {
 
807
        do  /* For all equalities on all key parts */
 
808
        {
 
809
          /* Check if this is "t.keypart = expr(outer_tables) */
 
810
          if (!(keyuse->used_tables & sj_inner_tables) &&
 
811
              !(keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL))
 
812
          {
 
813
            bound_parts |= 1 << keyuse->keypart;
 
814
          }
 
815
          keyuse++;
 
816
        } while (keyuse->key == key && keyuse->table == table);
 
817
 
 
818
        if (bound_parts == PREV_BITS(uint, keyinfo->key_parts))
 
819
          return true;
 
820
        if (keyuse->table != table)
 
821
          return false;
 
822
      }
 
823
      else
 
824
      {
 
825
        do
 
826
        {
 
827
          keyuse++;
 
828
          if (keyuse->table != table)
 
829
            return false;
 
830
        }
 
831
        while (keyuse->key == key);
 
832
      }
 
833
    }
 
834
  }
 
835
  return false;
 
836
}
 
837
 
455
838
/*****************************************************************************
456
 
  Create JoinTableS, make a guess about the table types,
 
839
  Create JOIN_TABS, make a guess about the table types,
457
840
  Approximate how many records will be used in each table
458
841
*****************************************************************************/
459
 
ha_rows get_quick_record_count(Session *session, optimizer::SqlSelect *select, Table *table, const key_map *keys,ha_rows limit)
 
842
ha_rows get_quick_record_count(Session *session, SQL_SELECT *select, Table *table, const key_map *keys,ha_rows limit)
460
843
{
461
844
  int error;
462
845
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
485
868
          keyuse     Pointer to possible keys
486
869
*****************************************************************************/
487
870
 
 
871
/**
 
872
  Merge new key definitions to old ones, remove those not used in both.
 
873
 
 
874
  This is called for OR between different levels.
 
875
 
 
876
  To be able to do 'ref_or_null' we merge a comparison of a column
 
877
  and 'column IS NULL' to one test.  This is useful for sub select queries
 
878
  that are internally transformed to something like:.
 
879
 
 
880
  @code
 
881
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
 
882
  @endcode
 
883
 
 
884
  KEY_FIELD::null_rejecting is processed as follows: @n
 
885
  result has null_rejecting=true if it is set for both ORed references.
 
886
  for example:
 
887
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
 
888
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
 
889
 
 
890
  @todo
 
891
    The result of this is that we're missing some 'ref' accesses.
 
892
    OptimizerTeam: Fix this
 
893
*/
 
894
static KEY_FIELD *merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end, uint32_t and_level)
 
895
{
 
896
  if (start == new_fields)
 
897
    return start;                               // Impossible or
 
898
  if (new_fields == end)
 
899
    return start;                               // No new fields, skip all
 
900
 
 
901
  KEY_FIELD *first_free=new_fields;
 
902
 
 
903
  /* Mark all found fields in old array */
 
904
  for (; new_fields != end ; new_fields++)
 
905
  {
 
906
    for (KEY_FIELD *old=start ; old != first_free ; old++)
 
907
    {
 
908
      if (old->field == new_fields->field)
 
909
      {
 
910
        /*
 
911
          NOTE: below const_item() call really works as "!used_tables()", i.e.
 
912
          it can return false where it is feasible to make it return true.
 
913
 
 
914
          The cause is as follows: Some of the tables are already known to be
 
915
          const tables (the detection code is in make_join_statistics(),
 
916
          above the update_ref_and_keys() call), but we didn't propagate
 
917
          information about this: Table::const_table is not set to true, and
 
918
          Item::update_used_tables() hasn't been called for each item.
 
919
          The result of this is that we're missing some 'ref' accesses.
 
920
          TODO: OptimizerTeam: Fix this
 
921
        */
 
922
        if (!new_fields->val->const_item())
 
923
        {
 
924
          /*
 
925
            If the value matches, we can use the key reference.
 
926
            If not, we keep it until we have examined all new values
 
927
          */
 
928
          if (old->val->eq(new_fields->val, old->field->binary()))
 
929
          {
 
930
            old->level= and_level;
 
931
            old->optimize= ((old->optimize & new_fields->optimize &
 
932
                KEY_OPTIMIZE_EXISTS) |
 
933
                ((old->optimize | new_fields->optimize) &
 
934
                KEY_OPTIMIZE_REF_OR_NULL));
 
935
                  old->null_rejecting= (old->null_rejecting &&
 
936
                                        new_fields->null_rejecting);
 
937
          }
 
938
        }
 
939
        else if (old->eq_func && new_fields->eq_func &&
 
940
                      old->val->eq_by_collation(new_fields->val,
 
941
                                                old->field->binary(),
 
942
                                                old->field->charset()))
 
943
 
 
944
        {
 
945
          old->level= and_level;
 
946
          old->optimize= ((old->optimize & new_fields->optimize &
 
947
              KEY_OPTIMIZE_EXISTS) |
 
948
              ((old->optimize | new_fields->optimize) &
 
949
              KEY_OPTIMIZE_REF_OR_NULL));
 
950
                old->null_rejecting= (old->null_rejecting &&
 
951
                                      new_fields->null_rejecting);
 
952
        }
 
953
        else if (old->eq_func && new_fields->eq_func &&
 
954
          ((old->val->const_item() && old->val->is_null()) ||
 
955
                        new_fields->val->is_null()))
 
956
        {
 
957
          /* field = expression OR field IS NULL */
 
958
          old->level= and_level;
 
959
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
 
960
          /*
 
961
                  Remember the NOT NULL value unless the value does not depend
 
962
                  on other tables.
 
963
                */
 
964
          if (!old->val->used_tables() && old->val->is_null())
 
965
            old->val= new_fields->val;
 
966
                /* The referred expression can be NULL: */
 
967
                old->null_rejecting= 0;
 
968
        }
 
969
        else
 
970
        {
 
971
          /*
 
972
            We are comparing two different const.  In this case we can't
 
973
            use a key-lookup on this so it's better to remove the value
 
974
            and let the range optimzier handle it
 
975
          */
 
976
          if (old == --first_free)              // If last item
 
977
            break;
 
978
          *old= *first_free;                    // Remove old value
 
979
          old--;                                // Retry this value
 
980
        }
 
981
      }
 
982
    }
 
983
  }
 
984
  /* Remove all not used items */
 
985
  for (KEY_FIELD *old=start ; old != first_free ;)
 
986
  {
 
987
    if (old->level != and_level)
 
988
    {                                           // Not used in all levels
 
989
      if (old == --first_free)
 
990
        break;
 
991
      *old= *first_free;                        // Remove old value
 
992
      continue;
 
993
    }
 
994
    old++;
 
995
  }
 
996
  return first_free;
 
997
}
 
998
 
 
999
/**
 
1000
  Add a possible key to array of possible keys if it's usable as a key
 
1001
 
 
1002
    @param key_fields      Pointer to add key, if usable
 
1003
    @param and_level       And level, to be stored in KEY_FIELD
 
1004
    @param cond            Condition predicate
 
1005
    @param field           Field used in comparision
 
1006
    @param eq_func         True if we used =, <=> or IS NULL
 
1007
    @param value           Value used for comparison with field
 
1008
    @param usable_tables   Tables which can be used for key optimization
 
1009
    @param sargables       IN/OUT Array of found sargable candidates
 
1010
 
 
1011
  @note
 
1012
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
 
1013
    table, we store this to be able to do not exists optimization later.
 
1014
 
 
1015
  @returns
 
1016
    *key_fields is incremented if we stored a key in the array
 
1017
*/
 
1018
static void add_key_field(KEY_FIELD **key_fields,
 
1019
                          uint32_t and_level,
 
1020
                          Item_func *cond,
 
1021
                          Field *field,
 
1022
                          bool eq_func,
 
1023
                          Item **value,
 
1024
                          uint32_t num_values,
 
1025
                          table_map usable_tables,
 
1026
                          SARGABLE_PARAM **sargables)
 
1027
{
 
1028
  uint32_t exists_optimize= 0;
 
1029
  if (!(field->flags & PART_KEY_FLAG))
 
1030
  {
 
1031
    // Don't remove column IS NULL on a LEFT JOIN table
 
1032
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
1033
        !field->table->maybe_null || field->null_ptr)
 
1034
      return;                                   // Not a key. Skip it
 
1035
    exists_optimize= KEY_OPTIMIZE_EXISTS;
 
1036
    assert(num_values == 1);
 
1037
  }
 
1038
  else
 
1039
  {
 
1040
    table_map used_tables=0;
 
1041
    bool optimizable=0;
 
1042
    for (uint32_t i=0; i<num_values; i++)
 
1043
    {
 
1044
      used_tables|=(value[i])->used_tables();
 
1045
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
 
1046
        optimizable=1;
 
1047
    }
 
1048
    if (!optimizable)
 
1049
      return;
 
1050
    if (!(usable_tables & field->table->map))
 
1051
    {
 
1052
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
1053
          !field->table->maybe_null || field->null_ptr)
 
1054
        return;                                 // Can't use left join optimize
 
1055
      exists_optimize= KEY_OPTIMIZE_EXISTS;
 
1056
    }
 
1057
    else
 
1058
    {
 
1059
      JOIN_TAB *stat=field->table->reginfo.join_tab;
 
1060
      key_map possible_keys= field->key_start;
 
1061
      possible_keys&= field->table->keys_in_use_for_query;
 
1062
      stat[0].keys|= possible_keys;             // Add possible keys
 
1063
 
 
1064
      /*
 
1065
        Save the following cases:
 
1066
        Field op constant
 
1067
        Field LIKE constant where constant doesn't start with a wildcard
 
1068
        Field = field2 where field2 is in a different table
 
1069
        Field op formula
 
1070
        Field IS NULL
 
1071
        Field IS NOT NULL
 
1072
        Field BETWEEN ...
 
1073
        Field IN ...
 
1074
      */
 
1075
      stat[0].key_dependent|= used_tables;
 
1076
 
 
1077
      bool is_const=1;
 
1078
      for (uint32_t i=0; i<num_values; i++)
 
1079
      {
 
1080
        if (!(is_const&= value[i]->const_item()))
 
1081
          break;
 
1082
      }
 
1083
      if (is_const)
 
1084
        stat[0].const_keys|= possible_keys;
 
1085
      else if (!eq_func)
 
1086
      {
 
1087
        /*
 
1088
          Save info to be able check whether this predicate can be
 
1089
          considered as sargable for range analisis after reading const tables.
 
1090
          We do not save info about equalities as update_const_equal_items
 
1091
          will take care of updating info on keys from sargable equalities.
 
1092
        */
 
1093
        (*sargables)--;
 
1094
        (*sargables)->field= field;
 
1095
        (*sargables)->arg_value= value;
 
1096
        (*sargables)->num_values= num_values;
 
1097
      }
 
1098
      /*
 
1099
        We can't always use indexes when comparing a string index to a
 
1100
        number. cmp_type() is checked to allow compare of dates to numbers.
 
1101
        eq_func is NEVER true when num_values > 1
 
1102
       */
 
1103
      if (!eq_func)
 
1104
      {
 
1105
        /*
 
1106
          Additional optimization: if we're processing
 
1107
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
 
1108
          "t.key = c1".
 
1109
          TODO: This is a very limited fix. A more generic fix is possible.
 
1110
          There are 2 options:
 
1111
          A) Make equality propagation code be able to handle BETWEEN
 
1112
             (including cases like t1.key BETWEEN t2.key AND t3.key)
 
1113
          B) Make range optimizer to infer additional "t.key = c" equalities
 
1114
             and use them in equality propagation process (see details in
 
1115
             OptimizerKBAndTodo)
 
1116
        */
 
1117
        if ((cond->functype() != Item_func::BETWEEN) ||
 
1118
            ((Item_func_between*) cond)->negated ||
 
1119
            !value[0]->eq(value[1], field->binary()))
 
1120
          return;
 
1121
        eq_func= true;
 
1122
      }
 
1123
 
 
1124
      if (field->result_type() == STRING_RESULT)
 
1125
      {
 
1126
        if ((*value)->result_type() != STRING_RESULT)
 
1127
        {
 
1128
          if (field->cmp_type() != (*value)->result_type())
 
1129
            return;
 
1130
        }
 
1131
        else
 
1132
        {
 
1133
          /*
 
1134
            We can't use indexes if the effective collation
 
1135
            of the operation differ from the field collation.
 
1136
          */
 
1137
          if (field->cmp_type() == STRING_RESULT &&
 
1138
              ((Field_str*)field)->charset() != cond->compare_collation())
 
1139
            return;
 
1140
        }
 
1141
      }
 
1142
    }
 
1143
  }
 
1144
  /*
 
1145
    For the moment eq_func is always true. This slot is reserved for future
 
1146
    extensions where we want to remembers other things than just eq comparisons
 
1147
  */
 
1148
  assert(eq_func);
 
1149
  /* Store possible eq field */
 
1150
  (*key_fields)->field=         field;
 
1151
  (*key_fields)->eq_func=       eq_func;
 
1152
  (*key_fields)->val=           *value;
 
1153
  (*key_fields)->level=         and_level;
 
1154
  (*key_fields)->optimize=      exists_optimize;
 
1155
  /*
 
1156
    If the condition has form "tbl.keypart = othertbl.field" and
 
1157
    othertbl.field can be NULL, there will be no matches if othertbl.field
 
1158
    has NULL value.
 
1159
    We use null_rejecting in add_not_null_conds() to add
 
1160
    'othertbl.field IS NOT NULL' to tab->select_cond.
 
1161
  */
 
1162
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
 
1163
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
 
1164
                                  ((*value)->type() == Item::FIELD_ITEM) &&
 
1165
                                  ((Item_field*)*value)->field->maybe_null());
 
1166
  (*key_fields)->cond_guard= NULL;
 
1167
  (*key_fields)->sj_pred_no= (cond->name >= subq_sj_cond_name &&
 
1168
                              cond->name < subq_sj_cond_name + 64)?
 
1169
                              cond->name - subq_sj_cond_name: UINT_MAX;
 
1170
  (*key_fields)++;
 
1171
}
 
1172
 
 
1173
/**
 
1174
  Add possible keys to array of possible keys originated from a simple
 
1175
  predicate.
 
1176
 
 
1177
    @param  key_fields     Pointer to add key, if usable
 
1178
    @param  and_level      And level, to be stored in KEY_FIELD
 
1179
    @param  cond           Condition predicate
 
1180
    @param  field          Field used in comparision
 
1181
    @param  eq_func        True if we used =, <=> or IS NULL
 
1182
    @param  value          Value used for comparison with field
 
1183
                           Is NULL for BETWEEN and IN
 
1184
    @param  usable_tables  Tables which can be used for key optimization
 
1185
    @param  sargables      IN/OUT Array of found sargable candidates
 
1186
 
 
1187
  @note
 
1188
    If field items f1 and f2 belong to the same multiple equality and
 
1189
    a key is added for f1, the the same key is added for f2.
 
1190
 
 
1191
  @returns
 
1192
    *key_fields is incremented if we stored a key in the array
 
1193
*/
 
1194
static void add_key_equal_fields(KEY_FIELD **key_fields,
 
1195
                                 uint32_t and_level,
 
1196
                                 Item_func *cond,
 
1197
                                 Item_field *field_item,
 
1198
                                 bool eq_func,
 
1199
                                 Item **val,
 
1200
                                 uint32_t num_values,
 
1201
                                 table_map usable_tables,
 
1202
                                 SARGABLE_PARAM **sargables)
 
1203
{
 
1204
  Field *field= field_item->field;
 
1205
  add_key_field(key_fields, and_level, cond, field,
 
1206
                eq_func, val, num_values, usable_tables, sargables);
 
1207
  Item_equal *item_equal= field_item->item_equal;
 
1208
  if (item_equal)
 
1209
  {
 
1210
    /*
 
1211
      Add to the set of possible key values every substitution of
 
1212
      the field for an equal field included into item_equal
 
1213
    */
 
1214
    Item_equal_iterator it(*item_equal);
 
1215
    Item_field *item;
 
1216
    while ((item= it++))
 
1217
    {
 
1218
      if (!field->eq(item->field))
 
1219
      {
 
1220
        add_key_field(key_fields, and_level, cond, item->field,
 
1221
                      eq_func, val, num_values, usable_tables,
 
1222
                      sargables);
 
1223
      }
 
1224
    }
 
1225
  }
 
1226
}
 
1227
 
 
1228
static void add_key_fields(JOIN *join, 
 
1229
                           KEY_FIELD **key_fields,
 
1230
                           uint32_t *and_level,
 
1231
                           COND *cond,
 
1232
                           table_map usable_tables,
 
1233
                           SARGABLE_PARAM **sargables)
 
1234
{
 
1235
  if (cond->type() == Item_func::COND_ITEM)
 
1236
  {
 
1237
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
 
1238
    KEY_FIELD *org_key_fields= *key_fields;
 
1239
 
 
1240
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
1241
    {
 
1242
      Item *item;
 
1243
      while ((item=li++))
 
1244
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
1245
                       sargables);
 
1246
      for (; org_key_fields != *key_fields ; org_key_fields++)
 
1247
        org_key_fields->level= *and_level;
 
1248
    }
 
1249
    else
 
1250
    {
 
1251
      (*and_level)++;
 
1252
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
 
1253
                     sargables);
 
1254
      Item *item;
 
1255
      while ((item=li++))
 
1256
      {
 
1257
        KEY_FIELD *start_key_fields= *key_fields;
 
1258
        (*and_level)++;
 
1259
              add_key_fields(join, key_fields, and_level, item, usable_tables,
 
1260
                            sargables);
 
1261
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
 
1262
                  *key_fields,++(*and_level));
 
1263
      }
 
1264
    }
 
1265
    return;
 
1266
  }
 
1267
 
 
1268
  /*
 
1269
    Subquery optimization: Conditions that are pushed down into subqueries
 
1270
    are wrapped into Item_func_trig_cond. We process the wrapped condition
 
1271
    but need to set cond_guard for KEYUSE elements generated from it.
 
1272
  */
 
1273
  {
 
1274
    if (cond->type() == Item::FUNC_ITEM &&
 
1275
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
 
1276
    {
 
1277
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
 
1278
      if (!join->group_list && !join->order &&
 
1279
          join->unit->item &&
 
1280
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
 
1281
          !join->unit->is_union())
 
1282
      {
 
1283
        KEY_FIELD *save= *key_fields;
 
1284
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
 
1285
                       sargables);
 
1286
        // Indicate that this ref access candidate is for subquery lookup:
 
1287
        for (; save != *key_fields; save++)
 
1288
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
 
1289
      }
 
1290
      return;
 
1291
    }
 
1292
  }
 
1293
 
 
1294
  /* If item is of type 'field op field/constant' add it to key_fields */
 
1295
  if (cond->type() != Item::FUNC_ITEM)
 
1296
    return;
 
1297
  Item_func *cond_func= (Item_func*) cond;
 
1298
  switch (cond_func->select_optimize()) {
 
1299
  case Item_func::OPTIMIZE_NONE:
 
1300
    break;
 
1301
  case Item_func::OPTIMIZE_KEY:
 
1302
  {
 
1303
    Item **values;
 
1304
    // BETWEEN, IN, NE
 
1305
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
 
1306
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
1307
    {
 
1308
      values= cond_func->arguments()+1;
 
1309
      if (cond_func->functype() == Item_func::NE_FUNC &&
 
1310
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
1311
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
1312
        values--;
 
1313
      assert(cond_func->functype() != Item_func::IN_FUNC ||
 
1314
                  cond_func->argument_count() != 2);
 
1315
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
1316
                           (Item_field*) (cond_func->key_item()->real_item()),
 
1317
                           0, values,
 
1318
                           cond_func->argument_count()-1,
 
1319
                           usable_tables, sargables);
 
1320
    }
 
1321
    if (cond_func->functype() == Item_func::BETWEEN)
 
1322
    {
 
1323
      values= cond_func->arguments();
 
1324
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
1325
      {
 
1326
        Item_field *field_item;
 
1327
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
 
1328
            &&
 
1329
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
 
1330
        {
 
1331
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
 
1332
          add_key_equal_fields(key_fields, *and_level, cond_func,
 
1333
                               field_item, 0, values, 1, usable_tables,
 
1334
                               sargables);
 
1335
        }
 
1336
      }
 
1337
    }
 
1338
    break;
 
1339
  }
 
1340
  case Item_func::OPTIMIZE_OP:
 
1341
  {
 
1342
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
 
1343
                     cond_func->functype() == Item_func::EQUAL_FUNC);
 
1344
 
 
1345
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
1346
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
1347
    {
 
1348
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
1349
                        (Item_field*) (cond_func->arguments()[0])->real_item(),
 
1350
                           equal_func,
 
1351
                           cond_func->arguments()+1, 1, usable_tables,
 
1352
                           sargables);
 
1353
    }
 
1354
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
1355
        cond_func->functype() != Item_func::LIKE_FUNC &&
 
1356
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
 
1357
    {
 
1358
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
1359
                       (Item_field*) (cond_func->arguments()[1])->real_item(), equal_func,
 
1360
                           cond_func->arguments(),1,usable_tables,
 
1361
                           sargables);
 
1362
    }
 
1363
    break;
 
1364
  }
 
1365
  case Item_func::OPTIMIZE_NULL:
 
1366
    /* column_name IS [NOT] NULL */
 
1367
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
1368
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
1369
    {
 
1370
      Item *tmp=new Item_null;
 
1371
      if (unlikely(!tmp))                       // Should never be true
 
1372
        return;
 
1373
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
1374
                    (Item_field*) (cond_func->arguments()[0])->real_item(),
 
1375
                    cond_func->functype() == Item_func::ISNULL_FUNC,
 
1376
                           &tmp, 1, usable_tables, sargables);
 
1377
    }
 
1378
    break;
 
1379
  case Item_func::OPTIMIZE_EQUAL:
 
1380
    Item_equal *item_equal= (Item_equal *) cond;
 
1381
    Item *const_item= item_equal->get_const();
 
1382
    Item_equal_iterator it(*item_equal);
 
1383
    Item_field *item;
 
1384
    if (const_item)
 
1385
    {
 
1386
      /*
 
1387
        For each field field1 from item_equal consider the equality
 
1388
        field1=const_item as a condition allowing an index access of the table
 
1389
        with field1 by the keys value of field1.
 
1390
      */
 
1391
      while ((item= it++))
 
1392
      {
 
1393
        add_key_field(key_fields, *and_level, cond_func, item->field,
 
1394
                      true, &const_item, 1, usable_tables, sargables);
 
1395
      }
 
1396
    }
 
1397
    else
 
1398
    {
 
1399
      /*
 
1400
        Consider all pairs of different fields included into item_equal.
 
1401
        For each of them (field1, field1) consider the equality
 
1402
        field1=field2 as a condition allowing an index access of the table
 
1403
        with field1 by the keys value of field2.
 
1404
      */
 
1405
      Item_equal_iterator fi(*item_equal);
 
1406
      while ((item= fi++))
 
1407
      {
 
1408
        Field *field= item->field;
 
1409
        while ((item= it++))
 
1410
        {
 
1411
          if (!field->eq(item->field))
 
1412
          {
 
1413
            add_key_field(key_fields, *and_level, cond_func, field,
 
1414
                          true, (Item **) &item, 1, usable_tables,
 
1415
                          sargables);
 
1416
          }
 
1417
        }
 
1418
        it.rewind();
 
1419
      }
 
1420
    }
 
1421
    break;
 
1422
  }
 
1423
}
488
1424
 
489
1425
/**
490
1426
  Add all keys with uses 'field' for some keypart.
498
1434
  return found;
499
1435
}
500
1436
 
501
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b)
 
1437
static void add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
 
1438
{
 
1439
  Field *field=key_field->field;
 
1440
  Table *form= field->table;
 
1441
  KEYUSE keyuse;
 
1442
 
 
1443
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
 
1444
  {
 
1445
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
1446
    {
 
1447
      if (!(form->keys_in_use_for_query.test(key)))
 
1448
        continue;
 
1449
 
 
1450
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
 
1451
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
1452
      {
 
1453
        if (field->eq(form->key_info[key].key_part[part].field))
 
1454
        {
 
1455
          keyuse.table= field->table;
 
1456
          keyuse.val =  key_field->val;
 
1457
          keyuse.key =  key;
 
1458
          keyuse.keypart=part;
 
1459
          keyuse.keypart_map= (key_part_map) 1 << part;
 
1460
          keyuse.used_tables=key_field->val->used_tables();
 
1461
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
 
1462
                keyuse.null_rejecting= key_field->null_rejecting;
 
1463
                keyuse.cond_guard= key_field->cond_guard;
 
1464
                keyuse.sj_pred_no= key_field->sj_pred_no;
 
1465
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
1466
        }
 
1467
      }
 
1468
    }
 
1469
  }
 
1470
}
 
1471
 
 
1472
static int sort_keyuse(KEYUSE *a,KEYUSE *b)
502
1473
{
503
1474
  int res;
504
 
  if (a->getTable()->tablenr != b->getTable()->tablenr)
505
 
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
506
 
  if (a->getKey() != b->getKey())
507
 
    return static_cast<int>((a->getKey() - b->getKey()));
508
 
  if (a->getKeypart() != b->getKeypart())
509
 
    return static_cast<int>((a->getKeypart() - b->getKeypart()));
 
1475
  if (a->table->tablenr != b->table->tablenr)
 
1476
    return (int) (a->table->tablenr - b->table->tablenr);
 
1477
  if (a->key != b->key)
 
1478
    return (int) (a->key - b->key);
 
1479
  if (a->keypart != b->keypart)
 
1480
    return (int) (a->keypart - b->keypart);
510
1481
  // Place const values before other ones
511
 
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
512
 
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
 
1482
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
 
1483
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
513
1484
    return res;
514
1485
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
515
 
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
516
 
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
517
 
}
518
 
 
 
1486
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
 
1487
                (b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
 
1488
}
 
1489
 
 
1490
/*
 
1491
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
 
1492
 
 
1493
    This function populates KEY_FIELD array with entries generated from the
 
1494
    ON condition of the given nested join, and does the same for nested joins
 
1495
    contained within this nested join.
 
1496
 
 
1497
  @param[in]      nested_join_table   Nested join pseudo-table to process
 
1498
  @param[in,out]  end                 End of the key field array
 
1499
  @param[in,out]  and_level           And-level
 
1500
  @param[in,out]  sargables           Array of found sargable candidates
 
1501
 
 
1502
 
 
1503
  @note
 
1504
    We can add accesses to the tables that are direct children of this nested
 
1505
    join (1), and are not inner tables w.r.t their neighbours (2).
 
1506
 
 
1507
    Example for #1 (outer brackets pair denotes nested join this function is
 
1508
    invoked for):
 
1509
    @code
 
1510
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
 
1511
    @endcode
 
1512
    Example for #2:
 
1513
    @code
 
1514
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
 
1515
    @endcode
 
1516
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
 
1517
    t1 only.
 
1518
    Example #3:
 
1519
    @code
 
1520
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
 
1521
    @endcode
 
1522
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
 
1523
*/
 
1524
static void add_key_fields_for_nj(JOIN *join,
 
1525
                                  TableList *nested_join_table,
 
1526
                                  KEY_FIELD **end,
 
1527
                                  uint32_t *and_level,
 
1528
                                  SARGABLE_PARAM **sargables)
 
1529
{
 
1530
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
 
1531
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
 
1532
  bool have_another = false;
 
1533
  table_map tables= 0;
 
1534
  TableList *table;
 
1535
  assert(nested_join_table->nested_join);
 
1536
 
 
1537
  while ((table= li++) || (have_another && (li=li2, have_another=false,
 
1538
                                            (table= li++))))
 
1539
  {
 
1540
    if (table->nested_join)
 
1541
    {
 
1542
      if (!table->on_expr)
 
1543
      {
 
1544
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
 
1545
        have_another= true;
 
1546
        li2= li;
 
1547
        li= List_iterator<TableList>(table->nested_join->join_list);
 
1548
      }
 
1549
      else
 
1550
        add_key_fields_for_nj(join, table, end, and_level, sargables);
 
1551
    }
 
1552
    else
 
1553
      if (!table->on_expr)
 
1554
        tables |= table->table->map;
 
1555
  }
 
1556
  if (nested_join_table->on_expr)
 
1557
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
 
1558
                   sargables);
 
1559
}
519
1560
 
520
1561
/**
521
1562
  Update keyuse array with all possible keys we can use to fetch rows.
522
1563
 
523
1564
  @param       session
524
 
  @param[out]  keyuse         Put here ordered array of KeyUse structures
 
1565
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
525
1566
  @param       join_tab       Array in tablenr_order
526
1567
  @param       tables         Number of tables in join
527
1568
  @param       cond           WHERE condition (note that the function analyzes
530
1571
                              for which we can make ref access based the WHERE
531
1572
                              clause)
532
1573
  @param       select_lex     current SELECT
533
 
  @param[out]  sargables      std::vector of found sargable candidates
 
1574
  @param[out]  sargables      Array of found sargable candidates
534
1575
 
535
1576
   @retval
536
1577
     0  OK
539
1580
*/
540
1581
bool update_ref_and_keys(Session *session,
541
1582
                         DYNAMIC_ARRAY *keyuse,
542
 
                         JoinTable *join_tab,
 
1583
                         JOIN_TAB *join_tab,
543
1584
                         uint32_t tables,
544
1585
                         COND *cond, 
545
1586
                         COND_EQUAL *,
546
1587
                         table_map normal_tables,
547
1588
                         Select_Lex *select_lex,
548
 
                         vector<optimizer::SargableParam> &sargables)
 
1589
                         SARGABLE_PARAM **sargables)
549
1590
{
550
 
  uint  and_level,found_eq_constant;
551
 
  optimizer::KeyField *key_fields, *end, *field;
 
1591
  uint  and_level,i,found_eq_constant;
 
1592
  KEY_FIELD *key_fields, *end, *field;
552
1593
  uint32_t sz;
553
 
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
 
1594
  uint32_t m= cmax(select_lex->max_equal_elems,(uint32_t)1);
554
1595
 
555
1596
  /*
556
 
    All predicates that are used to fill arrays of KeyField
557
 
    and SargableParam classes have at most 2 arguments
 
1597
    We use the same piece of memory to store both  KEY_FIELD
 
1598
    and SARGABLE_PARAM structure.
 
1599
    KEY_FIELD values are placed at the beginning this memory
 
1600
    while  SARGABLE_PARAM values are put at the end.
 
1601
    All predicates that are used to fill arrays of KEY_FIELD
 
1602
    and SARGABLE_PARAM structures have at most 2 arguments
558
1603
    except BETWEEN predicates that have 3 arguments and
559
1604
    IN predicates.
560
1605
    This any predicate if it's not BETWEEN/IN can be used
561
 
    directly to fill at most 2 array elements, either of KeyField 
562
 
    or SargableParam type. For a BETWEEN predicate 3 elements
 
1606
    directly to fill at most 2 array elements, either of KEY_FIELD
 
1607
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
563
1608
    can be filled as this predicate is considered as
564
1609
    saragable with respect to each of its argument.
565
1610
    An IN predicate can require at most 1 element as currently
569
1614
    can be not more than select_lex->max_equal_elems such
570
1615
    substitutions.
571
1616
  */
572
 
  sz= sizeof(optimizer::KeyField) *
 
1617
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
573
1618
      (((session->lex->current_select->cond_count+1)*2 +
574
1619
        session->lex->current_select->between_count)*m+1);
575
 
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
576
 
    return true;
 
1620
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
 
1621
    return true; /* purecov: inspected */
577
1622
  and_level= 0;
578
1623
  field= end= key_fields;
 
1624
  *sargables= (SARGABLE_PARAM *) key_fields +
 
1625
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
 
1626
  /* set a barrier for the array of SARGABLE_PARAM */
 
1627
  (*sargables)[0].field= 0;
579
1628
 
580
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
 
1629
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
581
1630
    return true;
582
1631
  if (cond)
583
1632
  {
584
1633
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
585
1634
                   sargables);
586
 
    for (; field != end; field++)
 
1635
    for (; field != end ; field++)
587
1636
    {
588
 
      add_key_part(keyuse, field);
 
1637
      add_key_part(keyuse,field);
589
1638
      /* Mark that we can optimize LEFT JOIN */
590
 
      if (field->getValue()->type() == Item::NULL_ITEM &&
591
 
          ! field->getField()->real_maybe_null())
592
 
      {
593
 
        field->getField()->getTable()->reginfo.not_exists_optimize= 1;
594
 
      }
 
1639
      if (field->val->type() == Item::NULL_ITEM &&
 
1640
          !field->field->real_maybe_null())
 
1641
        field->field->table->reginfo.not_exists_optimize=1;
595
1642
    }
596
1643
  }
597
 
  for (uint32_t i= 0; i < tables; i++)
 
1644
  for (i=0 ; i < tables ; i++)
598
1645
  {
599
1646
    /*
600
1647
      Block the creation of keys for inner tables of outer joins.
617
1664
    TableList *table;
618
1665
    while ((table= li++))
619
1666
    {
620
 
      if (table->getNestedJoin())
 
1667
      if (table->nested_join)
621
1668
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
622
1669
                              sargables);
623
1670
    }
638
1685
  */
639
1686
  if (keyuse->elements)
640
1687
  {
641
 
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
 
1688
    KEYUSE key_end,*prev,*save_pos,*use;
642
1689
 
643
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
644
 
                       (qsort_cmp) sort_keyuse);
 
1690
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
 
1691
          (qsort_cmp) sort_keyuse);
645
1692
 
646
1693
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
647
1694
    insert_dynamic(keyuse,(unsigned char*) &key_end);
648
1695
 
649
 
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
 
1696
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
650
1697
    prev= &key_end;
651
 
    found_eq_constant= 0;
 
1698
    found_eq_constant=0;
 
1699
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
652
1700
    {
653
 
      uint32_t i;
654
 
 
655
 
      for (i= 0; i < keyuse->elements-1; i++, use++)
 
1701
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
 
1702
        use->table->const_key_parts[use->key]|= use->keypart_map;
 
1703
      if (use->key == prev->key && use->table == prev->table)
656
1704
      {
657
 
        if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
658
 
          use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
659
 
        if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
660
 
        {
661
 
          if (prev->getKeypart() + 1 < use->getKeypart() || 
662
 
              ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
663
 
            continue;                           /* remove */
664
 
        }
665
 
        else if (use->getKeypart() != 0)                // First found must be 0
666
 
          continue;
 
1705
        if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
 
1706
          continue;                             /* remove */
 
1707
      }
 
1708
      else if (use->keypart != 0)               // First found must be 0
 
1709
        continue;
667
1710
 
668
 
#ifdef HAVE_VALGRIND
669
 
        /* Valgrind complains about overlapped memcpy when save_pos==use. */
670
 
        if (save_pos != use)
 
1711
#ifdef HAVE_purify
 
1712
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
 
1713
      if (save_pos != use)
671
1714
#endif
672
 
          *save_pos= *use;
673
 
        prev=use;
674
 
        found_eq_constant= ! use->getUsedTables();
675
 
        /* Save ptr to first use */
676
 
        if (! use->getTable()->reginfo.join_tab->keyuse)
677
 
          use->getTable()->reginfo.join_tab->keyuse= save_pos;
678
 
        use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
679
 
        save_pos++;
680
 
      }
681
 
      i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
682
 
      set_dynamic(keyuse, (unsigned char*) &key_end, i);
683
 
      keyuse->elements= i;
 
1715
        *save_pos= *use;
 
1716
      prev=use;
 
1717
      found_eq_constant= !use->used_tables;
 
1718
      /* Save ptr to first use */
 
1719
      if (!use->table->reginfo.join_tab->keyuse)
 
1720
        use->table->reginfo.join_tab->keyuse=save_pos;
 
1721
      use->table->reginfo.join_tab->checked_keys.set(use->key);
 
1722
      save_pos++;
684
1723
    }
 
1724
    i=(uint32_t) (save_pos-(KEYUSE*) keyuse->buffer);
 
1725
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
1726
    keyuse->elements=i;
685
1727
  }
686
1728
  return false;
687
1729
}
689
1731
/**
690
1732
  Update some values in keyuse for faster choose_plan() loop.
691
1733
*/
692
 
void optimize_keyuse(Join *join, DYNAMIC_ARRAY *keyuse_array)
 
1734
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
693
1735
{
694
 
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
695
 
                                                  0, 
696
 
                                                  optimizer::KeyUse*);
 
1736
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);
697
1737
 
698
1738
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
699
1739
  {
706
1746
      Constant tables are ignored.
707
1747
      To avoid bad matches, we don't make ref_table_rows less than 100.
708
1748
    */
709
 
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
710
 
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
 
1749
    keyuse->ref_table_rows= ~(ha_rows) 0;       // If no ref
 
1750
    if (keyuse->used_tables & (map= (keyuse->used_tables & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
711
1751
    {
712
1752
      uint32_t tablenr;
713
1753
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
714
1754
      if (map == 1)                     // Only one table
715
1755
      {
716
1756
        Table *tmp_table=join->all_tables[tablenr];
717
 
        keyuse->setTableRows(max(tmp_table->cursor->stats.records, (ha_rows)100));
 
1757
        keyuse->ref_table_rows= cmax(tmp_table->file->stats.records, (ha_rows)100);
718
1758
      }
719
1759
    }
720
1760
    /*
721
1761
      Outer reference (external field) is constant for single executing
722
1762
      of subquery
723
1763
    */
724
 
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
725
 
      keyuse->setTableRows(1);
 
1764
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
 
1765
      keyuse->ref_table_rows= 1;
726
1766
  }
727
1767
}
728
1768
 
744
1784
  @return
745
1785
    None
746
1786
*/
747
 
void add_group_and_distinct_keys(Join *join, JoinTable *join_tab)
 
1787
void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab)
748
1788
{
749
1789
  List<Item_field> indexed_fields;
750
1790
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
751
 
  Order      *cur_group;
 
1791
  order_st      *cur_group;
752
1792
  Item_field *cur_item;
753
1793
  key_map possible_keys(0);
754
1794
 
785
1825
    join_tab->const_keys|= possible_keys;
786
1826
}
787
1827
 
 
1828
/*****************************************************************************
 
1829
  Go through all combinations of not marked tables and find the one
 
1830
  which uses least records
 
1831
*****************************************************************************/
 
1832
 
 
1833
/*
 
1834
  Given a semi-join nest, find out which of the IN-equalities are bound
 
1835
 
 
1836
  SYNOPSIS
 
1837
    get_bound_sj_equalities()
 
1838
      sj_nest           Semi-join nest
 
1839
      remaining_tables  Tables that are not yet bound
 
1840
 
 
1841
  DESCRIPTION
 
1842
    Given a semi-join nest, find out which of the IN-equalities have their
 
1843
    left part expression bound (i.e. the said expression doesn't refer to
 
1844
    any of remaining_tables and can be evaluated).
 
1845
 
 
1846
  RETURN
 
1847
    Bitmap of bound IN-equalities.
 
1848
*/
 
1849
uint64_t get_bound_sj_equalities(TableList *sj_nest, table_map remaining_tables)
 
1850
{
 
1851
  List_iterator<Item> li(sj_nest->nested_join->sj_outer_expr_list);
 
1852
  Item *item;
 
1853
  uint32_t i= 0;
 
1854
  uint64_t res= 0;
 
1855
  while ((item= li++))
 
1856
  {
 
1857
    /*
 
1858
      Q: should this take into account equality propagation and how?
 
1859
      A: If e->outer_side is an Item_field, walk over the equality
 
1860
         class and see if there is an element that is bound?
 
1861
      (this is an optional feature)
 
1862
    */
 
1863
    if (!(item->used_tables() & remaining_tables))
 
1864
    {
 
1865
      res |= 1UL < i;
 
1866
    }
 
1867
  }
 
1868
  return res;
 
1869
}
 
1870
 
788
1871
/**
789
 
  Compare two JoinTable objects based on the number of accessed records.
 
1872
  Compare two JOIN_TAB objects based on the number of accessed records.
790
1873
 
791
 
  @param ptr1 pointer to first JoinTable object
792
 
  @param ptr2 pointer to second JoinTable object
 
1874
  @param ptr1 pointer to first JOIN_TAB object
 
1875
  @param ptr2 pointer to second JOIN_TAB object
793
1876
 
794
1877
  NOTES
795
1878
    The order relation implemented by join_tab_cmp() is not transitive,
811
1894
*/
812
1895
int join_tab_cmp(const void* ptr1, const void* ptr2)
813
1896
{
814
 
  JoinTable *jt1= *(JoinTable**) ptr1;
815
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
1897
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
1898
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
816
1899
 
817
1900
  if (jt1->dependent & jt2->table->map)
818
1901
    return 1;
830
1913
*/
831
1914
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
832
1915
{
833
 
  JoinTable *jt1= *(JoinTable**) ptr1;
834
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
1916
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
1917
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
835
1918
 
836
1919
  if (jt1->dependent & jt2->table->map)
837
1920
    return 1;
843
1926
/**
844
1927
  Find how much space the prevous read not const tables takes in cache.
845
1928
*/
846
 
void calc_used_field_length(Session *, JoinTable *join_tab)
 
1929
void calc_used_field_length(Session *, JOIN_TAB *join_tab)
847
1930
{
848
1931
  uint32_t null_fields,blobs,fields,rec_length;
849
1932
  Field **f_ptr,*field;
850
1933
 
851
1934
  null_fields= blobs= fields= rec_length=0;
852
 
  for (f_ptr=join_tab->table->getFields() ; (field= *f_ptr) ; f_ptr++)
 
1935
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
853
1936
  {
854
1937
    if (field->isReadSet())
855
1938
    {
868
1951
    rec_length+=sizeof(bool);
869
1952
  if (blobs)
870
1953
  {
871
 
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
872
 
                                     (join_tab->table->getRecordLength()- rec_length));
873
 
    rec_length+= max((uint32_t)4,blob_length);
 
1954
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
 
1955
                             (join_tab->table->getRecordLength()- rec_length));
 
1956
    rec_length+=(uint32_t) cmax((uint32_t)4,blob_length);
874
1957
  }
875
1958
  join_tab->used_fields= fields;
876
1959
  join_tab->used_fieldlength= rec_length;
878
1961
}
879
1962
 
880
1963
StoredKey *get_store_key(Session *session,
881
 
                         optimizer::KeyUse *keyuse,
 
1964
                         KEYUSE *keyuse,
882
1965
                         table_map used_tables,
883
 
                         KeyPartInfo *key_part,
 
1966
                               KEY_PART_INFO *key_part,
884
1967
                         unsigned char *key_buff,
885
1968
                         uint32_t maybe_null)
886
1969
{
887
 
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
888
 
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
1970
  if (!((~used_tables) & keyuse->used_tables))          // if const item
889
1971
  {
890
1972
    return new store_key_const_item(session,
891
1973
                                    key_part->field,
892
1974
                                    key_buff + maybe_null,
893
1975
                                    maybe_null ? key_buff : 0,
894
1976
                                    key_part->length,
895
 
                                    key_use_val);
 
1977
                                    keyuse->val);
896
1978
  }
897
 
  else if (key_use_val->type() == Item::FIELD_ITEM ||
898
 
           (key_use_val->type() == Item::REF_ITEM &&
899
 
            key_use_val->ref_type() == Item_ref::OUTER_REF &&
900
 
            (*(Item_ref**)((Item_ref*)key_use_val)->ref)->ref_type() == Item_ref::DIRECT_REF &&
901
 
            key_use_val->real_item()->type() == Item::FIELD_ITEM))
902
 
  {
 
1979
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
 
1980
           (keyuse->val->type() == Item::REF_ITEM &&
 
1981
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
 
1982
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
 
1983
             Item_ref::DIRECT_REF &&
 
1984
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
903
1985
    return new store_key_field(session,
904
1986
                               key_part->field,
905
1987
                               key_buff + maybe_null,
906
1988
                               maybe_null ? key_buff : 0,
907
1989
                               key_part->length,
908
 
                               ((Item_field*) key_use_val->real_item())->field,
909
 
                               key_use_val->full_name());
910
 
  }
 
1990
                               ((Item_field*) keyuse->val->real_item())->field,
 
1991
                               keyuse->val->full_name());
911
1992
  return new store_key_item(session,
912
1993
                            key_part->field,
913
1994
                            key_buff + maybe_null,
914
1995
                            maybe_null ? key_buff : 0,
915
1996
                            key_part->length,
916
 
                            key_use_val);
 
1997
                            keyuse->val);
917
1998
}
918
1999
 
919
2000
/**
925
2006
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
926
2007
{
927
2008
  bool error;
928
 
  Table *table= field->getTable();
 
2009
  Table *table= field->table;
929
2010
  Session *session= table->in_use;
930
2011
  ha_rows cuted_fields=session->cuted_fields;
931
2012
 
956
2037
    *e1= e2;
957
2038
}
958
2039
 
959
 
bool create_ref_for_key(Join *join, 
960
 
                        JoinTable *j, 
961
 
                        optimizer::KeyUse *org_keyuse,
962
 
                        table_map used_tables)
 
2040
bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
2041
             table_map used_tables)
963
2042
{
964
 
  optimizer::KeyUse *keyuse= org_keyuse;
 
2043
  KEYUSE *keyuse=org_keyuse;
965
2044
  Session  *session= join->session;
966
 
  uint32_t keyparts;
967
 
  uint32_t length;
968
 
  uint32_t key;
969
 
  Table *table= NULL;
970
 
  KeyInfo *keyinfo= NULL;
 
2045
  uint32_t keyparts,length,key;
 
2046
  Table *table;
 
2047
  KEY *keyinfo;
971
2048
 
972
2049
  /*  Use best key from find_best */
973
 
  table= j->table;
974
 
  key= keyuse->getKey();
975
 
  keyinfo= table->key_info + key;
 
2050
  table=j->table;
 
2051
  key=keyuse->key;
 
2052
  keyinfo=table->key_info+key;
976
2053
 
977
2054
  {
978
 
    keyparts= length= 0;
 
2055
    keyparts=length=0;
979
2056
    uint32_t found_part_ref_or_null= 0;
980
2057
    /*
981
2058
      Calculate length for the used key
984
2061
    */
985
2062
    do
986
2063
    {
987
 
      if (! (~used_tables & keyuse->getUsedTables()))
 
2064
      if (!(~used_tables & keyuse->used_tables))
988
2065
      {
989
 
        if (keyparts == keyuse->getKeypart() &&
990
 
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
 
2066
        if (keyparts == keyuse->keypart &&
 
2067
            !(found_part_ref_or_null & keyuse->optimize))
991
2068
        {
992
2069
          keyparts++;
993
 
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
994
 
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
 
2070
          length+= keyinfo->key_part[keyuse->keypart].store_length;
 
2071
          found_part_ref_or_null|= keyuse->optimize;
995
2072
        }
996
2073
      }
997
2074
      keyuse++;
998
 
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
 
2075
    } while (keyuse->table == table && keyuse->key == key);
999
2076
  }
1000
2077
 
1001
2078
  /* set up fieldref */
1018
2095
  keyuse=org_keyuse;
1019
2096
 
1020
2097
  StoredKey **ref_key= j->ref.key_copy;
1021
 
  unsigned char *key_buff= j->ref.key_buff, *null_ref_key= 0;
 
2098
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
1022
2099
  bool keyuse_uses_no_tables= true;
1023
2100
  {
1024
 
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
 
2101
    uint32_t i;
 
2102
    for (i=0 ; i < keyparts ; keyuse++,i++)
1025
2103
    {
1026
 
      while (keyuse->getKeypart() != i ||
1027
 
             ((~used_tables) & keyuse->getUsedTables()))
 
2104
      while (keyuse->keypart != i ||
 
2105
       ((~used_tables) & keyuse->used_tables))
1028
2106
        keyuse++;       /* Skip other parts */
1029
2107
 
1030
2108
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1031
 
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
1032
 
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
1033
 
      if (keyuse->isNullRejected())
 
2109
      j->ref.items[i]=keyuse->val;    // Save for cond removal
 
2110
      j->ref.cond_guards[i]= keyuse->cond_guard;
 
2111
      if (keyuse->null_rejecting)
1034
2112
        j->ref.null_rejecting |= 1 << i;
1035
 
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
1036
 
      if (! keyuse->getUsedTables() &&  !(join->select_options & SELECT_DESCRIBE))
 
2113
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
 
2114
      if (!keyuse->used_tables &&  !(join->select_options & SELECT_DESCRIBE))
1037
2115
      {         // Compare against constant
1038
2116
        store_key_item tmp(session, keyinfo->key_part[i].field,
1039
2117
                           key_buff + maybe_null,
1040
2118
                           maybe_null ?  key_buff : 0,
1041
 
                           keyinfo->key_part[i].length, keyuse->getVal());
 
2119
                           keyinfo->key_part[i].length, keyuse->val);
1042
2120
        if (session->is_fatal_error)
1043
2121
          return(true);
1044
2122
        tmp.copy();
1050
2128
          key_buff, maybe_null);
1051
2129
      /*
1052
2130
        Remember if we are going to use REF_OR_NULL
1053
 
        But only if field _really_ can be null i.e. we force AM_REF
1054
 
        instead of AM_REF_OR_NULL in case if field can't be null
 
2131
        But only if field _really_ can be null i.e. we force JT_REF
 
2132
        instead of JT_REF_OR_NULL in case if field can't be null
1055
2133
      */
1056
 
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
2134
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1057
2135
        null_ref_key= key_buff;
1058
2136
      key_buff+=keyinfo->key_part[i].store_length;
1059
2137
    }
1060
2138
  }
1061
 
  *ref_key= 0;       // end_marker
1062
 
  if (j->type == AM_CONST)
 
2139
  *ref_key=0;       // end_marker
 
2140
  if (j->type == JT_CONST)
1063
2141
    j->table->const_table= 1;
1064
2142
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1065
2143
           keyparts != keyinfo->key_parts || null_ref_key)
1066
2144
  {
1067
2145
    /* Must read with repeat */
1068
 
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
 
2146
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
1069
2147
    j->ref.null_ref_key= null_ref_key;
1070
2148
  }
1071
2149
  else if (keyuse_uses_no_tables)
1077
2155
      Here we should not mark the table as a 'const' as a field may
1078
2156
      have a 'normal' value or a NULL value.
1079
2157
    */
1080
 
    j->type= AM_CONST;
 
2158
    j->type=JT_CONST;
1081
2159
  }
1082
2160
  else
1083
 
    j->type= AM_EQ_REF;
1084
 
  return 0;
 
2161
    j->type=JT_EQ_REF;
 
2162
  return(0);
1085
2163
}
1086
2164
 
1087
2165
/**
1128
2206
 
1129
2207
    Implementation overview
1130
2208
      1. update_ref_and_keys() accumulates info about null-rejecting
1131
 
         predicates in in KeyField::null_rejecting
1132
 
      1.1 add_key_part saves these to KeyUse.
1133
 
      2. create_ref_for_key copies them to table_reference_st.
 
2209
         predicates in in KEY_FIELD::null_rejecting
 
2210
      1.1 add_key_part saves these to KEYUSE.
 
2211
      2. create_ref_for_key copies them to TABLE_REF.
1134
2212
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1135
 
         appropiate JoinTable members.
 
2213
         appropiate JOIN_TAB members.
1136
2214
*/
1137
 
void add_not_null_conds(Join *join)
 
2215
void add_not_null_conds(JOIN *join)
1138
2216
{
1139
 
  for (uint32_t i= join->const_tables; i < join->tables; i++)
 
2217
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1140
2218
  {
1141
 
    JoinTable *tab=join->join_tab+i;
1142
 
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1143
 
         tab->type == AM_REF_OR_NULL) &&
 
2219
    JOIN_TAB *tab=join->join_tab+i;
 
2220
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
 
2221
         tab->type == JT_REF_OR_NULL) &&
1144
2222
        !tab->table->maybe_null)
1145
2223
    {
1146
2224
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1151
2229
          Item *notnull;
1152
2230
          assert(item->type() == Item::FIELD_ITEM);
1153
2231
          Item_field *not_null_item= (Item_field*)item;
1154
 
          JoinTable *referred_tab= not_null_item->field->getTable()->reginfo.join_tab;
 
2232
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
1155
2233
          /*
1156
2234
            For UPDATE queries such as:
1157
2235
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1192
2270
    -  pointer to the guarded predicate, if success
1193
2271
    -  0, otherwise
1194
2272
*/
1195
 
COND *add_found_match_trig_cond(JoinTable *tab, COND *cond, JoinTable *root_tab)
 
2273
COND *add_found_match_trig_cond(JOIN_TAB *tab, COND *cond, JOIN_TAB *root_tab)
1196
2274
{
1197
2275
  COND *tmp;
1198
2276
  assert(cond != 0);
1208
2286
  return tmp;
1209
2287
}
1210
2288
 
 
2289
/*
 
2290
  Check if given expression uses only table fields covered by the given index
 
2291
 
 
2292
  SYNOPSIS
 
2293
    uses_index_fields_only()
 
2294
      item           Expression to check
 
2295
      tbl            The table having the index
 
2296
      keyno          The index number
 
2297
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
2298
 
 
2299
  DESCRIPTION
 
2300
    Check if given expression only uses fields covered by index #keyno in the
 
2301
    table tbl. The expression can use any fields in any other tables.
 
2302
 
 
2303
    The expression is guaranteed not to be AND or OR - those constructs are
 
2304
    handled outside of this function.
 
2305
 
 
2306
  RETURN
 
2307
    true   Yes
 
2308
    false  No
 
2309
*/
 
2310
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
 
2311
{
 
2312
  if (item->const_item())
 
2313
    return true;
 
2314
 
 
2315
  /*
 
2316
    Don't push down the triggered conditions. Nested outer joins execution
 
2317
    code may need to evaluate a condition several times (both triggered and
 
2318
    untriggered), and there is no way to put thi
 
2319
    TODO: Consider cloning the triggered condition and using the copies for:
 
2320
      1. push the first copy down, to have most restrictive index condition
 
2321
         possible
 
2322
      2. Put the second copy into tab->select_cond.
 
2323
  */
 
2324
  if (item->type() == Item::FUNC_ITEM &&
 
2325
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
 
2326
    return false;
 
2327
 
 
2328
  if (!(item->used_tables() & tbl->map))
 
2329
    return other_tbls_ok;
 
2330
 
 
2331
  Item::Type item_type= item->type();
 
2332
  switch (item_type) {
 
2333
  case Item::FUNC_ITEM:
 
2334
    {
 
2335
      /* This is a function, apply condition recursively to arguments */
 
2336
      Item_func *item_func= (Item_func*)item;
 
2337
      Item **child;
 
2338
      Item **item_end= (item_func->arguments()) + item_func->argument_count();
 
2339
      for (child= item_func->arguments(); child != item_end; child++)
 
2340
      {
 
2341
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
 
2342
          return false;
 
2343
      }
 
2344
      return true;
 
2345
    }
 
2346
  case Item::COND_ITEM:
 
2347
    {
 
2348
      /* This is a function, apply condition recursively to arguments */
 
2349
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
 
2350
      Item *list_item;
 
2351
      while ((list_item=li++))
 
2352
      {
 
2353
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
 
2354
          return false;
 
2355
      }
 
2356
      return true;
 
2357
    }
 
2358
  case Item::FIELD_ITEM:
 
2359
    {
 
2360
      Item_field *item_field= (Item_field*)item;
 
2361
      if (item_field->field->table != tbl)
 
2362
        return true;
 
2363
      return item_field->field->part_of_key.test(keyno);
 
2364
    }
 
2365
  case Item::REF_ITEM:
 
2366
    return uses_index_fields_only(item->real_item(), tbl, keyno,
 
2367
                                  other_tbls_ok);
 
2368
  default:
 
2369
    return false; /* Play it safe, don't push unknown non-const items */
 
2370
  }
 
2371
}
 
2372
 
1211
2373
#define ICP_COND_USES_INDEX_ONLY 10
1212
2374
 
 
2375
/*
 
2376
  Get a part of the condition that can be checked using only index fields
 
2377
 
 
2378
  SYNOPSIS
 
2379
    make_cond_for_index()
 
2380
      cond           The source condition
 
2381
      table          The table that is partially available
 
2382
      keyno          The index in the above table. Only fields covered by the index
 
2383
                     are available
 
2384
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
2385
 
 
2386
  DESCRIPTION
 
2387
    Get a part of the condition that can be checked when for the given table
 
2388
    we have values only of fields covered by some index. The condition may
 
2389
    refer to other tables, it is assumed that we have values of all of their
 
2390
    fields.
 
2391
 
 
2392
    Example:
 
2393
      make_cond_for_index(
 
2394
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
 
2395
          t2, keyno(t2.key1))
 
2396
      will return
 
2397
        "cond(t1.field) AND cond(t2.key2)"
 
2398
 
 
2399
  RETURN
 
2400
    Index condition, or NULL if no condition could be inferred.
 
2401
*/
 
2402
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
 
2403
{
 
2404
  if (!cond)
 
2405
    return NULL;
 
2406
  if (cond->type() == Item::COND_ITEM)
 
2407
  {
 
2408
    uint32_t n_marked= 0;
 
2409
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
2410
    {
 
2411
      Item_cond_and *new_cond=new Item_cond_and;
 
2412
      if (!new_cond)
 
2413
        return (COND*) 0;
 
2414
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
2415
      Item *item;
 
2416
      while ((item=li++))
 
2417
      {
 
2418
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
2419
        if (fix)
 
2420
          new_cond->argument_list()->push_back(fix);
 
2421
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
2422
      }
 
2423
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
2424
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
2425
      switch (new_cond->argument_list()->elements) {
 
2426
      case 0:
 
2427
        return (COND*) 0;
 
2428
      case 1:
 
2429
        return new_cond->argument_list()->head();
 
2430
      default:
 
2431
        new_cond->quick_fix_field();
 
2432
        return new_cond;
 
2433
      }
 
2434
    }
 
2435
    else /* It's OR */
 
2436
    {
 
2437
      Item_cond_or *new_cond=new Item_cond_or;
 
2438
      if (!new_cond)
 
2439
        return (COND*) 0;
 
2440
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
2441
      Item *item;
 
2442
      while ((item=li++))
 
2443
      {
 
2444
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
2445
        if (!fix)
 
2446
          return (COND*) 0;
 
2447
        new_cond->argument_list()->push_back(fix);
 
2448
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
2449
      }
 
2450
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
2451
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
2452
      new_cond->quick_fix_field();
 
2453
      new_cond->top_level_item();
 
2454
      return new_cond;
 
2455
    }
 
2456
  }
 
2457
 
 
2458
  if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
 
2459
    return (COND*) 0;
 
2460
  cond->marker= ICP_COND_USES_INDEX_ONLY;
 
2461
  return cond;
 
2462
}
 
2463
 
 
2464
 
 
2465
Item *make_cond_remainder(Item *cond, bool exclude_index)
 
2466
{
 
2467
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
 
2468
    return 0; /* Already checked */
 
2469
 
 
2470
  if (cond->type() == Item::COND_ITEM)
 
2471
  {
 
2472
    table_map tbl_map= 0;
 
2473
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
2474
    {
 
2475
      /* Create new top level AND item */
 
2476
      Item_cond_and *new_cond=new Item_cond_and;
 
2477
      if (!new_cond)
 
2478
        return (COND*) 0;
 
2479
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
2480
      Item *item;
 
2481
      while ((item=li++))
 
2482
      {
 
2483
        Item *fix= make_cond_remainder(item, exclude_index);
 
2484
        if (fix)
 
2485
        {
 
2486
          new_cond->argument_list()->push_back(fix);
 
2487
          tbl_map |= fix->used_tables();
 
2488
        }
 
2489
      }
 
2490
      switch (new_cond->argument_list()->elements) {
 
2491
      case 0:
 
2492
        return (COND*) 0;
 
2493
      case 1:
 
2494
        return new_cond->argument_list()->head();
 
2495
      default:
 
2496
        new_cond->quick_fix_field();
 
2497
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
2498
        return new_cond;
 
2499
      }
 
2500
    }
 
2501
    else /* It's OR */
 
2502
    {
 
2503
      Item_cond_or *new_cond=new Item_cond_or;
 
2504
      if (!new_cond)
 
2505
        return (COND*) 0;
 
2506
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
2507
      Item *item;
 
2508
      while ((item=li++))
 
2509
      {
 
2510
        Item *fix= make_cond_remainder(item, false);
 
2511
        if (!fix)
 
2512
          return (COND*) 0;
 
2513
        new_cond->argument_list()->push_back(fix);
 
2514
        tbl_map |= fix->used_tables();
 
2515
      }
 
2516
      new_cond->quick_fix_field();
 
2517
      ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
2518
      new_cond->top_level_item();
 
2519
      return new_cond;
 
2520
    }
 
2521
  }
 
2522
  return cond;
 
2523
}
 
2524
 
 
2525
/*
 
2526
  Try to extract and push the index condition
 
2527
 
 
2528
  SYNOPSIS
 
2529
    push_index_cond()
 
2530
      tab            A join tab that has tab->table->file and its condition
 
2531
                     in tab->select_cond
 
2532
      keyno          Index for which extract and push the condition
 
2533
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
2534
 
 
2535
  DESCRIPTION
 
2536
    Try to extract and push the index condition down to table handler
 
2537
*/
 
2538
void push_index_cond(JOIN_TAB *tab, uint32_t keyno, bool other_tbls_ok)
 
2539
{
 
2540
  Item *idx_cond;
 
2541
  if (tab->table->file->index_flags(keyno, 0, 1) & HA_DO_INDEX_COND_PUSHDOWN &&
 
2542
      tab->join->session->variables.engine_condition_pushdown)
 
2543
  {
 
2544
    idx_cond= make_cond_for_index(tab->select_cond, tab->table, keyno,
 
2545
                                  other_tbls_ok);
 
2546
 
 
2547
    if (idx_cond)
 
2548
    {
 
2549
      tab->pre_idx_push_select_cond= tab->select_cond;
 
2550
      Item *idx_remainder_cond= tab->table->file->idx_cond_push(keyno, idx_cond);
 
2551
 
 
2552
      /*
 
2553
        Disable eq_ref's "lookup cache" if we've pushed down an index
 
2554
        condition.
 
2555
        TODO: This check happens to work on current ICP implementations, but
 
2556
        there may exist a compliant implementation that will not work
 
2557
        correctly with it. Sort this out when we stabilize the condition
 
2558
        pushdown APIs.
 
2559
      */
 
2560
      if (idx_remainder_cond != idx_cond)
 
2561
        tab->ref.disable_cache= true;
 
2562
 
 
2563
      Item *row_cond= make_cond_remainder(tab->select_cond, true);
 
2564
 
 
2565
      if (row_cond)
 
2566
      {
 
2567
        if (!idx_remainder_cond)
 
2568
          tab->select_cond= row_cond;
 
2569
        else
 
2570
        {
 
2571
          tab->select_cond= new Item_cond_and(row_cond, idx_remainder_cond);
 
2572
          tab->select_cond->quick_fix_field();
 
2573
          ((Item_cond_and*)tab->select_cond)->used_tables_cache=
 
2574
            row_cond->used_tables() | idx_remainder_cond->used_tables();
 
2575
        }
 
2576
      }
 
2577
      else
 
2578
        tab->select_cond= idx_remainder_cond;
 
2579
      if (tab->select)
 
2580
      {
 
2581
        tab->select->cond= tab->select_cond;
 
2582
      }
 
2583
    }
 
2584
  }
 
2585
  return;
 
2586
}
1213
2587
 
1214
2588
/**
1215
 
  cleanup JoinTable.
 
2589
  cleanup JOIN_TAB.
1216
2590
*/
1217
 
void JoinTable::cleanup()
 
2591
void JOIN_TAB::cleanup()
1218
2592
{
1219
2593
  delete select;
1220
2594
  select= 0;
1221
2595
  delete quick;
1222
2596
  quick= 0;
1223
2597
  if (cache.buff)
1224
 
  {
1225
 
    size_t size= cache.end - cache.buff;
1226
 
    global_join_buffer.sub(size);
1227
2598
    free(cache.buff);
1228
 
  }
1229
2599
  cache.buff= 0;
1230
2600
  limit= 0;
1231
2601
  if (table)
1233
2603
    if (table->key_read)
1234
2604
    {
1235
2605
      table->key_read= 0;
1236
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
2606
      table->file->extra(HA_EXTRA_NO_KEYREAD);
1237
2607
    }
1238
 
    table->cursor->ha_index_or_rnd_end();
 
2608
    table->file->ha_index_or_rnd_end();
1239
2609
    /*
1240
2610
      We need to reset this for next select
1241
2611
      (Tested in part_of_refkey)
1242
2612
    */
1243
2613
    table->reginfo.join_tab= 0;
1244
2614
  }
1245
 
  read_record.end_read_record();
 
2615
  end_read_record(&read_record);
1246
2616
}
1247
2617
 
1248
 
bool only_eq_ref_tables(Join *join,Order *order,table_map tables)
 
2618
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
1249
2619
{
1250
 
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
 
2620
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
1251
2621
  {
1252
2622
    if (tables & 1 && !eq_ref_table(join, order, *tab))
1253
2623
      return 0;
1256
2626
}
1257
2627
 
1258
2628
/**
1259
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
2629
  Remove the following expressions from order_st BY and GROUP BY:
1260
2630
  Constant expressions @n
1261
2631
  Expression that only uses tables that are of type EQ_REF and the reference
1262
2632
  is in the order_st list or if all refereed tables are of the above type.
1263
2633
 
1264
2634
  In the following, the X field can be removed:
1265
2635
  @code
1266
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
1267
 
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
 
2636
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
 
2637
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1268
2638
  @endcode
1269
2639
 
1270
2640
  These can't be optimized:
1271
2641
  @code
1272
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
1273
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
1274
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
 
2642
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
 
2643
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
 
2644
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1275
2645
  @endcode
1276
2646
*/
1277
 
bool eq_ref_table(Join *join, Order *start_order, JoinTable *tab)
 
2647
bool eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
1278
2648
{
1279
2649
  if (tab->cached_eq_ref_table)                 // If cached
1280
2650
    return tab->eq_ref_table;
1281
2651
  tab->cached_eq_ref_table=1;
1282
2652
  /* We can skip const tables only if not an outer table */
1283
 
  if (tab->type == AM_CONST && !tab->first_inner)
1284
 
    return (tab->eq_ref_table=1);
1285
 
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
 
2653
  if (tab->type == JT_CONST && !tab->first_inner)
 
2654
    return (tab->eq_ref_table=1);               /* purecov: inspected */
 
2655
  if (tab->type != JT_EQ_REF || tab->table->maybe_null)
1286
2656
    return (tab->eq_ref_table=0);               // We must use this
1287
2657
  Item **ref_item=tab->ref.items;
1288
2658
  Item **end=ref_item+tab->ref.key_parts;
1293
2663
  {
1294
2664
    if (! (*ref_item)->const_item())
1295
2665
    {                                           // Not a const ref
1296
 
      Order *order;
 
2666
      order_st *order;
1297
2667
      for (order=start_order ; order ; order=order->next)
1298
2668
      {
1299
2669
        if ((*ref_item)->eq(order->item[0],0))
1342
2712
    - Item_equal for the found multiple equality predicate if a success;
1343
2713
    - NULL otherwise.
1344
2714
*/
1345
 
static Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
 
2715
Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl)
1346
2716
{
1347
2717
  Item_equal *item= 0;
1348
2718
  bool in_upper_level= false;
1985
3355
    can get more freedom in performing join operations.
1986
3356
    Althogh we don't use this property now, it probably makes sense to use
1987
3357
    it in the future.
1988
 
  @param session                      Thread Cursor
 
3358
  @param session                      Thread handler
1989
3359
  @param cond                condition to build the multiple equalities for
1990
3360
  @param inherited           path to all inherited multiple equality items
1991
3361
  @param join_list           list of join tables to which the condition
2033
3403
    {
2034
3404
      if (table->on_expr)
2035
3405
      {
2036
 
        List<TableList> *nested_join_list= table->getNestedJoin() ?
2037
 
          &table->getNestedJoin()->join_list : NULL;
 
3406
        List<TableList> *nested_join_list= table->nested_join ?
 
3407
          &table->nested_join->join_list : NULL;
2038
3408
        /*
2039
3409
          We can modify table->on_expr because its old value will
2040
3410
          be restored before re-execution of PS/SP.
2086
3456
  }
2087
3457
  if (outer_ref)
2088
3458
    return cmp;
2089
 
  JoinTable **idx= (JoinTable **) table_join_idx;
2090
 
  cmp= idx[field2->field->getTable()->tablenr]-idx[field1->field->getTable()->tablenr];
 
3459
  JOIN_TAB **idx= (JOIN_TAB **) table_join_idx;
 
3460
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2091
3461
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2092
3462
}
2093
3463
 
2307
3677
  @param cond       condition whose multiple equalities are to be checked
2308
3678
  @param table      constant table that has been read
2309
3679
*/
2310
 
static void update_const_equal_items(COND *cond, JoinTable *tab)
 
3680
static void update_const_equal_items(COND *cond, JOIN_TAB *tab)
2311
3681
{
2312
3682
  if (!(cond->used_tables() & tab->table->map))
2313
3683
    return;
2334
3704
      while ((item_field= it++))
2335
3705
      {
2336
3706
        Field *field= item_field->field;
2337
 
        JoinTable *stat= field->getTable()->reginfo.join_tab;
 
3707
        JOIN_TAB *stat= field->table->reginfo.join_tab;
2338
3708
        key_map possible_keys= field->key_start;
2339
 
        possible_keys&= field->getTable()->keys_in_use_for_query;
 
3709
        possible_keys&= field->table->keys_in_use_for_query;
2340
3710
        stat[0].const_keys|= possible_keys;
2341
3711
 
2342
3712
        /*
2346
3716
        */
2347
3717
        if (possible_keys.any())
2348
3718
        {
2349
 
          Table *field_tab= field->getTable();
2350
 
          optimizer::KeyUse *use;
2351
 
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
2352
 
            if (possible_keys.test(use->getKey()) &&
2353
 
                field_tab->key_info[use->getKey()].key_part[use->getKeypart()].field ==
 
3719
          Table *field_tab= field->table;
 
3720
          KEYUSE *use;
 
3721
          for (use= stat->keyuse; use && use->table == field_tab; use++)
 
3722
            if (possible_keys.test(use->key) &&
 
3723
                field_tab->key_info[use->key].key_part[use->keypart].field ==
2354
3724
                field)
2355
 
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
3725
              field_tab->const_key_parts[use->key]|= use->keypart_map;
2356
3726
        }
2357
3727
      }
2358
3728
    }
2377
3747
    Item *item;
2378
3748
    while ((item=li++))
2379
3749
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
2380
 
 
2381
3750
    return;
2382
3751
  }
2383
3752
  if (cond->eq_cmp_result() == Item::COND_OK)
2396
3765
       left_item->collation.collation == value->collation.collation))
2397
3766
  {
2398
3767
    Item *tmp=value->clone_item();
 
3768
    tmp->collation.set(right_item->collation);
 
3769
 
2399
3770
    if (tmp)
2400
3771
    {
2401
 
      tmp->collation.set(right_item->collation);
2402
3772
      session->change_item_tree(args + 1, tmp);
2403
3773
      func->update_used_tables();
2404
3774
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2418
3788
            right_item->collation.collation == value->collation.collation))
2419
3789
  {
2420
3790
    Item *tmp= value->clone_item();
 
3791
    tmp->collation.set(left_item->collation);
 
3792
 
2421
3793
    if (tmp)
2422
3794
    {
2423
 
      tmp->collation.set(left_item->collation);
2424
3795
      session->change_item_tree(args, tmp);
2425
3796
      value= tmp;
2426
3797
      func->update_used_tables();
2490
3861
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
2491
3862
      {
2492
3863
        Item **args= iter->cmp_func->arguments();
2493
 
        if (not args[0]->const_item())
 
3864
        if (!args[0]->const_item())
2494
3865
        {
2495
 
          change_cond_ref_to_const(session, save_list, iter->and_level,
2496
 
                                   iter->and_level, args[0], args[1] );
 
3866
          change_cond_ref_to_const( session, save, iter->and_level,
 
3867
                                    iter->and_level, args[0], args[1] );
2497
3868
        }
2498
3869
      }
2499
3870
    }
2612
3983
  @endverbatim
2613
3984
 
2614
3985
  @param join       Join being processed
 
3986
  @param last_tab   Last table in current partial join order (this function is
 
3987
                    not called for empty partial join orders)
2615
3988
  @param next_tab   Table we're going to extend the current partial join with
2616
3989
 
2617
3990
  @retval
2620
3993
  @retval
2621
3994
    true   Requested join order extension not allowed.
2622
3995
*/
2623
 
bool check_interleaving_with_nj(JoinTable *next_tab)
 
3996
bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
2624
3997
{
2625
 
  TableList *next_emb= next_tab->table->pos_in_table_list->getEmbedding();
2626
 
  Join *join= next_tab->join;
 
3998
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
 
3999
  JOIN *join= last_tab->join;
2627
4000
 
2628
 
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
 
4001
  if (join->cur_embedding_map & ~next_tab->embedding_map)
2629
4002
  {
2630
4003
    /*
2631
4004
      next_tab is outside of the "pair of brackets" we're currently in.
2638
4011
    Do update counters for "pairs of brackets" that we've left (marked as
2639
4012
    X,Y,Z in the above picture)
2640
4013
  */
2641
 
  for (;next_emb; next_emb= next_emb->getEmbedding())
 
4014
  for (;next_emb; next_emb= next_emb->embedding)
2642
4015
  {
2643
 
    next_emb->getNestedJoin()->counter_++;
2644
 
    if (next_emb->getNestedJoin()->counter_ == 1)
 
4016
    next_emb->nested_join->counter_++;
 
4017
    if (next_emb->nested_join->counter_ == 1)
2645
4018
    {
2646
4019
      /*
2647
4020
        next_emb is the first table inside a nested join we've "entered". In
2648
4021
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
2649
4022
        X bracket might have Y pair bracket.
2650
4023
      */
2651
 
      join->cur_embedding_map |= next_emb->getNestedJoin()->nj_map;
 
4024
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
2652
4025
    }
2653
4026
 
2654
 
    if (next_emb->getNestedJoin()->join_list.elements !=
2655
 
        next_emb->getNestedJoin()->counter_)
 
4027
    if (next_emb->nested_join->join_list.elements !=
 
4028
        next_emb->nested_join->counter_)
2656
4029
      break;
2657
4030
 
2658
4031
    /*
2659
4032
      We're currently at Y or Z-bracket as depicted in the above picture.
2660
4033
      Mark that we've left it and continue walking up the brackets hierarchy.
2661
4034
    */
2662
 
    join->cur_embedding_map &= ~next_emb->getNestedJoin()->nj_map;
 
4035
    join->cur_embedding_map &= ~next_emb->nested_join->nj_map;
2663
4036
  }
2664
4037
  return false;
2665
4038
}
2666
4039
 
2667
 
COND *optimize_cond(Join *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
 
4040
void advance_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
 
4041
{
 
4042
  TableList *emb_sj_nest;
 
4043
  if ((emb_sj_nest= tab->emb_sj_nest))
 
4044
  {
 
4045
    tab->join->cur_emb_sj_nests |= emb_sj_nest->sj_inner_tables;
 
4046
    /* Remove the sj_nest if all of its SJ-inner tables are in cur_table_map */
 
4047
    if (!(remaining_tables & emb_sj_nest->sj_inner_tables))
 
4048
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
4049
  }
 
4050
}
 
4051
 
 
4052
/*
 
4053
  we assume remaining_tables doesnt contain @tab.
 
4054
*/
 
4055
void restore_prev_sj_state(const table_map remaining_tables, const JOIN_TAB *tab)
 
4056
{
 
4057
  TableList *emb_sj_nest;
 
4058
  if ((emb_sj_nest= tab->emb_sj_nest))
 
4059
  {
 
4060
    /* If we're removing the last SJ-inner table, remove the sj-nest */
 
4061
    if ((remaining_tables & emb_sj_nest->sj_inner_tables) ==
 
4062
        (emb_sj_nest->sj_inner_tables & ~tab->table->map))
 
4063
    {
 
4064
      tab->join->cur_emb_sj_nests &= ~emb_sj_nest->sj_inner_tables;
 
4065
    }
 
4066
  }
 
4067
}
 
4068
 
 
4069
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
2668
4070
{
2669
4071
  Session *session= join->session;
2670
4072
 
2751
4153
          }
2752
4154
          break;
2753
4155
        case Item::COND_UNDEF:                  /* Impossible */
2754
 
          break;
 
4156
          break; /* purecov: deadcode */
2755
4157
      }
2756
4158
    }
2757
4159
 
2787
4189
    {
2788
4190
      Field *field= ((Item_field*) args[0])->field;
2789
4191
      if (field->flags & AUTO_INCREMENT_FLAG 
2790
 
          && ! field->getTable()->maybe_null 
 
4192
          && ! field->table->maybe_null 
2791
4193
          && session->options & OPTION_AUTO_IS_NULL
2792
4194
          && (
2793
4195
            session->first_successful_insert_id_in_prev_stmt > 0 
2845
4247
  /*
2846
4248
    TODO:
2847
4249
    Excluding all expensive functions is too restritive we should exclude only
2848
 
    materialized IN subquery predicates because they can't yet be evaluated
2849
 
    here (they need additional initialization that is done later on).
2850
 
 
2851
 
    The proper way to exclude the subqueries would be to walk the cond tree and
2852
 
    check for materialized subqueries there.
2853
 
 
 
4250
    materialized IN because it is created later than this phase, and cannot be
 
4251
    evaluated at this point.
 
4252
    The condition should be something as (need to fix member access):
 
4253
      !(cond->type() == Item::FUNC_ITEM &&
 
4254
        ((Item_func*)cond)->func_name() == "<in_optimizer>" &&
 
4255
        ((Item_in_optimizer*)cond)->is_expensive()))
2854
4256
  */
2855
4257
  {
2856
4258
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
2973
4375
  @return
2974
4376
    end_select function to use. This function can't fail.
2975
4377
*/
2976
 
Next_select_func setup_end_select_func(Join *join)
 
4378
Next_select_func setup_end_select_func(JOIN *join)
2977
4379
{
2978
4380
  Table *table= join->tmp_table;
2979
4381
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
2985
4387
    if (table->group && tmp_tbl->sum_func_count &&
2986
4388
        !tmp_tbl->precomputed_group_by)
2987
4389
    {
2988
 
      if (table->getShare()->sizeKeys())
 
4390
      if (table->s->keys)
2989
4391
      {
2990
4392
        end_select= end_update;
2991
4393
      }
2996
4398
    }
2997
4399
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
2998
4400
    {
2999
 
      end_select= end_write_group;
 
4401
      end_select=end_write_group;
3000
4402
    }
3001
4403
    else
3002
4404
    {
3003
 
      end_select= end_write;
 
4405
      end_select=end_write;
3004
4406
      if (tmp_tbl->precomputed_group_by)
3005
4407
      {
3006
4408
        /*
3038
4440
  @retval
3039
4441
    -1  if error should be sent
3040
4442
*/
3041
 
int do_select(Join *join, List<Item> *fields, Table *table)
 
4443
int do_select(JOIN *join, List<Item> *fields, Table *table)
3042
4444
{
3043
4445
  int rc= 0;
3044
4446
  enum_nested_loop_state error= NESTED_LOOP_OK;
3045
 
  JoinTable *join_tab= NULL;
 
4447
  JOIN_TAB *join_tab= NULL;
3046
4448
 
3047
4449
  join->tmp_table= table;                       /* Save for easy recursion */
3048
4450
  join->fields= fields;
3049
4451
 
3050
4452
  if (table)
3051
4453
  {
3052
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
 
4454
    table->file->extra(HA_EXTRA_WRITE_CACHE);
3053
4455
    table->emptyRecord();
3054
4456
    if (table->group && join->tmp_table_param.sum_func_count &&
3055
 
        table->getShare()->sizeKeys() && !table->cursor->inited)
3056
 
      table->cursor->startIndexScan(0, 0);
 
4457
        table->s->keys && !table->file->inited)
 
4458
      table->file->ha_index_init(0, 0);
3057
4459
  }
3058
4460
  /* Set up select_end */
3059
4461
  Next_select_func end_select= setup_end_select_func(join);
3125
4527
  if (table)
3126
4528
  {
3127
4529
    int tmp, new_errno= 0;
3128
 
    if ((tmp=table->cursor->extra(HA_EXTRA_NO_CACHE)))
 
4530
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
3129
4531
    {
3130
4532
      new_errno= tmp;
3131
4533
    }
3132
 
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
 
4534
    if ((tmp=table->file->ha_index_or_rnd_end()))
3133
4535
    {
3134
4536
      new_errno= tmp;
3135
4537
    }
3136
4538
    if (new_errno)
3137
 
      table->print_error(new_errno,MYF(0));
 
4539
      table->file->print_error(new_errno,MYF(0));
3138
4540
  }
3139
4541
  return(join->session->is_error() ? -1 : rc);
3140
4542
}
3141
4543
 
3142
 
enum_nested_loop_state sub_select_cache(Join *join, JoinTable *join_tab, bool end_of_records)
 
4544
enum_nested_loop_state sub_select_cache(JOIN *join, JOIN_TAB *join_tab, bool end_of_records)
3143
4545
{
3144
4546
  enum_nested_loop_state rc;
3145
4547
 
3150
4552
      rc= sub_select(join,join_tab,end_of_records);
3151
4553
    return rc;
3152
4554
  }
3153
 
  if (join->session->getKilled())               // If aborted by user
 
4555
  if (join->session->killed)            // If aborted by user
3154
4556
  {
3155
4557
    join->session->send_kill_message();
3156
 
    return NESTED_LOOP_KILLED;
 
4558
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
3157
4559
  }
3158
4560
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3159
4561
  {
3160
 
    if (! join_tab->cache.store_record_in_cache())
 
4562
    if (! store_record_in_cache(&join_tab->cache))
3161
4563
      return NESTED_LOOP_OK;                     // There is more room in cache
3162
4564
    return flush_cached_records(join,join_tab,false);
3163
4565
  }
3286
4688
  @return
3287
4689
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
3288
4690
*/
3289
 
enum_nested_loop_state sub_select(Join *join, JoinTable *join_tab, bool end_of_records)
 
4691
enum_nested_loop_state sub_select(JOIN *join,JOIN_TAB *join_tab,bool end_of_records)
3290
4692
{
3291
4693
  join_tab->table->null_row=0;
3292
4694
  if (end_of_records)
3294
4696
 
3295
4697
  int error;
3296
4698
  enum_nested_loop_state rc;
3297
 
  ReadRecord *info= &join_tab->read_record;
 
4699
  READ_RECORD *info= &join_tab->read_record;
 
4700
 
 
4701
  if (join_tab->flush_weedout_table)
 
4702
  {
 
4703
    do_sj_reset(join_tab->flush_weedout_table);
 
4704
  }
3298
4705
 
3299
4706
  if (join->resume_nested_loop)
3300
4707
  {
3347
4754
  return rc;
3348
4755
}
3349
4756
 
3350
 
int safe_index_read(JoinTable *tab)
 
4757
/*
 
4758
  SemiJoinDuplicateElimination: Reset the temporary table
 
4759
*/
 
4760
int do_sj_reset(SJ_TMP_TABLE *sj_tbl)
 
4761
{
 
4762
  if (sj_tbl->tmp_table)
 
4763
    return sj_tbl->tmp_table->file->ha_delete_all_rows();
 
4764
  return 0;
 
4765
}
 
4766
 
 
4767
int safe_index_read(JOIN_TAB *tab)
3351
4768
{
3352
4769
  int error;
3353
4770
  Table *table= tab->table;
3354
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
4771
  if ((error=table->file->index_read_map(table->record[0],
3355
4772
                                         tab->ref.key_buff,
3356
4773
                                         make_prev_keypart_map(tab->ref.key_parts),
3357
4774
                                         HA_READ_KEY_EXACT)))
3359
4776
  return 0;
3360
4777
}
3361
4778
 
3362
 
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
 
4779
int join_read_const_table(JOIN_TAB *tab, POSITION *pos)
3363
4780
{
3364
4781
  int error;
3365
4782
  Table *table=tab->table;
3367
4784
  table->null_row=0;
3368
4785
  table->status=STATUS_NO_RECORD;
3369
4786
 
3370
 
  if (tab->type == AM_SYSTEM)
 
4787
  if (tab->type == JT_SYSTEM)
3371
4788
  {
3372
4789
    if ((error=join_read_system(tab)))
3373
4790
    {                                           // Info for DESCRIBE
3374
4791
      tab->info="const row not found";
3375
4792
      /* Mark for EXPLAIN that the row was not found */
3376
 
      pos->setFanout(0.0);
3377
 
      pos->clearRefDependMap();
3378
 
      if (! table->maybe_null || error > 0)
 
4793
      pos->records_read=0.0;
 
4794
      pos->ref_depend_map= 0;
 
4795
      if (!table->maybe_null || error > 0)
3379
4796
        return(error);
3380
4797
    }
3381
4798
  }
3382
4799
  else
3383
4800
  {
3384
 
    if (! table->key_read && 
 
4801
    if (!table->key_read && 
3385
4802
        table->covering_keys.test(tab->ref.key) && 
3386
 
        ! table->no_keyread &&
 
4803
        !table->no_keyread &&
3387
4804
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
3388
4805
    {
3389
4806
      table->key_read=1;
3390
 
      table->cursor->extra(HA_EXTRA_KEYREAD);
 
4807
      table->file->extra(HA_EXTRA_KEYREAD);
3391
4808
      tab->index= tab->ref.key;
3392
4809
    }
3393
4810
    error=join_read_const(tab);
3394
4811
    if (table->key_read)
3395
4812
    {
3396
4813
      table->key_read=0;
3397
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
4814
      table->file->extra(HA_EXTRA_NO_KEYREAD);
3398
4815
    }
3399
4816
    if (error)
3400
4817
    {
3401
4818
      tab->info="unique row not found";
3402
4819
      /* Mark for EXPLAIN that the row was not found */
3403
 
      pos->setFanout(0.0);
3404
 
      pos->clearRefDependMap();
 
4820
      pos->records_read=0.0;
 
4821
      pos->ref_depend_map= 0;
3405
4822
      if (!table->maybe_null || error > 0)
3406
4823
        return(error);
3407
4824
    }
3415
4832
    table->maybe_null=0;
3416
4833
 
3417
4834
  /* Check appearance of new constant items in Item_equal objects */
3418
 
  Join *join= tab->join;
 
4835
  JOIN *join= tab->join;
3419
4836
  if (join->conds)
3420
4837
    update_const_equal_items(join->conds, tab);
3421
4838
  TableList *tbl;
3428
4845
      embedded= embedding;
3429
4846
      if (embedded->on_expr)
3430
4847
         update_const_equal_items(embedded->on_expr, tab);
3431
 
      embedding= embedded->getEmbedding();
 
4848
      embedding= embedded->embedding;
3432
4849
    }
3433
4850
    while (embedding &&
3434
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
4851
           embedding->nested_join->join_list.head() == embedded);
3435
4852
  }
3436
4853
 
3437
4854
  return(0);
3438
4855
}
3439
4856
 
3440
 
int join_read_system(JoinTable *tab)
 
4857
int join_read_system(JOIN_TAB *tab)
3441
4858
{
3442
4859
  Table *table= tab->table;
3443
4860
  int error;
3444
4861
  if (table->status & STATUS_GARBAGE)           // If first read
3445
4862
  {
3446
 
    if ((error=table->cursor->read_first_row(table->getInsertRecord(),
3447
 
                                           table->getShare()->getPrimaryKey())))
 
4863
    if ((error=table->file->read_first_row(table->record[0],
 
4864
                                           table->s->primary_key)))
3448
4865
    {
3449
4866
      if (error != HA_ERR_END_OF_FILE)
3450
4867
        return table->report_error(error);
3472
4889
  @retval
3473
4890
    1   Got an error (other than row not found) during read
3474
4891
*/
3475
 
int join_read_const(JoinTable *tab)
 
4892
int join_read_const(JOIN_TAB *tab)
3476
4893
{
3477
4894
  int error;
3478
4895
  Table *table= tab->table;
3483
4900
      error= HA_ERR_KEY_NOT_FOUND;
3484
4901
    else
3485
4902
    {
3486
 
      error=table->cursor->index_read_idx_map(table->getInsertRecord(),tab->ref.key,
 
4903
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
3487
4904
                                            (unsigned char*) tab->ref.key_buff,
3488
4905
                                            make_prev_keypart_map(tab->ref.key_parts),
3489
4906
                                            HA_READ_KEY_EXACT);
3513
4930
 
3514
4931
  SYNOPSIS
3515
4932
    join_read_key()
3516
 
      tab  JoinTable of the accessed table
 
4933
      tab  JOIN_TAB of the accessed table
3517
4934
 
3518
4935
  DESCRIPTION
3519
4936
    This is "read_fist" function for the "ref" access method. The difference
3524
4941
   -1  - Row not found
3525
4942
    1  - Error
3526
4943
*/
3527
 
int join_read_key(JoinTable *tab)
 
4944
int join_read_key(JOIN_TAB *tab)
3528
4945
{
3529
4946
  int error;
3530
4947
  Table *table= tab->table;
3531
4948
 
3532
 
  if (!table->cursor->inited)
 
4949
  if (!table->file->inited)
3533
4950
  {
3534
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
4951
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3535
4952
  }
3536
4953
 
3537
4954
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3543
4960
      table->status=STATUS_NOT_FOUND;
3544
4961
      return -1;
3545
4962
    }
3546
 
    error=table->cursor->index_read_map(table->getInsertRecord(),
 
4963
    error=table->file->index_read_map(table->record[0],
3547
4964
                                      tab->ref.key_buff,
3548
4965
                                      make_prev_keypart_map(tab->ref.key_parts),
3549
4966
                                      HA_READ_KEY_EXACT);
3559
4976
 
3560
4977
  SYNOPSIS
3561
4978
    join_read_always_key()
3562
 
      tab  JoinTable of the accessed table
 
4979
      tab  JOIN_TAB of the accessed table
3563
4980
 
3564
4981
  DESCRIPTION
3565
4982
    This is "read_first" function for the "ref" access method.
3572
4989
   -1  - Row not found
3573
4990
    1  - Error
3574
4991
*/
3575
 
int join_read_always_key(JoinTable *tab)
 
4992
int join_read_always_key(JOIN_TAB *tab)
3576
4993
{
3577
4994
  int error;
3578
4995
  Table *table= tab->table;
3579
4996
 
3580
4997
  /* Initialize the index first */
3581
 
  if (!table->cursor->inited)
3582
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
4998
  if (!table->file->inited)
 
4999
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3583
5000
 
3584
5001
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3585
5002
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3590
5007
 
3591
5008
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3592
5009
    return -1;
3593
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
5010
  if ((error=table->file->index_read_map(table->record[0],
3594
5011
                                         tab->ref.key_buff,
3595
5012
                                         make_prev_keypart_map(tab->ref.key_parts),
3596
5013
                                         HA_READ_KEY_EXACT)))
3597
5014
  {
3598
5015
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3599
5016
      return table->report_error(error);
3600
 
    return -1;
 
5017
    return -1; /* purecov: inspected */
3601
5018
  }
3602
5019
 
3603
5020
  return 0;
3604
5021
}
3605
5022
 
3606
5023
/**
3607
 
  This function is used when optimizing away ORDER BY in
3608
 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
 
5024
  This function is used when optimizing away order_st BY in
 
5025
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
3609
5026
*/
3610
 
int join_read_last_key(JoinTable *tab)
 
5027
int join_read_last_key(JOIN_TAB *tab)
3611
5028
{
3612
5029
  int error;
3613
5030
  Table *table= tab->table;
3614
5031
 
3615
 
  if (!table->cursor->inited)
3616
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
5032
  if (!table->file->inited)
 
5033
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3617
5034
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3618
5035
    return -1;
3619
 
  if ((error=table->cursor->index_read_last_map(table->getInsertRecord(),
 
5036
  if ((error=table->file->index_read_last_map(table->record[0],
3620
5037
                                              tab->ref.key_buff,
3621
5038
                                              make_prev_keypart_map(tab->ref.key_parts))))
3622
5039
  {
3623
5040
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3624
5041
      return table->report_error(error);
3625
 
    return -1;
 
5042
    return -1; /* purecov: inspected */
3626
5043
  }
3627
5044
  return 0;
3628
5045
}
3629
5046
 
3630
 
int join_no_more_records(ReadRecord *)
 
5047
int join_no_more_records(READ_RECORD *)
3631
5048
{
3632
5049
  return -1;
3633
5050
}
3634
5051
 
3635
 
int join_read_next_same_diff(ReadRecord *info)
 
5052
int join_read_next_same_diff(READ_RECORD *info)
3636
5053
{
3637
5054
  Table *table= info->table;
3638
 
  JoinTable *tab=table->reginfo.join_tab;
 
5055
  JOIN_TAB *tab=table->reginfo.join_tab;
3639
5056
  if (tab->insideout_match_tab->found_match)
3640
5057
  {
3641
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
5058
    KEY *key= tab->table->key_info + tab->index;
3642
5059
    do
3643
5060
    {
3644
5061
      int error;
3645
5062
      /* Save index tuple from record to the buffer */
3646
5063
      key_copy(tab->insideout_buf, info->record, key, 0);
3647
5064
 
3648
 
      if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
5065
      if ((error=table->file->index_next_same(table->record[0],
3649
5066
                                              tab->ref.key_buff,
3650
5067
                                              tab->ref.key_length)))
3651
5068
      {
3663
5080
    return join_read_next_same(info);
3664
5081
}
3665
5082
 
3666
 
int join_read_next_same(ReadRecord *info)
 
5083
int join_read_next_same(READ_RECORD *info)
3667
5084
{
3668
5085
  int error;
3669
5086
  Table *table= info->table;
3670
 
  JoinTable *tab=table->reginfo.join_tab;
 
5087
  JOIN_TAB *tab=table->reginfo.join_tab;
3671
5088
 
3672
 
  if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
5089
  if ((error=table->file->index_next_same(table->record[0],
3673
5090
                                          tab->ref.key_buff,
3674
5091
                                          tab->ref.key_length)))
3675
5092
  {
3682
5099
  return 0;
3683
5100
}
3684
5101
 
3685
 
int join_read_prev_same(ReadRecord *info)
 
5102
int join_read_prev_same(READ_RECORD *info)
3686
5103
{
3687
5104
  int error;
3688
5105
  Table *table= info->table;
3689
 
  JoinTable *tab=table->reginfo.join_tab;
 
5106
  JOIN_TAB *tab=table->reginfo.join_tab;
3690
5107
 
3691
 
  if ((error=table->cursor->index_prev(table->getInsertRecord())))
 
5108
  if ((error=table->file->index_prev(table->record[0])))
3692
5109
    return table->report_error(error);
3693
5110
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3694
5111
                      tab->ref.key_length))
3699
5116
  return error;
3700
5117
}
3701
5118
 
3702
 
int join_init_quick_read_record(JoinTable *tab)
 
5119
int join_init_quick_read_record(JOIN_TAB *tab)
3703
5120
{
3704
5121
  if (test_if_quick_select(tab) == -1)
3705
5122
    return -1;                                  /* No possible records */
3706
5123
  return join_init_read_record(tab);
3707
5124
}
3708
5125
 
3709
 
int init_read_record_seq(JoinTable *tab)
 
5126
int rr_sequential(READ_RECORD *info);
 
5127
int init_read_record_seq(JOIN_TAB *tab)
3710
5128
{
3711
 
  tab->read_record.init_reard_record_sequential();
3712
 
 
3713
 
  if (tab->read_record.cursor->startTableScan(1))
 
5129
  tab->read_record.read_record= rr_sequential;
 
5130
  if (tab->read_record.file->ha_rnd_init(1))
3714
5131
    return 1;
3715
5132
  return (*tab->read_record.read_record)(&tab->read_record);
3716
5133
}
3717
5134
 
3718
 
int test_if_quick_select(JoinTable *tab)
 
5135
int test_if_quick_select(JOIN_TAB *tab)
3719
5136
{
3720
5137
  delete tab->select->quick;
3721
5138
  tab->select->quick= 0;
3723
5140
                                        (table_map) 0, HA_POS_ERROR, 0, false);
3724
5141
}
3725
5142
 
3726
 
int join_init_read_record(JoinTable *tab)
 
5143
int join_init_read_record(JOIN_TAB *tab)
3727
5144
{
3728
5145
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3729
5146
    return 1;
3730
 
 
3731
 
  tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true);
3732
 
 
 
5147
  init_read_record(&tab->read_record, tab->join->session, tab->table,
 
5148
                   tab->select,1,1);
3733
5149
  return (*tab->read_record.read_record)(&tab->read_record);
3734
5150
}
3735
5151
 
3736
 
int join_read_first(JoinTable *tab)
 
5152
int join_read_first(JOIN_TAB *tab)
3737
5153
{
3738
5154
  int error;
3739
5155
  Table *table=tab->table;
3740
5156
  if (!table->key_read && table->covering_keys.test(tab->index) &&
3741
5157
      !table->no_keyread)
3742
5158
  {
3743
 
    table->key_read= 1;
3744
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
5159
    table->key_read=1;
 
5160
    table->file->extra(HA_EXTRA_KEYREAD);
3745
5161
  }
3746
 
  tab->table->status= 0;
 
5162
  tab->table->status=0;
3747
5163
  tab->read_record.table=table;
3748
 
  tab->read_record.cursor=table->cursor;
 
5164
  tab->read_record.file=table->file;
3749
5165
  tab->read_record.index=tab->index;
3750
 
  tab->read_record.record=table->getInsertRecord();
 
5166
  tab->read_record.record=table->record[0];
3751
5167
  if (tab->insideout_match_tab)
3752
5168
  {
3753
5169
    tab->read_record.do_insideout_scan= tab;
3760
5176
    tab->read_record.do_insideout_scan= 0;
3761
5177
  }
3762
5178
 
3763
 
  if (!table->cursor->inited)
3764
 
    table->cursor->startIndexScan(tab->index, tab->sorted);
3765
 
  if ((error=tab->table->cursor->index_first(tab->table->getInsertRecord())))
 
5179
  if (!table->file->inited)
 
5180
    table->file->ha_index_init(tab->index, tab->sorted);
 
5181
  if ((error=tab->table->file->index_first(tab->table->record[0])))
3766
5182
  {
3767
5183
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3768
5184
      table->report_error(error);
3772
5188
  return 0;
3773
5189
}
3774
5190
 
3775
 
int join_read_next_different(ReadRecord *info)
 
5191
int join_read_next_different(READ_RECORD *info)
3776
5192
{
3777
 
  JoinTable *tab= info->do_insideout_scan;
 
5193
  JOIN_TAB *tab= info->do_insideout_scan;
3778
5194
  if (tab->insideout_match_tab->found_match)
3779
5195
  {
3780
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
5196
    KEY *key= tab->table->key_info + tab->index;
3781
5197
    do
3782
5198
    {
3783
5199
      int error;
3784
5200
      /* Save index tuple from record to the buffer */
3785
5201
      key_copy(tab->insideout_buf, info->record, key, 0);
3786
5202
 
3787
 
      if ((error=info->cursor->index_next(info->record)))
 
5203
      if ((error=info->file->index_next(info->record)))
3788
5204
        return info->table->report_error(error);
3789
5205
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
3790
5206
                      tab->insideout_buf, key->key_length));
3795
5211
    return join_read_next(info);
3796
5212
}
3797
5213
 
3798
 
int join_read_next(ReadRecord *info)
 
5214
int join_read_next(READ_RECORD *info)
3799
5215
{
3800
5216
  int error;
3801
 
  if ((error=info->cursor->index_next(info->record)))
 
5217
  if ((error=info->file->index_next(info->record)))
3802
5218
    return info->table->report_error(error);
3803
5219
  return 0;
3804
5220
}
3805
5221
 
3806
 
int join_read_last(JoinTable *tab)
 
5222
int join_read_last(JOIN_TAB *tab)
3807
5223
{
3808
5224
  Table *table=tab->table;
3809
5225
  int error;
3811
5227
      !table->no_keyread)
3812
5228
  {
3813
5229
    table->key_read=1;
3814
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
5230
    table->file->extra(HA_EXTRA_KEYREAD);
3815
5231
  }
3816
5232
  tab->table->status=0;
3817
5233
  tab->read_record.read_record=join_read_prev;
3818
5234
  tab->read_record.table=table;
3819
 
  tab->read_record.cursor=table->cursor;
 
5235
  tab->read_record.file=table->file;
3820
5236
  tab->read_record.index=tab->index;
3821
 
  tab->read_record.record=table->getInsertRecord();
3822
 
  if (!table->cursor->inited)
3823
 
    table->cursor->startIndexScan(tab->index, 1);
3824
 
  if ((error= tab->table->cursor->index_last(tab->table->getInsertRecord())))
 
5237
  tab->read_record.record=table->record[0];
 
5238
  if (!table->file->inited)
 
5239
    table->file->ha_index_init(tab->index, 1);
 
5240
  if ((error= tab->table->file->index_last(tab->table->record[0])))
3825
5241
    return table->report_error(error);
3826
5242
 
3827
5243
  return 0;
3828
5244
}
3829
5245
 
3830
 
int join_read_prev(ReadRecord *info)
 
5246
int join_read_prev(READ_RECORD *info)
3831
5247
{
3832
5248
  int error;
3833
 
  if ((error= info->cursor->index_prev(info->record)))
 
5249
  if ((error= info->file->index_prev(info->record)))
3834
5250
    return info->table->report_error(error);
3835
5251
 
3836
5252
  return 0;
3839
5255
/**
3840
5256
  Reading of key with key reference and one part that may be NULL.
3841
5257
*/
3842
 
int join_read_always_key_or_null(JoinTable *tab)
 
5258
int join_read_always_key_or_null(JOIN_TAB *tab)
3843
5259
{
3844
5260
  int res;
3845
5261
 
3853
5269
  return safe_index_read(tab);
3854
5270
}
3855
5271
 
3856
 
int join_read_next_same_or_null(ReadRecord *info)
 
5272
int join_read_next_same_or_null(READ_RECORD *info)
3857
5273
{
3858
5274
  int error;
3859
5275
  if ((error= join_read_next_same(info)) >= 0)
3860
5276
    return error;
3861
 
  JoinTable *tab= info->table->reginfo.join_tab;
 
5277
  JOIN_TAB *tab= info->table->reginfo.join_tab;
3862
5278
 
3863
5279
  /* Test if we have already done a read after null key */
3864
5280
  if (*tab->ref.null_ref_key)
3867
5283
  return safe_index_read(tab);                  // then read null keys
3868
5284
}
3869
5285
 
3870
 
enum_nested_loop_state end_send_group(Join *join, JoinTable *, bool end_of_records)
 
5286
enum_nested_loop_state end_send_group(JOIN *join, JOIN_TAB *, bool end_of_records)
3871
5287
{
3872
5288
  int idx= -1;
3873
5289
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
3907
5323
          }
3908
5324
        }
3909
5325
        if (error > 0)
3910
 
          return(NESTED_LOOP_ERROR);
 
5326
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
3911
5327
        if (end_of_records)
3912
5328
          return(NESTED_LOOP_OK);
3913
5329
        if (join->send_records >= join->unit->select_limit_cnt &&
3956
5372
  return(NESTED_LOOP_OK);
3957
5373
}
3958
5374
 
3959
 
enum_nested_loop_state end_write_group(Join *join, JoinTable *, bool end_of_records)
 
5375
enum_nested_loop_state end_write_group(JOIN *join, JOIN_TAB *, bool end_of_records)
3960
5376
{
3961
5377
  Table *table=join->tmp_table;
3962
5378
  int     idx= -1;
3963
5379
 
3964
 
  if (join->session->getKilled())
 
5380
  if (join->session->killed)
3965
5381
  {                                             // Aborted by user
3966
5382
    join->session->send_kill_message();
3967
 
    return NESTED_LOOP_KILLED;
 
5383
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
3968
5384
  }
3969
5385
  if (!join->first_record || end_of_records ||
3970
5386
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
3982
5398
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
3983
5399
        if (!join->having || join->having->val_int())
3984
5400
        {
3985
 
          int error= table->cursor->insertRecord(table->getInsertRecord());
3986
 
 
3987
 
          if (error)
3988
 
          {
3989
 
            my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
3990
 
            return NESTED_LOOP_ERROR;
3991
 
          }
 
5401
          int error= table->file->ha_write_row(table->record[0]);
 
5402
          if (error && create_myisam_from_heap(join->session, table,
 
5403
                                              join->tmp_table_param.start_recinfo,
 
5404
                                                &join->tmp_table_param.recinfo,
 
5405
                                              error, 0))
 
5406
          return NESTED_LOOP_ERROR;
3992
5407
        }
3993
5408
        if (join->rollup.state != ROLLUP::STATE_NONE)
3994
5409
        {
4009
5424
    if (idx < (int) join->send_group_parts)
4010
5425
    {
4011
5426
      copy_fields(&join->tmp_table_param);
4012
 
      if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
4013
 
        return NESTED_LOOP_ERROR;
 
5427
      copy_funcs(join->tmp_table_param.items_to_copy);
4014
5428
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
4015
5429
        return NESTED_LOOP_ERROR;
4016
5430
      return NESTED_LOOP_OK;
4027
5441
  outer join table.
4028
5442
  We can't remove tests that are made against columns which are stored
4029
5443
  in sorted order.
 
5444
*****************************************************************************/
 
5445
 
 
5446
/**
4030
5447
  @return
4031
 
    1 if right_item used is a removable reference key on left_item
4032
 
    0 otherwise.
4033
 
****************************************************************************/
 
5448
    1 if right_item is used removable reference key on left_item
 
5449
*/
4034
5450
bool test_if_ref(Item_field *left_item,Item *right_item)
4035
5451
{
4036
5452
  Field *field=left_item->field;
4037
5453
  // No need to change const test. We also have to keep tests on LEFT JOIN
4038
 
  if (not field->getTable()->const_table && !field->getTable()->maybe_null)
 
5454
  if (!field->table->const_table && !field->table->maybe_null)
4039
5455
  {
4040
 
    Item *ref_item=part_of_refkey(field->getTable(),field);
 
5456
    Item *ref_item=part_of_refkey(field->table,field);
4041
5457
    if (ref_item && ref_item->eq(right_item,1))
4042
5458
    {
4043
5459
      right_item= right_item->real_item();
4122
5538
      /* Create new top level AND item */
4123
5539
      Item_cond_and *new_cond=new Item_cond_and;
4124
5540
      if (!new_cond)
4125
 
        return (COND*) 0;
 
5541
        return (COND*) 0;                       // OOM /* purecov: inspected */
4126
5542
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4127
5543
      Item *item;
4128
5544
      while ((item=li++))
4152
5568
    {                                           // Or list
4153
5569
      Item_cond_or *new_cond=new Item_cond_or;
4154
5570
      if (!new_cond)
4155
 
        return (COND*) 0;
 
5571
        return (COND*) 0;                       // OOM /* purecov: inspected */
4156
5572
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4157
5573
      Item *item;
4158
5574
      while ((item=li++))
4220
5636
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
4221
5637
  if (ref_parts)
4222
5638
  {
4223
 
    KeyPartInfo *key_part=
 
5639
    KEY_PART_INFO *key_part=
4224
5640
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
4225
5641
    uint32_t part;
4226
5642
 
4231
5647
    }
4232
5648
 
4233
5649
    for (part=0 ; part < ref_parts ; part++,key_part++)
4234
 
    {
4235
5650
      if (field->eq(key_part->field) &&
4236
 
          !(key_part->key_part_flag & HA_PART_KEY_SEG) &&
4237
 
          //If field can be NULL, we should not remove this predicate, as
4238
 
          //it may lead to non-rejection of NULL values. 
4239
 
          !(field->real_maybe_null()))
4240
 
      {
 
5651
          !(key_part->key_part_flag & HA_PART_KEY_SEG))
4241
5652
        return table->reginfo.join_tab->ref.items[part];
4242
 
      }
4243
 
    }
4244
5653
  }
4245
5654
  return (Item*) 0;
4246
5655
}
4265
5674
  @retval
4266
5675
    -1   Reverse key can be used
4267
5676
*/
4268
 
static int test_if_order_by_key(Order *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
 
5677
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
4269
5678
{
4270
 
  KeyPartInfo *key_part= NULL;
4271
 
  KeyPartInfo *key_part_end= NULL;
4272
 
  key_part= table->key_info[idx].key_part;
4273
 
  key_part_end= key_part + table->key_info[idx].key_parts;
 
5679
  KEY_PART_INFO *key_part,*key_part_end;
 
5680
  key_part=table->key_info[idx].key_part;
 
5681
  key_part_end=key_part+table->key_info[idx].key_parts;
4274
5682
  key_part_map const_key_parts=table->const_key_parts[idx];
4275
 
  int reverse= 0;
 
5683
  int reverse=0;
4276
5684
  bool on_primary_key= false;
4277
5685
 
4278
5686
  for (; order ; order=order->next, const_key_parts>>=1)
4282
5690
 
4283
5691
    /*
4284
5692
      Skip key parts that are constants in the WHERE clause.
4285
 
      These are already skipped in the ORDER BY by const_expression_in_where()
 
5693
      These are already skipped in the order_st BY by const_expression_in_where()
4286
5694
    */
4287
5695
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4288
5696
      key_part++;
4295
5703
        the primary key as a suffix.
4296
5704
      */
4297
5705
      if (!on_primary_key &&
4298
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
4299
 
          table->getShare()->hasPrimaryKey())
 
5706
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
5707
          table->s->primary_key != MAX_KEY)
4300
5708
      {
4301
5709
        on_primary_key= true;
4302
 
        key_part= table->key_info[table->getShare()->getPrimaryKey()].key_part;
4303
 
        key_part_end=key_part+table->key_info[table->getShare()->getPrimaryKey()].key_parts;
4304
 
        const_key_parts=table->const_key_parts[table->getShare()->getPrimaryKey()];
 
5710
        key_part= table->key_info[table->s->primary_key].key_part;
 
5711
        key_part_end=key_part+table->key_info[table->s->primary_key].key_parts;
 
5712
        const_key_parts=table->const_key_parts[table->s->primary_key];
4305
5713
 
4306
5714
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
4307
5715
          key_part++;
4329
5737
  }
4330
5738
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4331
5739
    (uint32_t) (key_part - table->key_info[idx].key_part);
4332
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
5740
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
4333
5741
                         HA_READ_PREV))
4334
5742
    reverse= 0;                                 // Index can't be used
4335
5743
  return(reverse);
4350
5758
  @retval
4351
5759
    0   no sub key
4352
5760
*/
4353
 
inline bool is_subkey(KeyPartInfo *key_part,
4354
 
                      KeyPartInfo *ref_key_part,
4355
 
                      KeyPartInfo *ref_key_part_end)
 
5761
inline bool is_subkey(KEY_PART_INFO *key_part,
 
5762
                      KEY_PART_INFO *ref_key_part,
 
5763
                            KEY_PART_INFO *ref_key_part_end)
4356
5764
{
4357
5765
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4358
 
    if (! key_part->field->eq(ref_key_part->field))
 
5766
    if (!key_part->field->eq(ref_key_part->field))
4359
5767
      return 0;
4360
5768
  return 1;
4361
5769
}
4371
5779
    - MAX_KEY                   If we can't use other key
4372
5780
    - the number of found key   Otherwise
4373
5781
*/
4374
 
static uint32_t test_if_subkey(Order *order,
 
5782
static uint32_t test_if_subkey(order_st *order,
4375
5783
                               Table *table,
4376
5784
                               uint32_t ref,
4377
5785
                               uint32_t ref_key_parts,
4378
 
                               const key_map *usable_keys)
 
5786
                                     const key_map *usable_keys)
4379
5787
{
4380
5788
  uint32_t nr;
4381
5789
  uint32_t min_length= UINT32_MAX;
4382
5790
  uint32_t best= MAX_KEY;
4383
5791
  uint32_t not_used;
4384
 
  KeyPartInfo *ref_key_part= table->key_info[ref].key_part;
4385
 
  KeyPartInfo *ref_key_part_end= ref_key_part + ref_key_parts;
 
5792
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
 
5793
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
4386
5794
 
4387
 
  for (nr= 0 ; nr < table->getShare()->sizeKeys() ; nr++)
 
5795
  for (nr= 0 ; nr < table->s->keys ; nr++)
4388
5796
  {
4389
5797
    if (usable_keys->test(nr) &&
4390
5798
        table->key_info[nr].key_length < min_length &&
4433
5841
*/
4434
5842
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
4435
5843
{
4436
 
  for (uint32_t keynr= 0; keynr < table->getShare()->sizeKeys(); keynr++)
 
5844
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
4437
5845
  {
4438
 
    if (keynr == table->getShare()->getPrimaryKey() ||
 
5846
    if (keynr == table->s->primary_key ||
4439
5847
         (table->key_info[keynr].flags & HA_NOSAME))
4440
5848
    {
4441
 
      KeyInfo *keyinfo= table->key_info + keynr;
4442
 
      KeyPartInfo *key_part= NULL;
4443
 
      KeyPartInfo *key_part_end= NULL;
 
5849
      KEY *keyinfo= table->key_info + keynr;
 
5850
      KEY_PART_INFO *key_part, *key_part_end;
4444
5851
 
4445
5852
      for (key_part=keyinfo->key_part,
4446
5853
           key_part_end=key_part+ keyinfo->key_parts;
4448
5855
           key_part++)
4449
5856
      {
4450
5857
        if (key_part->field->maybe_null() ||
4451
 
            ! find_func(key_part->field, data))
 
5858
            !find_func(key_part->field, data))
4452
5859
          break;
4453
5860
      }
4454
5861
      if (key_part == key_part_end)
4473
5880
*/
4474
5881
bool find_field_in_order_list (Field *field, void *data)
4475
5882
{
4476
 
  Order *group= (Order *) data;
 
5883
  order_st *group= (order_st *) data;
4477
5884
  bool part_found= 0;
4478
 
  for (Order *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
5885
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
4479
5886
  {
4480
5887
    Item *item= (*tmp_group->item)->real_item();
4481
5888
    if (item->type() == Item::FIELD_ITEM &&
4521
5928
}
4522
5929
 
4523
5930
/**
4524
 
  Test if we can skip the ORDER BY by using an index.
 
5931
  Test if we can skip the order_st BY by using an index.
4525
5932
 
4526
5933
  SYNOPSIS
4527
5934
    test_if_skip_sort_order()
4531
5938
      no_changes
4532
5939
      map
4533
5940
 
4534
 
  If we can use an index, the JoinTable / tab->select struct
 
5941
  If we can use an index, the JOIN_TAB / tab->select struct
4535
5942
  is changed to use the index.
4536
5943
 
4537
5944
  The index must cover all fields in <order>, or it will not be considered.
4545
5952
  @retval
4546
5953
    1    We can use an index.
4547
5954
*/
4548
 
bool test_if_skip_sort_order(JoinTable *tab, Order *order, ha_rows select_limit, bool no_changes, const key_map *map)
 
5955
bool test_if_skip_sort_order(JOIN_TAB *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
4549
5956
{
4550
5957
  int32_t ref_key;
4551
5958
  uint32_t ref_key_parts;
4552
5959
  int order_direction;
4553
5960
  uint32_t used_key_parts;
4554
5961
  Table *table=tab->table;
4555
 
  optimizer::SqlSelect *select= tab->select;
 
5962
  SQL_SELECT *select=tab->select;
4556
5963
  key_map usable_keys;
4557
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
5964
  QUICK_SELECT_I *save_quick= 0;
4558
5965
 
4559
5966
  /*
4560
5967
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4562
5969
  */
4563
5970
  usable_keys= *map;
4564
5971
 
4565
 
  for (Order *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
5972
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
4566
5973
  {
4567
5974
    Item *item= (*tmp_order->item)->real_item();
4568
5975
    if (item->type() != Item::FIELD_ITEM)
4581
5988
  {
4582
5989
    ref_key=       tab->ref.key;
4583
5990
    ref_key_parts= tab->ref.key_parts;
4584
 
    if (tab->type == AM_REF_OR_NULL)
 
5991
    if (tab->type == JT_REF_OR_NULL)
4585
5992
      return(0);
4586
5993
  }
4587
 
  else if (select && select->quick)             // Range found by optimizer/range
 
5994
  else if (select && select->quick)             // Range found by opt_range
4588
5995
  {
4589
5996
    int quick_type= select->quick->get_type();
4590
5997
    save_quick= select->quick;
4594
6001
      by clustered PK values.
4595
6002
    */
4596
6003
 
4597
 
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4598
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4599
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT)
 
6004
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
6005
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
6006
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
4600
6007
      return(0);
4601
6008
    ref_key=       select->quick->index;
4602
6009
    ref_key_parts= select->quick->used_key_parts;
4635
6042
            "part1 = const1 AND part2=const2".
4636
6043
            So we build tab->ref from scratch here.
4637
6044
          */
4638
 
          optimizer::KeyUse *keyuse= tab->keyuse;
4639
 
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
 
6045
          KEYUSE *keyuse= tab->keyuse;
 
6046
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
4640
6047
            keyuse++;
4641
6048
 
4642
6049
          if (create_ref_for_key(tab->join, tab, keyuse,
4646
6053
        else
4647
6054
        {
4648
6055
          /*
4649
 
            The range optimizer constructed QuickRange for ref_key, and
 
6056
            The range optimizer constructed QUICK_RANGE for ref_key, and
4650
6057
            we want to use instead new_ref_key as the index. We can't
4651
6058
            just change the index of the quick select, because this may
4652
6059
            result in an incosistent QUICK_SELECT object. Below we
4691
6098
    int best_key= -1;
4692
6099
    bool is_best_covering= false;
4693
6100
    double fanout= 1;
4694
 
    Join *join= tab->join;
 
6101
    JOIN *join= tab->join;
4695
6102
    uint32_t tablenr= tab - join->join_tab;
4696
 
    ha_rows table_records= table->cursor->stats.records;
 
6103
    ha_rows table_records= table->file->stats.records;
4697
6104
    bool group= join->group && order == join->group_list;
4698
 
    optimizer::Position cur_pos;
4699
6105
 
4700
6106
    /*
4701
6107
      If not used with LIMIT, only use keys if the whole query can be
4708
6114
        filesort() and join cache are usually faster than reading in
4709
6115
        index order and not using join cache
4710
6116
        */
4711
 
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
 
6117
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
4712
6118
        return(0);
4713
 
      keys= *table->cursor->keys_to_use_for_scanning();
 
6119
      keys= *table->file->keys_to_use_for_scanning();
4714
6120
      keys|= table->covering_keys;
4715
6121
 
4716
6122
      /*
4726
6132
    else
4727
6133
      keys= usable_keys;
4728
6134
 
4729
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4730
 
    read_time= cur_pos.getCost();
 
6135
    read_time= join->best_positions[tablenr].read_time;
4731
6136
    for (uint32_t i= tablenr+1; i < join->tables; i++)
4732
 
    {
4733
 
      cur_pos= join->getPosFromOptimalPlan(i);
4734
 
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
4735
 
    }
 
6137
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
4736
6138
 
4737
 
    for (nr=0; nr < table->getShare()->sizeKeys() ; nr++)
 
6139
    for (nr=0; nr < table->s->keys ; nr++)
4738
6140
    {
4739
6141
      int direction;
4740
6142
      if (keys.test(nr) &&
4741
6143
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4742
6144
      {
4743
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->getShare()->getPrimaryKey() && table->cursor->primary_key_is_clustered());
 
6145
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
4744
6146
 
4745
6147
        /*
4746
 
          Don't use an index scan with ORDER BY without limit.
 
6148
          Don't use an index scan with order_st BY without limit.
4747
6149
          For GROUP BY without limit always use index scan
4748
6150
          if there is a suitable index.
4749
6151
          Why we hold to this asymmetry hardly can be explained
4757
6159
        {
4758
6160
          double rec_per_key;
4759
6161
          double index_scan_time;
4760
 
          KeyInfo *keyinfo= tab->table->key_info+nr;
 
6162
          KEY *keyinfo= tab->table->key_info+nr;
4761
6163
          if (select_limit == HA_POS_ERROR)
4762
6164
            select_limit= table_records;
4763
6165
          if (group)
4810
6212
            Rows in such a sequence are supposed to be ordered
4811
6213
            by rowid/primary key. When reading the data
4812
6214
            in a sequence we'll touch not more pages than the
4813
 
            table cursor contains.
 
6215
            table file contains.
4814
6216
            TODO. Use the formula for a disk sweep sequential access
4815
6217
            to calculate the cost of accessing data rows for one
4816
6218
            index entry.
4817
6219
          */
4818
6220
          index_scan_time= select_limit/rec_per_key *
4819
 
                           min(rec_per_key, table->cursor->scan_time());
 
6221
                           cmin(rec_per_key, table->file->scan_time());
4820
6222
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
4821
6223
              index_scan_time < read_time)
4822
6224
          {
4826
6228
            if (table->quick_keys.test(nr))
4827
6229
              quick_records= table->quick_rows[nr];
4828
6230
            if (best_key < 0 ||
4829
 
                (select_limit <= min(quick_records,best_records) ?
 
6231
                (select_limit <= cmin(quick_records,best_records) ?
4830
6232
                 keyinfo->key_parts < best_key_parts :
4831
6233
                 quick_records < best_records))
4832
6234
            {
4862
6264
          tab->index= best_key;
4863
6265
          tab->read_first_record= best_key_direction > 0 ?
4864
6266
                                  join_read_first:join_read_last;
4865
 
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
 
6267
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
4866
6268
          if (select && select->quick)
4867
6269
          {
4868
6270
            delete select->quick;
4871
6273
          if (table->covering_keys.test(best_key))
4872
6274
          {
4873
6275
            table->key_read=1;
4874
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
6276
            table->file->extra(HA_EXTRA_KEYREAD);
4875
6277
          }
4876
 
          table->cursor->ha_index_or_rnd_end();
 
6278
          table->file->ha_index_or_rnd_end();
4877
6279
          if (join->select_options & SELECT_DESCRIBE)
4878
6280
          {
4879
6281
            tab->ref.key= -1;
4882
6284
              tab->limit= select_limit;
4883
6285
          }
4884
6286
        }
4885
 
        else if (tab->type != AM_ALL)
 
6287
        else if (tab->type != JT_ALL)
4886
6288
        {
4887
6289
          /*
4888
6290
            We're about to use a quick access to the table.
4890
6292
            method is actually used.
4891
6293
          */
4892
6294
          assert(tab->select->quick);
4893
 
          tab->type= AM_ALL;
 
6295
          tab->type=JT_ALL;
4894
6296
          tab->use_quick=1;
4895
6297
          tab->ref.key= -1;
4896
6298
          tab->ref.key_parts=0;         // Don't use ref key.
4897
6299
          tab->read_first_record= join_init_read_record;
 
6300
          /*
 
6301
            TODO: update the number of records in join->best_positions[tablenr]
 
6302
          */
4898
6303
        }
4899
6304
      }
4900
6305
      used_key_parts= best_key_parts;
4905
6310
  }
4906
6311
 
4907
6312
check_reverse_order:
4908
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
6313
  if (order_direction == -1)            // If order_st BY ... DESC
4909
6314
  {
4910
6315
    if (select && select->quick)
4911
6316
    {
4913
6318
        Don't reverse the sort order, if it's already done.
4914
6319
        (In some cases test_if_order_by_key() can be called multiple times
4915
6320
      */
4916
 
      if (! select->quick->reverse_sorted())
 
6321
      if (!select->quick->reverse_sorted())
4917
6322
      {
4918
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
6323
        QUICK_SELECT_DESC *tmp;
4919
6324
        bool error= false;
4920
6325
        int quick_type= select->quick->get_type();
4921
 
        if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4922
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT ||
4923
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4924
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX)
 
6326
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
6327
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
6328
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
6329
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
4925
6330
        {
4926
6331
          tab->limit= 0;
4927
6332
          select->quick= save_quick;
4928
 
          return 0; // Use filesort
 
6333
          return(0);                   // Use filesort
4929
6334
        }
4930
6335
 
4931
 
        /* ORDER BY range_key DESC */
4932
 
        tmp= new optimizer::QuickSelectDescending((optimizer::QuickRangeSelect*)(select->quick),
4933
 
                                                  used_key_parts, 
4934
 
                                                  &error);
4935
 
        if (! tmp || error)
 
6336
        /* order_st BY range_key DESC */
 
6337
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
6338
                                          used_key_parts, &error);
 
6339
        if (!tmp || error)
4936
6340
        {
4937
6341
          delete tmp;
4938
 
          select->quick= save_quick;
4939
 
          tab->limit= 0;
4940
 
          return 0; // Reverse sort not supported
 
6342
                select->quick= save_quick;
 
6343
                tab->limit= 0;
 
6344
          return(0);            // Reverse sort not supported
4941
6345
        }
4942
6346
        select->quick=tmp;
4943
6347
      }
4944
6348
    }
4945
 
    else if (tab->type != AM_NEXT &&
 
6349
    else if (tab->type != JT_NEXT &&
4946
6350
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
4947
6351
    {
4948
6352
      /*
4949
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
6353
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
4950
6354
 
4951
6355
        Use a traversal function that starts by reading the last row
4952
6356
        with key part (A) and then traverse the index backwards.
4957
6361
  }
4958
6362
  else if (select && select->quick)
4959
6363
    select->quick->sorted= 1;
4960
 
  return 1;
 
6364
  return(1);
4961
6365
}
4962
6366
 
4963
6367
/*
4965
6369
 
4966
6370
  SYNOPSIS
4967
6371
   create_sort_index()
4968
 
     session            Thread Cursor
 
6372
     session            Thread handler
4969
6373
     tab                Table to sort (in join structure)
4970
6374
     order              How table should be sorted
4971
6375
     filesort_limit     Max number of rows that needs to be sorted
4978
6382
  IMPLEMENTATION
4979
6383
   - If there is an index that can be used, 'tab' is modified to use
4980
6384
     this index.
4981
 
   - If no index, create with filesort() an index cursor that can be used to
 
6385
   - If no index, create with filesort() an index file that can be used to
4982
6386
     retrieve rows in order (should be done with 'read_record').
4983
6387
     The sorted data is stored in tab->table and will be freed when calling
4984
 
     tab->table->free_io_cache().
 
6388
     free_io_cache(tab->table).
4985
6389
 
4986
6390
  RETURN VALUES
4987
6391
    0           ok
4988
6392
    -1          Some fatal error
4989
6393
    1           No records
4990
6394
*/
4991
 
int create_sort_index(Session *session, Join *join, Order *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
 
6395
int create_sort_index(Session *session, JOIN *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
4992
6396
{
4993
6397
  uint32_t length= 0;
4994
6398
  ha_rows examined_rows;
4995
6399
  Table *table;
4996
 
  optimizer::SqlSelect *select= NULL;
4997
 
  JoinTable *tab;
 
6400
  SQL_SELECT *select;
 
6401
  JOIN_TAB *tab;
4998
6402
 
4999
6403
  if (join->tables == join->const_tables)
5000
6404
    return(0);                          // One row, no need to sort
5010
6414
  */
5011
6415
  if ((order != join->group_list ||
5012
6416
       !(join->select_options & SELECT_BIG_RESULT) ||
5013
 
       (select && select->quick && (select->quick->get_type() == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))) &&
 
6417
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
5014
6418
      test_if_skip_sort_order(tab,order,select_limit,0,
5015
6419
                              is_order_by ?  &table->keys_in_use_for_order_by :
5016
6420
                              &table->keys_in_use_for_group_by))
5017
6421
    return(0);
5018
 
  for (Order *ord= join->order; ord; ord= ord->next)
 
6422
  for (order_st *ord= join->order; ord; ord= ord->next)
5019
6423
    length++;
5020
 
  if (!(join->sortorder= make_unireg_sortorder(order, &length, join->sortorder)))
5021
 
  {
5022
 
    return(-1);
5023
 
  }
 
6424
  if (!(join->sortorder=
 
6425
        make_unireg_sortorder(order, &length, join->sortorder)))
 
6426
    goto err;                           /* purecov: inspected */
5024
6427
 
5025
 
  table->sort.io_cache= new internal::IO_CACHE;
 
6428
  table->sort.io_cache= new IO_CACHE;
 
6429
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
5026
6430
  table->status=0;                              // May be wrong if quick_select
5027
6431
 
5028
6432
  // If table has a range, move it to select
5039
6443
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
5040
6444
      {
5041
6445
        table->key_read=0;
5042
 
        table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
6446
        table->file->extra(HA_EXTRA_NO_KEYREAD);
5043
6447
      }
5044
6448
    }
5045
6449
    else
5050
6454
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5051
6455
        field, quick will contain an empty record set.
5052
6456
      */
5053
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
5054
 
                                                                 table, 
5055
 
                                                                 &tab->ref,
5056
 
                                                                 tab->found_records))))
5057
 
      {
5058
 
        return(-1);
5059
 
      }
 
6457
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
6458
                                                     tab->found_records))))
 
6459
        goto err;
5060
6460
    }
5061
6461
  }
5062
6462
 
5063
 
  if (table->getShare()->getType())
5064
 
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
 
6463
  /* Fill schema tables with data before filesort if it's necessary */
 
6464
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
 
6465
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
 
6466
    goto err;
5065
6467
 
5066
 
  FileSort filesort(*session);
5067
 
  table->sort.found_records=filesort.run(table,join->sortorder, length,
5068
 
                                         select, filesort_limit, 0,
5069
 
                                         examined_rows);
 
6468
  if (table->s->tmp_table)
 
6469
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
 
6470
  table->sort.found_records=filesort(session, table,join->sortorder, length,
 
6471
                                     select, filesort_limit, 0,
 
6472
                                     &examined_rows);
5070
6473
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
5071
6474
  if (select)
5072
6475
  {
5076
6479
  tab->select_cond=0;
5077
6480
  tab->last_inner= 0;
5078
6481
  tab->first_unmatched= 0;
5079
 
  tab->type= AM_ALL;                            // Read with normal read_record
 
6482
  tab->type=JT_ALL;                             // Read with normal read_record
5080
6483
  tab->read_first_record= join_init_read_record;
5081
6484
  tab->join->examined_rows+=examined_rows;
5082
6485
  if (table->key_read)                          // Restore if we used indexes
5083
6486
  {
5084
6487
    table->key_read=0;
5085
 
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
6488
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5086
6489
  }
5087
 
 
5088
6490
  return(table->sort.found_records == HA_POS_ERROR);
 
6491
err:
 
6492
  return(-1);
5089
6493
}
5090
6494
 
5091
6495
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5092
6496
{
5093
 
  Cursor *cursor=table->cursor;
 
6497
  handler *file=table->file;
5094
6498
  char *org_record,*new_record;
5095
6499
  unsigned char *record;
5096
6500
  int error;
5097
 
  uint32_t reclength= table->getShare()->getRecordLength() - offset;
5098
 
 
5099
 
  org_record=(char*) (record=table->getInsertRecord())+offset;
5100
 
  new_record=(char*) table->getUpdateRecord()+offset;
5101
 
 
5102
 
  cursor->startTableScan(1);
5103
 
  error=cursor->rnd_next(record);
 
6501
  uint32_t reclength= table->s->reclength-offset;
 
6502
 
 
6503
  org_record=(char*) (record=table->record[0])+offset;
 
6504
  new_record=(char*) table->record[1]+offset;
 
6505
 
 
6506
  file->ha_rnd_init(1);
 
6507
  error=file->rnd_next(record);
5104
6508
  for (;;)
5105
6509
  {
5106
 
    if (session->getKilled())
 
6510
    if (session->killed)
5107
6511
    {
5108
6512
      session->send_kill_message();
5109
6513
      error=0;
5119
6523
    }
5120
6524
    if (having && !having->val_int())
5121
6525
    {
5122
 
      if ((error=cursor->deleteRecord(record)))
 
6526
      if ((error=file->ha_delete_row(record)))
5123
6527
        goto err;
5124
 
      error=cursor->rnd_next(record);
 
6528
      error=file->rnd_next(record);
5125
6529
      continue;
5126
6530
    }
5127
6531
    if (copy_blobs(first_field))
5132
6536
    }
5133
6537
    memcpy(new_record,org_record,reclength);
5134
6538
 
5135
 
    /* Read through rest of cursor and mark duplicated rows deleted */
 
6539
    /* Read through rest of file and mark duplicated rows deleted */
5136
6540
    bool found=0;
5137
6541
    for (;;)
5138
6542
    {
5139
 
      if ((error=cursor->rnd_next(record)))
 
6543
      if ((error=file->rnd_next(record)))
5140
6544
      {
5141
6545
        if (error == HA_ERR_RECORD_DELETED)
5142
6546
          continue;
5146
6550
      }
5147
6551
      if (table->compare_record(first_field) == 0)
5148
6552
      {
5149
 
        if ((error=cursor->deleteRecord(record)))
 
6553
        if ((error=file->ha_delete_row(record)))
5150
6554
          goto err;
5151
6555
      }
5152
6556
      else if (!found)
5153
6557
      {
5154
6558
        found= 1;
5155
 
        cursor->position(record);       // Remember position
 
6559
        file->position(record); // Remember position
5156
6560
      }
5157
6561
    }
5158
6562
    if (!found)
5159
 
      break;                                    // End of cursor
5160
 
    /* Move current position to the next row */
5161
 
    error= cursor->rnd_pos(record, cursor->ref);
 
6563
      break;                                    // End of file
 
6564
    /* Restart search on next row */
 
6565
    error=file->restart_rnd_next(record,file->ref);
5162
6566
  }
5163
6567
 
5164
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6568
  file->extra(HA_EXTRA_NO_CACHE);
5165
6569
  return(0);
5166
6570
err:
5167
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6571
  file->extra(HA_EXTRA_NO_CACHE);
5168
6572
  if (error)
5169
 
    table->print_error(error,MYF(0));
 
6573
    file->print_error(error,MYF(0));
5170
6574
  return(1);
5171
6575
}
5172
6576
 
5183
6587
                               uint32_t key_length,
5184
6588
                               Item *having)
5185
6589
{
5186
 
  unsigned char *key_pos, *record=table->getInsertRecord();
 
6590
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5187
6591
  int error;
5188
 
  Cursor *cursor= table->cursor;
 
6592
  handler *file= table->file;
5189
6593
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5190
 
  uint32_t *field_length;
 
6594
  uint32_t *field_lengths,*field_length;
5191
6595
  HASH hash;
5192
 
  std::vector<unsigned char> key_buffer;
5193
 
  std::vector<uint32_t> field_lengths;
5194
6596
 
5195
 
  key_buffer.resize((key_length + extra_length) * (long) cursor->stats.records);
5196
 
  field_lengths.resize(field_count);
 
6597
  if (!my_multi_malloc(MYF(MY_WME),
 
6598
                       &key_buffer,
 
6599
                       (uint32_t) ((key_length + extra_length) *
 
6600
                               (long) file->stats.records),
 
6601
                       &field_lengths,
 
6602
                       (uint32_t) (field_count*sizeof(*field_lengths)),
 
6603
                       NULL))
 
6604
    return(1);
5197
6605
 
5198
6606
  {
5199
6607
    Field **ptr;
5200
6608
    uint32_t total_length= 0;
5201
 
 
5202
 
    for (ptr= first_field, field_length= &field_lengths[0] ; *ptr ; ptr++)
 
6609
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
5203
6610
    {
5204
6611
      uint32_t length= (*ptr)->sort_length();
5205
6612
      (*field_length++)= length;
5210
6617
    extra_length= ALIGN_SIZE(key_length)-key_length;
5211
6618
  }
5212
6619
 
5213
 
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor->stats.records, 0,
 
6620
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
5214
6621
                key_length, (hash_get_key) 0, 0, 0))
5215
6622
  {
 
6623
    free((char*) key_buffer);
5216
6624
    return(1);
5217
6625
  }
5218
6626
 
5219
 
  cursor->startTableScan(1);
5220
 
  key_pos= &key_buffer[0];
 
6627
  file->ha_rnd_init(1);
 
6628
  key_pos=key_buffer;
5221
6629
  for (;;)
5222
6630
  {
5223
6631
    unsigned char *org_key_pos;
5224
 
    if (session->getKilled())
 
6632
    if (session->killed)
5225
6633
    {
5226
6634
      session->send_kill_message();
5227
6635
      error=0;
5228
6636
      goto err;
5229
6637
    }
5230
 
    if ((error=cursor->rnd_next(record)))
 
6638
    if ((error=file->rnd_next(record)))
5231
6639
    {
5232
6640
      if (error == HA_ERR_RECORD_DELETED)
5233
6641
        continue;
5237
6645
    }
5238
6646
    if (having && !having->val_int())
5239
6647
    {
5240
 
      if ((error=cursor->deleteRecord(record)))
 
6648
      if ((error=file->ha_delete_row(record)))
5241
6649
        goto err;
5242
6650
      continue;
5243
6651
    }
5244
6652
 
5245
6653
    /* copy fields to key buffer */
5246
6654
    org_key_pos= key_pos;
5247
 
    field_length= &field_lengths[0];
 
6655
    field_length=field_lengths;
5248
6656
    for (Field **ptr= first_field ; *ptr ; ptr++)
5249
6657
    {
5250
6658
      (*ptr)->sort_string(key_pos,*field_length);
5254
6662
    if (hash_search(&hash, org_key_pos, key_length))
5255
6663
    {
5256
6664
      /* Duplicated found ; Remove the row */
5257
 
      if ((error=cursor->deleteRecord(record)))
 
6665
      if ((error=file->ha_delete_row(record)))
5258
6666
        goto err;
5259
6667
    }
5260
6668
    else
5261
6669
      (void) my_hash_insert(&hash, org_key_pos);
5262
6670
    key_pos+=extra_length;
5263
6671
  }
 
6672
  free((char*) key_buffer);
5264
6673
  hash_free(&hash);
5265
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5266
 
  (void) cursor->endTableScan();
 
6674
  file->extra(HA_EXTRA_NO_CACHE);
 
6675
  (void) file->ha_rnd_end();
5267
6676
  return(0);
5268
6677
 
5269
6678
err:
 
6679
  free((char*) key_buffer);
5270
6680
  hash_free(&hash);
5271
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5272
 
  (void) cursor->endTableScan();
 
6681
  file->extra(HA_EXTRA_NO_CACHE);
 
6682
  (void) file->ha_rnd_end();
5273
6683
  if (error)
5274
 
    table->print_error(error,MYF(0));
 
6684
    file->print_error(error,MYF(0));
5275
6685
  return(1);
5276
6686
}
5277
6687
 
5278
 
SortField *make_unireg_sortorder(Order *order, uint32_t *length, SortField *sortorder)
 
6688
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length, SORT_FIELD *sortorder)
5279
6689
{
5280
6690
  uint32_t count;
5281
 
  SortField *sort,*pos;
 
6691
  SORT_FIELD *sort,*pos;
5282
6692
 
5283
6693
  count=0;
5284
 
  for (Order *tmp = order; tmp; tmp=tmp->next)
 
6694
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5285
6695
    count++;
5286
6696
  if (!sortorder)
5287
 
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) *
5288
 
                                       (max(count, *length) + 1));
 
6697
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
 
6698
                                       (cmax(count, *length) + 1));
5289
6699
  pos= sort= sortorder;
5290
6700
 
5291
6701
  if (!pos)
5311
6721
  return(sort);
5312
6722
}
5313
6723
 
 
6724
void read_cached_record(JOIN_TAB *tab)
 
6725
{
 
6726
  unsigned char *pos;
 
6727
  uint32_t length;
 
6728
  bool last_record;
 
6729
  CACHE_FIELD *copy,*end_field;
 
6730
 
 
6731
  last_record= tab->cache.record_nr++ == tab->cache.ptr_record;
 
6732
  pos= tab->cache.pos;
 
6733
  for (copy= tab->cache.field, end_field= copy+tab->cache.fields;
 
6734
       copy < end_field;
 
6735
       copy++)
 
6736
  {
 
6737
    if (copy->blob_field)
 
6738
    {
 
6739
      if (last_record)
 
6740
      {
 
6741
        copy->blob_field->set_image(pos, copy->length+sizeof(char*),
 
6742
                  copy->blob_field->charset());
 
6743
        pos+=copy->length+sizeof(char*);
 
6744
      }
 
6745
      else
 
6746
      {
 
6747
        copy->blob_field->set_ptr(pos, pos+copy->length);
 
6748
        pos+=copy->length+copy->blob_field->get_length();
 
6749
      }
 
6750
    }
 
6751
    else
 
6752
    {
 
6753
      if (copy->strip)
 
6754
      {
 
6755
        length= uint2korr(pos);
 
6756
        memcpy(copy->str, pos+2, length);
 
6757
        memset(copy->str+length, ' ', copy->length-length);
 
6758
        pos+= 2 + length;
 
6759
      }
 
6760
      else
 
6761
      {
 
6762
        memcpy(copy->str,pos,copy->length);
 
6763
        pos+=copy->length;
 
6764
      }
 
6765
    }
 
6766
  }
 
6767
  tab->cache.pos=pos;
 
6768
  return;
 
6769
}
 
6770
 
5314
6771
/*
5315
6772
  eq_ref: Create the lookup key and check if it is the same as saved key
5316
6773
 
5329
6786
    false  The created key is the same as the previous one (and the record
5330
6787
           is already in table->record)
5331
6788
*/
5332
 
static bool cmp_buffer_with_ref(JoinTable *tab)
 
6789
static bool cmp_buffer_with_ref(JOIN_TAB *tab)
5333
6790
{
5334
6791
  bool no_prev_key;
5335
6792
  if (!tab->ref.disable_cache)
5349
6806
    != 0;
5350
6807
}
5351
6808
 
5352
 
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
 
6809
bool cp_buffer_from_ref(Session *session, TABLE_REF *ref)
5353
6810
{
5354
6811
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
5355
6812
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
5372
6829
*****************************************************************************/
5373
6830
 
5374
6831
/**
5375
 
  Resolve an ORDER BY or GROUP BY column reference.
 
6832
  Resolve an order_st BY or GROUP BY column reference.
5376
6833
 
5377
6834
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5378
6835
  BY clause, find the actual column it represents. If the column being
5379
6836
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5380
6837
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
5381
 
  the ORDER BY clause, only the SELECT list is being searched.
 
6838
  the order_st BY clause, only the SELECT list is being searched.
5382
6839
 
5383
6840
  If 'order' is resolved to an Item, then order->item is set to the found
5384
6841
  Item. If there is no item for the found column (that is, it was resolved
5406
6863
static bool find_order_in_list(Session *session, 
5407
6864
                               Item **ref_pointer_array, 
5408
6865
                               TableList *tables,
5409
 
                               Order *order,
 
6866
                               order_st *order,
5410
6867
                               List<Item> &fields,
5411
6868
                               List<Item> &all_fields,
5412
6869
                               bool is_group_field)
5438
6895
    return false;
5439
6896
  }
5440
6897
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
5441
 
  select_item= find_item_in_list(session, order_item, fields, &counter,
 
6898
  select_item= find_item_in_list(order_item, fields, &counter,
5442
6899
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
5443
6900
  if (!select_item)
5444
6901
    return true; /* The item is not unique, or some other error occured. */
5464
6921
        order_item_type == Item::REF_ITEM)
5465
6922
    {
5466
6923
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5467
 
                                       NULL, &view_ref, IGNORE_ERRORS, false);
 
6924
                                       NULL, &view_ref, IGNORE_ERRORS, true,
 
6925
                                       false);
5468
6926
      if (!from_field)
5469
6927
        from_field= (Field*) not_found_field;
5470
6928
    }
5505
6963
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
5506
6964
                          ER(ER_NON_UNIQ_ERROR),
5507
6965
                          ((Item_ident*) order_item)->field_name,
5508
 
                          session->where);
 
6966
                          current_session->where);
5509
6967
    }
5510
6968
  }
5511
6969
 
5545
7003
                TableList *tables,
5546
7004
                            List<Item> &fields,
5547
7005
                List<Item> &all_fields,
5548
 
                Order *order)
 
7006
                order_st *order)
5549
7007
{
5550
7008
  session->where="order clause";
5551
7009
  for (; order; order=order->next)
5560
7018
/**
5561
7019
  Intitialize the GROUP BY list.
5562
7020
 
5563
 
  @param session                        Thread Cursor
 
7021
  @param session                        Thread handler
5564
7022
  @param ref_pointer_array      We store references to all fields that was
5565
7023
                               not in 'fields' here.
5566
7024
  @param fields         All fields in the select part. Any item in
5587
7045
                TableList *tables,
5588
7046
                      List<Item> &fields,
5589
7047
                List<Item> &all_fields,
5590
 
                Order *order,
 
7048
                order_st *order,
5591
7049
                      bool *hidden_group_fields)
5592
7050
{
5593
7051
  *hidden_group_fields=0;
5594
 
  Order *ord;
 
7052
  order_st *ord;
5595
7053
 
5596
7054
  if (!order)
5597
7055
    return 0;                           /* Everything is ok */
5681
7139
  Try to use the fields in the order given by 'order' to allow one to
5682
7140
  optimize away 'order by'.
5683
7141
*/
5684
 
Order *create_distinct_group(Session *session,
 
7142
order_st *create_distinct_group(Session *session,
5685
7143
                                Item **ref_pointer_array,
5686
 
                                Order *order_list,
 
7144
                                order_st *order_list,
5687
7145
                                List<Item> &fields,
5688
7146
                                List<Item> &,
5689
7147
                                bool *all_order_by_fields_used)
5690
7148
{
5691
7149
  List_iterator<Item> li(fields);
5692
7150
  Item *item;
5693
 
  Order *order,*group,**prev;
 
7151
  order_st *order,*group,**prev;
5694
7152
 
5695
7153
  *all_order_by_fields_used= 1;
5696
7154
  while ((item=li++))
5701
7159
  {
5702
7160
    if (order->in_field_list)
5703
7161
    {
5704
 
      Order *ord=(Order*) session->memdup((char*) order,sizeof(Order));
 
7162
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
5705
7163
      if (!ord)
5706
7164
        return 0;
5707
7165
      *prev=ord;
5721
7179
        Don't put duplicate columns from the SELECT list into the
5722
7180
        GROUP BY list.
5723
7181
      */
5724
 
      Order *ord_iter;
 
7182
      order_st *ord_iter;
5725
7183
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
5726
7184
        if ((*ord_iter->item)->eq(item, 1))
5727
7185
          goto next_item;
5728
7186
 
5729
 
      Order *ord=(Order*) session->calloc(sizeof(Order));
 
7187
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
5730
7188
      if (!ord)
5731
7189
        return 0;
5732
7190
 
5913
7371
          saved value
5914
7372
        */
5915
7373
        field= item->field;
5916
 
        item->result_field=field->new_field(session->mem_root,field->getTable(), 1);
 
7374
        item->result_field=field->new_field(session->mem_root,field->table, 1);
5917
7375
              /*
5918
7376
                We need to allocate one extra byte for null handling and
5919
7377
                another extra byte to not get warnings from purify in
5920
7378
                Field_varstring::val_int
5921
7379
              */
5922
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
 
7380
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
5923
7381
          goto err;
5924
7382
        if (copy)
5925
7383
        {
5926
7384
          copy->set(tmp, item->result_field);
5927
7385
          item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1);
5928
 
#ifdef HAVE_VALGRIND
 
7386
#ifdef HAVE_purify
5929
7387
          copy->to_ptr[copy->from_length]= 0;
5930
7388
#endif
5931
7389
          copy++;
5965
7423
    itr++;
5966
7424
  itr.sublist(res_selected_fields, elements);
5967
7425
  /*
5968
 
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
 
7426
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
5969
7427
    reference used in these will resolve to a item that is already calculated
5970
7428
  */
5971
7429
  param->copy_funcs.concat(&extra_funcs);
6046
7504
      }
6047
7505
      else if ((field= item->get_tmp_table_field()))
6048
7506
      {
6049
 
        if (item->type() == Item::SUM_FUNC_ITEM && field->getTable()->group)
 
7507
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
6050
7508
          item_field= ((Item_sum*) item)->result_item(field);
6051
7509
        else
6052
7510
          item_field= (Item*) new Item_field(field);
6130
7588
/**
6131
7589
  Call ::setup for all sum functions.
6132
7590
 
6133
 
  @param session           thread Cursor
 
7591
  @param session           thread handler
6134
7592
  @param func_ptr      sum function list
6135
7593
 
6136
7594
  @retval
6198
7656
}
6199
7657
 
6200
7658
/** Copy result of functions to record in tmp_table. */
6201
 
bool copy_funcs(Item **func_ptr, const Session *session)
 
7659
void copy_funcs(Item **func_ptr)
6202
7660
{
6203
7661
  Item *func;
6204
7662
  for (; (func = *func_ptr) ; func_ptr++)
6205
 
  {
6206
7663
    func->save_in_result_field(1);
6207
 
    /*
6208
 
      Need to check the THD error state because Item::val_xxx() don't
6209
 
      return error code, but can generate errors
6210
 
      TODO: change it for a real status check when Item::val_xxx()
6211
 
      are extended to return status code.
6212
 
    */
6213
 
    if (session->is_error())
6214
 
      return true;
6215
 
  }
6216
 
  return false;
6217
7664
}
6218
7665
 
6219
7666
/**
6273
7720
  @retval
6274
7721
    1   on error
6275
7722
*/
6276
 
bool change_group_ref(Session *session, Item_func *expr, Order *group_list, bool *changed)
 
7723
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
6277
7724
{
6278
7725
  if (expr->arg_count)
6279
7726
  {
6287
7734
      Item *item= *arg;
6288
7735
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
6289
7736
      {
6290
 
        Order *group_tmp;
 
7737
        order_st *group_tmp;
6291
7738
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
6292
7739
        {
6293
7740
          if (item->eq(*group_tmp->item,0))
6316
7763
  return 0;
6317
7764
}
6318
7765
 
 
7766
/**
 
7767
  EXPLAIN handling.
 
7768
 
 
7769
  Send a description about what how the select will be done to stdout.
 
7770
*/
 
7771
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
 
7772
                     bool distinct,const char *message)
 
7773
{
 
7774
  List<Item> field_list;
 
7775
  List<Item> item_list;
 
7776
  Session *session=join->session;
 
7777
  select_result *result=join->result;
 
7778
  Item *item_null= new Item_null();
 
7779
  const CHARSET_INFO * const cs= system_charset_info;
 
7780
  int quick_type;
 
7781
  /* Don't log this into the slow query log */
 
7782
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
7783
  join->unit->offset_limit_cnt= 0;
 
7784
 
 
7785
  /*
 
7786
    NOTE: the number/types of items pushed into item_list must be in sync with
 
7787
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
 
7788
  */
 
7789
  if (message)
 
7790
  {
 
7791
    item_list.push_back(new Item_int((int32_t)
 
7792
                                     join->select_lex->select_number));
 
7793
    item_list.push_back(new Item_string(join->select_lex->type,
 
7794
                                        strlen(join->select_lex->type), cs));
 
7795
    for (uint32_t i=0 ; i < 7; i++)
 
7796
      item_list.push_back(item_null);
 
7797
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7798
      item_list.push_back(item_null);
 
7799
 
 
7800
    item_list.push_back(new Item_string(message,strlen(message),cs));
 
7801
    if (result->send_data(item_list))
 
7802
      join->error= 1;
 
7803
  }
 
7804
  else if (join->select_lex == join->unit->fake_select_lex)
 
7805
  {
 
7806
    /*
 
7807
      here we assume that the query will return at least two rows, so we
 
7808
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
 
7809
      and no filesort will be actually done, but executing all selects in
 
7810
      the UNION to provide precise EXPLAIN information will hardly be
 
7811
      appreciated :)
 
7812
    */
 
7813
    char table_name_buffer[NAME_LEN];
 
7814
    item_list.empty();
 
7815
    /* id */
 
7816
    item_list.push_back(new Item_null);
 
7817
    /* select_type */
 
7818
    item_list.push_back(new Item_string(join->select_lex->type,
 
7819
                                        strlen(join->select_lex->type),
 
7820
                                        cs));
 
7821
    /* table */
 
7822
    {
 
7823
      Select_Lex *sl= join->unit->first_select();
 
7824
      uint32_t len= 6, lastop= 0;
 
7825
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
 
7826
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
 
7827
      {
 
7828
        len+= lastop;
 
7829
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
 
7830
                         "%u,", sl->select_number);
 
7831
      }
 
7832
      if (sl || len + lastop >= NAME_LEN)
 
7833
      {
 
7834
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
 
7835
        len+= 4;
 
7836
      }
 
7837
      else
 
7838
      {
 
7839
        len+= lastop;
 
7840
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
 
7841
      }
 
7842
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
7843
    }
 
7844
    /* type */
 
7845
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
 
7846
                                          strlen(join_type_str[JT_ALL]),
 
7847
                                          cs));
 
7848
    /* possible_keys */
 
7849
    item_list.push_back(item_null);
 
7850
    /* key*/
 
7851
    item_list.push_back(item_null);
 
7852
    /* key_len */
 
7853
    item_list.push_back(item_null);
 
7854
    /* ref */
 
7855
    item_list.push_back(item_null);
 
7856
    /* in_rows */
 
7857
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7858
      item_list.push_back(item_null);
 
7859
    /* rows */
 
7860
    item_list.push_back(item_null);
 
7861
    /* extra */
 
7862
    if (join->unit->global_parameters->order_list.first)
 
7863
      item_list.push_back(new Item_string("Using filesort",
 
7864
                                          14, cs));
 
7865
    else
 
7866
      item_list.push_back(new Item_string("", 0, cs));
 
7867
 
 
7868
    if (result->send_data(item_list))
 
7869
      join->error= 1;
 
7870
  }
 
7871
  else
 
7872
  {
 
7873
    table_map used_tables=0;
 
7874
    for (uint32_t i=0 ; i < join->tables ; i++)
 
7875
    {
 
7876
      JOIN_TAB *tab=join->join_tab+i;
 
7877
      Table *table=tab->table;
 
7878
      TableList *table_list= tab->table->pos_in_table_list;
 
7879
      char buff[512];
 
7880
      char buff1[512], buff2[512], buff3[512];
 
7881
      char keylen_str_buf[64];
 
7882
      String extra(buff, sizeof(buff),cs);
 
7883
      char table_name_buffer[NAME_LEN];
 
7884
      String tmp1(buff1,sizeof(buff1),cs);
 
7885
      String tmp2(buff2,sizeof(buff2),cs);
 
7886
      String tmp3(buff3,sizeof(buff3),cs);
 
7887
      extra.length(0);
 
7888
      tmp1.length(0);
 
7889
      tmp2.length(0);
 
7890
      tmp3.length(0);
 
7891
 
 
7892
      quick_type= -1;
 
7893
      item_list.empty();
 
7894
      /* id */
 
7895
      item_list.push_back(new Item_uint((uint32_t)
 
7896
                                       join->select_lex->select_number));
 
7897
      /* select_type */
 
7898
      item_list.push_back(new Item_string(join->select_lex->type,
 
7899
                                          strlen(join->select_lex->type),
 
7900
                                          cs));
 
7901
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
 
7902
      {
 
7903
        quick_type= tab->select->quick->get_type();
 
7904
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
 
7905
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
 
7906
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
 
7907
          tab->type = JT_INDEX_MERGE;
 
7908
        else
 
7909
          tab->type = JT_RANGE;
 
7910
      }
 
7911
      /* table */
 
7912
      if (table->derived_select_number)
 
7913
      {
 
7914
        /* Derived table name generation */
 
7915
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
7916
                          "<derived%u>",
 
7917
                          table->derived_select_number);
 
7918
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
7919
      }
 
7920
      else
 
7921
      {
 
7922
        TableList *real_table= table->pos_in_table_list;
 
7923
        item_list.push_back(new Item_string(real_table->alias,
 
7924
                                            strlen(real_table->alias),
 
7925
                                            cs));
 
7926
      }
 
7927
      /* "type" column */
 
7928
      item_list.push_back(new Item_string(join_type_str[tab->type],
 
7929
                                          strlen(join_type_str[tab->type]),
 
7930
                                          cs));
 
7931
      /* Build "possible_keys" value and add it to item_list */
 
7932
      if (tab->keys.any())
 
7933
      {
 
7934
        uint32_t j;
 
7935
        for (j=0 ; j < table->s->keys ; j++)
 
7936
        {
 
7937
          if (tab->keys.test(j))
 
7938
          {
 
7939
            if (tmp1.length())
 
7940
              tmp1.append(',');
 
7941
            tmp1.append(table->key_info[j].name,
 
7942
                        strlen(table->key_info[j].name),
 
7943
                        system_charset_info);
 
7944
          }
 
7945
        }
 
7946
      }
 
7947
      if (tmp1.length())
 
7948
        item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
 
7949
      else
 
7950
        item_list.push_back(item_null);
 
7951
 
 
7952
      /* Build "key", "key_len", and "ref" values and add them to item_list */
 
7953
      if (tab->ref.key_parts)
 
7954
      {
 
7955
        KEY *key_info=table->key_info+ tab->ref.key;
 
7956
        register uint32_t length;
 
7957
        item_list.push_back(new Item_string(key_info->name,
 
7958
                                            strlen(key_info->name),
 
7959
                                            system_charset_info));
 
7960
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
 
7961
                keylen_str_buf;
 
7962
        item_list.push_back(new Item_string(keylen_str_buf, length,
 
7963
                                            system_charset_info));
 
7964
        for (StoredKey **ref=tab->ref.key_copy ; *ref ; ref++)
 
7965
        {
 
7966
          if (tmp2.length())
 
7967
            tmp2.append(',');
 
7968
          tmp2.append((*ref)->name(), strlen((*ref)->name()),
 
7969
                      system_charset_info);
 
7970
        }
 
7971
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
7972
      }
 
7973
      else if (tab->type == JT_NEXT)
 
7974
      {
 
7975
        KEY *key_info=table->key_info+ tab->index;
 
7976
        register uint32_t length;
 
7977
        item_list.push_back(new Item_string(key_info->name,
 
7978
                                            strlen(key_info->name),cs));
 
7979
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
 
7980
                keylen_str_buf;
 
7981
        item_list.push_back(new Item_string(keylen_str_buf,
 
7982
                                            length,
 
7983
                                            system_charset_info));
 
7984
        item_list.push_back(item_null);
 
7985
      }
 
7986
      else if (tab->select && tab->select->quick)
 
7987
      {
 
7988
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
 
7989
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
7990
        item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
 
7991
        item_list.push_back(item_null);
 
7992
      }
 
7993
      else
 
7994
      {
 
7995
        if (table_list->schema_table && 
 
7996
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
7997
        {
 
7998
          if (table_list->has_db_lookup_value)
 
7999
          {
 
8000
            int f_idx= table_list->schema_table->getFirstColumnIndex();
 
8001
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
8002
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
8003
          }
 
8004
          if (table_list->has_table_lookup_value)
 
8005
          {
 
8006
            if (table_list->has_db_lookup_value)
 
8007
              tmp2.append(',');
 
8008
            int f_idx= table_list->schema_table->getSecondColumnIndex();
 
8009
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
8010
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
8011
          }
 
8012
          if (tmp2.length())
 
8013
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
8014
          else
 
8015
            item_list.push_back(item_null);
 
8016
        }
 
8017
        else
 
8018
          item_list.push_back(item_null);
 
8019
        item_list.push_back(item_null);
 
8020
        item_list.push_back(item_null);
 
8021
      }
 
8022
 
 
8023
      /* Add "rows" field to item_list. */
 
8024
      if (table_list->schema_table)
 
8025
      {
 
8026
        /* in_rows */
 
8027
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
8028
          item_list.push_back(item_null);
 
8029
        /* rows */
 
8030
        item_list.push_back(item_null);
 
8031
      }
 
8032
      else
 
8033
      {
 
8034
        double examined_rows;
 
8035
        if (tab->select && tab->select->quick)
 
8036
          examined_rows= rows2double(tab->select->quick->records);
 
8037
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
 
8038
          examined_rows= rows2double(tab->limit ? tab->limit :
 
8039
                                     tab->table->file->records());
 
8040
        else
 
8041
          examined_rows= join->best_positions[i].records_read;
 
8042
 
 
8043
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
 
8044
                                         MY_INT64_NUM_DECIMAL_DIGITS));
 
8045
 
 
8046
        /* Add "filtered" field to item_list. */
 
8047
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
8048
        {
 
8049
          float f= 0.0;
 
8050
          if (examined_rows)
 
8051
            f= (float) (100.0 * join->best_positions[i].records_read /
 
8052
                        examined_rows);
 
8053
          item_list.push_back(new Item_float(f, 2));
 
8054
        }
 
8055
      }
 
8056
 
 
8057
      /* Build "Extra" field and add it to item_list. */
 
8058
      bool key_read=table->key_read;
 
8059
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
 
8060
          table->covering_keys.test(tab->index))
 
8061
        key_read=1;
 
8062
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
 
8063
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
 
8064
        key_read=1;
 
8065
 
 
8066
      if (tab->info)
 
8067
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
 
8068
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
 
8069
      {
 
8070
        if (tab->packed_info & TAB_INFO_USING_INDEX)
 
8071
          extra.append(STRING_WITH_LEN("; Using index"));
 
8072
        if (tab->packed_info & TAB_INFO_USING_WHERE)
 
8073
          extra.append(STRING_WITH_LEN("; Using where"));
 
8074
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
 
8075
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
8076
        /* Skip initial "; "*/
 
8077
        const char *str= extra.ptr();
 
8078
        uint32_t len= extra.length();
 
8079
        if (len)
 
8080
        {
 
8081
          str += 2;
 
8082
          len -= 2;
 
8083
        }
 
8084
        item_list.push_back(new Item_string(str, len, cs));
 
8085
      }
 
8086
      else
 
8087
      {
 
8088
        uint32_t keyno= MAX_KEY;
 
8089
        if (tab->ref.key_parts)
 
8090
          keyno= tab->ref.key;
 
8091
        else if (tab->select && tab->select->quick)
 
8092
          keyno = tab->select->quick->index;
 
8093
 
 
8094
        if (keyno != MAX_KEY && keyno == table->file->pushed_idx_cond_keyno &&
 
8095
            table->file->pushed_idx_cond)
 
8096
          extra.append(STRING_WITH_LEN("; Using index condition"));
 
8097
 
 
8098
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
8099
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
8100
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
 
8101
        {
 
8102
          extra.append(STRING_WITH_LEN("; Using "));
 
8103
          tab->select->quick->add_info_string(&extra);
 
8104
        }
 
8105
          if (tab->select)
 
8106
        {
 
8107
          if (tab->use_quick == 2)
 
8108
          {
 
8109
            /*
 
8110
             * To print out the bitset in tab->keys, we go through
 
8111
             * it 32 bits at a time. We need to do this to ensure
 
8112
             * that the to_ulong() method will not throw an
 
8113
             * out_of_range exception at runtime which would happen
 
8114
             * if the bitset we were working with was larger than 64
 
8115
             * bits on a 64-bit platform (for example).
 
8116
             */
 
8117
            stringstream s, w;
 
8118
            string str;
 
8119
            w << tab->keys;
 
8120
            w >> str;
 
8121
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
 
8122
            {
 
8123
              bitset<32> tmp(str, pos, 32);
 
8124
              if (tmp.any())
 
8125
                s << uppercase << hex << tmp.to_ulong();
 
8126
            }
 
8127
            extra.append(STRING_WITH_LEN("; Range checked for each "
 
8128
                                         "record (index map: 0x"));
 
8129
            extra.append(s.str().c_str());
 
8130
            extra.append(')');
 
8131
          }
 
8132
          else if (tab->select->cond)
 
8133
          {
 
8134
            const COND *pushed_cond= tab->table->file->pushed_cond;
 
8135
 
 
8136
            if (session->variables.engine_condition_pushdown && pushed_cond)
 
8137
            {
 
8138
              extra.append(STRING_WITH_LEN("; Using where with pushed "
 
8139
                                           "condition"));
 
8140
              if (session->lex->describe & DESCRIBE_EXTENDED)
 
8141
              {
 
8142
                extra.append(STRING_WITH_LEN(": "));
 
8143
                ((COND *)pushed_cond)->print(&extra, QT_ORDINARY);
 
8144
              }
 
8145
            }
 
8146
            else
 
8147
              extra.append(STRING_WITH_LEN("; Using where"));
 
8148
          }
 
8149
        }
 
8150
        if (key_read)
 
8151
        {
 
8152
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
 
8153
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
 
8154
          else
 
8155
            extra.append(STRING_WITH_LEN("; Using index"));
 
8156
        }
 
8157
        if (table->reginfo.not_exists_optimize)
 
8158
          extra.append(STRING_WITH_LEN("; Not exists"));
 
8159
 
 
8160
        if (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE &&
 
8161
            !(((QUICK_RANGE_SELECT*)(tab->select->quick))->mrr_flags &
 
8162
             HA_MRR_USE_DEFAULT_IMPL))
 
8163
        {
 
8164
          extra.append(STRING_WITH_LEN("; Using MRR"));
 
8165
        }
 
8166
 
 
8167
        if (table_list->schema_table &&
 
8168
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
8169
        {
 
8170
          if (!table_list->table_open_method)
 
8171
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
 
8172
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
 
8173
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
 
8174
          else
 
8175
            extra.append(STRING_WITH_LEN("; Open_full_table"));
 
8176
          if (table_list->has_db_lookup_value &&
 
8177
              table_list->has_table_lookup_value)
 
8178
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
 
8179
          else if (table_list->has_db_lookup_value ||
 
8180
                   table_list->has_table_lookup_value)
 
8181
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
 
8182
          else
 
8183
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
 
8184
        }
 
8185
        if (need_tmp_table)
 
8186
        {
 
8187
          need_tmp_table=0;
 
8188
          extra.append(STRING_WITH_LEN("; Using temporary"));
 
8189
        }
 
8190
        if (need_order)
 
8191
        {
 
8192
          need_order=0;
 
8193
          extra.append(STRING_WITH_LEN("; Using filesort"));
 
8194
        }
 
8195
        if (distinct & test_all_bits(used_tables,session->used_tables))
 
8196
          extra.append(STRING_WITH_LEN("; Distinct"));
 
8197
 
 
8198
        if (tab->insideout_match_tab)
 
8199
        {
 
8200
          extra.append(STRING_WITH_LEN("; LooseScan"));
 
8201
        }
 
8202
 
 
8203
        if (tab->flush_weedout_table)
 
8204
          extra.append(STRING_WITH_LEN("; Start temporary"));
 
8205
        else if (tab->check_weed_out_table)
 
8206
          extra.append(STRING_WITH_LEN("; End temporary"));
 
8207
        else if (tab->do_firstmatch)
 
8208
        {
 
8209
          extra.append(STRING_WITH_LEN("; FirstMatch("));
 
8210
          Table *prev_table=tab->do_firstmatch->table;
 
8211
          if (prev_table->derived_select_number)
 
8212
          {
 
8213
            char namebuf[NAME_LEN];
 
8214
            /* Derived table name generation */
 
8215
            int len= snprintf(namebuf, sizeof(namebuf)-1,
 
8216
                              "<derived%u>",
 
8217
                              prev_table->derived_select_number);
 
8218
            extra.append(namebuf, len);
 
8219
          }
 
8220
          else
 
8221
            extra.append(prev_table->pos_in_table_list->alias);
 
8222
          extra.append(STRING_WITH_LEN(")"));
 
8223
        }
 
8224
 
 
8225
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
8226
        {
 
8227
          if (tab->ref.cond_guards[part])
 
8228
          {
 
8229
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
8230
            break;
 
8231
          }
 
8232
        }
 
8233
 
 
8234
        if (i > 0 && tab[-1].next_select == sub_select_cache)
 
8235
          extra.append(STRING_WITH_LEN("; Using join buffer"));
 
8236
 
 
8237
        /* Skip initial "; "*/
 
8238
        const char *str= extra.ptr();
 
8239
        uint32_t len= extra.length();
 
8240
        if (len)
 
8241
        {
 
8242
          str += 2;
 
8243
          len -= 2;
 
8244
        }
 
8245
        item_list.push_back(new Item_string(str, len, cs));
 
8246
      }
 
8247
      // For next iteration
 
8248
      used_tables|=table->map;
 
8249
      if (result->send_data(item_list))
 
8250
        join->error= 1;
 
8251
    }
 
8252
  }
 
8253
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
 
8254
       unit;
 
8255
       unit= unit->next_unit())
 
8256
  {
 
8257
    if (mysql_explain_union(session, unit, result))
 
8258
      return;
 
8259
  }
 
8260
  return;
 
8261
}
 
8262
 
 
8263
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
 
8264
{
 
8265
  bool res= false;
 
8266
  Select_Lex *first= unit->first_select();
 
8267
 
 
8268
  for (Select_Lex *sl= first;
 
8269
       sl;
 
8270
       sl= sl->next_select())
 
8271
  {
 
8272
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
 
8273
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
8274
    sl->type= (((&session->lex->select_lex)==sl)?
 
8275
               (sl->first_inner_unit() || sl->next_select() ?
 
8276
                "PRIMARY" : "SIMPLE"):
 
8277
               ((sl == first)?
 
8278
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
 
8279
                 "DERIVED":
 
8280
                 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
8281
                  "DEPENDENT SUBQUERY":
 
8282
                  (uncacheable?"UNCACHEABLE SUBQUERY":
 
8283
                   "SUBQUERY"))):
 
8284
                ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
8285
                 "DEPENDENT UNION":
 
8286
                 uncacheable?"UNCACHEABLE UNION":
 
8287
                 "UNION")));
 
8288
    sl->options|= SELECT_DESCRIBE;
 
8289
  }
 
8290
  if (unit->is_union())
 
8291
  {
 
8292
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
 
8293
    unit->fake_select_lex->type= "UNION RESULT";
 
8294
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
 
8295
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
8296
      res= unit->exec();
 
8297
    res|= unit->cleanup();
 
8298
  }
 
8299
  else
 
8300
  {
 
8301
    session->lex->current_select= first;
 
8302
    unit->set_limit(unit->global_parameters);
 
8303
    res= mysql_select(session, &first->ref_pointer_array,
 
8304
                        (TableList*) first->table_list.first,
 
8305
                        first->with_wild, first->item_list,
 
8306
                        first->where,
 
8307
                        first->order_list.elements +
 
8308
                        first->group_list.elements,
 
8309
                        (order_st*) first->order_list.first,
 
8310
                        (order_st*) first->group_list.first,
 
8311
                        first->having,
 
8312
                        first->options | session->options | SELECT_DESCRIBE,
 
8313
                        result, unit, first);
 
8314
  }
 
8315
  return(res || session->is_error());
 
8316
}
6319
8317
 
6320
8318
static void print_table_array(Session *session, String *str, TableList **table,
6321
8319
                              TableList **end)
6332
8330
    }
6333
8331
    else if (curr->straight)
6334
8332
      str->append(STRING_WITH_LEN(" straight_join "));
 
8333
    else if (curr->sj_inner_tables)
 
8334
      str->append(STRING_WITH_LEN(" semi join "));
6335
8335
    else
6336
8336
      str->append(STRING_WITH_LEN(" join "));
6337
8337
    curr->print(session, str, QT_ORDINARY);
6346
8346
 
6347
8347
/**
6348
8348
  Print joins from the FROM clause.
6349
 
  @param session     thread Cursor
 
8349
  @param session     thread handler
6350
8350
  @param str     string where table should be printed
6351
8351
  @param tables  list of tables in join
6352
8352
  @query_type    type of the query is being generated
6363
8363
 
6364
8364
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
6365
8365
    *t= ti++;
 
8366
 
 
8367
  /*
 
8368
    If the first table is a semi-join nest, swap it with something that is
 
8369
    not a semi-join nest.
 
8370
  */
 
8371
  if ((*table)->sj_inner_tables)
 
8372
  {
 
8373
    TableList **end= table + tables->elements;
 
8374
    for (TableList **t2= table; t2!=end; t2++)
 
8375
    {
 
8376
      if (!(*t2)->sj_inner_tables)
 
8377
      {
 
8378
        TableList *tmp= *t2;
 
8379
        *t2= *table;
 
8380
        *table= tmp;
 
8381
        break;
 
8382
      }
 
8383
    }
 
8384
  }
6366
8385
  assert(tables->elements >= 1);
6367
8386
  print_table_array(session, str, table, table + tables->elements);
6368
8387
}
6370
8389
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
6371
8390
{
6372
8391
  /* QQ: session may not be set for sub queries, but this should be fixed */
6373
 
  if(not session)
 
8392
  if (!session)
6374
8393
    session= current_session;
6375
8394
 
6376
 
 
6377
8395
  str->append(STRING_WITH_LEN("select "));
6378
8396
 
6379
8397
  /* First add options */
6439
8457
  if (group_list.elements)
6440
8458
  {
6441
8459
    str->append(STRING_WITH_LEN(" group by "));
6442
 
    print_order(str, (Order *) group_list.first, query_type);
 
8460
    print_order(str, (order_st *) group_list.first, query_type);
6443
8461
    switch (olap)
6444
8462
    {
6445
8463
      case CUBE_TYPE:
6470
8488
  if (order_list.elements)
6471
8489
  {
6472
8490
    str->append(STRING_WITH_LEN(" order by "));
6473
 
    print_order(str, (Order *) order_list.first, query_type);
 
8491
    print_order(str, (order_st *) order_list.first, query_type);
6474
8492
  }
6475
8493
 
6476
8494
  // limit
6482
8500
/**
6483
8501
  @} (end of group Query_Optimizer)
6484
8502
*/
6485
 
 
6486
 
} /* namespace drizzled */