~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

Replace MAX_(DATE|TIME).*_WIDTH defines in definitions.h with real (and correct) static const members to Temporal types.

This fixes the buffer overflow in https://bugs.launchpad.net/drizzle/+bug/373468

It also removes a handwritten snprintf in field/datetime.cc
However... this caused us to have to change Temporal to have a way to not
"convert" the int64_t value (so 20090101 becomes 20090101000000 etc) as it
has already been converted and we just want the Temporal type to do the
to_string conversion.

This still causes a failure in 'metadata' test due to size of timestamp type. I need feedback from Jay on when the usecond code comes into play to know the correct fix for this.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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/memory/multi_malloc.h"
53
 
#include "drizzled/records.h"
54
 
#include "drizzled/internal/iocache.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"
 
49
 
 
50
#include <drizzled/sql_union.h>
 
51
 
 
52
#include <string>
 
53
#include <iostream>
64
54
 
65
55
using namespace std;
66
56
 
67
 
namespace drizzled
68
 
{
 
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
};
69
62
 
70
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
 
63
static int sort_keyuse(KEYUSE *a,KEYUSE *b);
71
64
static COND *build_equal_items(Session *session, COND *cond,
72
65
                               COND_EQUAL *inherited,
73
66
                               List<TableList> *join_list,
74
67
                               COND_EQUAL **cond_equal_ref);
75
68
 
76
69
static Item* part_of_refkey(Table *form,Field *field);
77
 
static bool cmp_buffer_with_ref(JoinTable *tab);
 
70
static bool cmp_buffer_with_ref(JOIN_TAB *tab);
78
71
static void change_cond_ref_to_const(Session *session,
79
72
                                     vector<COND_CMP>& save_list,
80
73
                                     Item *and_father,
82
75
                                     Item *field,
83
76
                                     Item *value);
84
77
static bool copy_blobs(Field **ptr);
85
 
 
86
78
static bool eval_const_cond(COND *cond)
87
79
{
88
80
    return ((Item_func*) cond)->val_int() ? true : false;
115
107
{
116
108
  bool res;
117
109
  register Select_Lex *select_lex= &lex->select_lex;
118
 
  DRIZZLE_SELECT_START(session->query.c_str());
 
110
  DRIZZLE_SELECT_START();
119
111
 
120
112
  if (select_lex->master_unit()->is_union() ||
121
113
      select_lex->master_unit()->fake_select_lex)
148
140
  if (unlikely(res))
149
141
    result->abort();
150
142
 
151
 
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
152
 
  return res;
 
143
  DRIZZLE_SELECT_END();
 
144
  return(res);
153
145
}
154
146
 
155
147
/*
285
277
      "Full scan on NULL key" (TAB_INFO_FULL_SCAN_ON_NULL)
286
278
    and set appropriate flags in join_tab->packed_info.
287
279
*/
288
 
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
 
280
void save_index_subquery_explain_info(JOIN_TAB *join_tab, Item* where)
289
281
{
290
282
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
291
283
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
305
297
/**
306
298
  An entry point to single-unit select (a select without UNION).
307
299
 
308
 
  @param session                  thread Cursor
 
300
  @param session                  thread handler
309
301
  @param rref_pointer_array   a reference to ref_pointer_array of
310
302
                              the top-level select_lex for this query
311
303
  @param tables               list of all tables used in this query.
321
313
                              for a, b and c in this list.
322
314
  @param conds                top level item of an expression representing
323
315
                              WHERE clause of the top level select
324
 
  @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
325
317
                              arguments
326
 
  @param order                linked list of ORDER BY agruments
 
318
  @param order                linked list of order_st BY agruments
327
319
  @param group                linked list of GROUP BY arguments
328
320
  @param having               top level item of HAVING expression
329
321
  @param select_options       select options (BIG_RESULT, etc)
346
338
*/
347
339
bool mysql_select(Session *session,
348
340
                  Item ***rref_pointer_array,
349
 
                  TableList *tables, 
 
341
                        TableList *tables, 
350
342
                  uint32_t wild_num, 
351
343
                  List<Item> &fields,
352
 
                  COND *conds, 
 
344
                        COND *conds, 
353
345
                  uint32_t og_num,  
354
346
                  order_st *order, 
355
347
                  order_st *group,
356
 
                  Item *having, 
 
348
                        Item *having, 
357
349
                  uint64_t select_options,
358
 
                  select_result *result, 
 
350
                        select_result *result, 
359
351
                  Select_Lex_Unit *unit,
360
 
                  Select_Lex *select_lex)
 
352
                        Select_Lex *select_lex)
361
353
{
362
354
  bool err;
363
355
  bool free_join= 1;
408
400
    }
409
401
  }
410
402
 
411
 
  err= join->optimize();
412
 
  if (err)
413
 
  {
414
 
    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
415
412
  }
416
413
 
417
414
  if (session->lex->describe & DESCRIBE_EXTENDED)
441
438
  return(join->error);
442
439
}
443
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
 
444
448
inline Item *and_items(Item* cond, Item *item)
445
449
{
446
450
  return (cond? (new Item_cond_and(cond, item)) : item);
447
451
}
448
452
 
449
 
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
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)
450
465
{
451
466
  List_iterator<TableList> it(*tlist);
452
467
  TableList *table;
459
474
  }
460
475
}
461
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
 
462
838
/*****************************************************************************
463
 
  Create JoinTableS, make a guess about the table types,
 
839
  Create JOIN_TABS, make a guess about the table types,
464
840
  Approximate how many records will be used in each table
465
841
*****************************************************************************/
466
 
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)
467
843
{
468
844
  int error;
469
845
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
492
868
          keyuse     Pointer to possible keys
493
869
*****************************************************************************/
494
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
}
495
1424
 
496
1425
/**
497
1426
  Add all keys with uses 'field' for some keypart.
505
1434
  return found;
506
1435
}
507
1436
 
508
 
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)
509
1473
{
510
1474
  int res;
511
 
  if (a->getTable()->tablenr != b->getTable()->tablenr)
512
 
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
513
 
  if (a->getKey() != b->getKey())
514
 
    return static_cast<int>((a->getKey() - b->getKey()));
515
 
  if (a->getKeypart() != b->getKeypart())
516
 
    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);
517
1481
  // Place const values before other ones
518
 
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
519
 
       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))))
520
1484
    return res;
521
1485
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
522
 
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
523
 
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
524
 
}
525
 
 
 
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
}
526
1560
 
527
1561
/**
528
1562
  Update keyuse array with all possible keys we can use to fetch rows.
529
1563
 
530
1564
  @param       session
531
 
  @param[out]  keyuse         Put here ordered array of KeyUse structures
 
1565
  @param[out]  keyuse         Put here ordered array of KEYUSE structures
532
1566
  @param       join_tab       Array in tablenr_order
533
1567
  @param       tables         Number of tables in join
534
1568
  @param       cond           WHERE condition (note that the function analyzes
537
1571
                              for which we can make ref access based the WHERE
538
1572
                              clause)
539
1573
  @param       select_lex     current SELECT
540
 
  @param[out]  sargables      std::vector of found sargable candidates
 
1574
  @param[out]  sargables      Array of found sargable candidates
541
1575
 
542
1576
   @retval
543
1577
     0  OK
546
1580
*/
547
1581
bool update_ref_and_keys(Session *session,
548
1582
                         DYNAMIC_ARRAY *keyuse,
549
 
                         JoinTable *join_tab,
 
1583
                         JOIN_TAB *join_tab,
550
1584
                         uint32_t tables,
551
1585
                         COND *cond, 
552
1586
                         COND_EQUAL *,
553
1587
                         table_map normal_tables,
554
1588
                         Select_Lex *select_lex,
555
 
                         vector<optimizer::SargableParam> &sargables)
 
1589
                         SARGABLE_PARAM **sargables)
556
1590
{
557
1591
  uint  and_level,i,found_eq_constant;
558
 
  optimizer::KeyField *key_fields, *end, *field;
 
1592
  KEY_FIELD *key_fields, *end, *field;
559
1593
  uint32_t sz;
560
 
  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);
561
1595
 
562
1596
  /*
563
 
    All predicates that are used to fill arrays of KeyField
564
 
    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
565
1603
    except BETWEEN predicates that have 3 arguments and
566
1604
    IN predicates.
567
1605
    This any predicate if it's not BETWEEN/IN can be used
568
 
    directly to fill at most 2 array elements, either of KeyField 
569
 
    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
570
1608
    can be filled as this predicate is considered as
571
1609
    saragable with respect to each of its argument.
572
1610
    An IN predicate can require at most 1 element as currently
576
1614
    can be not more than select_lex->max_equal_elems such
577
1615
    substitutions.
578
1616
  */
579
 
  sz= sizeof(optimizer::KeyField) *
