~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Padraig O'Sullivan
  • Date: 2009-08-08 04:22:33 UTC
  • mto: (1115.3.4 captain)
  • mto: This revision was merged to the branch mainline in revision 1117.
  • Revision ID: osullivan.padraig@gmail.com-20090808042233-q0z88zc490z3f3r7
Renamed the Command class to be Statement. Renamed the command directory to
statement and also the command header file to statement. Updated various
source files to reflect this renaming.

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/table_map_iterator.h"
33
28
 
34
29
#include "drizzled/error.h"
35
30
#include "drizzled/gettext.h"
38
33
#include "drizzled/nested_join.h"
39
34
#include "drizzled/probes.h"
40
35
#include "drizzled/show.h"
 
36
#include "drizzled/info_schema.h"
41
37
#include "drizzled/item/cache.h"
42
38
#include "drizzled/item/cmpfunc.h"
43
39
#include "drizzled/item/copy_string.h"
49
45
#include "drizzled/lock.h"
50
46
#include "drizzled/item/outer_ref.h"
51
47
#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"
 
48
 
 
49
#include <drizzled/sql_union.h>
 
50
 
 
51
#include <string>
 
52
#include <iostream>
 
53
#include <algorithm>
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,
115
108
{
116
109
  bool res;
117
110
  register Select_Lex *select_lex= &lex->select_lex;
118
 
  DRIZZLE_SELECT_START(session->query.c_str());
 
111
  DRIZZLE_SELECT_START();
119
112
 
120
113
  if (select_lex->master_unit()->is_union() ||
121
114
      select_lex->master_unit()->fake_select_lex)
148
141
  if (unlikely(res))
149
142
    result->abort();
150
143
 
151
 
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
152
 
  return res;
 
144
  DRIZZLE_SELECT_END();
 
145
  return(res);
153
146
}
154
147
 
155
148
/*
305
298
/**
306
299
  An entry point to single-unit select (a select without UNION).
307
300
 
308
 
  @param session                  thread Cursor
 
301
  @param session                  thread handler
309
302
  @param rref_pointer_array   a reference to ref_pointer_array of
310
303
                              the top-level select_lex for this query
311
304
  @param tables               list of all tables used in this query.
321
314
                              for a, b and c in this list.
322
315
  @param conds                top level item of an expression representing
323
316
                              WHERE clause of the top level select
324
 
  @param og_num               total number of ORDER BY and GROUP BY clauses
 
317
  @param og_num               total number of order_st BY and GROUP BY clauses
325
318
                              arguments
326
 
  @param order                linked list of ORDER BY agruments
 
319
  @param order                linked list of order_st BY agruments
327
320
  @param group                linked list of GROUP BY arguments
328
321
  @param having               top level item of HAVING expression
329
322
  @param select_options       select options (BIG_RESULT, etc)
346
339
*/
347
340
bool mysql_select(Session *session,
348
341
                  Item ***rref_pointer_array,
349
 
                  TableList *tables, 
 
342
                        TableList *tables, 
350
343
                  uint32_t wild_num, 
351
344
                  List<Item> &fields,
352
 
                  COND *conds, 
 
345
                        COND *conds, 
353
346
                  uint32_t og_num,  
354
347
                  order_st *order, 
355
348
                  order_st *group,
356
 
                  Item *having, 
 
349
                        Item *having, 
357
350
                  uint64_t select_options,
358
 
                  select_result *result, 
 
351
                        select_result *result, 
359
352
                  Select_Lex_Unit *unit,
360
 
                  Select_Lex *select_lex)
 
353
                        Select_Lex *select_lex)
361
354
{
362
355
  bool err;
363
356
  bool free_join= 1;
408
401
    }
409
402
  }
410
403
 
411
 
  err= join->optimize();
412
 
  if (err)
 
404
  if ((err= join->optimize()))
413
405
  {
414
 
    goto err; // 1
 
406
    goto err;                                   // 1
415
407
  }
416
408
 
417
409
  if (session->lex->describe & DESCRIBE_EXTENDED)
463
455
  Create JoinTableS, make a guess about the table types,
464
456
  Approximate how many records will be used in each table
465
457
*****************************************************************************/
466
 
ha_rows get_quick_record_count(Session *session, optimizer::SqlSelect *select, Table *table, const key_map *keys,ha_rows limit)
 
458
ha_rows get_quick_record_count(Session *session, SQL_SELECT *select, Table *table, const key_map *keys,ha_rows limit)
467
459
{
468
460
  int error;
469
461
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
492
484
          keyuse     Pointer to possible keys
493
485
*****************************************************************************/
494
486
 
 
487
/**
 
488
  Merge new key definitions to old ones, remove those not used in both.
 
489
 
 
490
  This is called for OR between different levels.
 
491
 
 
492
  To be able to do 'ref_or_null' we merge a comparison of a column
 
493
  and 'column IS NULL' to one test.  This is useful for sub select queries
 
494
  that are internally transformed to something like:.
 
495
 
 
496
  @code
 
497
  SELECT * FROM t1 WHERE t1.key=outer_ref_field or t1.key IS NULL
 
498
  @endcode
 
499
 
 
500
  KEY_FIELD::null_rejecting is processed as follows: @n
 
501
  result has null_rejecting=true if it is set for both ORed references.
 
502
  for example:
 
503
  -   (t2.key = t1.field OR t2.key  =  t1.field) -> null_rejecting=true
 
504
  -   (t2.key = t1.field OR t2.key <=> t1.field) -> null_rejecting=false
 
505
 
 
506
  @todo
 
507
    The result of this is that we're missing some 'ref' accesses.
 
508
    OptimizerTeam: Fix this
 
509
*/
 
510
static KEY_FIELD *merge_key_fields(KEY_FIELD *start,KEY_FIELD *new_fields,KEY_FIELD *end, uint32_t and_level)
 
511
{
 
512
  if (start == new_fields)
 
513
    return start;                               // Impossible or
 
514
  if (new_fields == end)
 
515
    return start;                               // No new fields, skip all
 
516
 
 
517
  KEY_FIELD *first_free=new_fields;
 
518
 
 
519
  /* Mark all found fields in old array */
 
520
  for (; new_fields != end ; new_fields++)
 
521
  {
 
522
    for (KEY_FIELD *old=start ; old != first_free ; old++)
 
523
    {
 
524
      if (old->field == new_fields->field)
 
525
      {
 
526
        /*
 
527
          NOTE: below const_item() call really works as "!used_tables()", i.e.
 
528
          it can return false where it is feasible to make it return true.
 
529
 
 
530
          The cause is as follows: Some of the tables are already known to be
 
531
          const tables (the detection code is in make_join_statistics(),
 
532
          above the update_ref_and_keys() call), but we didn't propagate
 
533
          information about this: Table::const_table is not set to true, and
 
534
          Item::update_used_tables() hasn't been called for each item.
 
535
          The result of this is that we're missing some 'ref' accesses.
 
536
          TODO: OptimizerTeam: Fix this
 
537
        */
 
538
        if (!new_fields->val->const_item())
 
539
        {
 
540
          /*
 
541
            If the value matches, we can use the key reference.
 
542
            If not, we keep it until we have examined all new values
 
543
          */
 
544
          if (old->val->eq(new_fields->val, old->field->binary()))
 
545
          {
 
546
            old->level= and_level;
 
547
            old->optimize= ((old->optimize & new_fields->optimize &
 
548
                KEY_OPTIMIZE_EXISTS) |
 
549
                ((old->optimize | new_fields->optimize) &
 
550
                KEY_OPTIMIZE_REF_OR_NULL));
 
551
                  old->null_rejecting= (old->null_rejecting &&
 
552
                                        new_fields->null_rejecting);
 
553
          }
 
554
        }
 
555
        else if (old->eq_func && new_fields->eq_func &&
 
556
                      old->val->eq_by_collation(new_fields->val,
 
557
                                                old->field->binary(),
 
558
                                                old->field->charset()))
 
559
 
 
560
        {
 
561
          old->level= and_level;
 
562
          old->optimize= ((old->optimize & new_fields->optimize &
 
563
              KEY_OPTIMIZE_EXISTS) |
 
564
              ((old->optimize | new_fields->optimize) &
 
565
              KEY_OPTIMIZE_REF_OR_NULL));
 
566
                old->null_rejecting= (old->null_rejecting &&
 
567
                                      new_fields->null_rejecting);
 
568
        }
 
569
        else if (old->eq_func && new_fields->eq_func &&
 
570
          ((old->val->const_item() && old->val->is_null()) ||
 
571
                        new_fields->val->is_null()))
 
572
        {
 
573
          /* field = expression OR field IS NULL */
 
574
          old->level= and_level;
 
575
          old->optimize= KEY_OPTIMIZE_REF_OR_NULL;
 
576
          /*
 
577
                  Remember the NOT NULL value unless the value does not depend
 
578
                  on other tables.
 
579
                */
 
580
          if (!old->val->used_tables() && old->val->is_null())
 
581
            old->val= new_fields->val;
 
582
                /* The referred expression can be NULL: */
 
583
                old->null_rejecting= 0;
 
584
        }
 
585
        else
 
586
        {
 
587
          /*
 
588
            We are comparing two different const.  In this case we can't
 
589
            use a key-lookup on this so it's better to remove the value
 
590
            and let the range optimzier handle it
 
591
          */
 
592
          if (old == --first_free)              // If last item
 
593
            break;
 
594
          *old= *first_free;                    // Remove old value
 
595
          old--;                                // Retry this value
 
596
        }
 
597
      }
 
598
    }
 
599
  }
 
600
  /* Remove all not used items */
 
601
  for (KEY_FIELD *old=start ; old != first_free ;)
 
602
  {
 
603
    if (old->level != and_level)
 
604
    {                                           // Not used in all levels
 
605
      if (old == --first_free)
 
606
        break;
 
607
      *old= *first_free;                        // Remove old value
 
608
      continue;
 
609
    }
 
610
    old++;
 
611
  }
 
612
  return first_free;
 
613
}
 
614
 
 
615
/**
 
616
  Add a possible key to array of possible keys if it's usable as a key
 
617
 
 
618
    @param key_fields      Pointer to add key, if usable
 
619
    @param and_level       And level, to be stored in KEY_FIELD
 
620
    @param cond            Condition predicate
 
621
    @param field           Field used in comparision
 
622
    @param eq_func         True if we used =, <=> or IS NULL
 
623
    @param value           Value used for comparison with field
 
624
    @param usable_tables   Tables which can be used for key optimization
 
625
    @param sargables       IN/OUT Array of found sargable candidates
 
626
 
 
627
  @note
 
628
    If we are doing a NOT NULL comparison on a NOT NULL field in a outer join
 
629
    table, we store this to be able to do not exists optimization later.
 
630
 
 
631
  @returns
 
632
    *key_fields is incremented if we stored a key in the array
 
633
*/
 
634
static void add_key_field(KEY_FIELD **key_fields,
 
635
                          uint32_t and_level,
 
636
                          Item_func *cond,
 
637
                          Field *field,
 
638
                          bool eq_func,
 
639
                          Item **value,
 
640
                          uint32_t num_values,
 
641
                          table_map usable_tables,
 
642
                          SARGABLE_PARAM **sargables)
 
643
{
 
644
  uint32_t exists_optimize= 0;
 
645
  if (!(field->flags & PART_KEY_FLAG))
 
646
  {
 
647
    // Don't remove column IS NULL on a LEFT JOIN table
 
648
    if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
649
        !field->table->maybe_null || field->null_ptr)
 
650
      return;                                   // Not a key. Skip it
 
651
    exists_optimize= KEY_OPTIMIZE_EXISTS;
 
652
    assert(num_values == 1);
 
653
  }
 
654
  else
 
655
  {
 
656
    table_map used_tables=0;
 
657
    bool optimizable=0;
 
658
    for (uint32_t i=0; i<num_values; i++)
 
659
    {
 
660
      used_tables|=(value[i])->used_tables();
 
661
      if (!((value[i])->used_tables() & (field->table->map | RAND_TABLE_BIT)))
 
662
        optimizable=1;
 
663
    }
 
664
    if (!optimizable)
 
665
      return;
 
666
    if (!(usable_tables & field->table->map))
 
667
    {
 
668
      if (!eq_func || (*value)->type() != Item::NULL_ITEM ||
 
669
          !field->table->maybe_null || field->null_ptr)
 
670
        return;                                 // Can't use left join optimize
 
671
      exists_optimize= KEY_OPTIMIZE_EXISTS;
 
672
    }
 
673
    else
 
674
    {
 
675
      JoinTable *stat=field->table->reginfo.join_tab;
 
676
      key_map possible_keys= field->key_start;
 
677
      possible_keys&= field->table->keys_in_use_for_query;
 
678
      stat[0].keys|= possible_keys;             // Add possible keys
 
679
 
 
680
      /*
 
681
        Save the following cases:
 
682
        Field op constant
 
683
        Field LIKE constant where constant doesn't start with a wildcard
 
684
        Field = field2 where field2 is in a different table
 
685
        Field op formula
 
686
        Field IS NULL
 
687
        Field IS NOT NULL
 
688
        Field BETWEEN ...
 
689
        Field IN ...
 
690
      */
 
691
      stat[0].key_dependent|= used_tables;
 
692
 
 
693
      bool is_const=1;
 
694
      for (uint32_t i=0; i<num_values; i++)
 
695
      {
 
696
        if (!(is_const&= value[i]->const_item()))
 
697
          break;
 
698
      }
 
699
      if (is_const)
 
700
        stat[0].const_keys|= possible_keys;
 
701
      else if (!eq_func)
 
702
      {
 
703
        /*
 
704
          Save info to be able check whether this predicate can be
 
705
          considered as sargable for range analisis after reading const tables.
 
706
          We do not save info about equalities as update_const_equal_items
 
707
          will take care of updating info on keys from sargable equalities.
 
708
        */
 
709
        (*sargables)--;
 
710
        (*sargables)->field= field;
 
711
        (*sargables)->arg_value= value;
 
712
        (*sargables)->num_values= num_values;
 
713
      }
 
714
      /*
 
715
        We can't always use indexes when comparing a string index to a
 
716
        number. cmp_type() is checked to allow compare of dates to numbers.
 
717
        eq_func is NEVER true when num_values > 1
 
718
       */
 
719
      if (!eq_func)
 
720
      {
 
721
        /*
 
722
          Additional optimization: if we're processing
 
723
          "t.key BETWEEN c1 AND c1" then proceed as if we were processing
 
724
          "t.key = c1".
 
725
          TODO: This is a very limited fix. A more generic fix is possible.
 
726
          There are 2 options:
 
727
          A) Make equality propagation code be able to handle BETWEEN
 
728
             (including cases like t1.key BETWEEN t2.key AND t3.key)
 
729
          B) Make range optimizer to infer additional "t.key = c" equalities
 
730
             and use them in equality propagation process (see details in
 
731
             OptimizerKBAndTodo)
 
732
        */
 
733
        if ((cond->functype() != Item_func::BETWEEN) ||
 
734
            ((Item_func_between*) cond)->negated ||
 
735
            !value[0]->eq(value[1], field->binary()))
 
736
          return;
 
737
        eq_func= true;
 
738
      }
 
739
 
 
740
      if (field->result_type() == STRING_RESULT)
 
741
      {
 
742
        if ((*value)->result_type() != STRING_RESULT)
 
743
        {
 
744
          if (field->cmp_type() != (*value)->result_type())
 
745
            return;
 
746
        }
 
747
        else
 
748
        {
 
749
          /*
 
750
            We can't use indexes if the effective collation
 
751
            of the operation differ from the field collation.
 
752
          */
 
753
          if (field->cmp_type() == STRING_RESULT &&
 
754
              ((Field_str*)field)->charset() != cond->compare_collation())
 
755
            return;
 
756
        }
 
757
      }
 
758
    }
 
759
  }
 
760
  /*
 
761
    For the moment eq_func is always true. This slot is reserved for future
 
762
    extensions where we want to remembers other things than just eq comparisons
 
763
  */
 
764
  assert(eq_func);
 
765
  /* Store possible eq field */
 
766
  (*key_fields)->field=         field;
 
767
  (*key_fields)->eq_func=       eq_func;
 
768
  (*key_fields)->val=           *value;
 
769
  (*key_fields)->level=         and_level;
 
770
  (*key_fields)->optimize=      exists_optimize;
 
771
  /*
 
772
    If the condition has form "tbl.keypart = othertbl.field" and
 
773
    othertbl.field can be NULL, there will be no matches if othertbl.field
 
774
    has NULL value.
 
775
    We use null_rejecting in add_not_null_conds() to add
 
776
    'othertbl.field IS NOT NULL' to tab->select_cond.
 
777
  */
 
778
  (*key_fields)->null_rejecting= ((cond->functype() == Item_func::EQ_FUNC ||
 
779
                                   cond->functype() == Item_func::MULT_EQUAL_FUNC) &&
 
780
                                  ((*value)->type() == Item::FIELD_ITEM) &&
 
781
                                  ((Item_field*)*value)->field->maybe_null());
 
782
  (*key_fields)->cond_guard= NULL;
 
783
  (*key_fields)++;
 
784
}
 