580
 
      (((session->lex->current_select->cond_count+1) +
 
1617
  sz= cmax(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
 
1618
      (((session->lex->current_select->cond_count+1)*2 +
581
1619
        session->lex->current_select->between_count)*m+1);
582
 
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
583
 
    return true;
 
1620
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
 
1621
    return true; /* purecov: inspected */
584
1622
  and_level= 0;
585
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;
586
1628
 
587
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
 
1629
  if (my_init_dynamic_array(keyuse,sizeof(KEYUSE),20,64))
588
1630
    return true;
589
1631
  if (cond)
590
1632
  {
591
1633
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
592
1634
                   sargables);
593
 
    for (; field != end; field++)
 
1635
    for (; field != end ; field++)
594
1636
    {
595
 
      add_key_part(keyuse, field);
 
1637
      add_key_part(keyuse,field);
596
1638
      /* Mark that we can optimize LEFT JOIN */
597
 
      if (field->getValue()->type() == Item::NULL_ITEM &&
598
 
          ! field->getField()->real_maybe_null())
599
 
      {
600
 
        field->getField()->table->reginfo.not_exists_optimize= 1;
601
 
      }
 
1639
      if (field->val->type() == Item::NULL_ITEM &&
 
1640
          !field->field->real_maybe_null())
 
1641
        field->field->table->reginfo.not_exists_optimize=1;
602
1642
    }
603
1643
  }
604
 
  for (i= 0; i < tables; i++)
 
1644
  for (i=0 ; i < tables ; i++)
605
1645
  {
606
1646
    /*
607
1647
      Block the creation of keys for inner tables of outer joins.
645
1685
  */
646
1686
  if (keyuse->elements)
647
1687
  {
648
 
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
 
1688
    KEYUSE key_end,*prev,*save_pos,*use;
649
1689
 
650
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
651
 
                       (qsort_cmp) sort_keyuse);
 
1690
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KEYUSE),
 
1691
          (qsort_cmp) sort_keyuse);
652
1692
 
653
1693
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
654
1694
    insert_dynamic(keyuse,(unsigned char*) &key_end);
655
1695
 
656
 
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
 
1696
    use=save_pos=dynamic_element(keyuse,0,KEYUSE*);
657
1697
    prev= &key_end;
658
 
    found_eq_constant= 0;
659
 
    for (i= 0; i < keyuse->elements-1; i++, use++)
 
1698
    found_eq_constant=0;
 
1699
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
660
1700
    {
661
 
      if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
662
 
        use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
663
 
      if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
 
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)
664
1704
      {
665
 
        if (prev->getKeypart() + 1 < use->getKeypart() || 
666
 
            ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
 
1705
        if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
667
1706
          continue;                             /* remove */
668
1707
      }
669
 
      else if (use->getKeypart() != 0)          // First found must be 0
 
1708
      else if (use->keypart != 0)               // First found must be 0
670
1709
        continue;
671
1710
 
672
1711
#ifdef HAVE_purify
675
1714
#endif
676
1715
        *save_pos= *use;
677
1716
      prev=use;
678
 
      found_eq_constant= ! use->getUsedTables();
 
1717
      found_eq_constant= !use->used_tables;
679
1718
      /* Save ptr to first use */
680
 
      if (! use->getTable()->reginfo.join_tab->keyuse)
681
 
        use->getTable()->reginfo.join_tab->keyuse= save_pos;
682
 
      use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
 
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);
683
1722
      save_pos++;
684
1723
    }
685
 
    i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
686
 
    set_dynamic(keyuse, (unsigned char*) &key_end, i);
687
 
    keyuse->elements= i;
 
1724
    i=(uint32_t) (save_pos-(KEYUSE*) keyuse->buffer);
 
1725
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
1726
    keyuse->elements=i;
688
1727
  }
689
1728
  return false;
690
1729
}
694
1733
*/
695
1734
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
696
1735
{
697
 
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
698
 
                                                  0, 
699
 
                                                  optimizer::KeyUse*);
 
1736
  KEYUSE *end,*keyuse= dynamic_element(keyuse_array, 0, KEYUSE*);
700
1737
 
701
1738
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
702
1739
  {
709
1746
      Constant tables are ignored.
710
1747
      To avoid bad matches, we don't make ref_table_rows less than 100.
711
1748
    */
712
 
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
713
 
    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)))
714
1751
    {
715
1752
      uint32_t tablenr;
716
1753
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
717
1754
      if (map == 1)                     // Only one table
718
1755
      {
719
1756
        Table *tmp_table=join->all_tables[tablenr];
720
 
        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);
721
1758
      }
722
1759
    }
723
1760
    /*
724
1761
      Outer reference (external field) is constant for single executing
725
1762
      of subquery
726
1763
    */
727
 
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
728
 
      keyuse->setTableRows(1);
 
1764
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
 
1765
      keyuse->ref_table_rows= 1;
729
1766
  }
730
1767
}
731
1768
 
747
1784
  @return
748
1785
    None
749
1786
*/
750
 
void add_group_and_distinct_keys(JOIN *join, JoinTable *join_tab)
 
1787
void add_group_and_distinct_keys(JOIN *join, JOIN_TAB *join_tab)
751
1788
{
752
1789
  List<Item_field> indexed_fields;
753
1790
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
788
1825
    join_tab->const_keys|= possible_keys;
789
1826
}
790
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
 
791
1871
/**
792
 
  Compare two JoinTable objects based on the number of accessed records.
 
1872
  Compare two JOIN_TAB objects based on the number of accessed records.
793
1873
 
794
 
  @param ptr1 pointer to first JoinTable object
795
 
  @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
796
1876
 
797
1877
  NOTES
798
1878
    The order relation implemented by join_tab_cmp() is not transitive,
814
1894
*/
815
1895
int join_tab_cmp(const void* ptr1, const void* ptr2)
816
1896
{
817
 
  JoinTable *jt1= *(JoinTable**) ptr1;
818
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
1897
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
1898
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
819
1899
 
820
1900
  if (jt1->dependent & jt2->table->map)
821
1901
    return 1;
833
1913
*/
834
1914
int join_tab_cmp_straight(const void* ptr1, const void* ptr2)
835
1915
{
836
 
  JoinTable *jt1= *(JoinTable**) ptr1;
837
 
  JoinTable *jt2= *(JoinTable**) ptr2;
 
1916
  JOIN_TAB *jt1= *(JOIN_TAB**) ptr1;
 
1917
  JOIN_TAB *jt2= *(JOIN_TAB**) ptr2;
838
1918
 
839
1919
  if (jt1->dependent & jt2->table->map)
840
1920
    return 1;
846
1926
/**
847
1927
  Find how much space the prevous read not const tables takes in cache.
848
1928
*/
849
 
void calc_used_field_length(Session *, JoinTable *join_tab)
 
1929
void calc_used_field_length(Session *, JOIN_TAB *join_tab)
850
1930
{
851
1931
  uint32_t null_fields,blobs,fields,rec_length;
852
1932
  Field **f_ptr,*field;
871
1951
    rec_length+=sizeof(bool);
872
1952
  if (blobs)
873
1953
  {
874
 
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
875
 
                                     (join_tab->table->getRecordLength()- rec_length));
876
 
    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);
877
1957
  }
878
1958
  join_tab->used_fields= fields;
879
1959
  join_tab->used_fieldlength= rec_length;
881
1961
}
882
1962
 
883
1963
StoredKey *get_store_key(Session *session,
884
 
                         optimizer::KeyUse *keyuse,
 
1964
                         KEYUSE *keyuse,
885
1965
                         table_map used_tables,
886
 
                         KEY_PART_INFO *key_part,
 
1966
                               KEY_PART_INFO *key_part,
887
1967
                         unsigned char *key_buff,
888
1968
                         uint32_t maybe_null)
889
1969
{
890
 
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
891
 
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
1970
  if (!((~used_tables) & keyuse->used_tables))          // if const item
892
1971
  {
893
1972
    return new store_key_const_item(session,
894
1973
                                    key_part->field,
895
1974
                                    key_buff + maybe_null,
896
1975
                                    maybe_null ? key_buff : 0,
897
1976
                                    key_part->length,
898
 
                                    key_use_val);
 
1977
                                    keyuse->val);
899
1978
  }
900
 
  else if (key_use_val->type() == Item::FIELD_ITEM ||
901
 
           (key_use_val->type() == Item::REF_ITEM &&
902
 
            key_use_val->ref_type() == Item_ref::OUTER_REF &&
903
 
            (*(Item_ref**)((Item_ref*)key_use_val)->ref)->ref_type() == Item_ref::DIRECT_REF &&
904
 
            key_use_val->real_item()->type() == Item::FIELD_ITEM))
905
 
  {
 
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))
906
1985
    return new store_key_field(session,
907
1986
                               key_part->field,
908
1987
                               key_buff + maybe_null,
909
1988
                               maybe_null ? key_buff : 0,
910
1989
                               key_part->length,
911
 
                               ((Item_field*) key_use_val->real_item())->field,
912
 
                               key_use_val->full_name());
913
 
  }
 
1990
                               ((Item_field*) keyuse->val->real_item())->field,
 
1991
                               keyuse->val->full_name());
914
1992
  return new store_key_item(session,
915
1993
                            key_part->field,
916
1994
                            key_buff + maybe_null,
917
1995
                            maybe_null ? key_buff : 0,
918
1996
                            key_part->length,
919
 
                            key_use_val);
 
1997
                            keyuse->val);
920
1998
}
921
1999
 
922
2000
/**
959
2037
    *e1= e2;
960
2038
}
961
2039
 
962
 
bool create_ref_for_key(JOIN *join, 
963
 
                        JoinTable *j, 
964
 
                        optimizer::KeyUse *org_keyuse,
965
 
                        table_map used_tables)
 
2040
bool create_ref_for_key(JOIN *join, JOIN_TAB *j, KEYUSE *org_keyuse,
 
2041
             table_map used_tables)
966
2042
{
967
 
  optimizer::KeyUse *keyuse= org_keyuse;
 
2043
  KEYUSE *keyuse=org_keyuse;
968
2044
  Session  *session= join->session;
969
 
  uint32_t keyparts;
970
 
  uint32_t length;
971
 
  uint32_t key;
972
 
  Table *table= NULL;
973
 
  KEY *keyinfo= NULL;
 
2045
  uint32_t keyparts,length,key;
 
2046
  Table *table;
 
2047
  KEY *keyinfo;
974
2048
 
975
2049
  /*  Use best key from find_best */
976
 
  table= j->table;
977
 
  key= keyuse->getKey();
978
 
  keyinfo= table->key_info + key;
 
2050
  table=j->table;
 
2051
  key=keyuse->key;
 
2052
  keyinfo=table->key_info+key;
979
2053
 
980
2054
  {
981
 
    keyparts= length= 0;
 
2055
    keyparts=length=0;
982
2056
    uint32_t found_part_ref_or_null= 0;
983
2057
    /*
984
2058
      Calculate length for the used key
987
2061
    */
988
2062
    do
989
2063
    {
990
 
      if (! (~used_tables & keyuse->getUsedTables()))
 
2064
      if (!(~used_tables & keyuse->used_tables))
991
2065
      {
992
 
        if (keyparts == keyuse->getKeypart() &&
993
 
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
 
2066
        if (keyparts == keyuse->keypart &&
 
2067
            !(found_part_ref_or_null & keyuse->optimize))
994
2068
        {
995
2069
          keyparts++;
996
 
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
997
 
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
 
2070
          length+= keyinfo->key_part[keyuse->keypart].store_length;
 
2071
          found_part_ref_or_null|= keyuse->optimize;
998
2072
        }
999
2073
      }
1000
2074
      keyuse++;
1001
 
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
 
2075
    } while (keyuse->table == table && keyuse->key == key);
1002
2076
  }
1003
2077
 
1004
2078
  /* set up fieldref */
1021
2095
  keyuse=org_keyuse;
1022
2096
 
1023
2097
  StoredKey **ref_key= j->ref.key_copy;
1024
 
  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;
1025
2099
  bool keyuse_uses_no_tables= true;
1026
2100
  {
1027
 
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
 
2101
    uint32_t i;
 
2102
    for (i=0 ; i < keyparts ; keyuse++,i++)
1028
2103
    {
1029
 
      while (keyuse->getKeypart() != i ||
1030
 
             ((~used_tables) & keyuse->getUsedTables()))
 
2104
      while (keyuse->keypart != i ||
 
2105
       ((~used_tables) & keyuse->used_tables))
1031
2106
        keyuse++;       /* Skip other parts */
1032
2107
 
1033
2108
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1034
 
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
1035
 
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
1036
 
      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)
1037
2112
        j->ref.null_rejecting |= 1 << i;
1038
 
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
1039
 
      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))
1040
2115
      {         // Compare against constant
1041
2116
        store_key_item tmp(session, keyinfo->key_part[i].field,
1042
2117
                           key_buff + maybe_null,
1043
2118
                           maybe_null ?  key_buff : 0,
1044
 
                           keyinfo->key_part[i].length, keyuse->getVal());
 
2119
                           keyinfo->key_part[i].length, keyuse->val);
1045
2120
        if (session->is_fatal_error)
1046
2121
          return(true);
1047
2122
        tmp.copy();
1053
2128
          key_buff, maybe_null);
1054
2129
      /*
1055
2130
        Remember if we are going to use REF_OR_NULL
1056
 
        But only if field _really_ can be null i.e. we force AM_REF
1057
 
        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
1058
2133
      */
1059
 
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
2134
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1060
2135
        null_ref_key= key_buff;
1061
2136
      key_buff+=keyinfo->key_part[i].store_length;
1062
2137
    }
1063
2138
  }
1064
 
  *ref_key= 0;       // end_marker
1065
 
  if (j->type == AM_CONST)
 
2139
  *ref_key=0;       // end_marker
 
2140
  if (j->type == JT_CONST)
1066
2141
    j->table->const_table= 1;
1067
2142
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1068
2143
           keyparts != keyinfo->key_parts || null_ref_key)
1069
2144
  {
1070
2145
    /* Must read with repeat */
1071
 
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
 
2146
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
1072
2147
    j->ref.null_ref_key= null_ref_key;
1073
2148
  }
1074
2149
  else if (keyuse_uses_no_tables)
1080
2155
      Here we should not mark the table as a 'const' as a field may
1081
2156
      have a 'normal' value or a NULL value.
1082
2157
    */
1083
 
    j->type= AM_CONST;
 
2158
    j->type=JT_CONST;
1084
2159
  }
1085
2160
  else
1086
 
    j->type= AM_EQ_REF;
1087
 
  return 0;
 
2161
    j->type=JT_EQ_REF;
 
2162
  return(0);
1088
2163
}
1089
2164
 
1090
2165
/**
1131
2206
 
1132
2207
    Implementation overview
1133
2208
      1. update_ref_and_keys() accumulates info about null-rejecting
1134
 
         predicates in in KeyField::null_rejecting
1135
 
      1.1 add_key_part saves these to KeyUse.
1136
 
      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.
1137
2212
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1138
 
         appropiate JoinTable members.
 
2213
         appropiate JOIN_TAB members.
1139
2214
*/
1140
2215
void add_not_null_conds(JOIN *join)
1141
2216
{
1142
 
  for (uint32_t i= join->const_tables; i < join->tables; i++)
 
2217
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1143
2218
  {
1144
 
    JoinTable *tab=join->join_tab+i;
1145
 
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1146
 
         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) &&
1147
2222
        !tab->table->maybe_null)
1148
2223
    {
1149
2224
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1154
2229
          Item *notnull;
1155
2230
          assert(item->type() == Item::FIELD_ITEM);
1156
2231
          Item_field *not_null_item= (Item_field*)item;
1157
 
          JoinTable *referred_tab= not_null_item->field->table->reginfo.join_tab;
 
2232
          JOIN_TAB *referred_tab= not_null_item->field->table->reginfo.join_tab;
1158
2233
          /*
1159
2234
            For UPDATE queries such as:
1160
2235
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1195
2270
    -  pointer to the guarded predicate, if success
1196
2271
    -  0, otherwise
1197
2272
*/
1198
 
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)
1199
2274
{
1200
2275
  COND *tmp;
1201
2276
  assert(cond != 0);
1232
2307
    true   Yes
1233
2308
    false  No
1234
2309
*/
1235
 
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
 
2310
bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
1236
2311
{
1237
2312
  if (item->const_item())
1238
2313
    return true;
1324
2399
  RETURN
1325
2400
    Index condition, or NULL if no condition could be inferred.
1326
2401
*/
1327
 
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
 
2402
Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
1328
2403
{
1329
2404
  if (!cond)
1330
2405
    return NULL;
1387
2462
}
1388
2463
 
1389
2464
 
1390
 
static Item *make_cond_remainder(Item *cond, bool exclude_index)
 
2465
Item *make_cond_remainder(Item *cond, bool exclude_index)
1391
2466
{
1392
2467
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
1393
2468
    return 0; /* Already checked */
1447
2522
  return cond;
1448
2523
}
1449
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
}
 
2587
 
1450
2588
/**
1451
 
  cleanup JoinTable.
 
2589
  cleanup JOIN_TAB.
1452
2590
*/
1453
 
void JoinTable::cleanup()
 
2591
void JOIN_TAB::cleanup()
1454
2592
{
1455
2593
  delete select;
1456
2594
  select= 0;
1465
2603
    if (table->key_read)
1466
2604
    {
1467
2605
      table->key_read= 0;
1468
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
2606
      table->file->extra(HA_EXTRA_NO_KEYREAD);
1469
2607
    }
1470
 
    table->cursor->ha_index_or_rnd_end();
 
2608
    table->file->ha_index_or_rnd_end();
1471
2609
    /*
1472
2610
      We need to reset this for next select
1473
2611
      (Tested in part_of_refkey)
1479
2617
 
1480
2618
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
1481
2619
{
1482
 
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
 
2620
  for (JOIN_TAB **tab=join->map2table ; tables ; tab++, tables>>=1)
1483
2621
  {
1484
2622
    if (tables & 1 && !eq_ref_table(join, order, *tab))
1485
2623
      return 0;
1488
2626
}
1489
2627
 
1490
2628
/**
1491
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
2629
  Remove the following expressions from order_st BY and GROUP BY:
1492
2630
  Constant expressions @n
1493
2631
  Expression that only uses tables that are of type EQ_REF and the reference
1494
2632
  is in the order_st list or if all refereed tables are of the above type.
1495
2633
 
1496
2634
  In the following, the X field can be removed:
1497
2635
  @code
1498
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
1499
 
  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
1500
2638
  @endcode
1501
2639
 
1502
2640
  These can't be optimized:
1503
2641
  @code
1504
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
1505
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
1506
 
  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
1507
2645
  @endcode
1508
2646
*/
1509
 
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
 
2647
bool eq_ref_table(JOIN *join, order_st *start_order, JOIN_TAB *tab)
1510
2648
{
1511
2649
  if (tab->cached_eq_ref_table)                 // If cached
1512
2650
    return tab->eq_ref_table;
1513
2651
  tab->cached_eq_ref_table=1;
1514
2652
  /* We can skip const tables only if not an outer table */
1515
 
  if (tab->type == AM_CONST && !tab->first_inner)
1516
 
    return (tab->eq_ref_table=1);
1517
 
  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)
1518
2656
    return (tab->eq_ref_table=0);               // We must use this
1519
2657
  Item **ref_item=tab->ref.items;
1520
2658
  Item **end=ref_item+tab->ref.key_parts;
1574
2712
    - Item_equal for the found multiple equality predicate if a success;
1575
2713
    - NULL otherwise.
1576
2714
*/
1577
 
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)
1578
2716
{
1579
2717
  Item_equal *item= 0;
1580
2718
  bool in_upper_level= false;
2217
3355
    can get more freedom in performing join operations.
2218
3356
    Althogh we don't use this property now, it probably makes sense to use
2219
3357
    it in the future.
2220
 
  @param session                      Thread Cursor
 
3358
  @param session                      Thread handler
2221
3359
  @param cond                condition to build the multiple equalities for
2222
3360
  @param inherited           path to all inherited multiple equality items
2223
3361
  @param join_list           list of join tables to which the condition
2318
3456
  }
2319
3457
  if (outer_ref)
2320
3458
    return cmp;
2321
 
  JoinTable **idx= (JoinTable **) table_join_idx;
 
3459
  JOIN_TAB **idx= (JOIN_TAB **) table_join_idx;
2322
3460
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2323
3461
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2324
3462
}
2539
3677
  @param cond       condition whose multiple equalities are to be checked
2540
3678
  @param table      constant table that has been read
2541
3679
*/
2542
 
static void update_const_equal_items(COND *cond, JoinTable *tab)
 
3680
static void update_const_equal_items(COND *cond, JOIN_TAB *tab)
2543
3681
{
2544
3682
  if (!(cond->used_tables() & tab->table->map))
2545
3683
    return;
2566
3704
      while ((item_field= it++))
2567
3705
      {
2568
3706
        Field *field= item_field->field;
2569
 
        JoinTable *stat= field->table->reginfo.join_tab;
 
3707
        JOIN_TAB *stat= field->table->reginfo.join_tab;
2570
3708
        key_map possible_keys= field->key_start;
2571
3709
        possible_keys&= field->table->keys_in_use_for_query;
2572
3710
        stat[0].const_keys|= possible_keys;
2579
3717
        if (possible_keys.any())
2580
3718
        {
2581
3719
          Table *field_tab= field->table;
2582
 
          optimizer::KeyUse *use;
2583
 
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
2584
 
            if (possible_keys.test(use->getKey()) &&
2585
 
                field_tab->key_info[use->getKey()].key_part[use->getKeypart()].field ==
 
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 ==
2586
3724
                field)
2587
 
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
3725
              field_tab->const_key_parts[use->key]|= use->keypart_map;
2588
3726
        }
2589
3727
      }
2590
3728
    }