785
 
 
786
/**
 
787
  Add possible keys to array of possible keys originated from a simple
 
788
  predicate.
 
789
 
 
790
    @param  key_fields     Pointer to add key, if usable
 
791
    @param  and_level      And level, to be stored in KEY_FIELD
 
792
    @param  cond           Condition predicate
 
793
    @param  field          Field used in comparision
 
794
    @param  eq_func        True if we used =, <=> or IS NULL
 
795
    @param  value          Value used for comparison with field
 
796
                           Is NULL for BETWEEN and IN
 
797
    @param  usable_tables  Tables which can be used for key optimization
 
798
    @param  sargables      IN/OUT Array of found sargable candidates
 
799
 
 
800
  @note
 
801
    If field items f1 and f2 belong to the same multiple equality and
 
802
    a key is added for f1, the the same key is added for f2.
 
803
 
 
804
  @returns
 
805
    *key_fields is incremented if we stored a key in the array
 
806
*/
 
807
static void add_key_equal_fields(KEY_FIELD **key_fields,
 
808
                                 uint32_t and_level,
 
809
                                 Item_func *cond,
 
810
                                 Item_field *field_item,
 
811
                                 bool eq_func,
 
812
                                 Item **val,
 
813
                                 uint32_t num_values,
 
814
                                 table_map usable_tables,
 
815
                                 SARGABLE_PARAM **sargables)
 
816
{
 
817
  Field *field= field_item->field;
 
818
  add_key_field(key_fields, and_level, cond, field,
 
819
                eq_func, val, num_values, usable_tables, sargables);
 
820
  Item_equal *item_equal= field_item->item_equal;
 
821
  if (item_equal)
 
822
  {
 
823
    /*
 
824
      Add to the set of possible key values every substitution of
 
825
      the field for an equal field included into item_equal
 
826
    */
 
827
    Item_equal_iterator it(*item_equal);
 
828
    Item_field *item;
 
829
    while ((item= it++))
 
830
    {
 
831
      if (!field->eq(item->field))
 
832
      {
 
833
        add_key_field(key_fields, and_level, cond, item->field,
 
834
                      eq_func, val, num_values, usable_tables,
 
835
                      sargables);
 
836
      }
 
837
    }
 
838
  }
 
839
}
 
840
 
 
841
static void add_key_fields(JOIN *join, 
 
842
                           KEY_FIELD **key_fields,
 
843
                           uint32_t *and_level,
 
844
                           COND *cond,
 
845
                           table_map usable_tables,
 
846
                           SARGABLE_PARAM **sargables)
 
847
{
 
848
  if (cond->type() == Item_func::COND_ITEM)
 
849
  {
 
850
    List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list());
 
851
    KEY_FIELD *org_key_fields= *key_fields;
 
852
 
 
853
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
854
    {
 
855
      Item *item;
 
856
      while ((item=li++))
 
857
        add_key_fields(join, key_fields, and_level, item, usable_tables,
 
858
                       sargables);
 
859
      for (; org_key_fields != *key_fields ; org_key_fields++)
 
860
        org_key_fields->level= *and_level;
 
861
    }
 
862
    else
 
863
    {
 
864
      (*and_level)++;
 
865
      add_key_fields(join, key_fields, and_level, li++, usable_tables,
 
866
                     sargables);
 
867
      Item *item;
 
868
      while ((item=li++))
 
869
      {
 
870
        KEY_FIELD *start_key_fields= *key_fields;
 
871
        (*and_level)++;
 
872
              add_key_fields(join, key_fields, and_level, item, usable_tables,
 
873
                            sargables);
 
874
        *key_fields=merge_key_fields(org_key_fields,start_key_fields,
 
875
                  *key_fields,++(*and_level));
 
876
      }
 
877
    }
 
878
    return;
 
879
  }
 
880
 
 
881
  /*
 
882
    Subquery optimization: Conditions that are pushed down into subqueries
 
883
    are wrapped into Item_func_trig_cond. We process the wrapped condition
 
884
    but need to set cond_guard for KeyUse elements generated from it.
 
885
  */
 
886
  {
 
887
    if (cond->type() == Item::FUNC_ITEM &&
 
888
        ((Item_func*)cond)->functype() == Item_func::TRIG_COND_FUNC)
 
889
    {
 
890
      Item *cond_arg= ((Item_func*)cond)->arguments()[0];
 
891
      if (!join->group_list && !join->order &&
 
892
          join->unit->item &&
 
893
          join->unit->item->substype() == Item_subselect::IN_SUBS &&
 
894
          !join->unit->is_union())
 
895
      {
 
896
        KEY_FIELD *save= *key_fields;
 
897
        add_key_fields(join, key_fields, and_level, cond_arg, usable_tables,
 
898
                       sargables);
 
899
        // Indicate that this ref access candidate is for subquery lookup:
 
900
        for (; save != *key_fields; save++)
 
901
          save->cond_guard= ((Item_func_trig_cond*)cond)->get_trig_var();
 
902
      }
 
903
      return;
 
904
    }
 
905
  }
 
906
 
 
907
  /* If item is of type 'field op field/constant' add it to key_fields */
 
908
  if (cond->type() != Item::FUNC_ITEM)
 
909
    return;
 
910
  Item_func *cond_func= (Item_func*) cond;
 
911
  switch (cond_func->select_optimize()) {
 
912
  case Item_func::OPTIMIZE_NONE:
 
913
    break;
 
914
  case Item_func::OPTIMIZE_KEY:
 
915
  {
 
916
    Item **values;
 
917
    // BETWEEN, IN, NE
 
918
    if (cond_func->key_item()->real_item()->type() == Item::FIELD_ITEM &&
 
919
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
920
    {
 
921
      values= cond_func->arguments()+1;
 
922
      if (cond_func->functype() == Item_func::NE_FUNC &&
 
923
        cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
924
             !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
925
        values--;
 
926
      assert(cond_func->functype() != Item_func::IN_FUNC ||
 
927
                  cond_func->argument_count() != 2);
 
928
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
929
                           (Item_field*) (cond_func->key_item()->real_item()),
 
930
                           0, values,
 
931
                           cond_func->argument_count()-1,
 
932
                           usable_tables, sargables);
 
933
    }
 
934
    if (cond_func->functype() == Item_func::BETWEEN)
 
935
    {
 
936
      values= cond_func->arguments();
 
937
      for (uint32_t i= 1 ; i < cond_func->argument_count() ; i++)
 
938
      {
 
939
        Item_field *field_item;
 
940
        if (cond_func->arguments()[i]->real_item()->type() == Item::FIELD_ITEM
 
941
            &&
 
942
            !(cond_func->arguments()[i]->used_tables() & OUTER_REF_TABLE_BIT))
 
943
        {
 
944
          field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
 
945
          add_key_equal_fields(key_fields, *and_level, cond_func,
 
946
                               field_item, 0, values, 1, usable_tables,
 
947
                               sargables);
 
948
        }
 
949
      }
 
950
    }
 
951
    break;
 
952
  }
 
953
  case Item_func::OPTIMIZE_OP:
 
954
  {
 
955
    bool equal_func=(cond_func->functype() == Item_func::EQ_FUNC ||
 
956
                     cond_func->functype() == Item_func::EQUAL_FUNC);
 
957
 
 
958
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
959
        !(cond_func->arguments()[0]->used_tables() & OUTER_REF_TABLE_BIT))
 
960
    {
 
961
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
962
                        (Item_field*) (cond_func->arguments()[0])->real_item(),
 
963
                           equal_func,
 
964
                           cond_func->arguments()+1, 1, usable_tables,
 
965
                           sargables);
 
966
    }
 
967
    if (cond_func->arguments()[1]->real_item()->type() == Item::FIELD_ITEM &&
 
968
        cond_func->functype() != Item_func::LIKE_FUNC &&
 
969
        !(cond_func->arguments()[1]->used_tables() & OUTER_REF_TABLE_BIT))
 
970
    {
 
971
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
972
                       (Item_field*) (cond_func->arguments()[1])->real_item(), equal_func,
 
973
                           cond_func->arguments(),1,usable_tables,
 
974
                           sargables);
 
975
    }
 
976
    break;
 
977
  }
 
978
  case Item_func::OPTIMIZE_NULL:
 
979
    /* column_name IS [NOT] NULL */
 
980
    if (cond_func->arguments()[0]->real_item()->type() == Item::FIELD_ITEM &&
 
981
        !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
 
982
    {
 
983
      Item *tmp=new Item_null;
 
984
      if (unlikely(!tmp))                       // Should never be true
 
985
        return;
 
986
      add_key_equal_fields(key_fields, *and_level, cond_func,
 
987
                    (Item_field*) (cond_func->arguments()[0])->real_item(),
 
988
                    cond_func->functype() == Item_func::ISNULL_FUNC,
 
989
                           &tmp, 1, usable_tables, sargables);
 
990
    }
 
991
    break;
 
992
  case Item_func::OPTIMIZE_EQUAL:
 
993
    Item_equal *item_equal= (Item_equal *) cond;
 
994
    Item *const_item= item_equal->get_const();
 
995
    Item_equal_iterator it(*item_equal);
 
996
    Item_field *item;
 
997
    if (const_item)
 
998
    {
 
999
      /*
 
1000
        For each field field1 from item_equal consider the equality
 
1001
        field1=const_item as a condition allowing an index access of the table
 
1002
        with field1 by the keys value of field1.
 
1003
      */
 
1004
      while ((item= it++))
 
1005
      {
 
1006
        add_key_field(key_fields, *and_level, cond_func, item->field,
 
1007
                      true, &const_item, 1, usable_tables, sargables);
 
1008
      }
 
1009
    }
 
1010
    else
 
1011
    {
 
1012
      /*
 
1013
        Consider all pairs of different fields included into item_equal.
 
1014
        For each of them (field1, field1) consider the equality
 
1015
        field1=field2 as a condition allowing an index access of the table
 
1016
        with field1 by the keys value of field2.
 
1017
      */
 
1018
      Item_equal_iterator fi(*item_equal);
 
1019
      while ((item= fi++))
 
1020
      {
 
1021
        Field *field= item->field;
 
1022
        while ((item= it++))
 
1023
        {
 
1024
          if (!field->eq(item->field))
 
1025
          {
 
1026
            add_key_field(key_fields, *and_level, cond_func, field,
 
1027
                          true, (Item **) &item, 1, usable_tables,
 
1028
                          sargables);
 
1029
          }
 
1030
        }
 
1031
        it.rewind();
 
1032
      }
 
1033
    }
 
1034
    break;
 
1035
  }
 
1036
}
495
1037
 
496
1038
/**
497
1039
  Add all keys with uses 'field' for some keypart.
505
1047
  return found;
506
1048
}
507
1049
 
508
 
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b)
 
1050
static void add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
 
1051
{
 
1052
  Field *field=key_field->field;
 
1053
  Table *form= field->table;
 
1054
  KeyUse keyuse;
 
1055
 
 
1056
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
 
1057
  {
 
1058
    for (uint32_t key= 0 ; key < form->sizeKeys() ; key++)
 
1059
    {
 
1060
      if (!(form->keys_in_use_for_query.test(key)))
 
1061
        continue;
 
1062
 
 
1063
      uint32_t key_parts= (uint32_t) form->key_info[key].key_parts;
 
1064
      for (uint32_t part=0 ; part <  key_parts ; part++)
 
1065
      {
 
1066
        if (field->eq(form->key_info[key].key_part[part].field))
 
1067
        {
 
1068
          keyuse.table= field->table;
 
1069
          keyuse.val =  key_field->val;
 
1070
          keyuse.key =  key;
 
1071
          keyuse.keypart=part;
 
1072
          keyuse.keypart_map= (key_part_map) 1 << part;
 
1073
          keyuse.used_tables=key_field->val->used_tables();
 
1074
          keyuse.optimize= key_field->optimize & KEY_OPTIMIZE_REF_OR_NULL;
 
1075
          keyuse.null_rejecting= key_field->null_rejecting;
 
1076
          keyuse.cond_guard= key_field->cond_guard;
 
1077
          insert_dynamic(keyuse_array,(unsigned char*) &keyuse);
 
1078
        }
 
1079
      }
 
1080
    }
 
1081
  }
 
1082
}
 
1083
 
 
1084
static int sort_keyuse(KeyUse *a,KeyUse *b)
509
1085
{
510
1086
  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()));
 
1087
  if (a->table->tablenr != b->table->tablenr)
 
1088
    return (int) (a->table->tablenr - b->table->tablenr);
 
1089
  if (a->key != b->key)
 
1090
    return (int) (a->key - b->key);
 
1091
  if (a->keypart != b->keypart)
 
1092
    return (int) (a->keypart - b->keypart);
517
1093
  // Place const values before other ones
518
 
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
519
 
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
 
1094
  if ((res= test((a->used_tables & ~OUTER_REF_TABLE_BIT)) -
 
1095
       test((b->used_tables & ~OUTER_REF_TABLE_BIT))))
520
1096
    return res;
521
1097
  /* 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
 
 
 
1098
  return (int) ((a->optimize & KEY_OPTIMIZE_REF_OR_NULL) -
 
1099
                (b->optimize & KEY_OPTIMIZE_REF_OR_NULL));
 
1100
}
 
1101
 
 
1102
/*
 
1103
  Add to KEY_FIELD array all 'ref' access candidates within nested join.
 
1104
 
 
1105
    This function populates KEY_FIELD array with entries generated from the
 
1106
    ON condition of the given nested join, and does the same for nested joins
 
1107
    contained within this nested join.
 
1108
 
 
1109
  @param[in]      nested_join_table   Nested join pseudo-table to process
 
1110
  @param[in,out]  end                 End of the key field array
 
1111
  @param[in,out]  and_level           And-level
 
1112
  @param[in,out]  sargables           Array of found sargable candidates
 
1113
 
 
1114
 
 
1115
  @note
 
1116
    We can add accesses to the tables that are direct children of this nested
 
1117
    join (1), and are not inner tables w.r.t their neighbours (2).
 
1118
 
 
1119
    Example for #1 (outer brackets pair denotes nested join this function is
 
1120
    invoked for):
 
1121
    @code
 
1122
     ... LEFT JOIN (t1 LEFT JOIN (t2 ... ) ) ON cond
 
1123
    @endcode
 
1124
    Example for #2:
 
1125
    @code
 
1126
     ... LEFT JOIN (t1 LEFT JOIN t2 ) ON cond
 
1127
    @endcode
 
1128
    In examples 1-2 for condition cond, we can add 'ref' access candidates to
 
1129
    t1 only.
 
1130
    Example #3:
 
1131
    @code
 
1132
     ... LEFT JOIN (t1, t2 LEFT JOIN t3 ON inner_cond) ON cond
 
1133
    @endcode
 
1134
    Here we can add 'ref' access candidates for t1 and t2, but not for t3.
 
1135
*/
 
1136
static void add_key_fields_for_nj(JOIN *join,
 
1137
                                  TableList *nested_join_table,
 
1138
                                  KEY_FIELD **end,
 
1139
                                  uint32_t *and_level,
 
1140
                                  SARGABLE_PARAM **sargables)
 
1141
{
 
1142
  List_iterator<TableList> li(nested_join_table->nested_join->join_list);
 
1143
  List_iterator<TableList> li2(nested_join_table->nested_join->join_list);
 
1144
  bool have_another = false;
 
1145
  table_map tables= 0;
 
1146
  TableList *table;
 
1147
  assert(nested_join_table->nested_join);
 
1148
 
 
1149
  while ((table= li++) || (have_another && (li=li2, have_another=false,
 
1150
                                            (table= li++))))
 
1151
  {
 
1152
    if (table->nested_join)
 
1153
    {
 
1154
      if (!table->on_expr)
 
1155
      {
 
1156
        /* It's a semi-join nest. Walk into it as if it wasn't a nest */
 
1157
        have_another= true;
 
1158
        li2= li;
 
1159
        li= List_iterator<TableList>(table->nested_join->join_list);
 
1160
      }
 
1161
      else
 
1162
        add_key_fields_for_nj(join, table, end, and_level, sargables);
 
1163
    }
 
1164
    else
 
1165
      if (!table->on_expr)
 
1166
        tables |= table->table->map;
 
1167
  }
 
1168
  if (nested_join_table->on_expr)
 
1169
    add_key_fields(join, end, and_level, nested_join_table->on_expr, tables,
 
1170
                   sargables);
 
1171
}
526
1172
 
527
1173
/**
528
1174
  Update keyuse array with all possible keys we can use to fetch rows.
537
1183
                              for which we can make ref access based the WHERE
538
1184
                              clause)
539
1185
  @param       select_lex     current SELECT
540
 
  @param[out]  sargables      std::vector of found sargable candidates
 
1186
  @param[out]  sargables      Array of found sargable candidates
541
1187
 
542
1188
   @retval
543
1189
     0  OK
552
1198
                         COND_EQUAL *,
553
1199
                         table_map normal_tables,
554
1200
                         Select_Lex *select_lex,
555
 
                         vector<optimizer::SargableParam> &sargables)
 
1201
                         SARGABLE_PARAM **sargables)
556
1202
{
557
1203
  uint  and_level,i,found_eq_constant;
558
 
  optimizer::KeyField *key_fields, *end, *field;
 
1204
  KEY_FIELD *key_fields, *end, *field;
559
1205
  uint32_t sz;
560
1206
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
561
1207
 
562
1208
  /*
563
 
    All predicates that are used to fill arrays of KeyField
564
 
    and SargableParam classes have at most 2 arguments
 
1209
    We use the same piece of memory to store both  KEY_FIELD
 
1210
    and SARGABLE_PARAM structure.
 
1211
    KEY_FIELD values are placed at the beginning this memory
 
1212
    while  SARGABLE_PARAM values are put at the end.
 
1213
    All predicates that are used to fill arrays of KEY_FIELD
 
1214
    and SARGABLE_PARAM structures have at most 2 arguments
565
1215
    except BETWEEN predicates that have 3 arguments and
566
1216
    IN predicates.
567
1217
    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
 
1218
    directly to fill at most 2 array elements, either of KEY_FIELD
 
1219
    or SARGABLE_PARAM type. For a BETWEEN predicate 3 elements
570
1220
    can be filled as this predicate is considered as
571
1221
    saragable with respect to each of its argument.
572
1222
    An IN predicate can require at most 1 element as currently
576
1226
    can be not more than select_lex->max_equal_elems such
577
1227
    substitutions.
578
1228
  */
579
 
  sz= sizeof(optimizer::KeyField) *
580
 
      (((session->lex->current_select->cond_count+1) +
 
1229
  sz= max(sizeof(KEY_FIELD),sizeof(SARGABLE_PARAM))*
 
1230
      (((session->lex->current_select->cond_count+1)*2 +
581
1231
        session->lex->current_select->between_count)*m+1);
582
 
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
583
 
    return true;
 
1232
  if (!(key_fields=(KEY_FIELD*) session->alloc(sz)))
 
1233
    return true; /* purecov: inspected */
584
1234
  and_level= 0;
585
1235
  field= end= key_fields;
 
1236
  *sargables= (SARGABLE_PARAM *) key_fields +
 
1237
                (sz - sizeof((*sargables)[0].field))/sizeof(SARGABLE_PARAM);
 
1238
  /* set a barrier for the array of SARGABLE_PARAM */
 
1239
  (*sargables)[0].field= 0;
586
1240
 
587
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
 
1241
  if (my_init_dynamic_array(keyuse,sizeof(KeyUse),20,64))
588
1242
    return true;
589
1243
  if (cond)
590
1244
  {
591
1245
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
592
1246
                   sargables);
593
 
    for (; field != end; field++)
 
1247
    for (; field != end ; field++)
594
1248
    {
595
 
      add_key_part(keyuse, field);
 
1249
      add_key_part(keyuse,field);
596
1250
      /* 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
 
      }
 
1251
      if (field->val->type() == Item::NULL_ITEM &&
 
1252
          !field->field->real_maybe_null())
 
1253
        field->field->table->reginfo.not_exists_optimize=1;
602
1254
    }
603
1255
  }
604
 
  for (i= 0; i < tables; i++)
 
1256
  for (i=0 ; i < tables ; i++)
605
1257
  {
606
1258
    /*
607
1259
      Block the creation of keys for inner tables of outer joins.
645
1297
  */
646
1298
  if (keyuse->elements)
647
1299
  {
648
 
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
 
1300
    KeyUse key_end,*prev,*save_pos,*use;
649
1301
 
650
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
651
 
                       (qsort_cmp) sort_keyuse);
 
1302
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(KeyUse),
 
1303
          (qsort_cmp) sort_keyuse);
652
1304
 
653
1305
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
654
1306
    insert_dynamic(keyuse,(unsigned char*) &key_end);
655
1307
 
656
 
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
 
1308
    use=save_pos=dynamic_element(keyuse,0,KeyUse*);
657
1309
    prev= &key_end;
658
 
    found_eq_constant= 0;
659
 
    for (i= 0; i < keyuse->elements-1; i++, use++)
 
1310
    found_eq_constant=0;
 
1311
    for (i=0 ; i < keyuse->elements-1 ; i++,use++)
660
1312
    {
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())
 
1313
      if (!use->used_tables && use->optimize != KEY_OPTIMIZE_REF_OR_NULL)
 
1314
        use->table->const_key_parts[use->key]|= use->keypart_map;
 
1315
      if (use->key == prev->key && use->table == prev->table)
664
1316
      {
665
 
        if (prev->getKeypart() + 1 < use->getKeypart() || 
666
 
            ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
 
1317
        if (prev->keypart+1 < use->keypart || ((prev->keypart == use->keypart) && found_eq_constant))
667
1318
          continue;                             /* remove */
668
1319
      }
669
 
      else if (use->getKeypart() != 0)          // First found must be 0
 
1320
      else if (use->keypart != 0)               // First found must be 0
670
1321
        continue;
671
1322
 
672
1323
#ifdef HAVE_purify
675
1326
#endif
676
1327
        *save_pos= *use;
677
1328
      prev=use;
678
 
      found_eq_constant= ! use->getUsedTables();
 
1329
      found_eq_constant= !use->used_tables;
679
1330
      /* 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());
 
1331
      if (!use->table->reginfo.join_tab->keyuse)
 
1332
        use->table->reginfo.join_tab->keyuse=save_pos;
 
1333
      use->table->reginfo.join_tab->checked_keys.set(use->key);
683
1334
      save_pos++;
684
1335
    }
685
 
    i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
686
 
    set_dynamic(keyuse, (unsigned char*) &key_end, i);
687
 
    keyuse->elements= i;
 
1336
    i=(uint32_t) (save_pos-(KeyUse*) keyuse->buffer);
 
1337
    set_dynamic(keyuse,(unsigned char*) &key_end,i);
 
1338
    keyuse->elements=i;
688
1339
  }
689
1340
  return false;
690
1341
}
694
1345
*/
695
1346
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
696
1347
{
697
 
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
698
 
                                                  0, 
699
 
                                                  optimizer::KeyUse*);
 
1348
  KeyUse *end,*keyuse= dynamic_element(keyuse_array, 0, KeyUse*);
700
1349
 
701
1350
  for (end= keyuse+ keyuse_array->elements ; keyuse < end ; keyuse++)
702
1351
  {
709
1358
      Constant tables are ignored.
710
1359
      To avoid bad matches, we don't make ref_table_rows less than 100.
711
1360
    */
712
 
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
713
 
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
 
1361
    keyuse->ref_table_rows= ~(ha_rows) 0;       // If no ref
 
1362
    if (keyuse->used_tables & (map= (keyuse->used_tables & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
714
1363
    {
715
1364
      uint32_t tablenr;
716
1365
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
717
1366
      if (map == 1)                     // Only one table
718
1367
      {
719
1368
        Table *tmp_table=join->all_tables[tablenr];
720
 
        keyuse->setTableRows(max(tmp_table->cursor->stats.records, (ha_rows)100));
 
1369
        keyuse->ref_table_rows= max(tmp_table->file->stats.records, (ha_rows)100);
721
1370
      }
722
1371
    }
723
1372
    /*
724
1373
      Outer reference (external field) is constant for single executing
725
1374
      of subquery
726
1375
    */
727
 
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
728
 
      keyuse->setTableRows(1);
 
1376
    if (keyuse->used_tables == OUTER_REF_TABLE_BIT)
 
1377
      keyuse->ref_table_rows= 1;
729
1378
  }
730
1379
}
731
1380
 
871
1520
    rec_length+=sizeof(bool);
872
1521
  if (blobs)
873
1522
  {
874
 
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
 
1523
    uint32_t blob_length=(uint32_t) (join_tab->table->file->stats.mean_rec_length-
875
1524
                                     (join_tab->table->getRecordLength()- rec_length));
876
1525
    rec_length+= max((uint32_t)4,blob_length);
877
1526
  }
881
1530
}
882
1531
 
883
1532
StoredKey *get_store_key(Session *session,
884
 
                         optimizer::KeyUse *keyuse,
 
1533
                         KeyUse *keyuse,
885
1534
                         table_map used_tables,
886
 
                         KEY_PART_INFO *key_part,
 
1535
                               KEY_PART_INFO *key_part,
887
1536
                         unsigned char *key_buff,
888
1537
                         uint32_t maybe_null)
889
1538
{
890
 
  Item_ref *key_use_val= static_cast<Item_ref *>(keyuse->getVal());
891
 
  if (! ((~used_tables) & keyuse->getUsedTables())) // if const item
 
1539
  if (!((~used_tables) & keyuse->used_tables))          // if const item
892
1540
  {
893
1541
    return new store_key_const_item(session,
894
1542
                                    key_part->field,
895
1543
                                    key_buff + maybe_null,
896
1544
                                    maybe_null ? key_buff : 0,
897
1545
                                    key_part->length,
898
 
                                    key_use_val);
 
1546
                                    keyuse->val);
899
1547
  }
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
 
  {
 
1548
  else if (keyuse->val->type() == Item::FIELD_ITEM ||
 
1549
           (keyuse->val->type() == Item::REF_ITEM &&
 
1550
            ((Item_ref*)keyuse->val)->ref_type() == Item_ref::OUTER_REF &&
 
1551
            (*(Item_ref**)((Item_ref*)keyuse->val)->ref)->ref_type() ==
 
1552
             Item_ref::DIRECT_REF &&
 
1553
            keyuse->val->real_item()->type() == Item::FIELD_ITEM))
906
1554
    return new store_key_field(session,
907
1555
                               key_part->field,
908
1556
                               key_buff + maybe_null,
909
1557
                               maybe_null ? key_buff : 0,
910
1558
                               key_part->length,
911
 
                               ((Item_field*) key_use_val->real_item())->field,
912
 
                               key_use_val->full_name());
913
 
  }
 
1559
                               ((Item_field*) keyuse->val->real_item())->field,
 
1560
                               keyuse->val->full_name());
914
1561
  return new store_key_item(session,
915
1562
                            key_part->field,
916
1563
                            key_buff + maybe_null,
917
1564
                            maybe_null ? key_buff : 0,
918
1565
                            key_part->length,
919
 
                            key_use_val);
 
1566
                            keyuse->val);
920
1567
}
921
1568
 
922
1569
/**
959
1606
    *e1= e2;
960
1607
}
961
1608
 
962
 
bool create_ref_for_key(JOIN *join, 
963
 
                        JoinTable *j, 
964
 
                        optimizer::KeyUse *org_keyuse,
965
 
                        table_map used_tables)
 
1609
bool create_ref_for_key(JOIN *join, JoinTable *j, KeyUse *org_keyuse,
 
1610
             table_map used_tables)
966
1611
{
967
 
  optimizer::KeyUse *keyuse= org_keyuse;
 
1612
  KeyUse *keyuse=org_keyuse;
968
1613
  Session  *session= join->session;
969
 
  uint32_t keyparts;
970
 
  uint32_t length;
971
 
  uint32_t key;
972
 
  Table *table= NULL;
973
 
  KEY *keyinfo= NULL;
 
1614
  uint32_t keyparts,length,key;
 
1615
  Table *table;
 
1616
  KEY *keyinfo;
974
1617
 
975
1618
  /*  Use best key from find_best */
976
 
  table= j->table;
977
 
  key= keyuse->getKey();
978
 
  keyinfo= table->key_info + key;
 
1619
  table=j->table;
 
1620
  key=keyuse->key;
 
1621
  keyinfo=table->key_info+key;
979
1622
 
980
1623
  {
981
 
    keyparts= length= 0;
 
1624
    keyparts=length=0;
982
1625
    uint32_t found_part_ref_or_null= 0;
983
1626
    /*
984
1627
      Calculate length for the used key
987
1630
    */
988
1631
    do
989
1632
    {
990
 
      if (! (~used_tables & keyuse->getUsedTables()))
 
1633
      if (!(~used_tables & keyuse->used_tables))
991
1634
      {
992
 
        if (keyparts == keyuse->getKeypart() &&
993
 
            ! (found_part_ref_or_null & keyuse->getOptimizeFlags()))
 
1635
        if (keyparts == keyuse->keypart &&
 
1636
            !(found_part_ref_or_null & keyuse->optimize))
994
1637
        {
995
1638
          keyparts++;
996
 
          length+= keyinfo->key_part[keyuse->getKeypart()].store_length;
997
 
          found_part_ref_or_null|= keyuse->getOptimizeFlags();
 
1639
          length+= keyinfo->key_part[keyuse->keypart].store_length;
 
1640
          found_part_ref_or_null|= keyuse->optimize;
998
1641
        }
999
1642
      }
1000
1643
      keyuse++;
1001
 
    } while (keyuse->getTable() == table && keyuse->getKey() == key);
 
1644
    } while (keyuse->table == table && keyuse->key == key);
1002
1645
  }