2855
3993
  @retval
2856
3994
    true   Requested join order extension not allowed.
2857
3995
*/
2858
 
bool check_interleaving_with_nj(JoinTable *last_tab, JoinTable *next_tab)
 
3996
bool check_interleaving_with_nj(JOIN_TAB *last_tab, JOIN_TAB *next_tab)
2859
3997
{
2860
3998
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
2861
3999
  JOIN *join= last_tab->join;
2862
4000
 
2863
 
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
 
4001
  if (join->cur_embedding_map & ~next_tab->embedding_map)
2864
4002
  {
2865
4003
    /*
2866
4004
      next_tab is outside of the "pair of brackets" we're currently in.
2899
4037
  return false;
2900
4038
}
2901
4039
 
 
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
 
2902
4069
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
2903
4070
{
2904
4071
  Session *session= join->session;
2986
4153
          }
2987
4154
          break;
2988
4155
        case Item::COND_UNDEF:                  /* Impossible */
2989
 
          break;
 
4156
          break; /* purecov: deadcode */
2990
4157
      }
2991
4158
    }
2992
4159
 
3277
4444
{
3278
4445
  int rc= 0;
3279
4446
  enum_nested_loop_state error= NESTED_LOOP_OK;
3280
 
  JoinTable *join_tab= NULL;
 
4447
  JOIN_TAB *join_tab= NULL;
3281
4448
 
3282
4449
  join->tmp_table= table;                       /* Save for easy recursion */
3283
4450
  join->fields= fields;
3284
4451
 
3285
4452
  if (table)
3286
4453
  {
3287
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
 
4454
    table->file->extra(HA_EXTRA_WRITE_CACHE);
3288
4455
    table->emptyRecord();
3289
4456
    if (table->group && join->tmp_table_param.sum_func_count &&
3290
 
        table->s->keys && !table->cursor->inited)
3291
 
      table->cursor->ha_index_init(0, 0);
 
4457
        table->s->keys && !table->file->inited)
 
4458
      table->file->ha_index_init(0, 0);
3292
4459
  }
3293
4460
  /* Set up select_end */
3294
4461
  Next_select_func end_select= setup_end_select_func(join);
3360
4527
  if (table)
3361
4528
  {
3362
4529
    int tmp, new_errno= 0;
3363
 
    if ((tmp=table->cursor->extra(HA_EXTRA_NO_CACHE)))
 
4530
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
3364
4531
    {
3365
4532
      new_errno= tmp;
3366
4533
    }
3367
 
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
 
4534
    if ((tmp=table->file->ha_index_or_rnd_end()))
3368
4535
    {
3369
4536
      new_errno= tmp;
3370
4537
    }
3371
4538
    if (new_errno)
3372
 
      table->print_error(new_errno,MYF(0));
 
4539
      table->file->print_error(new_errno,MYF(0));
3373
4540
  }
3374
4541
  return(join->session->is_error() ? -1 : rc);
3375
4542
}
3376
4543
 