1003
1646
 
1004
1647
  /* set up fieldref */
1021
1664
  keyuse=org_keyuse;
1022
1665
 
1023
1666
  StoredKey **ref_key= j->ref.key_copy;
1024
 
  unsigned char *key_buff= j->ref.key_buff, *null_ref_key= 0;
 
1667
  unsigned char *key_buff=j->ref.key_buff, *null_ref_key= 0;
1025
1668
  bool keyuse_uses_no_tables= true;
1026
1669
  {
1027
 
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
 
1670
    uint32_t i;
 
1671
    for (i=0 ; i < keyparts ; keyuse++,i++)
1028
1672
    {
1029
 
      while (keyuse->getKeypart() != i ||
1030
 
             ((~used_tables) & keyuse->getUsedTables()))
 
1673
      while (keyuse->keypart != i ||
 
1674
       ((~used_tables) & keyuse->used_tables))
1031
1675
        keyuse++;       /* Skip other parts */
1032
1676
 
1033
1677
      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())
 
1678
      j->ref.items[i]=keyuse->val;    // Save for cond removal
 
1679
      j->ref.cond_guards[i]= keyuse->cond_guard;
 
1680
      if (keyuse->null_rejecting)
1037
1681
        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))
 
1682
      keyuse_uses_no_tables= keyuse_uses_no_tables && !keyuse->used_tables;
 
1683
      if (!keyuse->used_tables &&  !(join->select_options & SELECT_DESCRIBE))
1040
1684
      {         // Compare against constant
1041
1685
        store_key_item tmp(session, keyinfo->key_part[i].field,
1042
1686
                           key_buff + maybe_null,
1043
1687
                           maybe_null ?  key_buff : 0,
1044
 
                           keyinfo->key_part[i].length, keyuse->getVal());
 
1688
                           keyinfo->key_part[i].length, keyuse->val);
1045
1689
        if (session->is_fatal_error)
1046
1690
          return(true);
1047
1691
        tmp.copy();
1053
1697
          key_buff, maybe_null);
1054
1698
      /*
1055
1699
        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
 
1700
        But only if field _really_ can be null i.e. we force JT_REF
 
1701
        instead of JT_REF_OR_NULL in case if field can't be null
1058
1702
      */
1059
 
      if ((keyuse->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
 
1703
      if ((keyuse->optimize & KEY_OPTIMIZE_REF_OR_NULL) && maybe_null)
1060
1704
        null_ref_key= key_buff;
1061
1705
      key_buff+=keyinfo->key_part[i].store_length;
1062
1706
    }
1063
1707
  }
1064
 
  *ref_key= 0;       // end_marker
1065
 
  if (j->type == AM_CONST)
 
1708
  *ref_key=0;       // end_marker
 
1709
  if (j->type == JT_CONST)
1066
1710
    j->table->const_table= 1;
1067
1711
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1068
1712
           keyparts != keyinfo->key_parts || null_ref_key)
1069
1713
  {
1070
1714
    /* Must read with repeat */
1071
 
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
 
1715
    j->type= null_ref_key ? JT_REF_OR_NULL : JT_REF;
1072
1716
    j->ref.null_ref_key= null_ref_key;
1073
1717
  }
1074
1718
  else if (keyuse_uses_no_tables)
1080
1724
      Here we should not mark the table as a 'const' as a field may
1081
1725
      have a 'normal' value or a NULL value.
1082
1726
    */
1083
 
    j->type= AM_CONST;
 
1727
    j->type=JT_CONST;
1084
1728
  }
1085
1729
  else
1086
 
    j->type= AM_EQ_REF;
1087
 
  return 0;
 
1730
    j->type=JT_EQ_REF;
 
1731
  return(0);
1088
1732
}
1089
1733
 
1090
1734
/**
1131
1775
 
1132
1776
    Implementation overview
1133
1777
      1. update_ref_and_keys() accumulates info about null-rejecting
1134
 
         predicates in in KeyField::null_rejecting
 
1778
         predicates in in KEY_FIELD::null_rejecting
1135
1779
      1.1 add_key_part saves these to KeyUse.
1136
1780
      2. create_ref_for_key copies them to table_reference_st.
1137
1781
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1139
1783
*/
1140
1784
void add_not_null_conds(JOIN *join)
1141
1785
{
1142
 
  for (uint32_t i= join->const_tables; i < join->tables; i++)
 
1786
  for (uint32_t i=join->const_tables ; i < join->tables ; i++)
1143
1787
  {
1144
1788
    JoinTable *tab=join->join_tab+i;
1145
 
    if ((tab->type == AM_REF || tab->type == AM_EQ_REF ||
1146
 
         tab->type == AM_REF_OR_NULL) &&
 
1789
    if ((tab->type == JT_REF || tab->type == JT_EQ_REF ||
 
1790
         tab->type == JT_REF_OR_NULL) &&
1147
1791
        !tab->table->maybe_null)
1148
1792
    {
1149
1793
      for (uint32_t keypart= 0; keypart < tab->ref.key_parts; keypart++)
1465
2109
    if (table->key_read)
1466
2110
    {
1467
2111
      table->key_read= 0;
1468
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
2112
      table->file->extra(HA_EXTRA_NO_KEYREAD);
1469
2113
    }
1470
 
    table->cursor->ha_index_or_rnd_end();
 
2114
    table->file->ha_index_or_rnd_end();
1471
2115
    /*
1472
2116
      We need to reset this for next select
1473
2117
      (Tested in part_of_refkey)
1488
2132
}
1489
2133
 
1490
2134
/**
1491
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
2135
  Remove the following expressions from order_st BY and GROUP BY:
1492
2136
  Constant expressions @n
1493
2137
  Expression that only uses tables that are of type EQ_REF and the reference
1494
2138
  is in the order_st list or if all refereed tables are of the above type.
1495
2139
 
1496
2140
  In the following, the X field can be removed:
1497
2141
  @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
 
2142
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
 
2143
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1500
2144
  @endcode
1501
2145
 
1502
2146
  These can't be optimized:
1503
2147
  @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
 
2148
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
 
2149
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
 
2150
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1507
2151
  @endcode
1508
2152
*/
1509
2153
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
1512
2156
    return tab->eq_ref_table;
1513
2157
  tab->cached_eq_ref_table=1;
1514
2158
  /* 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)
 
2159
  if (tab->type == JT_CONST && !tab->first_inner)
 
2160
    return (tab->eq_ref_table=1);               /* purecov: inspected */
 
2161
  if (tab->type != JT_EQ_REF || tab->table->maybe_null)
1518
2162
    return (tab->eq_ref_table=0);               // We must use this
1519
2163
  Item **ref_item=tab->ref.items;
1520
2164
  Item **end=ref_item+tab->ref.key_parts;
2217
2861
    can get more freedom in performing join operations.
2218
2862
    Althogh we don't use this property now, it probably makes sense to use
2219
2863
    it in the future.
2220
 
  @param session                      Thread Cursor
 
2864
  @param session                      Thread handler
2221
2865
  @param cond                condition to build the multiple equalities for
2222
2866
  @param inherited           path to all inherited multiple equality items
2223
2867
  @param join_list           list of join tables to which the condition
2579
3223
        if (possible_keys.any())
2580
3224
        {
2581
3225
          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 ==
 
3226
          KeyUse *use;
 
3227
          for (use= stat->keyuse; use && use->table == field_tab; use++)
 
3228
            if (possible_keys.test(use->key) &&
 
3229
                field_tab->key_info[use->key].key_part[use->keypart].field ==
2586
3230
                field)
2587
 
              field_tab->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
3231
              field_tab->const_key_parts[use->key]|= use->keypart_map;
2588
3232
        }
2589
3233
      }
2590
3234
    }
2860
3504
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
2861
3505
  JOIN *join= last_tab->join;
2862
3506
 
2863
 
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
 
3507
  if (join->cur_embedding_map & ~next_tab->embedding_map)
2864
3508
  {
2865
3509
    /*
2866
3510
      next_tab is outside of the "pair of brackets" we're currently in.
2986
3630
          }
2987
3631
          break;
2988
3632
        case Item::COND_UNDEF:                  /* Impossible */
2989
 
          break;
 
3633
          break; /* purecov: deadcode */
2990
3634
      }
2991
3635
    }
2992
3636
 
3284
3928
 
3285
3929
  if (table)
3286
3930
  {
3287
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
 
3931
    table->file->extra(HA_EXTRA_WRITE_CACHE);
3288
3932
    table->emptyRecord();
3289
3933
    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);
 
3934
        table->s->keys && !table->file->inited)
 
3935
      table->file->ha_index_init(0, 0);
3292
3936
  }
3293
3937
  /* Set up select_end */
3294
3938
  Next_select_func end_select= setup_end_select_func(join);
3360
4004
  if (table)
3361
4005
  {
3362
4006
    int tmp, new_errno= 0;
3363
 
    if ((tmp=table->cursor->extra(HA_EXTRA_NO_CACHE)))
 
4007
    if ((tmp=table->file->extra(HA_EXTRA_NO_CACHE)))
3364
4008
    {
3365
4009
      new_errno= tmp;
3366
4010
    }
3367
 
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
 
4011
    if ((tmp=table->file->ha_index_or_rnd_end()))
3368
4012
    {
3369
4013
      new_errno= tmp;
3370
4014
    }
3371
4015
    if (new_errno)
3372
 
      table->print_error(new_errno,MYF(0));
 
4016
      table->file->print_error(new_errno,MYF(0));
3373
4017
  }
3374
4018
  return(join->session->is_error() ? -1 : rc);
3375
4019
}
3388
4032
  if (join->session->killed)            // If aborted by user
3389
4033
  {
3390
4034
    join->session->send_kill_message();
3391
 
    return NESTED_LOOP_KILLED;
 
4035
    return NESTED_LOOP_KILLED;                   /* purecov: inspected */
3392
4036
  }
3393
4037
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3394
4038
  {
3586
4230
{
3587
4231
  int error;
3588
4232
  Table *table= tab->table;
3589
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
4233
  if ((error=table->file->index_read_map(table->record[0],
3590
4234
                                         tab->ref.key_buff,
3591
4235
                                         make_prev_keypart_map(tab->ref.key_parts),
3592
4236
                                         HA_READ_KEY_EXACT)))
3594
4238
  return 0;
3595
4239
}
3596
4240
 
3597
 
int join_read_const_table(JoinTable *tab, optimizer::Position *pos)
 
4241
int join_read_const_table(JoinTable *tab, POSITION *pos)
3598
4242
{
3599
4243
  int error;
3600
4244
  Table *table=tab->table;
3602
4246
  table->null_row=0;
3603
4247
  table->status=STATUS_NO_RECORD;
3604
4248
 
3605
 
  if (tab->type == AM_SYSTEM)
 
4249
  if (tab->type == JT_SYSTEM)
3606
4250
  {
3607
4251
    if ((error=join_read_system(tab)))
3608
4252
    {                                           // Info for DESCRIBE
3609
4253
      tab->info="const row not found";
3610
4254
      /* Mark for EXPLAIN that the row was not found */
3611
 
      pos->setFanout(0.0);
3612
 
      pos->clearRefDependMap();
3613
 
      if (! table->maybe_null || error > 0)
 
4255
      pos->records_read=0.0;
 
4256
      pos->ref_depend_map= 0;
 
4257
      if (!table->maybe_null || error > 0)
3614
4258
        return(error);
3615
4259
    }
3616
4260
  }
3617
4261
  else
3618
4262
  {
3619
 
    if (! table->key_read && 
 
4263
    if (!table->key_read && 
3620
4264
        table->covering_keys.test(tab->ref.key) && 
3621
 
        ! table->no_keyread &&
 
4265
        !table->no_keyread &&
3622
4266
        (int) table->reginfo.lock_type <= (int) TL_READ_WITH_SHARED_LOCKS)
3623
4267
    {
3624
4268
      table->key_read=1;
3625
 
      table->cursor->extra(HA_EXTRA_KEYREAD);
 
4269
      table->file->extra(HA_EXTRA_KEYREAD);
3626
4270
      tab->index= tab->ref.key;
3627
4271
    }
3628
4272
    error=join_read_const(tab);
3629
4273
    if (table->key_read)
3630
4274
    {
3631
4275
      table->key_read=0;
3632
 
      table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
4276
      table->file->extra(HA_EXTRA_NO_KEYREAD);
3633
4277
    }
3634
4278
    if (error)
3635
4279
    {
3636
4280
      tab->info="unique row not found";
3637
4281
      /* Mark for EXPLAIN that the row was not found */
3638
 
      pos->setFanout(0.0);
3639
 
      pos->clearRefDependMap();
 
4282
      pos->records_read=0.0;
 
4283
      pos->ref_depend_map= 0;
3640
4284
      if (!table->maybe_null || error > 0)
3641
4285
        return(error);
3642
4286
    }
3678
4322
  int error;
3679
4323
  if (table->status & STATUS_GARBAGE)           // If first read
3680
4324
  {
3681
 
    if ((error=table->cursor->read_first_row(table->record[0],
 
4325
    if ((error=table->file->read_first_row(table->record[0],
3682
4326
                                           table->s->primary_key)))
3683
4327
    {
3684
4328
      if (error != HA_ERR_END_OF_FILE)
3718
4362
      error= HA_ERR_KEY_NOT_FOUND;
3719
4363
    else
3720
4364
    {
3721
 
      error=table->cursor->index_read_idx_map(table->record[0],tab->ref.key,
 
4365
      error=table->file->index_read_idx_map(table->record[0],tab->ref.key,
3722
4366
                                            (unsigned char*) tab->ref.key_buff,
3723
4367
                                            make_prev_keypart_map(tab->ref.key_parts),
3724
4368
                                            HA_READ_KEY_EXACT);
3764
4408
  int error;
3765
4409
  Table *table= tab->table;
3766
4410
 
3767
 
  if (!table->cursor->inited)
 
4411
  if (!table->file->inited)
3768
4412
  {
3769
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
4413
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3770
4414
  }
3771
4415
 
3772
4416
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3778
4422
      table->status=STATUS_NOT_FOUND;
3779
4423
      return -1;
3780
4424
    }
3781
 
    error=table->cursor->index_read_map(table->record[0],
 
4425
    error=table->file->index_read_map(table->record[0],
3782
4426
                                      tab->ref.key_buff,
3783
4427
                                      make_prev_keypart_map(tab->ref.key_parts),
3784
4428
                                      HA_READ_KEY_EXACT);
3813
4457
  Table *table= tab->table;
3814
4458
 
3815
4459
  /* Initialize the index first */
3816
 
  if (!table->cursor->inited)
3817
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
4460
  if (!table->file->inited)
 
4461
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3818
4462
 
3819
4463
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3820
4464
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3825
4469
 
3826
4470
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3827
4471
    return -1;
3828
 
  if ((error=table->cursor->index_read_map(table->record[0],
 
4472
  if ((error=table->file->index_read_map(table->record[0],
3829
4473
                                         tab->ref.key_buff,
3830
4474
                                         make_prev_keypart_map(tab->ref.key_parts),
3831
4475
                                         HA_READ_KEY_EXACT)))
3832
4476
  {
3833
4477
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3834
4478
      return table->report_error(error);
3835
 
    return -1;
 
4479
    return -1; /* purecov: inspected */
3836
4480
  }
3837
4481
 
3838
4482
  return 0;
3839
4483
}
3840
4484
 
3841
4485
/**
3842
 
  This function is used when optimizing away ORDER BY in
3843
 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
 
4486
  This function is used when optimizing away order_st BY in
 
4487
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
3844
4488
*/
3845
4489
int join_read_last_key(JoinTable *tab)
3846
4490
{
3847
4491
  int error;
3848
4492
  Table *table= tab->table;
3849
4493
 
3850
 
  if (!table->cursor->inited)
3851
 
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
 
4494
  if (!table->file->inited)
 
4495
    table->file->ha_index_init(tab->ref.key, tab->sorted);
3852
4496
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3853
4497
    return -1;
3854
 
  if ((error=table->cursor->index_read_last_map(table->record[0],
 
4498
  if ((error=table->file->index_read_last_map(table->record[0],
3855
4499
                                              tab->ref.key_buff,
3856
4500
                                              make_prev_keypart_map(tab->ref.key_parts))))
3857
4501
  {
3858
4502
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3859
4503
      return table->report_error(error);
3860
 
    return -1;
 
4504
    return -1; /* purecov: inspected */
3861
4505
  }
3862
4506
  return 0;
3863
4507
}
3880
4524
      /* Save index tuple from record to the buffer */
3881
4525
      key_copy(tab->insideout_buf, info->record, key, 0);
3882
4526
 
3883
 
      if ((error=table->cursor->index_next_same(table->record[0],
 
4527
      if ((error=table->file->index_next_same(table->record[0],
3884
4528
                                              tab->ref.key_buff,
3885
4529
                                              tab->ref.key_length)))
3886
4530
      {
3904
4548
  Table *table= info->table;
3905
4549
  JoinTable *tab=table->reginfo.join_tab;
3906
4550
 
3907
 
  if ((error=table->cursor->index_next_same(table->record[0],
 
4551
  if ((error=table->file->index_next_same(table->record[0],
3908
4552
                                          tab->ref.key_buff,
3909
4553
                                          tab->ref.key_length)))
3910
4554
  {
3923
4567
  Table *table= info->table;
3924
4568
  JoinTable *tab=table->reginfo.join_tab;
3925
4569
 
3926
 
  if ((error=table->cursor->index_prev(table->record[0])))
 
4570
  if ((error=table->file->index_prev(table->record[0])))
3927
4571
    return table->report_error(error);
3928
4572
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3929
4573
                      tab->ref.key_length))
3945
4589
int init_read_record_seq(JoinTable *tab)
3946
4590
{
3947
4591
  tab->read_record.read_record= rr_sequential;
3948
 
  if (tab->read_record.cursor->ha_rnd_init(1))
 
4592
  if (tab->read_record.file->ha_rnd_init(1))
3949
4593
    return 1;
3950
4594
  return (*tab->read_record.read_record)(&tab->read_record);
3951
4595
}
3975
4619
      !table->no_keyread)
3976
4620
  {
3977
4621
    table->key_read=1;
3978
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
4622
    table->file->extra(HA_EXTRA_KEYREAD);
3979
4623
  }
3980
4624
  tab->table->status=0;
3981
4625
  tab->read_record.table=table;
3982
 
  tab->read_record.cursor=table->cursor;
 
4626
  tab->read_record.file=table->file;
3983
4627
  tab->read_record.index=tab->index;
3984
4628
  tab->read_record.record=table->record[0];
3985
4629
  if (tab->insideout_match_tab)
3994
4638
    tab->read_record.do_insideout_scan= 0;
3995
4639
  }
3996
4640
 
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])))
 
4641
  if (!table->file->inited)
 
4642
    table->file->ha_index_init(tab->index, tab->sorted);
 
4643
  if ((error=tab->table->file->index_first(tab->table->record[0])))
4000
4644
  {
4001
4645
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
4002
4646
      table->report_error(error);
4018
4662
      /* Save index tuple from record to the buffer */
4019
4663
      key_copy(tab->insideout_buf, info->record, key, 0);
4020
4664
 
4021
 
      if ((error=info->cursor->index_next(info->record)))
 
4665
      if ((error=info->file->index_next(info->record)))
4022
4666
        return info->table->report_error(error);
4023
4667
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
4024
4668
                      tab->insideout_buf, key->key_length));
4032
4676
int join_read_next(READ_RECORD *info)
4033
4677
{
4034
4678
  int error;
4035
 
  if ((error=info->cursor->index_next(info->record)))
 
4679
  if ((error=info->file->index_next(info->record)))
4036
4680
    return info->table->report_error(error);
4037
4681
  return 0;
4038
4682
}
4045
4689
      !table->no_keyread)
4046
4690
  {
4047
4691
    table->key_read=1;
4048
 
    table->cursor->extra(HA_EXTRA_KEYREAD);
 
4692
    table->file->extra(HA_EXTRA_KEYREAD);
4049
4693
  }
4050
4694
  tab->table->status=0;
4051
4695
  tab->read_record.read_record=join_read_prev;
4052
4696
  tab->read_record.table=table;
4053
 
  tab->read_record.cursor=table->cursor;
 
4697
  tab->read_record.file=table->file;
4054
4698
  tab->read_record.index=tab->index;
4055
4699
  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])))
 
4700
  if (!table->file->inited)
 
4701
    table->file->ha_index_init(tab->index, 1);
 
4702
  if ((error= tab->table->file->index_last(tab->table->record[0])))
4059
4703
    return table->report_error(error);
4060
4704
 
4061
4705
  return 0;
4064
4708
int join_read_prev(READ_RECORD *info)
4065
4709
{
4066
4710
  int error;
4067
 
  if ((error= info->cursor->index_prev(info->record)))
 
4711
  if ((error= info->file->index_prev(info->record)))
4068
4712
    return info->table->report_error(error);
4069
4713
 
4070
4714
  return 0;
4141
4785
          }
4142
4786
        }
4143
4787
        if (error > 0)
4144
 
          return(NESTED_LOOP_ERROR);
 
4788
          return(NESTED_LOOP_ERROR);        /* purecov: inspected */
4145
4789
        if (end_of_records)
4146
4790
          return(NESTED_LOOP_OK);
4147
4791
        if (join->send_records >= join->unit->select_limit_cnt &&
4198
4842
  if (join->session->killed)
4199
4843
  {                                             // Aborted by user
4200
4844
    join->session->send_kill_message();
4201
 
    return NESTED_LOOP_KILLED;
 
4845
    return NESTED_LOOP_KILLED;             /* purecov: inspected */
4202
4846
  }
4203
4847
  if (!join->first_record || end_of_records ||
4204
4848
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
4216
4860
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
4217
4861
        if (!join->having || join->having->val_int())
4218
4862
        {
4219
 
          int error= table->cursor->ha_write_row(table->record[0]);
 
4863
          int error= table->file->ha_write_row(table->record[0]);
4220
4864
          if (error && create_myisam_from_heap(join->session, table,
4221
4865
                                              join->tmp_table_param.start_recinfo,
4222
4866
                                                &join->tmp_table_param.recinfo,
4356
5000
      /* Create new top level AND item */
4357
5001
      Item_cond_and *new_cond=new Item_cond_and;
4358
5002
      if (!new_cond)
4359
 
        return (COND*) 0;
 
5003
        return (COND*) 0;                       // OOM /* purecov: inspected */
4360
5004
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4361
5005
      Item *item;
4362
5006
      while ((item=li++))
4386
5030
    {                                           // Or list
4387
5031
      Item_cond_or *new_cond=new Item_cond_or;
4388
5032
      if (!new_cond)
4389
 
        return (COND*) 0;
 
5033
        return (COND*) 0;                       // OOM /* purecov: inspected */
4390
5034
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
4391
5035
      Item *item;
4392
5036
      while ((item=li++))
4494
5138
*/
4495
5139
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
4496
5140
{
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;
 
5141
  KEY_PART_INFO *key_part,*key_part_end;
 
5142
  key_part=table->key_info[idx].key_part;
 
5143
  key_part_end=key_part+table->key_info[idx].key_parts;
4501
5144
  key_part_map const_key_parts=table->const_key_parts[idx];
4502
 
  int reverse= 0;
 
5145
  int reverse=0;
4503
5146
  bool on_primary_key= false;
4504
5147
 
4505
5148
  for (; order ; order=order->next, const_key_parts>>=1)
4509
5152
 
4510
5153
    /*
4511
5154
      Skip key parts that are constants in the WHERE clause.
4512
 
      These are already skipped in the ORDER BY by const_expression_in_where()
 
5155
      These are already skipped in the order_st BY by const_expression_in_where()
4513
5156
    */
4514
5157
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4515
5158
      key_part++;
4522
5165
        the primary key as a suffix.
4523
5166
      */
4524
5167
      if (!on_primary_key &&
4525
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
 
5168
          (table->file->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
4526
5169
          table->s->primary_key != MAX_KEY)
4527
5170
      {
4528
5171
        on_primary_key= true;
4556
5199
  }
4557
5200
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4558
5201
    (uint32_t) (key_part - table->key_info[idx].key_part);
4559
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
5202
  if (reverse == -1 && !(table->file->index_flags(idx, *used_key_parts-1, 1) &
4560
5203
                         HA_READ_PREV))
4561
5204
    reverse= 0;                                 // Index can't be used
4562
5205
  return(reverse);
4579
5222
*/
4580
5223
inline bool is_subkey(KEY_PART_INFO *key_part,
4581
5224
                      KEY_PART_INFO *ref_key_part,
4582
 
                      KEY_PART_INFO *ref_key_part_end)
 
5225
                            KEY_PART_INFO *ref_key_part_end)
4583
5226
{
4584
5227
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4585
 
    if (! key_part->field->eq(ref_key_part->field))
 
5228
    if (!key_part->field->eq(ref_key_part->field))
4586
5229
      return 0;
4587
5230
  return 1;
4588
5231
}
4602
5245
                               Table *table,
4603
5246
                               uint32_t ref,
4604
5247
                               uint32_t ref_key_parts,
4605
 
                               const key_map *usable_keys)
 
5248
                                     const key_map *usable_keys)
4606
5249
{
4607
5250
  uint32_t nr;
4608
5251
  uint32_t min_length= UINT32_MAX;
4666
5309
         (table->key_info[keynr].flags & HA_NOSAME))
4667
5310
    {
4668
5311
      KEY *keyinfo= table->key_info + keynr;
4669
 
      KEY_PART_INFO *key_part= NULL;
4670
 
      KEY_PART_INFO *key_part_end= NULL;
 
5312
      KEY_PART_INFO *key_part, *key_part_end;
4671
5313
 
4672
5314
      for (key_part=keyinfo->key_part,
4673
5315
           key_part_end=key_part+ keyinfo->key_parts;
4675
5317
           key_part++)
4676
5318
      {
4677
5319
        if (key_part->field->maybe_null() ||
4678
 
            ! find_func(key_part->field, data))
 
5320
            !find_func(key_part->field, data))
4679
5321
          break;
4680
5322
      }
4681
5323
      if (key_part == key_part_end)
4748
5390
}
4749
5391
 
4750
5392
/**
4751
 
  Test if we can skip the ORDER BY by using an index.
 
5393
  Test if we can skip the order_st BY by using an index.
4752
5394
 
4753
5395
  SYNOPSIS
4754
5396
    test_if_skip_sort_order()
4779
5421
  int order_direction;
4780
5422
  uint32_t used_key_parts;
4781
5423
  Table *table=tab->table;
4782
 
  optimizer::SqlSelect *select= tab->select;
 
5424
  SQL_SELECT *select=tab->select;
4783
5425
  key_map usable_keys;
4784
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
5426
  QUICK_SELECT_I *save_quick= 0;
4785
5427
 
4786
5428
  /*
4787
5429
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4808
5450
  {
4809
5451
    ref_key=       tab->ref.key;
4810
5452
    ref_key_parts= tab->ref.key_parts;
4811
 
    if (tab->type == AM_REF_OR_NULL)
 
5453
    if (tab->type == JT_REF_OR_NULL)
4812
5454
      return(0);
4813
5455
  }
4814
 
  else if (select && select->quick)             // Range found by optimizer/range
 
5456
  else if (select && select->quick)             // Range found by opt_range
4815
5457
  {
4816
5458
    int quick_type= select->quick->get_type();
4817
5459
    save_quick= select->quick;
4821
5463
      by clustered PK values.
4822
5464
    */
4823
5465
 
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)
 
5466
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
5467
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
5468
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
4827
5469
      return(0);
4828
5470
    ref_key=       select->quick->index;
4829
5471
    ref_key_parts= select->quick->used_key_parts;
4862
5504
            "part1 = const1 AND part2=const2".
4863
5505
            So we build tab->ref from scratch here.
4864
5506
          */
4865
 
          optimizer::KeyUse *keyuse= tab->keyuse;
4866
 
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
 
5507
          KeyUse *keyuse= tab->keyuse;
 
5508
          while (keyuse->key != new_ref_key && keyuse->table == tab->table)
4867
5509
            keyuse++;
4868
5510
 
4869
5511
          if (create_ref_for_key(tab->join, tab, keyuse,
4873
5515
        else
4874
5516
        {
4875
5517
          /*
4876
 
            The range optimizer constructed QuickRange for ref_key, and
 
5518
            The range optimizer constructed QUICK_RANGE for ref_key, and
4877
5519
            we want to use instead new_ref_key as the index. We can't
4878
5520
            just change the index of the quick select, because this may
4879
5521
            result in an incosistent QUICK_SELECT object. Below we
4920
5562
    double fanout= 1;
4921
5563
    JOIN *join= tab->join;
4922
5564
    uint32_t tablenr= tab - join->join_tab;
4923
 
    ha_rows table_records= table->cursor->stats.records;
 
5565
    ha_rows table_records= table->file->stats.records;
4924
5566
    bool group= join->group && order == join->group_list;
4925
 
    optimizer::Position cur_pos;
4926
5567
 
4927
5568
    /*
4928
5569
      If not used with LIMIT, only use keys if the whole query can be
4935
5576
        filesort() and join cache are usually faster than reading in
4936
5577
        index order and not using join cache
4937
5578
        */
4938
 
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
 
5579
      if (tab->type == JT_ALL && tab->join->tables > tab->join->const_tables + 1)
4939
5580
        return(0);
4940
 
      keys= *table->cursor->keys_to_use_for_scanning();
 
5581
      keys= *table->file->keys_to_use_for_scanning();
4941
5582
      keys|= table->covering_keys;
4942
5583
 
4943
5584
      /*
4953
5594
    else
4954
5595
      keys= usable_keys;
4955
5596
 
4956
 
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4957
 
    read_time= cur_pos.getCost();
 
5597
    read_time= join->best_positions[tablenr].read_time;
4958
5598
    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
 
    }
 
5599
      fanout*= join->best_positions[i].records_read; // fanout is always >= 1
4963
5600
 
4964
5601
    for (nr=0; nr < table->s->keys ; nr++)
4965
5602
    {
4967
5604
      if (keys.test(nr) &&
4968
5605
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4969
5606
      {
4970
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->cursor->primary_key_is_clustered());
 
5607
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->file->primary_key_is_clustered());
4971
5608
 
4972
5609
        /*
4973
 
          Don't use an index scan with ORDER BY without limit.
 
5610
          Don't use an index scan with order_st BY without limit.
4974
5611
          For GROUP BY without limit always use index scan
4975
5612
          if there is a suitable index.
4976
5613
          Why we hold to this asymmetry hardly can be explained
5037
5674
            Rows in such a sequence are supposed to be ordered
5038
5675
            by rowid/primary key. When reading the data
5039
5676
            in a sequence we'll touch not more pages than the
5040
 
            table cursor contains.
 
5677
            table file contains.
5041
5678
            TODO. Use the formula for a disk sweep sequential access
5042
5679
            to calculate the cost of accessing data rows for one
5043
5680
            index entry.
5044
5681
          */
5045
5682
          index_scan_time= select_limit/rec_per_key *
5046
 
                           min(rec_per_key, table->cursor->scan_time());
 
5683
                           min(rec_per_key, table->file->scan_time());
5047
5684
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
5048
5685
              index_scan_time < read_time)
5049
5686
          {
5089
5726
          tab->index= best_key;
5090
5727
          tab->read_first_record= best_key_direction > 0 ?
5091
5728
                                  join_read_first:join_read_last;
5092
 
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
 
5729
          tab->type=JT_NEXT;           // Read with index_first(), index_next()
5093
5730
          if (select && select->quick)
5094
5731
          {
5095
5732
            delete select->quick;
5098
5735
          if (table->covering_keys.test(best_key))
5099
5736
          {
5100
5737
            table->key_read=1;
5101
 
            table->cursor->extra(HA_EXTRA_KEYREAD);
 
5738
            table->file->extra(HA_EXTRA_KEYREAD);
5102
5739
          }
5103
 
          table->cursor->ha_index_or_rnd_end();
 
5740
          table->file->ha_index_or_rnd_end();
5104
5741
          if (join->select_options & SELECT_DESCRIBE)
5105
5742
          {
5106
5743
            tab->ref.key= -1;
5109
5746
              tab->limit= select_limit;
5110
5747
          }
5111
5748
        }
5112
 
        else if (tab->type != AM_ALL)
 
5749
        else if (tab->type != JT_ALL)
5113
5750
        {
5114
5751
          /*
5115
5752
            We're about to use a quick access to the table.
5117
5754
            method is actually used.
5118
5755
          */
5119
5756
          assert(tab->select->quick);
5120
 
          tab->type= AM_ALL;
 
5757
          tab->type=JT_ALL;
5121
5758
          tab->use_quick=1;
5122
5759
          tab->ref.key= -1;
5123
5760
          tab->ref.key_parts=0;         // Don't use ref key.
5124
5761
          tab->read_first_record= join_init_read_record;
 
5762
          /*
 
5763
            TODO: update the number of records in join->best_positions[tablenr]
 
5764
          */
5125
5765
        }
5126
5766
      }
5127
5767
      used_key_parts= best_key_parts;
5132
5772
  }
5133
5773
 
5134
5774
check_reverse_order:
5135
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
5775
  if (order_direction == -1)            // If order_st BY ... DESC
5136
5776
  {
5137
5777
    if (select && select->quick)
5138
5778
    {
5140
5780
        Don't reverse the sort order, if it's already done.
5141
5781
        (In some cases test_if_order_by_key() can be called multiple times
5142
5782
      */
5143
 
      if (! select->quick->reverse_sorted())
 
5783
      if (!select->quick->reverse_sorted())
5144
5784
      {
5145
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
5785
        QUICK_SELECT_DESC *tmp;
5146
5786
        bool error= false;
5147
5787
        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)
 
5788
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
5789
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
5790
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
5791
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
5152
5792
        {
5153
5793
          tab->limit= 0;
5154
5794
          select->quick= save_quick;
5155
 
          return 0; // Use filesort
 
5795
          return(0);                   // Use filesort
5156
5796
        }
5157
5797
 
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)
 
5798
        /* order_st BY range_key DESC */
 
5799
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
5800
                                          used_key_parts, &error);
 
5801
        if (!tmp || error)
5163
5802
        {
5164
5803
          delete tmp;
5165
 
          select->quick= save_quick;
5166
 
          tab->limit= 0;
5167
 
          return 0; // Reverse sort not supported
 
5804
                select->quick= save_quick;
 
5805
                tab->limit= 0;
 
5806
          return(0);            // Reverse sort not supported
5168
5807
        }
5169
5808
        select->quick=tmp;
5170
5809
      }
5171
5810
    }
5172
 
    else if (tab->type != AM_NEXT &&
 
5811
    else if (tab->type != JT_NEXT &&
5173
5812
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
5174
5813
    {
5175
5814
      /*
5176
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
5815
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
5177
5816
 
5178
5817
        Use a traversal function that starts by reading the last row
5179
5818
        with key part (A) and then traverse the index backwards.
5184
5823
  }
5185
5824
  else if (select && select->quick)
5186
5825
    select->quick->sorted= 1;
5187
 
  return 1;
 
5826
  return(1);
5188
5827
}
5189
5828
 
5190
5829
/*
5192
5831
 
5193
5832
  SYNOPSIS
5194
5833
   create_sort_index()
5195
 
     session            Thread Cursor
 
5834
     session            Thread handler
5196
5835
     tab                Table to sort (in join structure)
5197
5836
     order              How table should be sorted
5198
5837
     filesort_limit     Max number of rows that needs to be sorted
5205
5844
  IMPLEMENTATION
5206
5845
   - If there is an index that can be used, 'tab' is modified to use
5207
5846
     this index.
5208
 
   - If no index, create with filesort() an index cursor that can be used to
 
5847
   - If no index, create with filesort() an index file that can be used to
5209
5848
     retrieve rows in order (should be done with 'read_record').
5210
5849
     The sorted data is stored in tab->table and will be freed when calling
5211
5850
     tab->table->free_io_cache().
5220
5859
  uint32_t length= 0;
5221
5860
  ha_rows examined_rows;
5222
5861
  Table *table;
5223
 
  optimizer::SqlSelect *select= NULL;
 
5862
  SQL_SELECT *select;
5224
5863
  JoinTable *tab;
5225
5864
 
5226
5865
  if (join->tables == join->const_tables)
5237
5876
  */
5238
5877
  if ((order != join->group_list ||
5239
5878
       !(join->select_options & SELECT_BIG_RESULT) ||
5240
 
       (select && select->quick && (select->quick->get_type() == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))) &&
 
5879
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
5241
5880
      test_if_skip_sort_order(tab,order,select_limit,0,
5242
5881
                              is_order_by ?  &table->keys_in_use_for_order_by :
5243
5882
                              &table->keys_in_use_for_group_by))
5246
5885
    length++;
5247
5886
  if (!(join->sortorder=
5248
5887
        make_unireg_sortorder(order, &length, join->sortorder)))
5249
 
    goto err;
 
5888
    goto err;                           /* purecov: inspected */
5250
5889
 
5251
 
  table->sort.io_cache= new internal::IO_CACHE;
5252
 
  memset(table->sort.io_cache, 0, sizeof(internal::IO_CACHE));
 
5890
  table->sort.io_cache= new IO_CACHE;
 
5891
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
5253
5892
  table->status=0;                              // May be wrong if quick_select
5254
5893
 
5255
5894
  // If table has a range, move it to select
5266
5905
      if (table->key_read && ((uint32_t) tab->ref.key != select->quick->index))
5267
5906
      {
5268
5907
        table->key_read=0;
5269
 
        table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
5908
        table->file->extra(HA_EXTRA_NO_KEYREAD);
5270
5909
      }
5271
5910
    }
5272
5911
    else
5277
5916
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5278
5917
        field, quick will contain an empty record set.
5279
5918
      */
5280
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
5281
 
                                                                 table, 
5282
 
                                                                 &tab->ref,
5283
 
                                                                 tab->found_records))))
5284
 
      {
 
5919
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
5920
                                                     tab->found_records))))
5285
5921
        goto err;
5286
 
      }
5287
5922
    }
5288
5923
  }
5289
5924
 
 
5925
  /* Fill schema tables with data before filesort if it's necessary */
 
5926
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
 
5927
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
 
5928
    goto err;
 
5929
 
5290
5930
  if (table->s->tmp_table)
5291
 
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
 
5931
    table->file->info(HA_STATUS_VARIABLE);      // Get record count
5292
5932
  table->sort.found_records=filesort(session, table,join->sortorder, length,
5293
5933
                                     select, filesort_limit, 0,
5294
5934
                                     &examined_rows);
5301
5941
  tab->select_cond=0;
5302
5942
  tab->last_inner= 0;
5303
5943
  tab->first_unmatched= 0;
5304
 
  tab->type= AM_ALL;                            // Read with normal read_record
 
5944
  tab->type=JT_ALL;                             // Read with normal read_record
5305
5945
  tab->read_first_record= join_init_read_record;
5306
5946
  tab->join->examined_rows+=examined_rows;
5307
5947
  if (table->key_read)                          // Restore if we used indexes
5308
5948
  {
5309
5949
    table->key_read=0;
5310
 
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
 
5950
    table->file->extra(HA_EXTRA_NO_KEYREAD);
5311
5951
  }
5312
5952
  return(table->sort.found_records == HA_POS_ERROR);
5313
5953
err:
5316
5956
 
5317
5957
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5318
5958
{
5319
 
  Cursor *cursor=table->cursor;
 
5959
  handler *file=table->file;
5320
5960
  char *org_record,*new_record;
5321
5961
  unsigned char *record;
5322
5962
  int error;
5325
5965
  org_record=(char*) (record=table->record[0])+offset;
5326
5966
  new_record=(char*) table->record[1]+offset;
5327
5967
 
5328
 
  cursor->ha_rnd_init(1);
5329
 
  error=cursor->rnd_next(record);
 
5968
  file->ha_rnd_init(1);
 
5969
  error=file->rnd_next(record);
5330
5970
  for (;;)
5331
5971
  {
5332
5972
    if (session->killed)
5345
5985
    }
5346
5986
    if (having && !having->val_int())
5347
5987
    {
5348
 
      if ((error=cursor->ha_delete_row(record)))
 
5988
      if ((error=file->ha_delete_row(record)))
5349
5989
        goto err;
5350
 
      error=cursor->rnd_next(record);
 
5990
      error=file->rnd_next(record);
5351
5991
      continue;
5352
5992
    }
5353
5993
    if (copy_blobs(first_field))
5358
5998
    }
5359
5999
    memcpy(new_record,org_record,reclength);
5360
6000
 
5361
 
    /* Read through rest of cursor and mark duplicated rows deleted */
 
6001
    /* Read through rest of file and mark duplicated rows deleted */
5362
6002
    bool found=0;
5363
6003
    for (;;)
5364
6004
    {
5365
 
      if ((error=cursor->rnd_next(record)))
 
6005
      if ((error=file->rnd_next(record)))
5366
6006
      {
5367
6007
        if (error == HA_ERR_RECORD_DELETED)
5368
6008
          continue;
5372
6012
      }
5373
6013
      if (table->compare_record(first_field) == 0)
5374
6014
      {
5375
 
        if ((error=cursor->ha_delete_row(record)))
 
6015
        if ((error=file->ha_delete_row(record)))
5376
6016
          goto err;
5377
6017
      }
5378
6018
      else if (!found)
5379
6019
      {
5380
6020
        found= 1;
5381
 
        cursor->position(record);       // Remember position
 
6021
        file->position(record); // Remember position
5382
6022
      }
5383
6023
    }
5384
6024
    if (!found)
5385
 
      break;                                    // End of cursor
 
6025
      break;                                    // End of file
5386
6026
    /* Restart search on next row */
5387
 
    error=cursor->restart_rnd_next(record,cursor->ref);
 
6027
    error=file->restart_rnd_next(record,file->ref);
5388
6028
  }
5389
6029
 
5390
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6030
  file->extra(HA_EXTRA_NO_CACHE);
5391
6031
  return(0);
5392
6032
err:
5393
 
  cursor->extra(HA_EXTRA_NO_CACHE);
 
6033
  file->extra(HA_EXTRA_NO_CACHE);
5394
6034
  if (error)
5395
 
    table->print_error(error,MYF(0));
 
6035
    file->print_error(error,MYF(0));
5396
6036
  return(1);
5397
6037
}
5398
6038
 
5411
6051
{
5412
6052
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5413
6053
  int error;
5414
 
  Cursor *cursor= table->cursor;
 
6054
  handler *file= table->file;
5415
6055
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5416
6056
  uint32_t *field_lengths,*field_length;
5417
6057
  HASH hash;
5418
6058
 
5419
 
  if (! memory::multi_malloc(false,
 
6059
  if (!my_multi_malloc(MYF(MY_WME),
5420
6060
                       &key_buffer,
5421
6061
                       (uint32_t) ((key_length + extra_length) *
5422
 
                               (long) cursor->stats.records),
 
6062
                               (long) file->stats.records),
5423
6063
                       &field_lengths,
5424
6064
                       (uint32_t) (field_count*sizeof(*field_lengths)),
5425
6065
                       NULL))
5439
6079
    extra_length= ALIGN_SIZE(key_length)-key_length;
5440
6080
  }
5441
6081
 
5442
 
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor->stats.records, 0,
 
6082
  if (hash_init(&hash, &my_charset_bin, (uint32_t) file->stats.records, 0,
5443
6083
                key_length, (hash_get_key) 0, 0, 0))
5444
6084
  {
5445
6085
    free((char*) key_buffer);
5446
6086
    return(1);
5447
6087
  }
5448
6088
 
5449
 
  cursor->ha_rnd_init(1);
 
6089
  file->ha_rnd_init(1);
5450
6090
  key_pos=key_buffer;
5451
6091
  for (;;)
5452
6092
  {
5457
6097
      error=0;
5458
6098
      goto err;
5459
6099
    }
5460
 
    if ((error=cursor->rnd_next(record)))
 
6100
    if ((error=file->rnd_next(record)))
5461
6101
    {
5462
6102
      if (error == HA_ERR_RECORD_DELETED)
5463
6103
        continue;
5467
6107
    }
5468
6108
    if (having && !having->val_int())
5469
6109
    {
5470
 
      if ((error=cursor->ha_delete_row(record)))
 
6110
      if ((error=file->ha_delete_row(record)))
5471
6111
        goto err;
5472
6112
      continue;
5473
6113
    }
5484
6124
    if (hash_search(&hash, org_key_pos, key_length))
5485
6125
    {
5486
6126
      /* Duplicated found ; Remove the row */
5487
 
      if ((error=cursor->ha_delete_row(record)))
 
6127
      if ((error=file->ha_delete_row(record)))
5488
6128
        goto err;
5489
6129
    }
5490
6130
    else
5493
6133
  }
5494
6134
  free((char*) key_buffer);
5495
6135
  hash_free(&hash);
5496
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5497
 
  (void) cursor->ha_rnd_end();
 
6136
  file->extra(HA_EXTRA_NO_CACHE);
 
6137
  (void) file->ha_rnd_end();
5498
6138
  return(0);
5499
6139
 
5500
6140
err:
5501
6141
  free((char*) key_buffer);
5502
6142
  hash_free(&hash);
5503
 
  cursor->extra(HA_EXTRA_NO_CACHE);
5504
 
  (void) cursor->ha_rnd_end();
 
6143
  file->extra(HA_EXTRA_NO_CACHE);
 
6144
  (void) file->ha_rnd_end();
5505
6145
  if (error)
5506
 
    table->print_error(error,MYF(0));
 
6146
    file->print_error(error,MYF(0));
5507
6147
  return(1);
5508
6148
}
5509
6149
 
5516
6156
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5517
6157
    count++;
5518
6158
  if (!sortorder)
5519
 
    sortorder= (SORT_FIELD*) memory::sql_alloc(sizeof(SORT_FIELD) *
 
6159
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
5520
6160
                                       (max(count, *length) + 1));
5521
6161
  pos= sort= sortorder;
5522
6162
 
5604
6244
*****************************************************************************/
5605
6245
 
5606
6246
/**
5607
 
  Resolve an ORDER BY or GROUP BY column reference.
 
6247
  Resolve an order_st BY or GROUP BY column reference.
5608
6248
 
5609
6249
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5610
6250
  BY clause, find the actual column it represents. If the column being
5611
6251
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5612
6252
  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.
 
6253
  the order_st BY clause, only the SELECT list is being searched.
5614
6254
 
5615
6255
  If 'order' is resolved to an Item, then order->item is set to the found
5616
6256
  Item. If there is no item for the found column (that is, it was resolved
5696
6336
        order_item_type == Item::REF_ITEM)
5697
6337
    {
5698
6338
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5699
 
                                       NULL, &view_ref, IGNORE_ERRORS, false);
 
6339
                                       NULL, &view_ref, IGNORE_ERRORS, true,
 
6340
                                       false);
5700
6341
      if (!from_field)
5701
6342
        from_field= (Field*) not_found_field;
5702
6343
    }
5792
6433
/**
5793
6434
  Intitialize the GROUP BY list.
5794
6435
 
5795
 
  @param session                        Thread Cursor
 
6436
  @param session                        Thread handler
5796
6437
  @param ref_pointer_array      We store references to all fields that was
5797
6438
                               not in 'fields' here.
5798
6439
  @param fields         All fields in the select part. Any item in
6151
6792
                another extra byte to not get warnings from purify in
6152
6793
                Field_varstring::val_int
6153
6794
              */
6154
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
 
6795
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
6155
6796
          goto err;
6156
6797
        if (copy)
6157
6798
        {
6197
6838
    itr++;
6198
6839
  itr.sublist(res_selected_fields, elements);
6199
6840
  /*
6200
 
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
 
6841
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
6201
6842
    reference used in these will resolve to a item that is already calculated
6202
6843
  */
6203
6844
  param->copy_funcs.concat(&extra_funcs);
6362
7003
/**
6363
7004
  Call ::setup for all sum functions.
6364
7005
 
6365
 
  @param session           thread Cursor
 
7006
  @param session           thread handler
6366
7007
  @param func_ptr      sum function list
6367
7008
 
6368
7009
  @retval
6537
7178
  return 0;
6538
7179
}
6539
7180
 
 
7181
/**
 
7182
  EXPLAIN handling.
 
7183
 
 
7184
  Send a description about what how the select will be done to stdout.
 
7185
*/
 
7186
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
 
7187
                     bool distinct,const char *message)
 
7188
{
 
7189
  List<Item> field_list;
 
7190
  List<Item> item_list;
 
7191
  Session *session=join->session;
 
7192
  select_result *result=join->result;
 
7193
  Item *item_null= new Item_null();
 
7194
  const CHARSET_INFO * const cs= system_charset_info;
 
7195
  int quick_type;
 
7196
  /* Don't log this into the slow query log */
 
7197
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
7198
  join->unit->offset_limit_cnt= 0;
 
7199
 
 
7200
  /*
 
7201
    NOTE: the number/types of items pushed into item_list must be in sync with
 
7202
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
 
7203
  */
 
7204
  if (message)
 
7205
  {
 
7206
    item_list.push_back(new Item_int((int32_t)
 
7207
                                     join->select_lex->select_number));
 
7208
    item_list.push_back(new Item_string(join->select_lex->type,
 
7209
                                        strlen(join->select_lex->type), cs));
 
7210
    for (uint32_t i=0 ; i < 7; i++)
 
7211
      item_list.push_back(item_null);
 
7212
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7213
      item_list.push_back(item_null);
 
7214
 
 
7215
    item_list.push_back(new Item_string(message,strlen(message),cs));
 
7216
    if (result->send_data(item_list))
 
7217
      join->error= 1;
 
7218
  }
 
7219
  else if (join->select_lex == join->unit->fake_select_lex)
 
7220
  {
 
7221
    /*
 
7222
      here we assume that the query will return at least two rows, so we
 
7223
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
 
7224
      and no filesort will be actually done, but executing all selects in
 
7225
      the UNION to provide precise EXPLAIN information will hardly be
 
7226
      appreciated :)
 
7227
    */
 
7228
    char table_name_buffer[NAME_LEN];
 
7229
    item_list.empty();
 
7230
    /* id */
 
7231
    item_list.push_back(new Item_null);
 
7232
    /* select_type */
 
7233
    item_list.push_back(new Item_string(join->select_lex->type,
 
7234
                                        strlen(join->select_lex->type),
 
7235
                                        cs));
 
7236
    /* table */
 
7237
    {
 
7238
      Select_Lex *sl= join->unit->first_select();
 
7239
      uint32_t len= 6, lastop= 0;
 
7240
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
 
7241
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
 
7242
      {
 
7243
        len+= lastop;
 
7244
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
 
7245
                         "%u,", sl->select_number);
 
7246
      }
 
7247
      if (sl || len + lastop >= NAME_LEN)
 
7248
      {
 
7249
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
 
7250
        len+= 4;
 
7251
      }
 
7252
      else
 
7253
      {
 
7254
        len+= lastop;
 
7255
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
 
7256
      }
 
7257
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
7258
    }
 
7259
    /* type */
 
7260
    item_list.push_back(new Item_string(join_type_str[JT_ALL],
 
7261
                                          strlen(join_type_str[JT_ALL]),
 
7262
                                          cs));
 
7263
    /* possible_keys */
 
7264
    item_list.push_back(item_null);
 
7265
    /* key*/
 
7266
    item_list.push_back(item_null);
 
7267
    /* key_len */
 
7268
    item_list.push_back(item_null);
 
7269
    /* ref */
 
7270
    item_list.push_back(item_null);
 
7271
    /* in_rows */
 
7272
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7273
      item_list.push_back(item_null);
 
7274
    /* rows */
 
7275
    item_list.push_back(item_null);
 
7276
    /* extra */
 
7277
    if (join->unit->global_parameters->order_list.first)
 
7278
      item_list.push_back(new Item_string("Using filesort",
 
7279
                                          14, cs));
 
7280
    else
 
7281
      item_list.push_back(new Item_string("", 0, cs));
 
7282
 
 
7283
    if (result->send_data(item_list))
 
7284
      join->error= 1;
 
7285
  }
 
7286
  else
 
7287
  {
 
7288
    table_map used_tables=0;
 
7289
    for (uint32_t i=0 ; i < join->tables ; i++)
 
7290
    {
 
7291
      JoinTable *tab=join->join_tab+i;
 
7292
      Table *table=tab->table;
 
7293
      TableList *table_list= tab->table->pos_in_table_list;
 
7294
      char buff[512];
 
7295
      char buff1[512], buff2[512], buff3[512];
 
7296
      char keylen_str_buf[64];
 
7297
      String extra(buff, sizeof(buff),cs);
 
7298
      char table_name_buffer[NAME_LEN];
 
7299
      String tmp1(buff1,sizeof(buff1),cs);
 
7300
      String tmp2(buff2,sizeof(buff2),cs);
 
7301
      String tmp3(buff3,sizeof(buff3),cs);
 
7302
      extra.length(0);
 
7303
      tmp1.length(0);
 
7304
      tmp2.length(0);
 
7305
      tmp3.length(0);
 
7306
 
 
7307
      quick_type= -1;
 
7308
      item_list.empty();
 
7309
      /* id */
 
7310
      item_list.push_back(new Item_uint((uint32_t)
 
7311
                                       join->select_lex->select_number));
 
7312
      /* select_type */
 
7313
      item_list.push_back(new Item_string(join->select_lex->type,
 
7314
                                          strlen(join->select_lex->type),
 
7315
                                          cs));
 
7316
      if (tab->type == JT_ALL && tab->select && tab->select->quick)
 
7317
      {
 
7318
        quick_type= tab->select->quick->get_type();
 
7319
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
 
7320
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
 
7321
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
 
7322
          tab->type = JT_INDEX_MERGE;
 
7323
        else
 
7324
          tab->type = JT_RANGE;
 
7325
      }
 
7326
      /* table */
 
7327
      if (table->derived_select_number)
 
7328
      {
 
7329
        /* Derived table name generation */
 
7330
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
7331
                          "<derived%u>",
 
7332
                          table->derived_select_number);
 
7333
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
7334
      }
 
7335
      else
 
7336
      {
 
7337
        TableList *real_table= table->pos_in_table_list;
 
7338
        item_list.push_back(new Item_string(real_table->alias,
 
7339
                                            strlen(real_table->alias),
 
7340
                                            cs));
 
7341
      }
 
7342
      /* "type" column */
 
7343
      item_list.push_back(new Item_string(join_type_str[tab->type],
 
7344
                                          strlen(join_type_str[tab->type]),
 
7345
                                          cs));
 
7346
      /* Build "possible_keys" value and add it to item_list */
 
7347
      if (tab->keys.any())
 
7348
      {
 
7349
        uint32_t j;
 
7350
        for (j=0 ; j < table->s->keys ; j++)
 
7351
        {
 
7352
          if (tab->keys.test(j))
 
7353
          {
 
7354
            if (tmp1.length())
 
7355
              tmp1.append(',');
 
7356
            tmp1.append(table->key_info[j].name,
 
7357
                        strlen(table->key_info[j].name),
 
7358
                        system_charset_info);
 
7359
          }
 
7360
        }
 
7361
      }
 
7362
      if (tmp1.length())
 
7363
        item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
 
7364
      else
 
7365
        item_list.push_back(item_null);
 
7366
 
 
7367
      /* Build "key", "key_len", and "ref" values and add them to item_list */
 
7368
      if (tab->ref.key_parts)
 
7369
      {
 
7370
        KEY *key_info=table->key_info+ tab->ref.key;
 
7371
        register uint32_t length;
 
7372
        item_list.push_back(new Item_string(key_info->name,
 
7373
                                            strlen(key_info->name),
 
7374
                                            system_charset_info));
 
7375
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
 
7376
                keylen_str_buf;
 
7377
        item_list.push_back(new Item_string(keylen_str_buf, length,
 
7378
                                            system_charset_info));
 
7379
        for (StoredKey **ref=tab->ref.key_copy ; *ref ; ref++)
 
7380
        {
 
7381
          if (tmp2.length())
 
7382
            tmp2.append(',');
 
7383
          tmp2.append((*ref)->name(), strlen((*ref)->name()),
 
7384
                      system_charset_info);
 
7385
        }
 
7386
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
7387
      }
 
7388
      else if (tab->type == JT_NEXT)
 
7389
      {
 
7390
        KEY *key_info=table->key_info+ tab->index;
 
7391
        register uint32_t length;
 
7392
        item_list.push_back(new Item_string(key_info->name,
 
7393
                                            strlen(key_info->name),cs));
 
7394
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
 
7395
                keylen_str_buf;
 
7396
        item_list.push_back(new Item_string(keylen_str_buf,
 
7397
                                            length,
 
7398
                                            system_charset_info));
 
7399
        item_list.push_back(item_null);
 
7400
      }
 
7401
      else if (tab->select && tab->select->quick)
 
7402
      {
 
7403
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
 
7404
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
7405
        item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
 
7406
        item_list.push_back(item_null);
 
7407
      }
 
7408
      else
 
7409
      {
 
7410
        if (table_list->schema_table && 
 
7411
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
7412
        {
 
7413
          if (table_list->has_db_lookup_value)
 
7414
          {
 
7415
            int f_idx= table_list->schema_table->getFirstColumnIndex();
 
7416
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
7417
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
7418
          }
 
7419
          if (table_list->has_table_lookup_value)
 
7420
          {
 
7421
            if (table_list->has_db_lookup_value)
 
7422
              tmp2.append(',');
 
7423
            int f_idx= table_list->schema_table->getSecondColumnIndex();
 
7424
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
7425
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
7426
          }
 
7427
          if (tmp2.length())
 
7428
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
7429
          else
 
7430
            item_list.push_back(item_null);
 
7431
        }
 
7432
        else
 
7433
          item_list.push_back(item_null);
 
7434
        item_list.push_back(item_null);
 
7435
        item_list.push_back(item_null);
 
7436
      }
 
7437
 
 
7438
      /* Add "rows" field to item_list. */
 
7439
      if (table_list->schema_table)
 
7440
      {
 
7441
        /* in_rows */
 
7442
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7443
          item_list.push_back(item_null);
 
7444
        /* rows */
 
7445
        item_list.push_back(item_null);
 
7446
      }
 
7447
      else
 
7448
      {
 
7449
        double examined_rows;
 
7450
        if (tab->select && tab->select->quick)
 
7451
          examined_rows= rows2double(tab->select->quick->records);
 
7452
        else if (tab->type == JT_NEXT || tab->type == JT_ALL)
 
7453
          examined_rows= rows2double(tab->limit ? tab->limit :
 
7454
                                     tab->table->file->records());
 
7455
        else
 
7456
          examined_rows= join->best_positions[i].records_read;
 
7457
 
 
7458
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
 
7459
                                         MY_INT64_NUM_DECIMAL_DIGITS));
 
7460
 
 
7461
        /* Add "filtered" field to item_list. */
 
7462
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
7463
        {
 
7464
          float f= 0.0;
 
7465
          if (examined_rows)
 
7466
            f= (float) (100.0 * join->best_positions[i].records_read /
 
7467
                        examined_rows);
 
7468
          item_list.push_back(new Item_float(f, 2));
 
7469
        }
 
7470
      }
 
7471
 
 
7472
      /* Build "Extra" field and add it to item_list. */
 
7473
      bool key_read=table->key_read;
 
7474
      if ((tab->type == JT_NEXT || tab->type == JT_CONST) &&
 
7475
          table->covering_keys.test(tab->index))
 
7476
        key_read=1;
 
7477
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
 
7478
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
 
7479
        key_read=1;
 
7480
 
 
7481
      if (tab->info)
 
7482
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
 
7483
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
 
7484
      {
 
7485
        if (tab->packed_info & TAB_INFO_USING_INDEX)
 
7486
          extra.append(STRING_WITH_LEN("; Using index"));
 
7487
        if (tab->packed_info & TAB_INFO_USING_WHERE)
 
7488
          extra.append(STRING_WITH_LEN("; Using where"));
 
7489
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
 
7490
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
7491
        /* Skip initial "; "*/
 
7492
        const char *str= extra.ptr();
 
7493
        uint32_t len= extra.length();
 
7494
        if (len)
 
7495
        {
 
7496
          str += 2;
 
7497
          len -= 2;
 
7498
        }
 
7499
        item_list.push_back(new Item_string(str, len, cs));
 
7500
      }
 
7501
      else
 
7502
      {
 
7503
        uint32_t keyno= MAX_KEY;
 
7504
        if (tab->ref.key_parts)
 
7505
          keyno= tab->ref.key;
 
7506
        else if (tab->select && tab->select->quick)
 
7507
          keyno = tab->select->quick->index;
 
7508
 
 
7509
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
7510
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
7511
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
 
7512
        {
 
7513
          extra.append(STRING_WITH_LEN("; Using "));
 
7514
          tab->select->quick->add_info_string(&extra);
 
7515
        }
 
7516
          if (tab->select)
 
7517
        {
 
7518
          if (tab->use_quick == 2)
 
7519
          {
 
7520
            /*
 
7521
             * To print out the bitset in tab->keys, we go through
 
7522
             * it 32 bits at a time. We need to do this to ensure
 
7523
             * that the to_ulong() method will not throw an
 
7524
             * out_of_range exception at runtime which would happen
 
7525
             * if the bitset we were working with was larger than 64
 
7526
             * bits on a 64-bit platform (for example).
 
7527
             */
 
7528
            stringstream s, w;
 
7529
            string str;
 
7530
            w << tab->keys;
 
7531
            w >> str;
 
7532
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
 
7533
            {
 
7534
              bitset<32> tmp(str, pos, 32);
 
7535
              if (tmp.any())
 
7536
                s << uppercase << hex << tmp.to_ulong();
 
7537
            }
 
7538
            extra.append(STRING_WITH_LEN("; Range checked for each "
 
7539
                                         "record (index map: 0x"));
 
7540
            extra.append(s.str().c_str());
 
7541
            extra.append(')');
 
7542
          }
 
7543
          else if (tab->select->cond)
 
7544
          {
 
7545
            extra.append(STRING_WITH_LEN("; Using where"));
 
7546
          }
 
7547
        }
 
7548
        if (key_read)
 
7549
        {
 
7550
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
 
7551
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
 
7552
          else
 
7553
            extra.append(STRING_WITH_LEN("; Using index"));
 
7554
        }
 
7555
        if (table->reginfo.not_exists_optimize)
 
7556
          extra.append(STRING_WITH_LEN("; Not exists"));
 
7557
 
 
7558
        if (table_list->schema_table &&
 
7559
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
7560
        {
 
7561
          if (!table_list->table_open_method)
 
7562
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
 
7563
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
 
7564
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
 
7565
          else
 
7566
            extra.append(STRING_WITH_LEN("; Open_full_table"));
 
7567
          if (table_list->has_db_lookup_value &&
 
7568
              table_list->has_table_lookup_value)
 
7569
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
 
7570
          else if (table_list->has_db_lookup_value ||
 
7571
                   table_list->has_table_lookup_value)
 
7572
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
 
7573
          else
 
7574
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
 
7575
        }
 
7576
        if (need_tmp_table)
 
7577
        {
 
7578
          need_tmp_table=0;
 
7579
          extra.append(STRING_WITH_LEN("; Using temporary"));
 
7580
        }
 
7581
        if (need_order)
 
7582
        {
 
7583
          need_order=0;
 
7584
          extra.append(STRING_WITH_LEN("; Using filesort"));
 
7585
        }
 
7586
        if (distinct & test_all_bits(used_tables,session->used_tables))
 
7587
          extra.append(STRING_WITH_LEN("; Distinct"));
 
7588
 
 
7589
        if (tab->insideout_match_tab)
 
7590
        {
 
7591
          extra.append(STRING_WITH_LEN("; LooseScan"));
 
7592
        }
 
7593
 
 
7594
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
7595
        {
 
7596
          if (tab->ref.cond_guards[part])
 
7597
          {
 
7598
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
7599
            break;
 
7600
          }
 
7601
        }
 
7602
 
 
7603
        if (i > 0 && tab[-1].next_select == sub_select_cache)
 
7604
          extra.append(STRING_WITH_LEN("; Using join buffer"));
 
7605
 
 
7606
        /* Skip initial "; "*/
 
7607
        const char *str= extra.ptr();
 
7608
        uint32_t len= extra.length();
 
7609
        if (len)
 
7610
        {
 
7611
          str += 2;
 
7612
          len -= 2;
 
7613
        }
 
7614
        item_list.push_back(new Item_string(str, len, cs));
 
7615
      }
 
7616
      // For next iteration
 
7617
      used_tables|=table->map;
 
7618
      if (result->send_data(item_list))
 
7619
        join->error= 1;
 
7620
    }
 
7621
  }
 