3377
 
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)
3378
4545
{
3379
4546
  enum_nested_loop_state rc;
3380
4547
 
3388
4555
  if (join->session->killed)            // If aborted by user
3389
4556
  {
3390
4557
    join->session->send_kill_message();
3391
 
    return NESTED_LOOP_KILLED;
 
4558
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
3392
4559
  }
3393
4560
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3394
4561
  {
3521
4688
  @return
3522
4689
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
3523
4690
*/
3524
 
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)
3525
4692
{
3526
4693
  join_tab->table->null_row=0;
3527
4694
  if (end_of_records)
3531
4698
  enum_nested_loop_state rc;
3532
4699
  READ_RECORD *info= &join_tab->read_record;
3533
4700
 
 
4701
  if (join_tab->flush_weedout_table)
 
4702
  {
 
4703
    do_sj_reset(join_tab->flush_weedout_table);
 
4704
  }
 
4705
 
3534
4706
  if (join->resume_nested_loop)
3535
4707
  {
3536
4708
    /* If not the last table, plunge down the nested loop */
3582
4754
  return rc;
3583
4755
}
3584
4756
 
3585
 
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)
3586
4768
{
3587
4769
  int error;
3588
4770
  Table *table= tab->table;
3589
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
4771
  if ((error=table->file->index_read_map(table->record[0],
3590
4772
                                         tab->ref.key_buff,
3591
4773
                                         make_prev_keypart_map(tab->ref.key_parts),
3592
4774
                                         HA_READ_KEY_EXACT)))
3594
4776
  return 0;
3595
4777
}
3596
4778
 
3597
 
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
 
4779
int join_read_const_table(JOIN_TAB *tab, POSITION *pos)
3598
4780
{
3599
4781
  int error;
3600
4782
  Table *table=tab->table;
3602
4784
  table->null_row=0;
3603
4785
  table->status=STATUS_NO_RECORD;
3604
4786
 
3605
 
  if (tab->type == AM_SYSTEM)
 
4787
  if (tab->type == JT_SYSTEM)
3606
4788
  {
3607
4789
    if ((error=join_read_system(tab)))
3608
4790
    {                                           // Info for DESCRIBE
3609
4791
      tab->info="const row not found";
3610
4792
      /* Mark for EXPLAIN that the row was not found */
3611
 
      pos->setFanout(0.0);
3612
 
      pos->clearRefDependMap();
3613
 
      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)
3614
4796
        return(error);
3615
4797
    }
3616
4798
  }
3617
4799
  else
3618
4800
  {
3619
 
    if (! table->key_read && 
 
4801
    if (!table->key_read && 
3620
4802
        table->covering_keys.test(tab->ref.key) && 
3621
 
        ! table->no_keyread &&
 
4803
        !table->no_keyread &&
3622
4804
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
3623
4805
    {
3624
4806
      table->key_read=1;
3625
 
      table->cursor->extra(HA_EXTRA_KEYREAD);
 
4807
      table->file->extra(HA_EXTRA_KEYREAD);
3626
4808
      tab->index= tab->ref.key;
3627
4809
    }
3628
4810
    error=join_read_const(tab);
3629
4811
    if (table->key_read)
3630
4812
    {
3631
4813
      table->key_read=0;
3632
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
4814
      table->file->extra(HA_EXTRA_NO_KEYREAD);
3633
4815
    }
3634
4816
    if (error)
3635
4817
    {
3636
4818
      tab->info="unique row not found";
3637
4819
      /* Mark for EXPLAIN that the row was not found */
3638
 
      pos->setFanout(0.0);
3639
 
      pos->clearRefDependMap();
 
4820
      pos->records_read=0.0;
 
4821
      pos->ref_depend_map= 0;
3640
4822
      if (!table->maybe_null || error > 0)
3641
4823
        return(error);
3642
4824
    }
3672
4854
  return(0);
3673
4855
}
3674
4856
 
3675
 
int join_read_system(JoinTable *tab)
 
4857
int join_read_system(JOIN_TAB *tab)
3676
4858
{
3677
4859
  Table *table= tab->table;
3678
4860
  int error;
3679
4861
  if (table->status & STATUS_GARBAGE)           // If first read
3680
4862
  {
3681
 
    if ((error=table->cursor->read_first_row(table->record[0],
 
4863
    if ((error=table->file->read_first_row(table->record[0],
3682
4864
                                           table->s->primary_key)))
3683
4865
    {
3684
4866
      if (error != HA_ERR_END_OF_FILE)
3707
4889
  @retval
3708
4890
    1   Got an error (other than row not found) during read
3709
4891
*/
3710
 
int join_read_const(JoinTable *tab)
 
4892
int join_read_const(JOIN_TAB *tab)
3711
4893
{
3712
4894
  int error;
3713
4895
  Table *table= tab->table;
3718
4900
      error= HA_ERR_KEY_NOT_FOUND;
3719
4901
    else
3720
4902
    {
3721
 
      error=table->cursor->index_read_idx_map(table->record[0],tab->ref.key,
 
4903
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
3722
4904
                                            (unsigned char*) tab->ref.key_buff,
3723
4905
                                            make_prev_keypart_map(tab->ref.key_parts),
3724
4906
                                            HA_READ_KEY_EXACT);
3748
4930
 
3749
4931
  SYNOPSIS
3750
4932
    join_read_key()
3751
 
      tab  JoinTable of the accessed table
 
4933
      tab  JOIN_TAB of the accessed table
3752
4934
 
3753
4935
  DESCRIPTION
3754
4936
    This is "read_fist" function for the "ref" access method. The difference
3759
4941
   -1  - Row not found
3760
4942
    1  - Error
3761
4943
*/
3762
 
int join_read_key(JoinTable *tab)
 
4944
int join_read_key(JOIN_TAB *tab)
3763
4945
{
3764
4946
  int error;
3765
4947
  Table *table= tab->table;
3766
4948
 
3767
 
  if (!table->cursor->inited)
 
4949
  if (!table->file->inited)
3768
4950
  {
3769
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
4951
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3770
4952
  }
3771
4953
 
3772
4954
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3778
4960
      table->status=STATUS_NOT_FOUND;
3779
4961
      return -1;
3780
4962
    }
3781
 
    error=table->cursor->index_read_map(table->record[0],
 
4963
    error=table->file->index_read_map(table->record[0],
3782
4964
                                      tab->ref.key_buff,
3783
4965
                                      make_prev_keypart_map(tab->ref.key_parts),
3784
4966
                                      HA_READ_KEY_EXACT);
3794
4976
 
3795
4977
  SYNOPSIS
3796
4978
    join_read_always_key()
3797
 
      tab  JoinTable of the accessed table
 
4979
      tab  JOIN_TAB of the accessed table
3798
4980
 
3799
4981
  DESCRIPTION
3800
4982
    This is "read_first" function for the "ref" access method.
3807
4989
   -1  - Row not found
3808
4990
    1  - Error
3809
4991
*/
3810
 
int join_read_always_key(JoinTable *tab)
 
4992
int join_read_always_key(JOIN_TAB *tab)
3811
4993
{
3812
4994
  int error;
3813
4995
  Table *table= tab->table;
3814
4996
 
3815
4997
  /* Initialize the index first */
3816
 
  if (!table->cursor->inited)
3817
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
4998
  if (!table->file->inited)
 
4999
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3818
5000
 
3819
5001
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3820
5002
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3825
5007
 
3826
5008
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3827
5009
    return -1;
3828
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
5010
  if ((error=table->file->index_read_map(table->record[0],
3829
5011
                                         tab->ref.key_buff,
3830
5012
                                         make_prev_keypart_map(tab->ref.key_parts),
3831
5013
                                         HA_READ_KEY_EXACT)))
3832
5014
  {
3833
5015
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3834
5016
      return table->report_error(error);
3835
 
    return -1;
 
5017
    return -1; /* purecov: inspected */
3836
5018
  }
3837
5019
 
3838
5020
  return 0;
3839
5021
}
3840
5022
 
3841
5023
/**
3842
 
  This function is used when optimizing away ORDER BY in
3843
 
  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.
3844
5026
*/
3845
 
int join_read_last_key(JoinTable *tab)
 
5027
int join_read_last_key(JOIN_TAB *tab)
3846
5028
{
3847
5029
  int error;
3848
5030
  Table *table= tab->table;
3849
5031
 
3850
 
  if (!table->cursor->inited)
3851
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
5032
  if (!table->file->inited)
 
5033
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3852
5034
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3853
5035
    return -1;
3854
 
  if ((error=table->cursor->index_read_last_map(table->record[0],
 
5036
  if ((error=table->file->index_read_last_map(table->record[0],
3855
5037
                                              tab->ref.key_buff,
3856
5038
                                              make_prev_keypart_map(tab->ref.key_parts))))
3857
5039
  {
3858
5040
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3859
5041
      return table->report_error(error);
3860
 
    return -1;
 
5042
    return -1; /* purecov: inspected */
3861
5043
  }
3862
5044
  return 0;
3863
5045
}
3870
5052
int join_read_next_same_diff(READ_RECORD *info)
3871
5053
{
3872
5054
  Table *table= info->table;
3873
 
  JoinTable *tab=table->reginfo.join_tab;
 
5055
  JOIN_TAB *tab=table->reginfo.join_tab;
3874
5056
  if (tab->insideout_match_tab->found_match)
3875
5057
  {
3876
5058
    KEY *key= tab->table->key_info + tab->index;
3880
5062
      /* Save index tuple from record to the buffer */
3881
5063
      key_copy(tab->insideout_buf, info->record, key, 0);
3882
5064
 
3883
 
      if ((error=table->cursor->index_next_same(table->record[0],
 
5065
      if ((error=table->file->index_next_same(table->record[0],
3884
5066
                                              tab->ref.key_buff,
3885
5067
                                              tab->ref.key_length)))
3886
5068
      {
3902
5084
{
3903
5085
  int error;
3904
5086
  Table *table= info->table;
3905
 
  JoinTable *tab=table->reginfo.join_tab;
 
5087
  JOIN_TAB *tab=table->reginfo.join_tab;
3906
5088
 
3907
 
  if ((error=table->cursor->index_next_same(table->record[0],
 
5089
  if ((error=table->file->index_next_same(table->record[0],
3908
5090
                                          tab->ref.key_buff,
3909
5091
                                          tab->ref.key_length)))
3910
5092
  {
3921
5103
{
3922
5104
  int error;
3923
5105
  Table *table= info->table;
3924
 
  JoinTable *tab=table->reginfo.join_tab;
 
5106
  JOIN_TAB *tab=table->reginfo.join_tab;
3925
5107
 
3926
 
  if ((error=table->cursor->index_prev(table->record[0])))
 
5108
  if ((error=table->file->index_prev(table->record[0])))
3927
5109
    return table->report_error(error);
3928
5110
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3929
5111
                      tab->ref.key_length))
3934
5116
  return error;
3935
5117
}
3936
5118
 
3937
 
int join_init_quick_read_record(JoinTable *tab)
 
5119
int join_init_quick_read_record(JOIN_TAB *tab)
3938
5120
{
3939
5121
  if (test_if_quick_select(tab) == -1)
3940
5122
    return -1;                                  /* No possible records */
3942
5124
}
3943
5125
 
3944
5126
int rr_sequential(READ_RECORD *info);
3945
 
int init_read_record_seq(JoinTable *tab)
 
5127
int init_read_record_seq(JOIN_TAB *tab)
3946
5128
{
3947
5129
  tab->read_record.read_record= rr_sequential;
3948
 
  if (tab->read_record.cursor->ha_rnd_init(1))
 
5130
  if (tab->read_record.file->ha_rnd_init(1))
3949
5131
    return 1;
3950
5132
  return (*tab->read_record.read_record)(&tab->read_record);
3951
5133
}
3952
5134
 
3953
 
int test_if_quick_select(JoinTable *tab)
 
5135
int test_if_quick_select(JOIN_TAB *tab)
3954
5136
{
3955
5137
  delete tab->select->quick;
3956
5138
  tab->select->quick= 0;
3958
5140
                                        (table_map) 0, HA_POS_ERROR, 0, false);
3959
5141
}
3960
5142
 
3961
 
int join_init_read_record(JoinTable *tab)
 
5143
int join_init_read_record(JOIN_TAB *tab)
3962
5144
{
3963
5145
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3964
5146
    return 1;
3967
5149
  return (*tab->read_record.read_record)(&tab->read_record);
3968
5150
}
3969
5151
 
3970
 
int join_read_first(JoinTable *tab)
 
5152
int join_read_first(JOIN_TAB *tab)
3971
5153
{
3972
5154
  int error;
3973
5155
  Table *table=tab->table;
3975
5157
      !table->no_keyread)
3976
5158
  {
3977
5159
    table->key_read=1;
3978
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
5160
    table->file->extra(HA_EXTRA_KEYREAD);
3979
5161
  }
3980
5162
  tab->table->status=0;
3981
5163
  tab->read_record.table=table;
3982
 
  tab->read_record.cursor=table->cursor;
 
5164
  tab->read_record.file=table->file;
3983
5165
  tab->read_record.index=tab->index;
3984
5166
  tab->read_record.record=table->record[0];
3985
5167
  if (tab->insideout_match_tab)
3994
5176
    tab->read_record.do_insideout_scan= 0;
3995
5177
  }
3996
5178
 
3997
 
  if (!table->cursor->inited)
3998
 
    table->cursor->ha_index_init(tab->index, tab->sorted);
3999
 
  if ((error=tab->table->cursor->index_first(tab->table->record[0])))
 
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])))
4000
5182
  {
4001
5183
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
4002
5184
      table->report_error(error);
4008
5190
 
4009
5191
int join_read_next_different(READ_RECORD *info)
4010
5192
{
4011
 
  JoinTable *tab= info->do_insideout_scan;
 
5193
  JOIN_TAB *tab= info->do_insideout_scan;
4012
5194
  if (tab->insideout_match_tab->found_match)
4013
5195
  {
4014
5196
    KEY *key= tab->table->key_info + tab->index;
4018
5200
      /* Save index tuple from record to the buffer */
4019
5201
      key_copy(tab->insideout_buf, info->record, key, 0);
4020
5202
 
4021
 
      if ((error=info->cursor->index_next(info->record)))
 
5203
      if ((error=info->file->index_next(info->record)))
4022
5204
        return info->table->report_error(error);
4023
5205
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
4024
5206
                      tab->insideout_buf, key->key_length));
4032
5214
int join_read_next(READ_RECORD *info)
4033
5215
{
4034
5216
  int error;
4035
 
  if ((error=info->cursor->index_next(info->record)))
 
5217
  if ((error=info->file->index_next(info->record)))
4036
5218
    return info->table->report_error(error);
4037
5219
  return 0;
4038
5220
}
4039
5221
 
4040
 
int join_read_last(JoinTable *tab)
 
5222
int join_read_last(JOIN_TAB *tab)
4041
5223
{
4042
5224
  Table *table=tab->table;
4043
5225
  int error;
4045
5227
      !table->no_keyread)
4046
5228
  {
4047
5229
    table->key_read=1;
4048
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
5230
    table->file->extra(HA_EXTRA_KEYREAD);
4049
5231
  }
4050
5232
  tab->table->status=0;
4051
5233
  tab->read_record.read_record=join_read_prev;
4052
5234
  tab->read_record.table=table;
4053
 
  tab->read_record.cursor=table->cursor;
 
5235
  tab->read_record.file=table->file;
4054
5236
  tab->read_record.index=tab->index;
4055
5237
  tab->read_record.record=table->record[0];
4056
 
  if (!table->cursor->inited)
4057
 
    table->cursor->ha_index_init(tab->index, 1);
4058
 
  if ((error= tab->table->cursor->index_last(tab->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])))
4059
5241
    return table->report_error(error);
4060
5242
 
4061
5243
  return 0;
4064
5246
int join_read_prev(READ_RECORD *info)
4065
5247
{
4066
5248
  int error;
4067
 
  if ((error= info->cursor->index_prev(info->record)))
 
5249
  if ((error= info->file->index_prev(info->record)))
4068
5250
    return info->table->report_error(error);
4069
5251
 
4070
5252
  return 0;
4073
5255
/**
4074
5256
  Reading of key with key reference and one part that may be NULL.
4075
5257
*/
4076
 
int join_read_always_key_or_null(JoinTable *tab)
 
5258
int join_read_always_key_or_null(JOIN_TAB *tab)
4077
5259
{
4078
5260
  int res;
4079
5261
 
4092
5274
  int error;
4093
5275
  if ((error= join_read_next_same(info)) >= 0)
4094
5276
    return error;
4095
 
  JoinTable *tab= info->table->reginfo.join_tab;
 
5277
  JOIN_TAB *tab= info->table->reginfo.join_tab;
4096
5278
 
4097
5279
  /* Test if we have already done a read after null key */
4098
5280
  if (*tab->ref.null_ref_key)
4101
5283
  return safe_index_read(tab);                  // then read null keys
4102
5284
}
4103
5285
 
4104
 
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)
4105
5287
{
4106
5288
  int idx= -1;
4107
5289
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
4141
5323
          }
4142
5324
        }
4143
5325
        if (error > 0)
4144
 
          return(NESTED_LOOP_ERROR);
 
5326
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
4145
5327
        if (end_of_records)
4146
5328
          return(NESTED_LOOP_OK);
4147
5329
        if (join->send_records >= join->unit->select_limit_cnt &&
4190
5372
  return(NESTED_LOOP_OK);
4191
5373
}
4192
5374
 
4193
 
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)
4194
5376
{
4195
5377
  Table *table=join->tmp_table;
4196
5378
  int     idx= -1;
4198
5380
  if (join->session->killed)
4199
5381
  {                                             // Aborted by user
4200
5382
    join->session->send_kill_message();
4201
 
    return NESTED_LOOP_KILLED;
 
5383
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
4202
5384
  }
4203
5385
  if (!join->first_record || end_of_records ||
4204
5386
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
4216
5398
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
4217
5399
        if (!join->having || join->having->val_int())
4218
5400
        {
4219
 
          int error= table->cursor->ha_write_row(table->record[0]);
 
5401
          int error= table->file->ha_write_row(table->record[0]);
4220
5402
          if (error && create_myisam_from_heap(join->session, table,
4221
5403
                                              join->tmp_table_param.start_recinfo,
4222
5404
                                                &join->tmp_table_param.recinfo,
4356
5538
      /* Create new top level AND item */
4357
5539
      Item_cond_and *new_cond=new Item_cond_and;
4358
5540
      if (!new_cond)
4359
 
        return (COND*) 0;
 
5541
        return (COND*) 0;                       // OOM /* purecov: inspected */
4360
5542
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4361
5543
      Item *item;
4362
5544
      while ((item=li++))
4386
5568
    {                                           // Or list
4387
5569
      Item_cond_or *new_cond=new Item_cond_or;
4388
5570
      if (!new_cond)
4389
 
        return (COND*) 0;
 
5571
        return (COND*) 0;                       // OOM /* purecov: inspected */
4390
5572
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4391
5573
      Item *item;
4392
5574
      while ((item=li++))
4494
5676
*/
4495
5677
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
4496
5678
{
4497
 
  KEY_PART_INFO *key_part= NULL;
4498
 
  KEY_PART_INFO *key_part_end= NULL;
4499
 
  key_part= table->key_info[idx].key_part;
4500
 
  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;
4501
5682
  key_part_map const_key_parts=table->const_key_parts[idx];
4502
 
  int reverse= 0;
 
5683
  int reverse=0;
4503
5684
  bool on_primary_key= false;
4504
5685
 
4505
5686
  for (; order ; order=order->next, const_key_parts>>=1)
4509
5690
 
4510
5691
    /*
4511
5692
      Skip key parts that are constants in the WHERE clause.
4512
 
      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()
4513
5694
    */
4514
5695
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4515
5696
      key_part++;
4522
5703
        the primary key as a suffix.
4523
5704
      */
4524
5705
      if (!on_primary_key &&
4525
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
 
5706
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
4526
5707
          table->s->primary_key != MAX_KEY)
4527
5708
      {
4528
5709
        on_primary_key= true;
4556
5737
  }
4557
5738
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4558
5739
    (uint32_t) (key_part - table->key_info[idx].key_part);
4559
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
5740
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
4560
5741
                         HA_READ_PREV))
4561
5742
    reverse= 0;                                 // Index can't be used
4562
5743
  return(reverse);
4579
5760
*/
4580
5761
inline bool is_subkey(KEY_PART_INFO *key_part,
4581
5762
                      KEY_PART_INFO *ref_key_part,
4582
 
                      KEY_PART_INFO *ref_key_part_end)
 
5763
                            KEY_PART_INFO *ref_key_part_end)
4583
5764
{
4584
5765
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4585
 
    if (! key_part->field->eq(ref_key_part->field))
 
5766
    if (!key_part->field->eq(ref_key_part->field))
4586
5767
      return 0;
4587
5768
  return 1;
4588
5769
}
4602
5783
                               Table *table,
4603
5784
                               uint32_t ref,
4604
5785
                               uint32_t ref_key_parts,
4605
 
                               const key_map *usable_keys)
 
5786
                                     const key_map *usable_keys)
4606
5787
{
4607
5788
  uint32_t nr;
4608
5789
  uint32_t min_length= UINT32_MAX;
4666
5847
         (table->key_info[keynr].flags & HA_NOSAME))
4667
5848
    {
4668
5849
      KEY *keyinfo= table->key_info + keynr;
4669
 
      KEY_PART_INFO *key_part= NULL;
4670
 
      KEY_PART_INFO *key_part_end= NULL;
 
5850
      KEY_PART_INFO *key_part, *key_part_end;
4671
5851
 
4672
5852
      for (key_part=keyinfo->key_part,
4673
5853
           key_part_end=key_part+ keyinfo->key_parts;
4675
5855
           key_part++)
4676
5856
      {
4677
5857
        if (key_part->field->maybe_null() ||
4678
 
            ! find_func(key_part->field, data))
 
5858
            !find_func(key_part->field, data))
4679
5859
          break;
4680
5860
      }
4681
5861
      if (key_part == key_part_end)
4748
5928
}
4749
5929
 
4750
5930
/**
4751
 
  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.
4752
5932
 
4753
5933
  SYNOPSIS
4754
5934
    test_if_skip_sort_order()
4758
5938
      no_changes
4759
5939
      map
4760
5940
 
4761
 
  If we can use an index, the JoinTable / tab->select struct
 
5941
  If we can use an index, the JOIN_TAB / tab->select struct
4762
5942
  is changed to use the index.
4763
5943
 
4764
5944
  The index must cover all fields in <order>, or it will not be considered.
4772
5952
  @retval
4773
5953
    1    We can use an index.
4774
5954
*/
4775
 
bool test_if_skip_sort_order(JoinTable *tab, order_st *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)
4776
5956
{
4777
5957
  int32_t ref_key;
4778
5958
  uint32_t ref_key_parts;
4779
5959
  int order_direction;
4780
5960
  uint32_t used_key_parts;
4781
5961
  Table *table=tab->table;
4782
 
  optimizer::SqlSelect *select= tab->select;
 
5962
  SQL_SELECT *select=tab->select;
4783
5963
  key_map usable_keys;
4784
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
5964
  QUICK_SELECT_I *save_quick= 0;
4785
5965
 
4786
5966
  /*
4787
5967
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4808
5988
  {
4809
5989
    ref_key=       tab->ref.key;
4810
5990
    ref_key_parts= tab->ref.key_parts;
4811
 
    if (tab->type == AM_REF_OR_NULL)
 
5991
    if (tab->type == JT_REF_OR_NULL)
4812
5992
      return(0);
4813
5993
  }
4814
 
  else if (select && select->quick)             // Range found by optimizer/range
 
5994
  else if (select && select->quick)             // Range found by opt_range
4815
5995
  {
4816
5996
    int quick_type= select->quick->get_type();
4817
5997
    save_quick= select->quick;
4821
6001
      by clustered PK values.
4822
6002
    */
4823
6003
 
4824
 
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4825
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4826
 
        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)
4827
6007
      return(0);
4828
6008
    ref_key=       select->quick->index;
4829
6009
    ref_key_parts= select->quick->used_key_parts;
4862
6042
            "part1 = const1 AND part2=const2".
4863
6043
            So we build tab->ref from scratch here.
4864
6044
          */
4865
 
          optimizer::KeyUse *keyuse= tab->keyuse;
4866
 
          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)
4867
6047
            keyuse++;
4868
6048
 
4869
6049
          if (create_ref_for_key(tab->join, tab, keyuse,
4873
6053
        else
4874
6054
        {
4875
6055
          /*
4876
 
            The range optimizer constructed QuickRange for ref_key, and
 
6056
            The range optimizer constructed QUICK_RANGE for ref_key, and
4877
6057
            we want to use instead new_ref_key as the index. We can't
4878
6058
            just change the index of the quick select, because this may
4879
6059
            result in an incosistent QUICK_SELECT object. Below we
4920
6100
    double fanout= 1;
4921
6101
    JOIN *join= tab->join;
4922
6102
    uint32_t tablenr= tab - join->join_tab;
4923
 
    ha_rows table_records= table->cursor->stats.records;
 
6103
    ha_rows table_records= table->file->stats.records;
4924
6104
    bool group= join->group && order == join->group_list;
4925
 
    optimizer::Position cur_pos;
4926
6105
 
4927
6106
    /*
4928
6107
      If not used with LIMIT, only use keys if the whole query can be
4935
6114
        filesort() and join cache are usually faster than reading in
4936
6115
        index order and not using join cache
4937
6116
        */
4938
 
      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)
4939
6118
        return(0);
4940
 
      keys= *table->cursor->keys_to_use_for_scanning();
 
6119
      keys= *table->file->keys_to_use_for_scanning();
4941
6120
      keys|= table->covering_keys;
4942
6121
 
4943
6122
      /*
4953
6132
    else
4954
6133
      keys= usable_keys;
4955
6134
 
4956
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4957
 
    read_time= cur_pos.getCost();
 
6135
    read_time= join->best_positions[tablenr].read_time;
4958
6136
    for (uint32_t i= tablenr+1; i < join->tables; i++)
4959
 
    {
4960
 
      cur_pos= join->getPosFromOptimalPlan(i);
4961
 
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
4962
 
    }
 
6137
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
4963
6138
 
4964
6139
    for (nr=0; nr < table->s->keys ; nr++)
4965
6140
    {
4967
6142
      if (keys.test(nr) &&
4968
6143
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4969
6144
      {
4970
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && 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());
4971
6146
 
4972
6147
        /*
4973
 
          Don't use an index scan with ORDER BY without limit.
 
6148
          Don't use an index scan with order_st BY without limit.
4974
6149
          For GROUP BY without limit always use index scan
4975
6150
          if there is a suitable index.
4976
6151
          Why we hold to this asymmetry hardly can be explained
5037
6212
            Rows in such a sequence are supposed to be ordered
5038
6213
            by rowid/primary key. When reading the data
5039
6214
            in a sequence we'll touch not more pages than the
5040
 
            table cursor contains.
 
6215
            table file contains.
5041
6216
            TODO. Use the formula for a disk sweep sequential access
5042
6217
            to calculate the cost of accessing data rows for one
5043
6218
            index entry.
5044
6219
          */
5045
6220
          index_scan_time= select_limit/rec_per_key *
5046
 
                           min(rec_per_key, table->cursor->scan_time());
 
6221
                           cmin(rec_per_key, table->file->scan_time());
5047
6222
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
5048
6223
              index_scan_time < read_time)
5049
6224
          {
5053
6228
            if (table->quick_keys.test(nr))
5054
6229
              quick_records= table->quick_rows[nr];
5055
6230
            if (best_key < 0 ||
5056
 
                (select_limit <= min(quick_records,best_records) ?
 
6231
                (select_limit <= cmin(quick_records,best_records) ?
5057
6232
                 keyinfo->key_parts < best_key_parts :
5058
6233
                 quick_records < best_records))
5059
6234
            {
5089
6264
          tab->index= best_key;
5090
6265
          tab->read_first_record= best_key_direction > 0 ?
5091
6266
                                  join_read_first:join_read_last;
5092
 
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
 
6267
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
5093
6268
          if (select && select->quick)
5094
6269
          {
5095
6270
            delete select->quick;
5098
6273
          if (table->covering_keys.test(best_key))
5099
6274
          {
5100
6275
            table->key_read=1;
5101
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
6276
            table->file->extra(HA_EXTRA_KEYREAD);
5102
6277
          }
5103
 
          table->cursor->ha_index_or_rnd_end();
 
6278
          table->file->ha_index_or_rnd_end();
5104
6279
          if (join->select_options & SELECT_DESCRIBE)
5105
6280
          {
5106
6281
            tab->ref.key= -1;
5109
6284
              tab->limit= select_limit;
5110
6285
          }
5111
6286
        }
5112
 
        else if (tab->type != AM_ALL)
 
6287
        else if (tab->type != JT_ALL)
5113
6288
        {
5114
6289
          /*
5115
6290
            We're about to use a quick access to the table.
5117
6292
            method is actually used.
5118
6293
          */
5119
6294
          assert(tab->select->quick);
5120
 
          tab->type= AM_ALL;
 
6295
          tab->type=JT_ALL;
5121
6296
          tab->use_quick=1;
5122
6297
          tab->ref.key= -1;
5123
6298
          tab->ref.key_parts=0;         // Don't use ref key.
5124
6299
          tab->read_first_record= join_init_read_record;
 
6300
          /*
 
6301
            TODO: update the number of records in join->best_positions[tablenr]
 
6302
          */
5125
6303
        }
5126
6304
      }
5127
6305
      used_key_parts= best_key_parts;
5132
6310
  }
5133
6311
 
5134
6312
check_reverse_order:
5135
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
6313
  if (order_direction == -1)            // If order_st BY ... DESC
5136
6314
  {
5137
6315
    if (select && select->quick)
5138
6316
    {
5140
6318
        Don't reverse the sort order, if it's already done.
5141
6319
        (In some cases test_if_order_by_key() can be called multiple times
5142
6320
      */
5143
 
      if (! select->quick->reverse_sorted())
 
6321
      if (!select->quick->reverse_sorted())
5144
6322
      {
5145
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
6323
        QUICK_SELECT_DESC *tmp;
5146
6324
        bool error= false;
5147
6325
        int quick_type= select->quick->get_type();
5148
 
        if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
5149
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT ||
5150
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
5151
 
            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)
5152
6330
        {
5153
6331
          tab->limit= 0;
5154
6332
          select->quick= save_quick;
5155
 
          return 0; // Use filesort
 
6333
          return(0);                   // Use filesort
5156
6334
        }
5157
6335
 
5158
 
        /* ORDER BY range_key DESC */
5159
 
        tmp= new optimizer::QuickSelectDescending((optimizer::QuickRangeSelect*)(select->quick),
5160
 
                                                  used_key_parts, 
5161
 
                                                  &error);
5162
 
        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)
5163
6340
        {
5164
6341
          delete tmp;
5165
 
          select->quick= save_quick;
5166
 
          tab->limit= 0;
5167
 
          return 0; // Reverse sort not supported
 
6342
                select->quick= save_quick;
 
6343
                tab->limit= 0;
 
6344
          return(0);            // Reverse sort not supported
5168
6345
        }
5169
6346
        select->quick=tmp;
5170
6347
      }
5171
6348
    }
5172
 
    else if (tab->type != AM_NEXT &&
 
6349
    else if (tab->type != JT_NEXT &&
5173
6350
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
5174
6351
    {
5175
6352
      /*
5176
 
        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
5177
6354
 
5178
6355
        Use a traversal function that starts by reading the last row
5179
6356
        with key part (A) and then traverse the index backwards.
5184
6361
  }
5185
6362
  else if (select && select->quick)
5186
6363
    select->quick->sorted= 1;
5187
 
  return 1;
 
6364
  return(1);
5188
6365
}
5189
6366
 
5190
6367
/*
5192
6369
 
5193
6370
  SYNOPSIS
5194
6371
   create_sort_index()
5195
 
     session            Thread Cursor
 
6372
     session            Thread handler
5196
6373
     tab                Table to sort (in join structure)
5197
6374
     order              How table should be sorted
5198
6375
     filesort_limit     Max number of rows that needs to be sorted
5205
6382
  IMPLEMENTATION
5206
6383
   - If there is an index that can be used, 'tab' is modified to use
5207
6384
     this index.
5208
 
   - 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
5209
6386
     retrieve rows in order (should be done with 'read_record').
5210
6387
     The sorted data is stored in tab->table and will be freed when calling
5211
 
     tab->table->free_io_cache().
 
6388
     free_io_cache(tab->table).
5212
6389
 
5213
6390
  RETURN VALUES
5214
6391
    0           ok
5220
6397
  uint32_t length= 0;
5221
6398
  ha_rows examined_rows;
5222
6399
  Table *table;
5223
 
  optimizer::SqlSelect *select= NULL;
5224
 
  JoinTable *tab;
 
6400
  SQL_SELECT *select;
 
6401
  JOIN_TAB *tab;
5225
6402
 
5226
6403
  if (join->tables == join->const_tables)
5227
6404
    return(0);                          // One row, no need to sort
5237
6414
  */
5238
6415
  if ((order != join->group_list ||
5239
6416
       !(join->select_options & SELECT_BIG_RESULT) ||
5240
 
       (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))) &&
5241
6418
      test_if_skip_sort_order(tab,order,select_limit,0,
5242
6419
                              is_order_by ?  &table->keys_in_use_for_order_by :
5243
6420
                              &table->keys_in_use_for_group_by))
5246
6423
    length++;
5247
6424
  if (!(join->sortorder=
5248
6425
        make_unireg_sortorder(order, &length, join->sortorder)))
5249
 
    goto err;
 
6426
    goto err;                           /* purecov: inspected */
5250
6427
 
5251
 
  table->sort.io_cache= new internal::IO_CACHE;
5252
 
  memset(table->sort.io_cache, 0, sizeof(internal::IO_CACHE));
 
6428
  table->sort.io_cache= new IO_CACHE;
 
6429
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
5253
6430
  table->status=0;                              // May be wrong if quick_select
5254
6431
 
5255
6432
  // If table has a range, move it to select
5266
6443
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
5267
6444
      {
5268
6445
        table->key_read=0;
5269
 
        table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
6446
        table->file->extra(HA_EXTRA_NO_KEYREAD);
5270
6447
      }
5271
6448
    }
5272
6449
    else
5277
6454
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5278
6455
        field, quick will contain an empty record set.
5279
6456
      */
5280
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
5281
 
                                                                 table, 
5282
 
                                                                 &tab->ref,
5283
 
                                                                 tab->found_records))))
5284
 
      {
 
6457
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
6458
                                                     tab->found_records))))
5285
6459
        goto err;
5286
 
      }
5287
6460
    }
5288
6461
  }
5289
6462
 
 
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;
 
6467
 
5290
6468
  if (table->s->tmp_table)
5291
 
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
 
6469
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
5292
6470
  table->sort.found_records=filesort(session, table,join->sortorder, length,
5293
6471
                                     select, filesort_limit, 0,
5294
6472
                                     &examined_rows);
5301
6479
  tab->select_cond=0;
5302
6480
  tab->last_inner= 0;
5303
6481
  tab->first_unmatched= 0;
5304
 
  tab->type= AM_ALL;                            // Read with normal read_record
 
6482
  tab->type=JT_ALL;                             // Read with normal read_record
5305
6483
  tab->read_first_record= join_init_read_record;
5306
6484
  tab->join->examined_rows+=examined_rows;
5307
6485
  if (table->key_read)                          // Restore if we used indexes
5308
6486
  {
5309
6487
    table->key_read=0;
5310
 
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
6488
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5311
6489
  }
5312
6490
  return(table->sort.found_records == HA_POS_ERROR);
5313
6491
err:
5316
6494
 
5317
6495
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5318
6496
{
5319
 
  Cursor *cursor=table->cursor;
 
6497
  handler *file=table->file;
5320
6498
  char *org_record,*new_record;
5321
6499
  unsigned char *record;
5322
6500
  int error;
5325
6503
  org_record=(char*) (record=table->record[0])+offset;
5326
6504
  new_record=(char*) table->record[1]+offset;
5327
6505
 
5328
 
  cursor->ha_rnd_init(1);
5329
 
  error=cursor->rnd_next(record);
 
6506
  file->ha_rnd_init(1);
 
6507
  error=file->rnd_next(record);
5330
6508
  for (;;)
5331
6509
  {
5332
6510
    if (session->killed)
5345
6523
    }
5346
6524
    if (having && !having->val_int())
5347
6525
    {
5348
 
      if ((error=cursor->ha_delete_row(record)))
 
6526
      if ((error=file->ha_delete_row(record)))
5349
6527
        goto err;
5350
 
      error=cursor->rnd_next(record);
 
6528
      error=file->rnd_next(record);
5351
6529
      continue;
5352
6530
    }
5353
6531
    if (copy_blobs(first_field))
5358
6536
    }
5359
6537
    memcpy(new_record,org_record,reclength);
5360
6538
 
5361
 
    /* Read through rest of cursor and mark duplicated rows deleted */
 
6539
    /* Read through rest of file and mark duplicated rows deleted */
5362
6540
    bool found=0;
5363
6541
    for (;;)
5364
6542
    {
5365
 
      if ((error=cursor->rnd_next(record)))
 
6543
      if ((error=file->rnd_next(record)))
5366
6544
      {
5367
6545
        if (error == HA_ERR_RECORD_DELETED)
5368
6546
          continue;
5372
6550
      }
5373
6551
      if (table->compare_record(first_field) == 0)
5374
6552
      {
5375
 
        if ((error=cursor->ha_delete_row(record)))
 
6553
        if ((error=file->ha_delete_row(record)))
5376
6554
          goto err;
5377
6555
      }
5378
6556
      else if (!found)
5379
6557
      {
5380
6558
        found= 1;
5381
 
        cursor->position(record);       // Remember position
 
6559
        file->position(record); // Remember position
5382
6560
      }
5383
6561
    }
5384
6562
    if (!found)
5385
 
      break;                                    // End of cursor
 
6563
      break;                                    // End of file
5386
6564
    /* Restart search on next row */
5387
 
    error=cursor->restart_rnd_next(record,cursor->ref);
 
6565
    error=file->restart_rnd_next(record,file->ref);
5388
6566
  }
5389
6567
 
5390
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6568
  file->extra(HA_EXTRA_NO_CACHE);
5391
6569
  return(0);
5392
6570
err:
5393
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6571
  file->extra(HA_EXTRA_NO_CACHE);
5394
6572
  if (error)
5395
 
    table->print_error(error,MYF(0));
 
6573
    file->print_error(error,MYF(0));
5396
6574
  return(1);
5397
6575
}
5398
6576
 
5411
6589
{
5412
6590
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5413
6591
  int error;
5414
 
  Cursor *cursor= table->cursor;
 
6592
  handler *file= table->file;
5415
6593
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5416
6594
  uint32_t *field_lengths,*field_length;
5417
6595
  HASH hash;
5418
6596
 
5419
 
  if (! memory::multi_malloc(false,
 
6597
  if (!my_multi_malloc(MYF(MY_WME),
5420
6598
                       &key_buffer,
5421
6599
                       (uint32_t) ((key_length + extra_length) *
5422
 
                               (long) cursor->stats.records),
 
6600
                               (long) file->stats.records),
5423
6601
                       &field_lengths,
5424
6602
                       (uint32_t) (field_count*sizeof(*field_lengths)),
5425
6603
                       NULL))
5439
6617
    extra_length= ALIGN_SIZE(key_length)-key_length;
5440
6618
  }
5441
6619
 
5442
 
  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,
5443
6621
                key_length, (hash_get_key) 0, 0, 0))
5444
6622
  {
5445
6623
    free((char*) key_buffer);
5446
6624
    return(1);
5447
6625
  }
5448
6626
 
5449
 
  cursor->ha_rnd_init(1);
 
6627
  file->ha_rnd_init(1);
5450
6628
  key_pos=key_buffer;
5451
6629
  for (;;)
5452
6630
  {
5457
6635
      error=0;
5458
6636
      goto err;
5459
6637
    }
5460
 
    if ((error=cursor->rnd_next(record)))
 
6638
    if ((error=file->rnd_next(record)))
5461
6639
    {
5462
6640
      if (error == HA_ERR_RECORD_DELETED)
5463
6641
        continue;
5467
6645
    }
5468
6646
    if (having && !having->val_int())
5469
6647
    {
5470
 
      if ((error=cursor->ha_delete_row(record)))
 
6648
      if ((error=file->ha_delete_row(record)))
5471
6649
        goto err;
5472
6650
      continue;
5473
6651
    }
5484
6662
    if (hash_search(&hash, org_key_pos, key_length))
5485
6663
    {
5486
6664
      /* Duplicated found ; Remove the row */
5487
 
      if ((error=cursor->ha_delete_row(record)))
 
6665
      if ((error=file->ha_delete_row(record)))
5488
6666
        goto err;
5489
6667
    }
5490
6668
    else
5493
6671
  }
5494
6672
  free((char*) key_buffer);
5495
6673
  hash_free(&hash);
5496
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5497
 
  (void) cursor->ha_rnd_end();
 
6674
  file->extra(HA_EXTRA_NO_CACHE);
 
6675
  (void) file->ha_rnd_end();
5498
6676
  return(0);
5499
6677
 
5500
6678
err:
5501
6679
  free((char*) key_buffer);
5502
6680
  hash_free(&hash);
5503
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5504
 
  (void) cursor->ha_rnd_end();
 
6681
  file->extra(HA_EXTRA_NO_CACHE);
 
6682
  (void) file->ha_rnd_end();
5505
6683
  if (error)
5506
 
    table->print_error(error,MYF(0));
 
6684
    file->print_error(error,MYF(0));
5507
6685
  return(1);
5508
6686
}
5509
6687
 
5516
6694
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5517
6695
    count++;
5518
6696
  if (!sortorder)
5519
 
    sortorder= (SORT_FIELD*) memory::sql_alloc(sizeof(SORT_FIELD) *
5520
 
                                       (max(count, *length) + 1));
 
6697
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
 
6698
                                       (cmax(count, *length) + 1));
5521
6699
  pos= sort= sortorder;
5522
6700
 
5523
6701
  if (!pos)
5543
6721
  return(sort);
5544
6722
}
5545
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
 
5546
6771
/*
5547
6772
  eq_ref: Create the lookup key and check if it is the same as saved key
5548
6773
 
5561
6786
    false  The created key is the same as the previous one (and the record
5562
6787
           is already in table->record)
5563
6788
*/
5564
 
static bool cmp_buffer_with_ref(JoinTable *tab)
 
6789
static bool cmp_buffer_with_ref(JOIN_TAB *tab)
5565
6790
{
5566
6791
  bool no_prev_key;
5567
6792
  if (!tab->ref.disable_cache)
5581
6806
    != 0;
5582
6807
}
5583
6808
 
5584
 
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
 
6809
bool cp_buffer_from_ref(Session *session, TABLE_REF *ref)
5585
6810
{
5586
6811
  enum enum_check_fields save_count_cuted_fields= session->count_cuted_fields;
5587
6812
  session->count_cuted_fields= CHECK_FIELD_IGNORE;
5604
6829
*****************************************************************************/
5605
6830
 
5606
6831
/**
5607
 
  Resolve an ORDER BY or GROUP BY column reference.
 
6832
  Resolve an order_st BY or GROUP BY column reference.
5608
6833
 
5609
6834
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5610
6835
  BY clause, find the actual column it represents. If the column being
5611
6836
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5612
6837
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
5613
 
  the ORDER BY clause, only the SELECT list is being searched.
 
6838
  the order_st BY clause, only the SELECT list is being searched.
5614
6839
 
5615
6840
  If 'order' is resolved to an Item, then order->item is set to the found
5616
6841
  Item. If there is no item for the found column (that is, it was resolved
5696
6921
        order_item_type == Item::REF_ITEM)
5697
6922
    {
5698
6923
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5699
 
                                       NULL, &view_ref, IGNORE_ERRORS, false);
 
6924
                                       NULL, &view_ref, IGNORE_ERRORS, true,
 
6925
                                       false);
5700
6926
      if (!from_field)
5701
6927
        from_field= (Field*) not_found_field;
5702
6928
    }
5792
7018
/**
5793
7019
  Intitialize the GROUP BY list.
5794
7020
 
5795
 
  @param session                        Thread Cursor
 
7021
  @param session                        Thread handler
5796
7022
  @param ref_pointer_array      We store references to all fields that was
5797
7023
                               not in 'fields' here.
5798
7024
  @param fields         All fields in the select part. Any item in
6151
7377
                another extra byte to not get warnings from purify in
6152
7378
                Field_varstring::val_int
6153
7379
              */
6154
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
 
7380
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
6155
7381
          goto err;
6156
7382
        if (copy)
6157
7383
        {
6197
7423
    itr++;
6198
7424
  itr.sublist(res_selected_fields, elements);
6199
7425
  /*
6200
 
    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
6201
7427
    reference used in these will resolve to a item that is already calculated
6202
7428
  */
6203
7429
  param->copy_funcs.concat(&extra_funcs);
6362
7588
/**
6363
7589
  Call ::setup for all sum functions.
6364
7590
 
6365
 
  @param session           thread Cursor
 
7591
  @param session           thread handler
6366
7592
  @param func_ptr      sum function list
6367
7593
 
6368
7594
  @retval
6537
7763
  return 0;
6538
7764
}
6539
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
}
6540
8317
 
6541
8318
static void print_table_array(Session *session, String *str, TableList **table,
6542
8319
                              TableList **end)
6553
8330
    }
6554
8331
    else if (curr->straight)
6555
8332
      str->append(STRING_WITH_LEN(" straight_join "));
 
8333
    else if (curr->sj_inner_tables)
 
8334
      str->append(STRING_WITH_LEN(" semi join "));
6556
8335
    else
6557
8336
      str->append(STRING_WITH_LEN(" join "));
6558
8337
    curr->print(session, str, QT_ORDINARY);
6567
8346
 
6568
8347
/**
6569
8348
  Print joins from the FROM clause.
6570
 
  @param session     thread Cursor
 
8349
  @param session     thread handler
6571
8350
  @param str     string where table should be printed
6572
8351
  @param tables  list of tables in join
6573
8352
  @query_type    type of the query is being generated
6584
8363
 
6585
8364
  for (TableList **t= table + (tables->elements - 1); t >= table; t--)
6586
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
  }
6587
8385
  assert(tables->elements >= 1);
6588
8386
  print_table_array(session, str, table, table + tables->elements);
6589
8387
}
6702
8500
/**
6703
8501
  @} (end of group Query_Optimizer)
6704
8502
*/
6705
 
 
6706
 
} /* namespace drizzled */