7622
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
 
7623
       unit;
 
7624
       unit= unit->next_unit())
 
7625
  {
 
7626
    if (mysql_explain_union(session, unit, result))
 
7627
      return;
 
7628
  }
 
7629
  return;
 
7630
}
 
7631
 
 
7632
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
 
7633
{
 
7634
  bool res= false;
 
7635
  Select_Lex *first= unit->first_select();
 
7636
 
 
7637
  for (Select_Lex *sl= first;
 
7638
       sl;
 
7639
       sl= sl->next_select())
 
7640
  {
 
7641
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
 
7642
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
7643
    sl->type= (((&session->lex->select_lex)==sl)?
 
7644
               (sl->first_inner_unit() || sl->next_select() ?
 
7645
                "PRIMARY" : "SIMPLE"):
 
7646
               ((sl == first)?
 
7647
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
 
7648
                 "DERIVED":
 
7649
                 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
7650
                  "DEPENDENT SUBQUERY":
 
7651
                  (uncacheable?"UNCACHEABLE SUBQUERY":
 
7652
                   "SUBQUERY"))):
 
7653
                ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
7654
                 "DEPENDENT UNION":
 
7655
                 uncacheable?"UNCACHEABLE UNION":
 
7656
                 "UNION")));
 
7657
    sl->options|= SELECT_DESCRIBE;
 
7658
  }
 
7659
  if (unit->is_union())
 
7660
  {
 
7661
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
 
7662
    unit->fake_select_lex->type= "UNION RESULT";
 
7663
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
 
7664
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
7665
      res= unit->exec();
 
7666
    res|= unit->cleanup();
 
7667
  }
 
7668
  else
 
7669
  {
 
7670
    session->lex->current_select= first;
 
7671
    unit->set_limit(unit->global_parameters);
 
7672
    res= mysql_select(session, &first->ref_pointer_array,
 
7673
                        (TableList*) first->table_list.first,
 
7674
                        first->with_wild, first->item_list,
 
7675
                        first->where,
 
7676
                        first->order_list.elements +
 
7677
                        first->group_list.elements,
 
7678
                        (order_st*) first->order_list.first,
 
7679
                        (order_st*) first->group_list.first,
 
7680
                        first->having,
 
7681
                        first->options | session->options | SELECT_DESCRIBE,
 
7682
                        result, unit, first);
 
7683
  }
 
7684
  return(res || session->is_error());
 
7685
}
6540
7686
 
6541
7687
static void print_table_array(Session *session, String *str, TableList **table,
6542
7688
                              TableList **end)
6567
7713
 
6568
7714
/**
6569
7715
  Print joins from the FROM clause.
6570
 
  @param session     thread Cursor
 
7716
  @param session     thread handler
6571
7717
  @param str     string where table should be printed
6572
7718
  @param tables  list of tables in join
6573
7719
  @query_type    type of the query is being generated
6702
7848
/**
6703
7849
  @} (end of group Query_Optimizer)
6704
7850
*/
6705
 
 
6706
 
} /* namespace drizzled */