~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

New merge for TableShare

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
 
12
12
   You should have received a copy of the GNU General Public License
13
13
   along with this program; if not, write to the Free Software
14
 
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
15
15
 
16
16
/**
17
17
  @file
22
22
  @defgroup Query_Optimizer  Query Optimizer
23
23
  @{
24
24
*/
25
 
#include "config.h"
 
25
#include "drizzled/server_includes.h"
26
26
 
27
27
#include <string>
28
28
#include <iostream>
30
30
#include <vector>
31
31
 
32
32
#include "drizzled/sql_select.h" /* include join.h */
 
33
#include "drizzled/table_map_iterator.h"
33
34
 
34
35
#include "drizzled/error.h"
35
36
#include "drizzled/gettext.h"
38
39
#include "drizzled/nested_join.h"
39
40
#include "drizzled/probes.h"
40
41
#include "drizzled/show.h"
 
42
#include "drizzled/plugin/info_schema_table.h"
41
43
#include "drizzled/item/cache.h"
42
44
#include "drizzled/item/cmpfunc.h"
43
45
#include "drizzled/item/copy_string.h"
49
51
#include "drizzled/lock.h"
50
52
#include "drizzled/item/outer_ref.h"
51
53
#include "drizzled/index_hint.h"
52
 
#include "drizzled/records.h"
53
 
#include "drizzled/internal/iocache.h"
54
 
#include "drizzled/drizzled.h"
 
54
#include "drizzled/memory/multi_malloc.h"
55
55
 
56
56
#include "drizzled/sql_union.h"
57
57
#include "drizzled/optimizer/key_field.h"
58
58
#include "drizzled/optimizer/position.h"
59
59
#include "drizzled/optimizer/sargable_param.h"
60
60
#include "drizzled/optimizer/key_use.h"
61
 
#include "drizzled/optimizer/range.h"
62
 
#include "drizzled/optimizer/quick_range_select.h"
63
 
#include "drizzled/optimizer/quick_ror_intersect_select.h"
64
 
 
65
 
#include "drizzled/filesort.h"
66
61
 
67
62
using namespace std;
 
63
using namespace drizzled;
68
64
 
69
 
namespace drizzled
 
65
static const string access_method_str[]=
70
66
{
 
67
  "UNKNOWN",
 
68
  "system",
 
69
  "const",
 
70
  "eq_ref",
 
71
  "ref",
 
72
  "MAYBE_REF",
 
73
  "ALL",
 
74
  "range",
 
75
  "index",
 
76
  "ref_or_null",
 
77
  "unique_subquery",
 
78
  "index_subquery",
 
79
  "index_merge"
 
80
};
71
81
 
72
82
static int sort_keyuse(optimizer::KeyUse *a, optimizer::KeyUse *b);
73
83
static COND *build_equal_items(Session *session, COND *cond,
117
127
{
118
128
  bool res;
119
129
  register Select_Lex *select_lex= &lex->select_lex;
120
 
  DRIZZLE_SELECT_START(session->getQueryString()->c_str());
 
130
  DRIZZLE_SELECT_START(session->query);
121
131
 
122
132
  if (select_lex->master_unit()->is_union() ||
123
133
      select_lex->master_unit()->fake_select_lex)
124
 
  {
125
134
    res= drizzle_union(session, lex, result, &lex->unit,
126
135
                       setup_tables_done_option);
127
 
  }
128
136
  else
129
137
  {
130
138
    Select_Lex_Unit *unit= &lex->unit;
135
143
      every PS/SP execution new, we will not need reset this flag if
136
144
      setup_tables_done_option changed for next rexecution
137
145
    */
138
 
    res= mysql_select(session,
139
 
                      &select_lex->ref_pointer_array,
 
146
    res= mysql_select(session, &select_lex->ref_pointer_array,
140
147
                      (TableList*) select_lex->table_list.first,
141
 
                      select_lex->with_wild,
142
 
                      select_lex->item_list,
 
148
                      select_lex->with_wild, select_lex->item_list,
143
149
                      select_lex->where,
144
150
                      select_lex->order_list.elements +
145
151
                      select_lex->group_list.elements,
146
 
                      (Order*) select_lex->order_list.first,
147
 
                      (Order*) select_lex->group_list.first,
 
152
                      (order_st*) select_lex->order_list.first,
 
153
                      (order_st*) select_lex->group_list.first,
148
154
                      select_lex->having,
149
155
                      select_lex->options | session->options |
150
156
                      setup_tables_done_option,
327
333
                              for a, b and c in this list.
328
334
  @param conds                top level item of an expression representing
329
335
                              WHERE clause of the top level select
330
 
  @param og_num               total number of ORDER BY and GROUP BY clauses
 
336
  @param og_num               total number of order_st BY and GROUP BY clauses
331
337
                              arguments
332
 
  @param order                linked list of ORDER BY agruments
 
338
  @param order                linked list of order_st BY agruments
333
339
  @param group                linked list of GROUP BY arguments
334
340
  @param having               top level item of HAVING expression
335
341
  @param select_options       select options (BIG_RESULT, etc)
352
358
*/
353
359
bool mysql_select(Session *session,
354
360
                  Item ***rref_pointer_array,
355
 
                  TableList *tables, 
 
361
                        TableList *tables, 
356
362
                  uint32_t wild_num, 
357
363
                  List<Item> &fields,
358
 
                  COND *conds, 
 
364
                        COND *conds, 
359
365
                  uint32_t og_num,  
360
 
                  Order *order,
361
 
                  Order *group,
362
 
                  Item *having, 
 
366
                  order_st *order, 
 
367
                  order_st *group,
 
368
                        Item *having, 
363
369
                  uint64_t select_options,
364
 
                  select_result *result, 
 
370
                        select_result *result, 
365
371
                  Select_Lex_Unit *unit,
366
 
                  Select_Lex *select_lex)
 
372
                        Select_Lex *select_lex)
367
373
{
368
374
  bool err;
369
375
  bool free_join= 1;
370
376
 
371
377
  select_lex->context.resolve_in_select_list= true;
372
 
  Join *join;
 
378
  JOIN *join;
373
379
  if (select_lex->join != 0)
374
380
  {
375
381
    join= select_lex->join;
402
408
  }
403
409
  else
404
410
  {
405
 
    if (!(join= new Join(session, fields, select_options, result)))
 
411
    if (!(join= new JOIN(session, fields, select_options, result)))
406
412
      return(true);
407
413
    session->set_proc_info("init");
408
414
    session->used_tables=0;                         // Updated by setup_fields
414
420
    }
415
421
  }
416
422
 
417
 
  err= join->optimize();
418
 
  if (err)
 
423
  if ((err= join->optimize()))
419
424
  {
420
 
    goto err; // 1
 
425
    goto err;                                   // 1
421
426
  }
422
427
 
423
428
  if (session->lex->describe & DESCRIBE_EXTENDED)
452
457
  return (cond? (new Item_cond_and(cond, item)) : item);
453
458
}
454
459
 
 
460
static void fix_list_after_tbl_changes(Select_Lex *new_parent, List<TableList> *tlist)
 
461
{
 
462
  List_iterator<TableList> it(*tlist);
 
463
  TableList *table;
 
464
  while ((table= it++))
 
465
  {
 
466
    if (table->on_expr)
 
467
      table->on_expr->fix_after_pullout(new_parent, &table->on_expr);
 
468
    if (table->nested_join)
 
469
      fix_list_after_tbl_changes(new_parent, &table->nested_join->join_list);
 
470
  }
 
471
}
 
472
 
455
473
/*****************************************************************************
456
474
  Create JoinTableS, make a guess about the table types,
457
475
  Approximate how many records will be used in each table
458
476
*****************************************************************************/
459
 
ha_rows get_quick_record_count(Session *session, optimizer::SqlSelect *select, Table *table, const key_map *keys,ha_rows limit)
 
477
ha_rows get_quick_record_count(Session *session, SQL_SELECT *select, Table *table, const key_map *keys,ha_rows limit)
460
478
{
461
479
  int error;
462
480
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
547
565
                         Select_Lex *select_lex,
548
566
                         vector<optimizer::SargableParam> &sargables)
549
567
{
550
 
  uint  and_level,found_eq_constant;
 
568
  uint  and_level,i,found_eq_constant;
551
569
  optimizer::KeyField *key_fields, *end, *field;
552
570
  uint32_t sz;
553
571
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
570
588
    substitutions.
571
589
  */
572
590
  sz= sizeof(optimizer::KeyField) *
573
 
      (((session->lex->current_select->cond_count+1)*2 +
 
591
      (((session->lex->current_select->cond_count+1) +
574
592
        session->lex->current_select->between_count)*m+1);
575
593
  if (! (key_fields= (optimizer::KeyField*) session->alloc(sz)))
576
594
    return true;
590
608
      if (field->getValue()->type() == Item::NULL_ITEM &&
591
609
          ! field->getField()->real_maybe_null())
592
610
      {
593
 
        field->getField()->getTable()->reginfo.not_exists_optimize= 1;
 
611
        field->getField()->table->reginfo.not_exists_optimize= 1;
594
612
      }
595
613
    }
596
614
  }
597
 
  for (uint32_t i= 0; i < tables; i++)
 
615
  for (i= 0; i < tables; i++)
598
616
  {
599
617
    /*
600
618
      Block the creation of keys for inner tables of outer joins.
617
635
    TableList *table;
618
636
    while ((table= li++))
619
637
    {
620
 
      if (table->getNestedJoin())
 
638
      if (table->nested_join)
621
639
        add_key_fields_for_nj(join_tab->join, table, &end, &and_level,
622
640
                              sargables);
623
641
    }
640
658
  {
641
659
    optimizer::KeyUse key_end,*prev,*save_pos,*use;
642
660
 
643
 
    internal::my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
644
 
                       (qsort_cmp) sort_keyuse);
 
661
    my_qsort(keyuse->buffer,keyuse->elements,sizeof(optimizer::KeyUse),
 
662
          (qsort_cmp) sort_keyuse);
645
663
 
646
664
    memset(&key_end, 0, sizeof(key_end)); /* Add for easy testing */
647
665
    insert_dynamic(keyuse,(unsigned char*) &key_end);
649
667
    use= save_pos= dynamic_element(keyuse, 0, optimizer::KeyUse*);
650
668
    prev= &key_end;
651
669
    found_eq_constant= 0;
 
670
    for (i= 0; i < keyuse->elements-1; i++, use++)
652
671
    {
653
 
      uint32_t i;
654
 
 
655
 
      for (i= 0; i < keyuse->elements-1; i++, use++)
 
672
      if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
 
673
        use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
674
      if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
656
675
      {
657
 
        if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
658
 
          use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
659
 
        if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
660
 
        {
661
 
          if (prev->getKeypart() + 1 < use->getKeypart() || 
662
 
              ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
663
 
            continue;                           /* remove */
664
 
        }
665
 
        else if (use->getKeypart() != 0)                // First found must be 0
666
 
          continue;
 
676
        if (prev->getKeypart() + 1 < use->getKeypart() || 
 
677
            ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
 
678
          continue;                             /* remove */
 
679
      }
 
680
      else if (use->getKeypart() != 0)          // First found must be 0
 
681
        continue;
667
682
 
668
 
#ifdef HAVE_VALGRIND
669
 
        /* Valgrind complains about overlapped memcpy when save_pos==use. */
670
 
        if (save_pos != use)
 
683
#ifdef HAVE_purify
 
684
      /* Valgrind complains about overlapped memcpy when save_pos==use. */
 
685
      if (save_pos != use)
671
686
#endif
672
 
          *save_pos= *use;
673
 
        prev=use;
674
 
        found_eq_constant= ! use->getUsedTables();
675
 
        /* Save ptr to first use */
676
 
        if (! use->getTable()->reginfo.join_tab->keyuse)
677
 
          use->getTable()->reginfo.join_tab->keyuse= save_pos;
678
 
        use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
679
 
        save_pos++;
680
 
      }
681
 
      i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
682
 
      set_dynamic(keyuse, (unsigned char*) &key_end, i);
683
 
      keyuse->elements= i;
 
687
        *save_pos= *use;
 
688
      prev=use;
 
689
      found_eq_constant= ! use->getUsedTables();
 
690
      /* Save ptr to first use */
 
691
      if (! use->getTable()->reginfo.join_tab->keyuse)
 
692
        use->getTable()->reginfo.join_tab->keyuse= save_pos;
 
693
      use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
 
694
      save_pos++;
684
695
    }
 
696
    i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
 
697
    set_dynamic(keyuse, (unsigned char*) &key_end, i);
 
698
    keyuse->elements= i;
685
699
  }
686
700
  return false;
687
701
}
689
703
/**
690
704
  Update some values in keyuse for faster choose_plan() loop.
691
705
*/
692
 
void optimize_keyuse(Join *join, DYNAMIC_ARRAY *keyuse_array)
 
706
void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array)
693
707
{
694
708
  optimizer::KeyUse *end,*keyuse= dynamic_element(keyuse_array, 
695
709
                                                  0, 
744
758
  @return
745
759
    None
746
760
*/
747
 
void add_group_and_distinct_keys(Join *join, JoinTable *join_tab)
 
761
void add_group_and_distinct_keys(JOIN *join, JoinTable *join_tab)
748
762
{
749
763
  List<Item_field> indexed_fields;
750
764
  List_iterator<Item_field> indexed_fields_it(indexed_fields);
751
 
  Order      *cur_group;
 
765
  order_st      *cur_group;
752
766
  Item_field *cur_item;
753
767
  key_map possible_keys(0);
754
768
 
849
863
  Field **f_ptr,*field;
850
864
 
851
865
  null_fields= blobs= fields= rec_length=0;
852
 
  for (f_ptr=join_tab->table->getFields() ; (field= *f_ptr) ; f_ptr++)
 
866
  for (f_ptr=join_tab->table->field ; (field= *f_ptr) ; f_ptr++)
853
867
  {
854
868
    if (field->isReadSet())
855
869
    {
880
894
StoredKey *get_store_key(Session *session,
881
895
                         optimizer::KeyUse *keyuse,
882
896
                         table_map used_tables,
883
 
                         KeyPartInfo *key_part,
 
897
                         KEY_PART_INFO *key_part,
884
898
                         unsigned char *key_buff,
885
899
                         uint32_t maybe_null)
886
900
{
925
939
bool store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
926
940
{
927
941
  bool error;
928
 
  Table *table= field->getTable();
 
942
  Table *table= field->table;
929
943
  Session *session= table->in_use;
930
944
  ha_rows cuted_fields=session->cuted_fields;
931
945
 
956
970
    *e1= e2;
957
971
}
958
972
 
959
 
bool create_ref_for_key(Join *join, 
 
973
bool create_ref_for_key(JOIN *join, 
960
974
                        JoinTable *j, 
961
975
                        optimizer::KeyUse *org_keyuse,
962
976
                        table_map used_tables)
967
981
  uint32_t length;
968
982
  uint32_t key;
969
983
  Table *table= NULL;
970
 
  KeyInfo *keyinfo= NULL;
 
984
  KEY *keyinfo= NULL;
971
985
 
972
986
  /*  Use best key from find_best */
973
987
  table= j->table;
1134
1148
      3. add_not_null_conds adds "x IS NOT NULL" to join_tab->select_cond of
1135
1149
         appropiate JoinTable members.
1136
1150
*/
1137
 
void add_not_null_conds(Join *join)
 
1151
void add_not_null_conds(JOIN *join)
1138
1152
{
1139
1153
  for (uint32_t i= join->const_tables; i < join->tables; i++)
1140
1154
  {
1151
1165
          Item *notnull;
1152
1166
          assert(item->type() == Item::FIELD_ITEM);
1153
1167
          Item_field *not_null_item= (Item_field*)item;
1154
 
          JoinTable *referred_tab= not_null_item->field->getTable()->reginfo.join_tab;
 
1168
          JoinTable *referred_tab= not_null_item->field->table->reginfo.join_tab;
1155
1169
          /*
1156
1170
            For UPDATE queries such as:
1157
1171
            UPDATE t1 SET t1.f2=(SELECT MAX(t2.f4) FROM t2 WHERE t2.f3=t1.f1);
1208
1222
  return tmp;
1209
1223
}
1210
1224
 
 
1225
/*
 
1226
  Check if given expression uses only table fields covered by the given index
 
1227
 
 
1228
  SYNOPSIS
 
1229
    uses_index_fields_only()
 
1230
      item           Expression to check
 
1231
      tbl            The table having the index
 
1232
      keyno          The index number
 
1233
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
1234
 
 
1235
  DESCRIPTION
 
1236
    Check if given expression only uses fields covered by index #keyno in the
 
1237
    table tbl. The expression can use any fields in any other tables.
 
1238
 
 
1239
    The expression is guaranteed not to be AND or OR - those constructs are
 
1240
    handled outside of this function.
 
1241
 
 
1242
  RETURN
 
1243
    true   Yes
 
1244
    false  No
 
1245
*/
 
1246
static bool uses_index_fields_only(Item *item, Table *tbl, uint32_t keyno, bool other_tbls_ok)
 
1247
{
 
1248
  if (item->const_item())
 
1249
    return true;
 
1250
 
 
1251
  /*
 
1252
    Don't push down the triggered conditions. Nested outer joins execution
 
1253
    code may need to evaluate a condition several times (both triggered and
 
1254
    untriggered), and there is no way to put thi
 
1255
    TODO: Consider cloning the triggered condition and using the copies for:
 
1256
      1. push the first copy down, to have most restrictive index condition
 
1257
         possible
 
1258
      2. Put the second copy into tab->select_cond.
 
1259
  */
 
1260
  if (item->type() == Item::FUNC_ITEM &&
 
1261
      ((Item_func*)item)->functype() == Item_func::TRIG_COND_FUNC)
 
1262
    return false;
 
1263
 
 
1264
  if (!(item->used_tables() & tbl->map))
 
1265
    return other_tbls_ok;
 
1266
 
 
1267
  Item::Type item_type= item->type();
 
1268
  switch (item_type) {
 
1269
  case Item::FUNC_ITEM:
 
1270
    {
 
1271
      /* This is a function, apply condition recursively to arguments */
 
1272
      Item_func *item_func= (Item_func*)item;
 
1273
      Item **child;
 
1274
      Item **item_end= (item_func->arguments()) + item_func->argument_count();
 
1275
      for (child= item_func->arguments(); child != item_end; child++)
 
1276
      {
 
1277
        if (!uses_index_fields_only(*child, tbl, keyno, other_tbls_ok))
 
1278
          return false;
 
1279
      }
 
1280
      return true;
 
1281
    }
 
1282
  case Item::COND_ITEM:
 
1283
    {
 
1284
      /* This is a function, apply condition recursively to arguments */
 
1285
      List_iterator<Item> li(*((Item_cond*)item)->argument_list());
 
1286
      Item *list_item;
 
1287
      while ((list_item=li++))
 
1288
      {
 
1289
        if (!uses_index_fields_only(item, tbl, keyno, other_tbls_ok))
 
1290
          return false;
 
1291
      }
 
1292
      return true;
 
1293
    }
 
1294
  case Item::FIELD_ITEM:
 
1295
    {
 
1296
      Item_field *item_field= (Item_field*)item;
 
1297
      if (item_field->field->table != tbl)
 
1298
        return true;
 
1299
      return item_field->field->part_of_key.test(keyno);
 
1300
    }
 
1301
  case Item::REF_ITEM:
 
1302
    return uses_index_fields_only(item->real_item(), tbl, keyno,
 
1303
                                  other_tbls_ok);
 
1304
  default:
 
1305
    return false; /* Play it safe, don't push unknown non-const items */
 
1306
  }
 
1307
}
 
1308
 
1211
1309
#define ICP_COND_USES_INDEX_ONLY 10
1212
1310
 
 
1311
/*
 
1312
  Get a part of the condition that can be checked using only index fields
 
1313
 
 
1314
  SYNOPSIS
 
1315
    make_cond_for_index()
 
1316
      cond           The source condition
 
1317
      table          The table that is partially available
 
1318
      keyno          The index in the above table. Only fields covered by the index
 
1319
                     are available
 
1320
      other_tbls_ok  true <=> Fields of other non-const tables are allowed
 
1321
 
 
1322
  DESCRIPTION
 
1323
    Get a part of the condition that can be checked when for the given table
 
1324
    we have values only of fields covered by some index. The condition may
 
1325
    refer to other tables, it is assumed that we have values of all of their
 
1326
    fields.
 
1327
 
 
1328
    Example:
 
1329
      make_cond_for_index(
 
1330
         "cond(t1.field) AND cond(t2.key1) AND cond(t2.non_key) AND cond(t2.key2)",
 
1331
          t2, keyno(t2.key1))
 
1332
      will return
 
1333
        "cond(t1.field) AND cond(t2.key2)"
 
1334
 
 
1335
  RETURN
 
1336
    Index condition, or NULL if no condition could be inferred.
 
1337
*/
 
1338
static Item *make_cond_for_index(Item *cond, Table *table, uint32_t keyno, bool other_tbls_ok)
 
1339
{
 
1340
  if (!cond)
 
1341
    return NULL;
 
1342
  if (cond->type() == Item::COND_ITEM)
 
1343
  {
 
1344
    uint32_t n_marked= 0;
 
1345
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
1346
    {
 
1347
      Item_cond_and *new_cond=new Item_cond_and;
 
1348
      if (!new_cond)
 
1349
        return (COND*) 0;
 
1350
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1351
      Item *item;
 
1352
      while ((item=li++))
 
1353
      {
 
1354
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1355
        if (fix)
 
1356
          new_cond->argument_list()->push_back(fix);
 
1357
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
1358
      }
 
1359
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
1360
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1361
      switch (new_cond->argument_list()->elements) {
 
1362
      case 0:
 
1363
        return (COND*) 0;
 
1364
      case 1:
 
1365
        return new_cond->argument_list()->head();
 
1366
      default:
 
1367
        new_cond->quick_fix_field();
 
1368
        return new_cond;
 
1369
      }
 
1370
    }
 
1371
    else /* It's OR */
 
1372
    {
 
1373
      Item_cond_or *new_cond=new Item_cond_or;
 
1374
      if (!new_cond)
 
1375
        return (COND*) 0;
 
1376
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1377
      Item *item;
 
1378
      while ((item=li++))
 
1379
      {
 
1380
        Item *fix= make_cond_for_index(item, table, keyno, other_tbls_ok);
 
1381
        if (!fix)
 
1382
          return (COND*) 0;
 
1383
        new_cond->argument_list()->push_back(fix);
 
1384
        n_marked += test(item->marker == ICP_COND_USES_INDEX_ONLY);
 
1385
      }
 
1386
      if (n_marked ==((Item_cond*)cond)->argument_list()->elements)
 
1387
        cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1388
      new_cond->quick_fix_field();
 
1389
      new_cond->top_level_item();
 
1390
      return new_cond;
 
1391
    }
 
1392
  }
 
1393
 
 
1394
  if (!uses_index_fields_only(cond, table, keyno, other_tbls_ok))
 
1395
    return (COND*) 0;
 
1396
  cond->marker= ICP_COND_USES_INDEX_ONLY;
 
1397
  return cond;
 
1398
}
 
1399
 
 
1400
 
 
1401
static Item *make_cond_remainder(Item *cond, bool exclude_index)
 
1402
{
 
1403
  if (exclude_index && cond->marker == ICP_COND_USES_INDEX_ONLY)
 
1404
    return 0; /* Already checked */
 
1405
 
 
1406
  if (cond->type() == Item::COND_ITEM)
 
1407
  {
 
1408
    table_map tbl_map= 0;
 
1409
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
1410
    {
 
1411
      /* Create new top level AND item */
 
1412
      Item_cond_and *new_cond=new Item_cond_and;
 
1413
      if (!new_cond)
 
1414
        return (COND*) 0;
 
1415
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1416
      Item *item;
 
1417
      while ((item=li++))
 
1418
      {
 
1419
        Item *fix= make_cond_remainder(item, exclude_index);
 
1420
        if (fix)
 
1421
        {
 
1422
          new_cond->argument_list()->push_back(fix);
 
1423
          tbl_map |= fix->used_tables();
 
1424
        }
 
1425
      }
 
1426
      switch (new_cond->argument_list()->elements) {
 
1427
      case 0:
 
1428
        return (COND*) 0;
 
1429
      case 1:
 
1430
        return new_cond->argument_list()->head();
 
1431
      default:
 
1432
        new_cond->quick_fix_field();
 
1433
        ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
1434
        return new_cond;
 
1435
      }
 
1436
    }
 
1437
    else /* It's OR */
 
1438
    {
 
1439
      Item_cond_or *new_cond=new Item_cond_or;
 
1440
      if (!new_cond)
 
1441
        return (COND*) 0;
 
1442
      List_iterator<Item> li(*((Item_cond*) cond)->argument_list());
 
1443
      Item *item;
 
1444
      while ((item=li++))
 
1445
      {
 
1446
        Item *fix= make_cond_remainder(item, false);
 
1447
        if (!fix)
 
1448
          return (COND*) 0;
 
1449
        new_cond->argument_list()->push_back(fix);
 
1450
        tbl_map |= fix->used_tables();
 
1451
      }
 
1452
      new_cond->quick_fix_field();
 
1453
      ((Item_cond*)new_cond)->used_tables_cache= tbl_map;
 
1454
      new_cond->top_level_item();
 
1455
      return new_cond;
 
1456
    }
 
1457
  }
 
1458
  return cond;
 
1459
}
1213
1460
 
1214
1461
/**
1215
1462
  cleanup JoinTable.
1221
1468
  delete quick;
1222
1469
  quick= 0;
1223
1470
  if (cache.buff)
1224
 
  {
1225
 
    size_t size= cache.end - cache.buff;
1226
 
    global_join_buffer.sub(size);
1227
1471
    free(cache.buff);
1228
 
  }
1229
1472
  cache.buff= 0;
1230
1473
  limit= 0;
1231
1474
  if (table)
1242
1485
    */
1243
1486
    table->reginfo.join_tab= 0;
1244
1487
  }
1245
 
  read_record.end_read_record();
 
1488
  end_read_record(&read_record);
1246
1489
}
1247
1490
 
1248
 
bool only_eq_ref_tables(Join *join,Order *order,table_map tables)
 
1491
bool only_eq_ref_tables(JOIN *join,order_st *order,table_map tables)
1249
1492
{
1250
1493
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1251
1494
  {
1256
1499
}
1257
1500
 
1258
1501
/**
1259
 
  Remove the following expressions from ORDER BY and GROUP BY:
 
1502
  Remove the following expressions from order_st BY and GROUP BY:
1260
1503
  Constant expressions @n
1261
1504
  Expression that only uses tables that are of type EQ_REF and the reference
1262
1505
  is in the order_st list or if all refereed tables are of the above type.
1263
1506
 
1264
1507
  In the following, the X field can be removed:
1265
1508
  @code
1266
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t1.a,t2.X
1267
 
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b ORDER BY t1.a,t3.X
 
1509
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t1.a,t2.X
 
1510
  SELECT * FROM t1,t2,t3 WHERE t1.a=t2.a AND t2.b=t3.b order_st BY t1.a,t3.X
1268
1511
  @endcode
1269
1512
 
1270
1513
  These can't be optimized:
1271
1514
  @code
1272
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.X,t1.a
1273
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b ORDER BY t1.a,t2.c
1274
 
  SELECT * FROM t1,t2 WHERE t1.a=t2.a ORDER BY t2.b,t1.a
 
1515
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.X,t1.a
 
1516
  SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t1.b=t2.b order_st BY t1.a,t2.c
 
1517
  SELECT * FROM t1,t2 WHERE t1.a=t2.a order_st BY t2.b,t1.a
1275
1518
  @endcode
1276
1519
*/
1277
 
bool eq_ref_table(Join *join, Order *start_order, JoinTable *tab)
 
1520
bool eq_ref_table(JOIN *join, order_st *start_order, JoinTable *tab)
1278
1521
{
1279
1522
  if (tab->cached_eq_ref_table)                 // If cached
1280
1523
    return tab->eq_ref_table;
1293
1536
  {
1294
1537
    if (! (*ref_item)->const_item())
1295
1538
    {                                           // Not a const ref
1296
 
      Order *order;
 
1539
      order_st *order;
1297
1540
      for (order=start_order ; order ; order=order->next)
1298
1541
      {
1299
1542
        if ((*ref_item)->eq(order->item[0],0))
2033
2276
    {
2034
2277
      if (table->on_expr)
2035
2278
      {
2036
 
        List<TableList> *nested_join_list= table->getNestedJoin() ?
2037
 
          &table->getNestedJoin()->join_list : NULL;
 
2279
        List<TableList> *nested_join_list= table->nested_join ?
 
2280
          &table->nested_join->join_list : NULL;
2038
2281
        /*
2039
2282
          We can modify table->on_expr because its old value will
2040
2283
          be restored before re-execution of PS/SP.
2087
2330
  if (outer_ref)
2088
2331
    return cmp;
2089
2332
  JoinTable **idx= (JoinTable **) table_join_idx;
2090
 
  cmp= idx[field2->field->getTable()->tablenr]-idx[field1->field->getTable()->tablenr];
 
2333
  cmp= idx[field2->field->table->tablenr]-idx[field1->field->table->tablenr];
2091
2334
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2092
2335
}
2093
2336
 
2334
2577
      while ((item_field= it++))
2335
2578
      {
2336
2579
        Field *field= item_field->field;
2337
 
        JoinTable *stat= field->getTable()->reginfo.join_tab;
 
2580
        JoinTable *stat= field->table->reginfo.join_tab;
2338
2581
        key_map possible_keys= field->key_start;
2339
 
        possible_keys&= field->getTable()->keys_in_use_for_query;
 
2582
        possible_keys&= field->table->keys_in_use_for_query;
2340
2583
        stat[0].const_keys|= possible_keys;
2341
2584
 
2342
2585
        /*
2346
2589
        */
2347
2590
        if (possible_keys.any())
2348
2591
        {
2349
 
          Table *field_tab= field->getTable();
 
2592
          Table *field_tab= field->table;
2350
2593
          optimizer::KeyUse *use;
2351
2594
          for (use= stat->keyuse; use && use->getTable() == field_tab; use++)
2352
2595
            if (possible_keys.test(use->getKey()) &&
2377
2620
    Item *item;
2378
2621
    while ((item=li++))
2379
2622
      change_cond_ref_to_const(session, save_list, and_level ? cond : item, item, field, value);
2380
 
 
2381
2623
    return;
2382
2624
  }
2383
2625
  if (cond->eq_cmp_result() == Item::COND_OK)
2396
2638
       left_item->collation.collation == value->collation.collation))
2397
2639
  {
2398
2640
    Item *tmp=value->clone_item();
 
2641
    tmp->collation.set(right_item->collation);
 
2642
 
2399
2643
    if (tmp)
2400
2644
    {
2401
 
      tmp->collation.set(right_item->collation);
2402
2645
      session->change_item_tree(args + 1, tmp);
2403
2646
      func->update_used_tables();
2404
2647
      if ((functype == Item_func::EQ_FUNC || functype == Item_func::EQUAL_FUNC) &&
2418
2661
            right_item->collation.collation == value->collation.collation))
2419
2662
  {
2420
2663
    Item *tmp= value->clone_item();
 
2664
    tmp->collation.set(left_item->collation);
 
2665
 
2421
2666
    if (tmp)
2422
2667
    {
2423
 
      tmp->collation.set(left_item->collation);
2424
2668
      session->change_item_tree(args, tmp);
2425
2669
      value= tmp;
2426
2670
      func->update_used_tables();
2490
2734
      for (vector<COND_CMP>::iterator iter= save.begin(); iter != save.end(); ++iter)
2491
2735
      {
2492
2736
        Item **args= iter->cmp_func->arguments();
2493
 
        if (not args[0]->const_item())
 
2737
        if (!args[0]->const_item())
2494
2738
        {
2495
 
          change_cond_ref_to_const(session, save_list, iter->and_level,
2496
 
                                   iter->and_level, args[0], args[1] );
 
2739
          change_cond_ref_to_const( session, save, iter->and_level,
 
2740
                                    iter->and_level, args[0], args[1] );
2497
2741
        }
2498
2742
      }
2499
2743
    }
2612
2856
  @endverbatim
2613
2857
 
2614
2858
  @param join       Join being processed
 
2859
  @param last_tab   Last table in current partial join order (this function is
 
2860
                    not called for empty partial join orders)
2615
2861
  @param next_tab   Table we're going to extend the current partial join with
2616
2862
 
2617
2863
  @retval
2620
2866
  @retval
2621
2867
    true   Requested join order extension not allowed.
2622
2868
*/
2623
 
bool check_interleaving_with_nj(JoinTable *next_tab)
 
2869
bool check_interleaving_with_nj(JoinTable *last_tab, JoinTable *next_tab)
2624
2870
{
2625
 
  TableList *next_emb= next_tab->table->pos_in_table_list->getEmbedding();
2626
 
  Join *join= next_tab->join;
 
2871
  TableList *next_emb= next_tab->table->pos_in_table_list->embedding;
 
2872
  JOIN *join= last_tab->join;
2627
2873
 
2628
2874
  if ((join->cur_embedding_map & ~next_tab->embedding_map).any())
2629
2875
  {
2638
2884
    Do update counters for "pairs of brackets" that we've left (marked as
2639
2885
    X,Y,Z in the above picture)
2640
2886
  */
2641
 
  for (;next_emb; next_emb= next_emb->getEmbedding())
 
2887
  for (;next_emb; next_emb= next_emb->embedding)
2642
2888
  {
2643
 
    next_emb->getNestedJoin()->counter_++;
2644
 
    if (next_emb->getNestedJoin()->counter_ == 1)
 
2889
    next_emb->nested_join->counter_++;
 
2890
    if (next_emb->nested_join->counter_ == 1)
2645
2891
    {
2646
2892
      /*
2647
2893
        next_emb is the first table inside a nested join we've "entered". In
2648
2894
        the picture above, we're looking at the 'X' bracket. Don't exit yet as
2649
2895
        X bracket might have Y pair bracket.
2650
2896
      */
2651
 
      join->cur_embedding_map |= next_emb->getNestedJoin()->nj_map;
 
2897
      join->cur_embedding_map |= next_emb->nested_join->nj_map;
2652
2898
    }
2653
2899
 
2654
 
    if (next_emb->getNestedJoin()->join_list.elements !=
2655
 
        next_emb->getNestedJoin()->counter_)
 
2900
    if (next_emb->nested_join->join_list.elements !=
 
2901
        next_emb->nested_join->counter_)
2656
2902
      break;
2657
2903
 
2658
2904
    /*
2659
2905
      We're currently at Y or Z-bracket as depicted in the above picture.
2660
2906
      Mark that we've left it and continue walking up the brackets hierarchy.
2661
2907
    */
2662
 
    join->cur_embedding_map &= ~next_emb->getNestedJoin()->nj_map;
 
2908
    join->cur_embedding_map &= ~next_emb->nested_join->nj_map;
2663
2909
  }
2664
2910
  return false;
2665
2911
}
2666
2912
 
2667
 
COND *optimize_cond(Join *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
 
2913
COND *optimize_cond(JOIN *join, COND *conds, List<TableList> *join_list, Item::cond_result *cond_value)
2668
2914
{
2669
2915
  Session *session= join->session;
2670
2916
 
2787
3033
    {
2788
3034
      Field *field= ((Item_field*) args[0])->field;
2789
3035
      if (field->flags & AUTO_INCREMENT_FLAG 
2790
 
          && ! field->getTable()->maybe_null 
 
3036
          && ! field->table->maybe_null 
2791
3037
          && session->options & OPTION_AUTO_IS_NULL
2792
3038
          && (
2793
3039
            session->first_successful_insert_id_in_prev_stmt > 0 
2845
3091
  /*
2846
3092
    TODO:
2847
3093
    Excluding all expensive functions is too restritive we should exclude only
2848
 
    materialized IN subquery predicates because they can't yet be evaluated
2849
 
    here (they need additional initialization that is done later on).
2850
 
 
2851
 
    The proper way to exclude the subqueries would be to walk the cond tree and
2852
 
    check for materialized subqueries there.
2853
 
 
 
3094
    materialized IN because it is created later than this phase, and cannot be
 
3095
    evaluated at this point.
 
3096
    The condition should be something as (need to fix member access):
 
3097
      !(cond->type() == Item::FUNC_ITEM &&
 
3098
        ((Item_func*)cond)->func_name() == "<in_optimizer>" &&
 
3099
        ((Item_in_optimizer*)cond)->is_expensive()))
2854
3100
  */
2855
3101
  {
2856
3102
    *cond_value= eval_const_cond(cond) ? Item::COND_TRUE : Item::COND_FALSE;
2973
3219
  @return
2974
3220
    end_select function to use. This function can't fail.
2975
3221
*/
2976
 
Next_select_func setup_end_select_func(Join *join)
 
3222
Next_select_func setup_end_select_func(JOIN *join)
2977
3223
{
2978
3224
  Table *table= join->tmp_table;
2979
3225
  Tmp_Table_Param *tmp_tbl= &join->tmp_table_param;
2985
3231
    if (table->group && tmp_tbl->sum_func_count &&
2986
3232
        !tmp_tbl->precomputed_group_by)
2987
3233
    {
2988
 
      if (table->getShare()->sizeKeys())
 
3234
      if (table->s->keys)
2989
3235
      {
2990
3236
        end_select= end_update;
2991
3237
      }
2996
3242
    }
2997
3243
    else if (join->sort_and_group && !tmp_tbl->precomputed_group_by)
2998
3244
    {
2999
 
      end_select= end_write_group;
 
3245
      end_select=end_write_group;
3000
3246
    }
3001
3247
    else
3002
3248
    {
3003
 
      end_select= end_write;
 
3249
      end_select=end_write;
3004
3250
      if (tmp_tbl->precomputed_group_by)
3005
3251
      {
3006
3252
        /*
3038
3284
  @retval
3039
3285
    -1  if error should be sent
3040
3286
*/
3041
 
int do_select(Join *join, List<Item> *fields, Table *table)
 
3287
int do_select(JOIN *join, List<Item> *fields, Table *table)
3042
3288
{
3043
3289
  int rc= 0;
3044
3290
  enum_nested_loop_state error= NESTED_LOOP_OK;
3052
3298
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
3053
3299
    table->emptyRecord();
3054
3300
    if (table->group && join->tmp_table_param.sum_func_count &&
3055
 
        table->getShare()->sizeKeys() && !table->cursor->inited)
3056
 
      table->cursor->startIndexScan(0, 0);
 
3301
        table->s->keys && !table->cursor->inited)
 
3302
      table->cursor->ha_index_init(0, 0);
3057
3303
  }
3058
3304
  /* Set up select_end */
3059
3305
  Next_select_func end_select= setup_end_select_func(join);
3139
3385
  return(join->session->is_error() ? -1 : rc);
3140
3386
}
3141
3387
 
3142
 
enum_nested_loop_state sub_select_cache(Join *join, JoinTable *join_tab, bool end_of_records)
 
3388
enum_nested_loop_state sub_select_cache(JOIN *join, JoinTable *join_tab, bool end_of_records)
3143
3389
{
3144
3390
  enum_nested_loop_state rc;
3145
3391
 
3150
3396
      rc= sub_select(join,join_tab,end_of_records);
3151
3397
    return rc;
3152
3398
  }
3153
 
  if (join->session->getKilled())               // If aborted by user
 
3399
  if (join->session->killed)            // If aborted by user
3154
3400
  {
3155
3401
    join->session->send_kill_message();
3156
3402
    return NESTED_LOOP_KILLED;
3157
3403
  }
3158
3404
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3159
3405
  {
3160
 
    if (! join_tab->cache.store_record_in_cache())
 
3406
    if (! store_record_in_cache(&join_tab->cache))
3161
3407
      return NESTED_LOOP_OK;                     // There is more room in cache
3162
3408
    return flush_cached_records(join,join_tab,false);
3163
3409
  }
3286
3532
  @return
3287
3533
    return one of enum_nested_loop_state, except NESTED_LOOP_NO_MORE_ROWS.
3288
3534
*/
3289
 
enum_nested_loop_state sub_select(Join *join, JoinTable *join_tab, bool end_of_records)
 
3535
enum_nested_loop_state sub_select(JOIN *join, JoinTable *join_tab, bool end_of_records)
3290
3536
{
3291
3537
  join_tab->table->null_row=0;
3292
3538
  if (end_of_records)
3294
3540
 
3295
3541
  int error;
3296
3542
  enum_nested_loop_state rc;
3297
 
  ReadRecord *info= &join_tab->read_record;
 
3543
  READ_RECORD *info= &join_tab->read_record;
3298
3544
 
3299
3545
  if (join->resume_nested_loop)
3300
3546
  {
3351
3597
{
3352
3598
  int error;
3353
3599
  Table *table= tab->table;
3354
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
3600
  if ((error=table->cursor->index_read_map(table->record[0],
3355
3601
                                         tab->ref.key_buff,
3356
3602
                                         make_prev_keypart_map(tab->ref.key_parts),
3357
3603
                                         HA_READ_KEY_EXACT)))
3415
3661
    table->maybe_null=0;
3416
3662
 
3417
3663
  /* Check appearance of new constant items in Item_equal objects */
3418
 
  Join *join= tab->join;
 
3664
  JOIN *join= tab->join;
3419
3665
  if (join->conds)
3420
3666
    update_const_equal_items(join->conds, tab);
3421
3667
  TableList *tbl;
3428
3674
      embedded= embedding;
3429
3675
      if (embedded->on_expr)
3430
3676
         update_const_equal_items(embedded->on_expr, tab);
3431
 
      embedding= embedded->getEmbedding();
 
3677
      embedding= embedded->embedding;
3432
3678
    }
3433
3679
    while (embedding &&
3434
 
           embedding->getNestedJoin()->join_list.head() == embedded);
 
3680
           embedding->nested_join->join_list.head() == embedded);
3435
3681
  }
3436
3682
 
3437
3683
  return(0);
3443
3689
  int error;
3444
3690
  if (table->status & STATUS_GARBAGE)           // If first read
3445
3691
  {
3446
 
    if ((error=table->cursor->read_first_row(table->getInsertRecord(),
3447
 
                                           table->getShare()->getPrimaryKey())))
 
3692
    if ((error=table->cursor->read_first_row(table->record[0],
 
3693
                                           table->s->primary_key)))
3448
3694
    {
3449
3695
      if (error != HA_ERR_END_OF_FILE)
3450
3696
        return table->report_error(error);
3483
3729
      error= HA_ERR_KEY_NOT_FOUND;
3484
3730
    else
3485
3731
    {
3486
 
      error=table->cursor->index_read_idx_map(table->getInsertRecord(),tab->ref.key,
 
3732
      error=table->cursor->index_read_idx_map(table->record[0],tab->ref.key,
3487
3733
                                            (unsigned char*) tab->ref.key_buff,
3488
3734
                                            make_prev_keypart_map(tab->ref.key_parts),
3489
3735
                                            HA_READ_KEY_EXACT);
3531
3777
 
3532
3778
  if (!table->cursor->inited)
3533
3779
  {
3534
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
3780
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
3535
3781
  }
3536
3782
 
3537
3783
  /* TODO: Why don't we do "Late NULLs Filtering" here? */
3543
3789
      table->status=STATUS_NOT_FOUND;
3544
3790
      return -1;
3545
3791
    }
3546
 
    error=table->cursor->index_read_map(table->getInsertRecord(),
 
3792
    error=table->cursor->index_read_map(table->record[0],
3547
3793
                                      tab->ref.key_buff,
3548
3794
                                      make_prev_keypart_map(tab->ref.key_parts),
3549
3795
                                      HA_READ_KEY_EXACT);
3579
3825
 
3580
3826
  /* Initialize the index first */
3581
3827
  if (!table->cursor->inited)
3582
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
3828
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
3583
3829
 
3584
3830
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3585
3831
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3590
3836
 
3591
3837
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3592
3838
    return -1;
3593
 
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
 
3839
  if ((error=table->cursor->index_read_map(table->record[0],
3594
3840
                                         tab->ref.key_buff,
3595
3841
                                         make_prev_keypart_map(tab->ref.key_parts),
3596
3842
                                         HA_READ_KEY_EXACT)))
3604
3850
}
3605
3851
 
3606
3852
/**
3607
 
  This function is used when optimizing away ORDER BY in
3608
 
  SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC.
 
3853
  This function is used when optimizing away order_st BY in
 
3854
  SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC.
3609
3855
*/
3610
3856
int join_read_last_key(JoinTable *tab)
3611
3857
{
3613
3859
  Table *table= tab->table;
3614
3860
 
3615
3861
  if (!table->cursor->inited)
3616
 
    table->cursor->startIndexScan(tab->ref.key, tab->sorted);
 
3862
    table->cursor->ha_index_init(tab->ref.key, tab->sorted);
3617
3863
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
3618
3864
    return -1;
3619
 
  if ((error=table->cursor->index_read_last_map(table->getInsertRecord(),
 
3865
  if ((error=table->cursor->index_read_last_map(table->record[0],
3620
3866
                                              tab->ref.key_buff,
3621
3867
                                              make_prev_keypart_map(tab->ref.key_parts))))
3622
3868
  {
3627
3873
  return 0;
3628
3874
}
3629
3875
 
3630
 
int join_no_more_records(ReadRecord *)
 
3876
int join_no_more_records(READ_RECORD *)
3631
3877
{
3632
3878
  return -1;
3633
3879
}
3634
3880
 
3635
 
int join_read_next_same_diff(ReadRecord *info)
 
3881
int join_read_next_same_diff(READ_RECORD *info)
3636
3882
{
3637
3883
  Table *table= info->table;
3638
3884
  JoinTable *tab=table->reginfo.join_tab;
3639
3885
  if (tab->insideout_match_tab->found_match)
3640
3886
  {
3641
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
3887
    KEY *key= tab->table->key_info + tab->index;
3642
3888
    do
3643
3889
    {
3644
3890
      int error;
3645
3891
      /* Save index tuple from record to the buffer */
3646
3892
      key_copy(tab->insideout_buf, info->record, key, 0);
3647
3893
 
3648
 
      if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
3894
      if ((error=table->cursor->index_next_same(table->record[0],
3649
3895
                                              tab->ref.key_buff,
3650
3896
                                              tab->ref.key_length)))
3651
3897
      {
3663
3909
    return join_read_next_same(info);
3664
3910
}
3665
3911
 
3666
 
int join_read_next_same(ReadRecord *info)
 
3912
int join_read_next_same(READ_RECORD *info)
3667
3913
{
3668
3914
  int error;
3669
3915
  Table *table= info->table;
3670
3916
  JoinTable *tab=table->reginfo.join_tab;
3671
3917
 
3672
 
  if ((error=table->cursor->index_next_same(table->getInsertRecord(),
 
3918
  if ((error=table->cursor->index_next_same(table->record[0],
3673
3919
                                          tab->ref.key_buff,
3674
3920
                                          tab->ref.key_length)))
3675
3921
  {
3682
3928
  return 0;
3683
3929
}
3684
3930
 
3685
 
int join_read_prev_same(ReadRecord *info)
 
3931
int join_read_prev_same(READ_RECORD *info)
3686
3932
{
3687
3933
  int error;
3688
3934
  Table *table= info->table;
3689
3935
  JoinTable *tab=table->reginfo.join_tab;
3690
3936
 
3691
 
  if ((error=table->cursor->index_prev(table->getInsertRecord())))
 
3937
  if ((error=table->cursor->index_prev(table->record[0])))
3692
3938
    return table->report_error(error);
3693
3939
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3694
3940
                      tab->ref.key_length))
3706
3952
  return join_init_read_record(tab);
3707
3953
}
3708
3954
 
 
3955
int rr_sequential(READ_RECORD *info);
3709
3956
int init_read_record_seq(JoinTable *tab)
3710
3957
{
3711
 
  tab->read_record.init_reard_record_sequential();
3712
 
 
3713
 
  if (tab->read_record.cursor->startTableScan(1))
 
3958
  tab->read_record.read_record= rr_sequential;
 
3959
  if (tab->read_record.cursor->ha_rnd_init(1))
3714
3960
    return 1;
3715
3961
  return (*tab->read_record.read_record)(&tab->read_record);
3716
3962
}
3727
3973
{
3728
3974
  if (tab->select && tab->select->quick && tab->select->quick->reset())
3729
3975
    return 1;
3730
 
 
3731
 
  tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true);
3732
 
 
 
3976
  init_read_record(&tab->read_record, tab->join->session, tab->table,
 
3977
                   tab->select,1,1);
3733
3978
  return (*tab->read_record.read_record)(&tab->read_record);
3734
3979
}
3735
3980
 
3740
3985
  if (!table->key_read && table->covering_keys.test(tab->index) &&
3741
3986
      !table->no_keyread)
3742
3987
  {
3743
 
    table->key_read= 1;
 
3988
    table->key_read=1;
3744
3989
    table->cursor->extra(HA_EXTRA_KEYREAD);
3745
3990
  }
3746
 
  tab->table->status= 0;
 
3991
  tab->table->status=0;
3747
3992
  tab->read_record.table=table;
3748
3993
  tab->read_record.cursor=table->cursor;
3749
3994
  tab->read_record.index=tab->index;
3750
 
  tab->read_record.record=table->getInsertRecord();
 
3995
  tab->read_record.record=table->record[0];
3751
3996
  if (tab->insideout_match_tab)
3752
3997
  {
3753
3998
    tab->read_record.do_insideout_scan= tab;
3761
4006
  }
3762
4007
 
3763
4008
  if (!table->cursor->inited)
3764
 
    table->cursor->startIndexScan(tab->index, tab->sorted);
3765
 
  if ((error=tab->table->cursor->index_first(tab->table->getInsertRecord())))
 
4009
    table->cursor->ha_index_init(tab->index, tab->sorted);
 
4010
  if ((error=tab->table->cursor->index_first(tab->table->record[0])))
3766
4011
  {
3767
4012
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
3768
4013
      table->report_error(error);
3772
4017
  return 0;
3773
4018
}
3774
4019
 
3775
 
int join_read_next_different(ReadRecord *info)
 
4020
int join_read_next_different(READ_RECORD *info)
3776
4021
{
3777
4022
  JoinTable *tab= info->do_insideout_scan;
3778
4023
  if (tab->insideout_match_tab->found_match)
3779
4024
  {
3780
 
    KeyInfo *key= tab->table->key_info + tab->index;
 
4025
    KEY *key= tab->table->key_info + tab->index;
3781
4026
    do
3782
4027
    {
3783
4028
      int error;
3795
4040
    return join_read_next(info);
3796
4041
}
3797
4042
 
3798
 
int join_read_next(ReadRecord *info)
 
4043
int join_read_next(READ_RECORD *info)
3799
4044
{
3800
4045
  int error;
3801
4046
  if ((error=info->cursor->index_next(info->record)))
3818
4063
  tab->read_record.table=table;
3819
4064
  tab->read_record.cursor=table->cursor;
3820
4065
  tab->read_record.index=tab->index;
3821
 
  tab->read_record.record=table->getInsertRecord();
 
4066
  tab->read_record.record=table->record[0];
3822
4067
  if (!table->cursor->inited)
3823
 
    table->cursor->startIndexScan(tab->index, 1);
3824
 
  if ((error= tab->table->cursor->index_last(tab->table->getInsertRecord())))
 
4068
    table->cursor->ha_index_init(tab->index, 1);
 
4069
  if ((error= tab->table->cursor->index_last(tab->table->record[0])))
3825
4070
    return table->report_error(error);
3826
4071
 
3827
4072
  return 0;
3828
4073
}
3829
4074
 
3830
 
int join_read_prev(ReadRecord *info)
 
4075
int join_read_prev(READ_RECORD *info)
3831
4076
{
3832
4077
  int error;
3833
4078
  if ((error= info->cursor->index_prev(info->record)))
3853
4098
  return safe_index_read(tab);
3854
4099
}
3855
4100
 
3856
 
int join_read_next_same_or_null(ReadRecord *info)
 
4101
int join_read_next_same_or_null(READ_RECORD *info)
3857
4102
{
3858
4103
  int error;
3859
4104
  if ((error= join_read_next_same(info)) >= 0)
3867
4112
  return safe_index_read(tab);                  // then read null keys
3868
4113
}
3869
4114
 
3870
 
enum_nested_loop_state end_send_group(Join *join, JoinTable *, bool end_of_records)
 
4115
enum_nested_loop_state end_send_group(JOIN *join, JoinTable *, bool end_of_records)
3871
4116
{
3872
4117
  int idx= -1;
3873
4118
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
3956
4201
  return(NESTED_LOOP_OK);
3957
4202
}
3958
4203
 
3959
 
enum_nested_loop_state end_write_group(Join *join, JoinTable *, bool end_of_records)
 
4204
enum_nested_loop_state end_write_group(JOIN *join, JoinTable *, bool end_of_records)
3960
4205
{
3961
4206
  Table *table=join->tmp_table;
3962
4207
  int     idx= -1;
3963
4208
 
3964
 
  if (join->session->getKilled())
 
4209
  if (join->session->killed)
3965
4210
  {                                             // Aborted by user
3966
4211
    join->session->send_kill_message();
3967
4212
    return NESTED_LOOP_KILLED;
3982
4227
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
3983
4228
        if (!join->having || join->having->val_int())
3984
4229
        {
3985
 
          int error= table->cursor->insertRecord(table->getInsertRecord());
3986
 
 
3987
 
          if (error)
3988
 
          {
3989
 
            my_error(ER_USE_SQL_BIG_RESULT, MYF(0));
3990
 
            return NESTED_LOOP_ERROR;
3991
 
          }
 
4230
          int error= table->cursor->ha_write_row(table->record[0]);
 
4231
          if (error && create_myisam_from_heap(join->session, table,
 
4232
                                              join->tmp_table_param.start_recinfo,
 
4233
                                                &join->tmp_table_param.recinfo,
 
4234
                                              error, 0))
 
4235
          return NESTED_LOOP_ERROR;
3992
4236
        }
3993
4237
        if (join->rollup.state != ROLLUP::STATE_NONE)
3994
4238
        {
4009
4253
    if (idx < (int) join->send_group_parts)
4010
4254
    {
4011
4255
      copy_fields(&join->tmp_table_param);
4012
 
      if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
4013
 
        return NESTED_LOOP_ERROR;
 
4256
      copy_funcs(join->tmp_table_param.items_to_copy);
4014
4257
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
4015
4258
        return NESTED_LOOP_ERROR;
4016
4259
      return NESTED_LOOP_OK;
4027
4270
  outer join table.
4028
4271
  We can't remove tests that are made against columns which are stored
4029
4272
  in sorted order.
 
4273
*****************************************************************************/
 
4274
 
 
4275
/**
4030
4276
  @return
4031
 
    1 if right_item used is a removable reference key on left_item
4032
 
    0 otherwise.
4033
 
****************************************************************************/
 
4277
    1 if right_item is used removable reference key on left_item
 
4278
*/
4034
4279
bool test_if_ref(Item_field *left_item,Item *right_item)
4035
4280
{
4036
4281
  Field *field=left_item->field;
4037
4282
  // No need to change const test. We also have to keep tests on LEFT JOIN
4038
 
  if (not field->getTable()->const_table && !field->getTable()->maybe_null)
 
4283
  if (!field->table->const_table && !field->table->maybe_null)
4039
4284
  {
4040
 
    Item *ref_item=part_of_refkey(field->getTable(),field);
 
4285
    Item *ref_item=part_of_refkey(field->table,field);
4041
4286
    if (ref_item && ref_item->eq(right_item,1))
4042
4287
    {
4043
4288
      right_item= right_item->real_item();
4220
4465
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
4221
4466
  if (ref_parts)
4222
4467
  {
4223
 
    KeyPartInfo *key_part=
 
4468
    KEY_PART_INFO *key_part=
4224
4469
      table->key_info[table->reginfo.join_tab->ref.key].key_part;
4225
4470
    uint32_t part;
4226
4471
 
4231
4476
    }
4232
4477
 
4233
4478
    for (part=0 ; part < ref_parts ; part++,key_part++)
4234
 
    {
4235
4479
      if (field->eq(key_part->field) &&
4236
 
          !(key_part->key_part_flag & HA_PART_KEY_SEG) &&
4237
 
          //If field can be NULL, we should not remove this predicate, as
4238
 
          //it may lead to non-rejection of NULL values. 
4239
 
          !(field->real_maybe_null()))
4240
 
      {
 
4480
          !(key_part->key_part_flag & HA_PART_KEY_SEG))
4241
4481
        return table->reginfo.join_tab->ref.items[part];
4242
 
      }
4243
 
    }
4244
4482
  }
4245
4483
  return (Item*) 0;
4246
4484
}
4265
4503
  @retval
4266
4504
    -1   Reverse key can be used
4267
4505
*/
4268
 
static int test_if_order_by_key(Order *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
 
4506
static int test_if_order_by_key(order_st *order, Table *table, uint32_t idx, uint32_t *used_key_parts)
4269
4507
{
4270
 
  KeyPartInfo *key_part= NULL;
4271
 
  KeyPartInfo *key_part_end= NULL;
 
4508
  KEY_PART_INFO *key_part= NULL;
 
4509
  KEY_PART_INFO *key_part_end= NULL;
4272
4510
  key_part= table->key_info[idx].key_part;
4273
4511
  key_part_end= key_part + table->key_info[idx].key_parts;
4274
4512
  key_part_map const_key_parts=table->const_key_parts[idx];
4282
4520
 
4283
4521
    /*
4284
4522
      Skip key parts that are constants in the WHERE clause.
4285
 
      These are already skipped in the ORDER BY by const_expression_in_where()
 
4523
      These are already skipped in the order_st BY by const_expression_in_where()
4286
4524
    */
4287
4525
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
4288
4526
      key_part++;
4295
4533
        the primary key as a suffix.
4296
4534
      */
4297
4535
      if (!on_primary_key &&
4298
 
          (table->cursor->getEngine()->check_flag(HTON_BIT_PRIMARY_KEY_IN_READ_INDEX)) &&
4299
 
          table->getShare()->hasPrimaryKey())
 
4536
          (table->cursor->ha_table_flags() & HA_PRIMARY_KEY_IN_READ_INDEX) &&
 
4537
          table->s->primary_key != MAX_KEY)
4300
4538
      {
4301
4539
        on_primary_key= true;
4302
 
        key_part= table->key_info[table->getShare()->getPrimaryKey()].key_part;
4303
 
        key_part_end=key_part+table->key_info[table->getShare()->getPrimaryKey()].key_parts;
4304
 
        const_key_parts=table->const_key_parts[table->getShare()->getPrimaryKey()];
 
4540
        key_part= table->key_info[table->s->primary_key].key_part;
 
4541
        key_part_end=key_part+table->key_info[table->s->primary_key].key_parts;
 
4542
        const_key_parts=table->const_key_parts[table->s->primary_key];
4305
4543
 
4306
4544
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
4307
4545
          key_part++;
4329
4567
  }
4330
4568
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4331
4569
    (uint32_t) (key_part - table->key_info[idx].key_part);
4332
 
  if (reverse == -1 && !(table->index_flags(idx) &
 
4570
  if (reverse == -1 && !(table->cursor->index_flags(idx, *used_key_parts-1, 1) &
4333
4571
                         HA_READ_PREV))
4334
4572
    reverse= 0;                                 // Index can't be used
4335
4573
  return(reverse);
4350
4588
  @retval
4351
4589
    0   no sub key
4352
4590
*/
4353
 
inline bool is_subkey(KeyPartInfo *key_part,
4354
 
                      KeyPartInfo *ref_key_part,
4355
 
                      KeyPartInfo *ref_key_part_end)
 
4591
inline bool is_subkey(KEY_PART_INFO *key_part,
 
4592
                      KEY_PART_INFO *ref_key_part,
 
4593
                      KEY_PART_INFO *ref_key_part_end)
4356
4594
{
4357
4595
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
4358
4596
    if (! key_part->field->eq(ref_key_part->field))
4371
4609
    - MAX_KEY                   If we can't use other key
4372
4610
    - the number of found key   Otherwise
4373
4611
*/
4374
 
static uint32_t test_if_subkey(Order *order,
 
4612
static uint32_t test_if_subkey(order_st *order,
4375
4613
                               Table *table,
4376
4614
                               uint32_t ref,
4377
4615
                               uint32_t ref_key_parts,
4381
4619
  uint32_t min_length= UINT32_MAX;
4382
4620
  uint32_t best= MAX_KEY;
4383
4621
  uint32_t not_used;
4384
 
  KeyPartInfo *ref_key_part= table->key_info[ref].key_part;
4385
 
  KeyPartInfo *ref_key_part_end= ref_key_part + ref_key_parts;
 
4622
  KEY_PART_INFO *ref_key_part= table->key_info[ref].key_part;
 
4623
  KEY_PART_INFO *ref_key_part_end= ref_key_part + ref_key_parts;
4386
4624
 
4387
 
  for (nr= 0 ; nr < table->getShare()->sizeKeys() ; nr++)
 
4625
  for (nr= 0 ; nr < table->s->keys ; nr++)
4388
4626
  {
4389
4627
    if (usable_keys->test(nr) &&
4390
4628
        table->key_info[nr].key_length < min_length &&
4433
4671
*/
4434
4672
bool list_contains_unique_index(Table *table, bool (*find_func) (Field *, void *), void *data)
4435
4673
{
4436
 
  for (uint32_t keynr= 0; keynr < table->getShare()->sizeKeys(); keynr++)
 
4674
  for (uint32_t keynr= 0; keynr < table->s->keys; keynr++)
4437
4675
  {
4438
 
    if (keynr == table->getShare()->getPrimaryKey() ||
 
4676
    if (keynr == table->s->primary_key ||
4439
4677
         (table->key_info[keynr].flags & HA_NOSAME))
4440
4678
    {
4441
 
      KeyInfo *keyinfo= table->key_info + keynr;
4442
 
      KeyPartInfo *key_part= NULL;
4443
 
      KeyPartInfo *key_part_end= NULL;
 
4679
      KEY *keyinfo= table->key_info + keynr;
 
4680
      KEY_PART_INFO *key_part= NULL;
 
4681
      KEY_PART_INFO *key_part_end= NULL;
4444
4682
 
4445
4683
      for (key_part=keyinfo->key_part,
4446
4684
           key_part_end=key_part+ keyinfo->key_parts;
4473
4711
*/
4474
4712
bool find_field_in_order_list (Field *field, void *data)
4475
4713
{
4476
 
  Order *group= (Order *) data;
 
4714
  order_st *group= (order_st *) data;
4477
4715
  bool part_found= 0;
4478
 
  for (Order *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
 
4716
  for (order_st *tmp_group= group; tmp_group; tmp_group=tmp_group->next)
4479
4717
  {
4480
4718
    Item *item= (*tmp_group->item)->real_item();
4481
4719
    if (item->type() == Item::FIELD_ITEM &&
4521
4759
}
4522
4760
 
4523
4761
/**
4524
 
  Test if we can skip the ORDER BY by using an index.
 
4762
  Test if we can skip the order_st BY by using an index.
4525
4763
 
4526
4764
  SYNOPSIS
4527
4765
    test_if_skip_sort_order()
4545
4783
  @retval
4546
4784
    1    We can use an index.
4547
4785
*/
4548
 
bool test_if_skip_sort_order(JoinTable *tab, Order *order, ha_rows select_limit, bool no_changes, const key_map *map)
 
4786
bool test_if_skip_sort_order(JoinTable *tab, order_st *order, ha_rows select_limit, bool no_changes, const key_map *map)
4549
4787
{
4550
4788
  int32_t ref_key;
4551
4789
  uint32_t ref_key_parts;
4552
4790
  int order_direction;
4553
4791
  uint32_t used_key_parts;
4554
4792
  Table *table=tab->table;
4555
 
  optimizer::SqlSelect *select= tab->select;
 
4793
  SQL_SELECT *select=tab->select;
4556
4794
  key_map usable_keys;
4557
 
  optimizer::QuickSelectInterface *save_quick= NULL;
 
4795
  QUICK_SELECT_I *save_quick= 0;
4558
4796
 
4559
4797
  /*
4560
4798
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
4562
4800
  */
4563
4801
  usable_keys= *map;
4564
4802
 
4565
 
  for (Order *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
 
4803
  for (order_st *tmp_order=order; tmp_order ; tmp_order=tmp_order->next)
4566
4804
  {
4567
4805
    Item *item= (*tmp_order->item)->real_item();
4568
4806
    if (item->type() != Item::FIELD_ITEM)
4584
4822
    if (tab->type == AM_REF_OR_NULL)
4585
4823
      return(0);
4586
4824
  }
4587
 
  else if (select && select->quick)             // Range found by optimizer/range
 
4825
  else if (select && select->quick)             // Range found by opt_range
4588
4826
  {
4589
4827
    int quick_type= select->quick->get_type();
4590
4828
    save_quick= select->quick;
4594
4832
      by clustered PK values.
4595
4833
    */
4596
4834
 
4597
 
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4598
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4599
 
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT)
 
4835
    if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
4836
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
4837
        quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT)
4600
4838
      return(0);
4601
4839
    ref_key=       select->quick->index;
4602
4840
    ref_key_parts= select->quick->used_key_parts;
4646
4884
        else
4647
4885
        {
4648
4886
          /*
4649
 
            The range optimizer constructed QuickRange for ref_key, and
 
4887
            The range optimizer constructed QUICK_RANGE for ref_key, and
4650
4888
            we want to use instead new_ref_key as the index. We can't
4651
4889
            just change the index of the quick select, because this may
4652
4890
            result in an incosistent QUICK_SELECT object. Below we
4691
4929
    int best_key= -1;
4692
4930
    bool is_best_covering= false;
4693
4931
    double fanout= 1;
4694
 
    Join *join= tab->join;
 
4932
    JOIN *join= tab->join;
4695
4933
    uint32_t tablenr= tab - join->join_tab;
4696
4934
    ha_rows table_records= table->cursor->stats.records;
4697
4935
    bool group= join->group && order == join->group_list;
4734
4972
      fanout*= cur_pos.getFanout(); // fanout is always >= 1
4735
4973
    }
4736
4974
 
4737
 
    for (nr=0; nr < table->getShare()->sizeKeys() ; nr++)
 
4975
    for (nr=0; nr < table->s->keys ; nr++)
4738
4976
    {
4739
4977
      int direction;
4740
4978
      if (keys.test(nr) &&
4741
4979
          (direction= test_if_order_by_key(order, table, nr, &used_key_parts)))
4742
4980
      {
4743
 
        bool is_covering= table->covering_keys.test(nr) || (nr == table->getShare()->getPrimaryKey() && table->cursor->primary_key_is_clustered());
 
4981
        bool is_covering= table->covering_keys.test(nr) || (nr == table->s->primary_key && table->cursor->primary_key_is_clustered());
4744
4982
 
4745
4983
        /*
4746
 
          Don't use an index scan with ORDER BY without limit.
 
4984
          Don't use an index scan with order_st BY without limit.
4747
4985
          For GROUP BY without limit always use index scan
4748
4986
          if there is a suitable index.
4749
4987
          Why we hold to this asymmetry hardly can be explained
4757
4995
        {
4758
4996
          double rec_per_key;
4759
4997
          double index_scan_time;
4760
 
          KeyInfo *keyinfo= tab->table->key_info+nr;
 
4998
          KEY *keyinfo= tab->table->key_info+nr;
4761
4999
          if (select_limit == HA_POS_ERROR)
4762
5000
            select_limit= table_records;
4763
5001
          if (group)
4905
5143
  }
4906
5144
 
4907
5145
check_reverse_order:
4908
 
  if (order_direction == -1)            // If ORDER BY ... DESC
 
5146
  if (order_direction == -1)            // If order_st BY ... DESC
4909
5147
  {
4910
5148
    if (select && select->quick)
4911
5149
    {
4913
5151
        Don't reverse the sort order, if it's already done.
4914
5152
        (In some cases test_if_order_by_key() can be called multiple times
4915
5153
      */
4916
 
      if (! select->quick->reverse_sorted())
 
5154
      if (!select->quick->reverse_sorted())
4917
5155
      {
4918
 
        optimizer::QuickSelectDescending *tmp= NULL;
 
5156
        QUICK_SELECT_DESC *tmp;
4919
5157
        bool error= false;
4920
5158
        int quick_type= select->quick->get_type();
4921
 
        if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4922
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT ||
4923
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4924
 
            quick_type == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX)
 
5159
        if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
 
5160
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
5161
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
5162
            quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
4925
5163
        {
4926
5164
          tab->limit= 0;
4927
5165
          select->quick= save_quick;
4928
 
          return 0; // Use filesort
 
5166
          return(0);                   // Use filesort
4929
5167
        }
4930
5168
 
4931
 
        /* ORDER BY range_key DESC */
4932
 
        tmp= new optimizer::QuickSelectDescending((optimizer::QuickRangeSelect*)(select->quick),
4933
 
                                                  used_key_parts, 
4934
 
                                                  &error);
4935
 
        if (! tmp || error)
 
5169
        /* order_st BY range_key DESC */
 
5170
        tmp= new QUICK_SELECT_DESC((QUICK_RANGE_SELECT*)(select->quick),
 
5171
                                          used_key_parts, &error);
 
5172
        if (!tmp || error)
4936
5173
        {
4937
5174
          delete tmp;
4938
 
          select->quick= save_quick;
4939
 
          tab->limit= 0;
4940
 
          return 0; // Reverse sort not supported
 
5175
                select->quick= save_quick;
 
5176
                tab->limit= 0;
 
5177
          return(0);            // Reverse sort not supported
4941
5178
        }
4942
5179
        select->quick=tmp;
4943
5180
      }
4946
5183
             tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
4947
5184
    {
4948
5185
      /*
4949
 
        SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
 
5186
        SELECT * FROM t1 WHERE a=1 order_st BY a DESC,b DESC
4950
5187
 
4951
5188
        Use a traversal function that starts by reading the last row
4952
5189
        with key part (A) and then traverse the index backwards.
4957
5194
  }
4958
5195
  else if (select && select->quick)
4959
5196
    select->quick->sorted= 1;
4960
 
  return 1;
 
5197
  return(1);
4961
5198
}
4962
5199
 
4963
5200
/*
4988
5225
    -1          Some fatal error
4989
5226
    1           No records
4990
5227
*/
4991
 
int create_sort_index(Session *session, Join *join, Order *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
 
5228
int create_sort_index(Session *session, JOIN *join, order_st *order, ha_rows filesort_limit, ha_rows select_limit, bool is_order_by)
4992
5229
{
4993
5230
  uint32_t length= 0;
4994
5231
  ha_rows examined_rows;
4995
5232
  Table *table;
4996
 
  optimizer::SqlSelect *select= NULL;
 
5233
  SQL_SELECT *select;
4997
5234
  JoinTable *tab;
4998
5235
 
4999
5236
  if (join->tables == join->const_tables)
5010
5247
  */
5011
5248
  if ((order != join->group_list ||
5012
5249
       !(join->select_options & SELECT_BIG_RESULT) ||
5013
 
       (select && select->quick && (select->quick->get_type() == optimizer::QuickSelectInterface::QS_TYPE_GROUP_MIN_MAX))) &&
 
5250
       (select && select->quick && (select->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))) &&
5014
5251
      test_if_skip_sort_order(tab,order,select_limit,0,
5015
5252
                              is_order_by ?  &table->keys_in_use_for_order_by :
5016
5253
                              &table->keys_in_use_for_group_by))
5017
5254
    return(0);
5018
 
  for (Order *ord= join->order; ord; ord= ord->next)
 
5255
  for (order_st *ord= join->order; ord; ord= ord->next)
5019
5256
    length++;
5020
 
  if (!(join->sortorder= make_unireg_sortorder(order, &length, join->sortorder)))
5021
 
  {
5022
 
    return(-1);
5023
 
  }
 
5257
  if (!(join->sortorder=
 
5258
        make_unireg_sortorder(order, &length, join->sortorder)))
 
5259
    goto err;
5024
5260
 
5025
 
  table->sort.io_cache= new internal::IO_CACHE;
 
5261
  table->sort.io_cache= new IO_CACHE;
 
5262
  memset(table->sort.io_cache, 0, sizeof(IO_CACHE));
5026
5263
  table->status=0;                              // May be wrong if quick_select
5027
5264
 
5028
5265
  // If table has a range, move it to select
5050
5287
        For impossible ranges (like when doing a lookup on NULL on a NOT NULL
5051
5288
        field, quick will contain an empty record set.
5052
5289
      */
5053
 
      if (! (select->quick= (optimizer::get_quick_select_for_ref(session, 
5054
 
                                                                 table, 
5055
 
                                                                 &tab->ref,
5056
 
                                                                 tab->found_records))))
5057
 
      {
5058
 
        return(-1);
5059
 
      }
 
5290
      if (!(select->quick= (get_quick_select_for_ref(session, table, &tab->ref,
 
5291
                                                     tab->found_records))))
 
5292
        goto err;
5060
5293
    }
5061
5294
  }
5062
5295
 
5063
 
  if (table->getShare()->getType())
 
5296
  /* Fill schema tables with data before filesort if it's necessary */
 
5297
  if ((join->select_lex->options & OPTION_SCHEMA_TABLE) &&
 
5298
      get_schema_tables_result(join, PROCESSED_BY_CREATE_SORT_INDEX))
 
5299
    goto err;
 
5300
 
 
5301
  if (table->s->tmp_table)
5064
5302
    table->cursor->info(HA_STATUS_VARIABLE);    // Get record count
5065
 
 
5066
 
  FileSort filesort(*session);
5067
 
  table->sort.found_records=filesort.run(table,join->sortorder, length,
5068
 
                                         select, filesort_limit, 0,
5069
 
                                         examined_rows);
 
5303
  table->sort.found_records=filesort(session, table,join->sortorder, length,
 
5304
                                     select, filesort_limit, 0,
 
5305
                                     &examined_rows);
5070
5306
  tab->records= table->sort.found_records;      // For SQL_CALC_ROWS
5071
5307
  if (select)
5072
5308
  {
5084
5320
    table->key_read=0;
5085
5321
    table->cursor->extra(HA_EXTRA_NO_KEYREAD);
5086
5322
  }
5087
 
 
5088
5323
  return(table->sort.found_records == HA_POS_ERROR);
 
5324
err:
 
5325
  return(-1);
5089
5326
}
5090
5327
 
5091
5328
int remove_dup_with_compare(Session *session, Table *table, Field **first_field, uint32_t offset, Item *having)
5094
5331
  char *org_record,*new_record;
5095
5332
  unsigned char *record;
5096
5333
  int error;
5097
 
  uint32_t reclength= table->getShare()->getRecordLength() - offset;
5098
 
 
5099
 
  org_record=(char*) (record=table->getInsertRecord())+offset;
5100
 
  new_record=(char*) table->getUpdateRecord()+offset;
5101
 
 
5102
 
  cursor->startTableScan(1);
 
5334
  uint32_t reclength= table->s->reclength-offset;
 
5335
 
 
5336
  org_record=(char*) (record=table->record[0])+offset;
 
5337
  new_record=(char*) table->record[1]+offset;
 
5338
 
 
5339
  cursor->ha_rnd_init(1);
5103
5340
  error=cursor->rnd_next(record);
5104
5341
  for (;;)
5105
5342
  {
5106
 
    if (session->getKilled())
 
5343
    if (session->killed)
5107
5344
    {
5108
5345
      session->send_kill_message();
5109
5346
      error=0;
5119
5356
    }
5120
5357
    if (having && !having->val_int())
5121
5358
    {
5122
 
      if ((error=cursor->deleteRecord(record)))
 
5359
      if ((error=cursor->ha_delete_row(record)))
5123
5360
        goto err;
5124
5361
      error=cursor->rnd_next(record);
5125
5362
      continue;
5146
5383
      }
5147
5384
      if (table->compare_record(first_field) == 0)
5148
5385
      {
5149
 
        if ((error=cursor->deleteRecord(record)))
 
5386
        if ((error=cursor->ha_delete_row(record)))
5150
5387
          goto err;
5151
5388
      }
5152
5389
      else if (!found)
5157
5394
    }
5158
5395
    if (!found)
5159
5396
      break;                                    // End of cursor
5160
 
    /* Move current position to the next row */
5161
 
    error= cursor->rnd_pos(record, cursor->ref);
 
5397
    /* Restart search on next row */
 
5398
    error=cursor->restart_rnd_next(record,cursor->ref);
5162
5399
  }
5163
5400
 
5164
5401
  cursor->extra(HA_EXTRA_NO_CACHE);
5183
5420
                               uint32_t key_length,
5184
5421
                               Item *having)
5185
5422
{
5186
 
  unsigned char *key_pos, *record=table->getInsertRecord();
 
5423
  unsigned char *key_buffer, *key_pos, *record=table->record[0];
5187
5424
  int error;
5188
5425
  Cursor *cursor= table->cursor;
5189
5426
  uint32_t extra_length= ALIGN_SIZE(key_length)-key_length;
5190
 
  uint32_t *field_length;
 
5427
  uint32_t *field_lengths,*field_length;
5191
5428
  HASH hash;
5192
 
  std::vector<unsigned char> key_buffer;
5193
 
  std::vector<uint32_t> field_lengths;
5194
5429
 
5195
 
  key_buffer.resize((key_length + extra_length) * (long) cursor->stats.records);
5196
 
  field_lengths.resize(field_count);
 
5430
  if (! memory::multi_malloc(false,
 
5431
                       &key_buffer,
 
5432
                       (uint32_t) ((key_length + extra_length) *
 
5433
                               (long) cursor->stats.records),
 
5434
                       &field_lengths,
 
5435
                       (uint32_t) (field_count*sizeof(*field_lengths)),
 
5436
                       NULL))
 
5437
    return(1);
5197
5438
 
5198
5439
  {
5199
5440
    Field **ptr;
5200
5441
    uint32_t total_length= 0;
5201
 
 
5202
 
    for (ptr= first_field, field_length= &field_lengths[0] ; *ptr ; ptr++)
 
5442
    for (ptr= first_field, field_length=field_lengths ; *ptr ; ptr++)
5203
5443
    {
5204
5444
      uint32_t length= (*ptr)->sort_length();
5205
5445
      (*field_length++)= length;
5213
5453
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor->stats.records, 0,
5214
5454
                key_length, (hash_get_key) 0, 0, 0))
5215
5455
  {
 
5456
    free((char*) key_buffer);
5216
5457
    return(1);
5217
5458
  }
5218
5459
 
5219
 
  cursor->startTableScan(1);
5220
 
  key_pos= &key_buffer[0];
 
5460
  cursor->ha_rnd_init(1);
 
5461
  key_pos=key_buffer;
5221
5462
  for (;;)
5222
5463
  {
5223
5464
    unsigned char *org_key_pos;
5224
 
    if (session->getKilled())
 
5465
    if (session->killed)
5225
5466
    {
5226
5467
      session->send_kill_message();
5227
5468
      error=0;
5237
5478
    }
5238
5479
    if (having && !having->val_int())
5239
5480
    {
5240
 
      if ((error=cursor->deleteRecord(record)))
 
5481
      if ((error=cursor->ha_delete_row(record)))
5241
5482
        goto err;
5242
5483
      continue;
5243
5484
    }
5244
5485
 
5245
5486
    /* copy fields to key buffer */
5246
5487
    org_key_pos= key_pos;
5247
 
    field_length= &field_lengths[0];
 
5488
    field_length=field_lengths;
5248
5489
    for (Field **ptr= first_field ; *ptr ; ptr++)
5249
5490
    {
5250
5491
      (*ptr)->sort_string(key_pos,*field_length);
5254
5495
    if (hash_search(&hash, org_key_pos, key_length))
5255
5496
    {
5256
5497
      /* Duplicated found ; Remove the row */
5257
 
      if ((error=cursor->deleteRecord(record)))
 
5498
      if ((error=cursor->ha_delete_row(record)))
5258
5499
        goto err;
5259
5500
    }
5260
5501
    else
5261
5502
      (void) my_hash_insert(&hash, org_key_pos);
5262
5503
    key_pos+=extra_length;
5263
5504
  }
 
5505
  free((char*) key_buffer);
5264
5506
  hash_free(&hash);
5265
5507
  cursor->extra(HA_EXTRA_NO_CACHE);
5266
 
  (void) cursor->endTableScan();
 
5508
  (void) cursor->ha_rnd_end();
5267
5509
  return(0);
5268
5510
 
5269
5511
err:
 
5512
  free((char*) key_buffer);
5270
5513
  hash_free(&hash);
5271
5514
  cursor->extra(HA_EXTRA_NO_CACHE);
5272
 
  (void) cursor->endTableScan();
 
5515
  (void) cursor->ha_rnd_end();
5273
5516
  if (error)
5274
5517
    table->print_error(error,MYF(0));
5275
5518
  return(1);
5276
5519
}
5277
5520
 
5278
 
SortField *make_unireg_sortorder(Order *order, uint32_t *length, SortField *sortorder)
 
5521
SORT_FIELD *make_unireg_sortorder(order_st *order, uint32_t *length, SORT_FIELD *sortorder)
5279
5522
{
5280
5523
  uint32_t count;
5281
 
  SortField *sort,*pos;
 
5524
  SORT_FIELD *sort,*pos;
5282
5525
 
5283
5526
  count=0;
5284
 
  for (Order *tmp = order; tmp; tmp=tmp->next)
 
5527
  for (order_st *tmp = order; tmp; tmp=tmp->next)
5285
5528
    count++;
5286
5529
  if (!sortorder)
5287
 
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) *
 
5530
    sortorder= (SORT_FIELD*) sql_alloc(sizeof(SORT_FIELD) *
5288
5531
                                       (max(count, *length) + 1));
5289
5532
  pos= sort= sortorder;
5290
5533
 
5372
5615
*****************************************************************************/
5373
5616
 
5374
5617
/**
5375
 
  Resolve an ORDER BY or GROUP BY column reference.
 
5618
  Resolve an order_st BY or GROUP BY column reference.
5376
5619
 
5377
5620
  Given a column reference (represented by 'order') from a GROUP BY or order_st
5378
5621
  BY clause, find the actual column it represents. If the column being
5379
5622
  resolved is from the GROUP BY clause, the procedure searches the SELECT
5380
5623
  list 'fields' and the columns in the FROM list 'tables'. If 'order' is from
5381
 
  the ORDER BY clause, only the SELECT list is being searched.
 
5624
  the order_st BY clause, only the SELECT list is being searched.
5382
5625
 
5383
5626
  If 'order' is resolved to an Item, then order->item is set to the found
5384
5627
  Item. If there is no item for the found column (that is, it was resolved
5406
5649
static bool find_order_in_list(Session *session, 
5407
5650
                               Item **ref_pointer_array, 
5408
5651
                               TableList *tables,
5409
 
                               Order *order,
 
5652
                               order_st *order,
5410
5653
                               List<Item> &fields,
5411
5654
                               List<Item> &all_fields,
5412
5655
                               bool is_group_field)
5438
5681
    return false;
5439
5682
  }
5440
5683
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
5441
 
  select_item= find_item_in_list(session, order_item, fields, &counter,
 
5684
  select_item= find_item_in_list(order_item, fields, &counter,
5442
5685
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
5443
5686
  if (!select_item)
5444
5687
    return true; /* The item is not unique, or some other error occured. */
5505
5748
      push_warning_printf(session, DRIZZLE_ERROR::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
5506
5749
                          ER(ER_NON_UNIQ_ERROR),
5507
5750
                          ((Item_ident*) order_item)->field_name,
5508
 
                          session->where);
 
5751
                          current_session->where);
5509
5752
    }
5510
5753
  }
5511
5754
 
5545
5788
                TableList *tables,
5546
5789
                            List<Item> &fields,
5547
5790
                List<Item> &all_fields,
5548
 
                Order *order)
 
5791
                order_st *order)
5549
5792
{
5550
5793
  session->where="order clause";
5551
5794
  for (; order; order=order->next)
5587
5830
                TableList *tables,
5588
5831
                      List<Item> &fields,
5589
5832
                List<Item> &all_fields,
5590
 
                Order *order,
 
5833
                order_st *order,
5591
5834
                      bool *hidden_group_fields)
5592
5835
{
5593
5836
  *hidden_group_fields=0;
5594
 
  Order *ord;
 
5837
  order_st *ord;
5595
5838
 
5596
5839
  if (!order)
5597
5840
    return 0;                           /* Everything is ok */
5681
5924
  Try to use the fields in the order given by 'order' to allow one to
5682
5925
  optimize away 'order by'.
5683
5926
*/
5684
 
Order *create_distinct_group(Session *session,
 
5927
order_st *create_distinct_group(Session *session,
5685
5928
                                Item **ref_pointer_array,
5686
 
                                Order *order_list,
 
5929
                                order_st *order_list,
5687
5930
                                List<Item> &fields,
5688
5931
                                List<Item> &,
5689
5932
                                bool *all_order_by_fields_used)
5690
5933
{
5691
5934
  List_iterator<Item> li(fields);
5692
5935
  Item *item;
5693
 
  Order *order,*group,**prev;
 
5936
  order_st *order,*group,**prev;
5694
5937
 
5695
5938
  *all_order_by_fields_used= 1;
5696
5939
  while ((item=li++))
5701
5944
  {
5702
5945
    if (order->in_field_list)
5703
5946
    {
5704
 
      Order *ord=(Order*) session->memdup((char*) order,sizeof(Order));
 
5947
      order_st *ord=(order_st*) session->memdup((char*) order,sizeof(order_st));
5705
5948
      if (!ord)
5706
5949
        return 0;
5707
5950
      *prev=ord;
5721
5964
        Don't put duplicate columns from the SELECT list into the
5722
5965
        GROUP BY list.
5723
5966
      */
5724
 
      Order *ord_iter;
 
5967
      order_st *ord_iter;
5725
5968
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
5726
5969
        if ((*ord_iter->item)->eq(item, 1))
5727
5970
          goto next_item;
5728
5971
 
5729
 
      Order *ord=(Order*) session->calloc(sizeof(Order));
 
5972
      order_st *ord=(order_st*) session->calloc(sizeof(order_st));
5730
5973
      if (!ord)
5731
5974
        return 0;
5732
5975
 
5913
6156
          saved value
5914
6157
        */
5915
6158
        field= item->field;
5916
 
        item->result_field=field->new_field(session->mem_root,field->getTable(), 1);
 
6159
        item->result_field=field->new_field(session->mem_root,field->table, 1);
5917
6160
              /*
5918
6161
                We need to allocate one extra byte for null handling and
5919
6162
                another extra byte to not get warnings from purify in
5920
6163
                Field_varstring::val_int
5921
6164
              */
5922
 
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
 
6165
        if (!(tmp= (unsigned char*) sql_alloc(field->pack_length()+2)))
5923
6166
          goto err;
5924
6167
        if (copy)
5925
6168
        {
5926
6169
          copy->set(tmp, item->result_field);
5927
6170
          item->result_field->move_field(copy->to_ptr,copy->to_null_ptr,1);
5928
 
#ifdef HAVE_VALGRIND
 
6171
#ifdef HAVE_purify
5929
6172
          copy->to_ptr[copy->from_length]= 0;
5930
6173
#endif
5931
6174
          copy++;
5965
6208
    itr++;
5966
6209
  itr.sublist(res_selected_fields, elements);
5967
6210
  /*
5968
 
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
 
6211
    Put elements from HAVING, order_st BY and GROUP BY last to ensure that any
5969
6212
    reference used in these will resolve to a item that is already calculated
5970
6213
  */
5971
6214
  param->copy_funcs.concat(&extra_funcs);
6046
6289
      }
6047
6290
      else if ((field= item->get_tmp_table_field()))
6048
6291
      {
6049
 
        if (item->type() == Item::SUM_FUNC_ITEM && field->getTable()->group)
 
6292
        if (item->type() == Item::SUM_FUNC_ITEM && field->table->group)
6050
6293
          item_field= ((Item_sum*) item)->result_item(field);
6051
6294
        else
6052
6295
          item_field= (Item*) new Item_field(field);
6198
6441
}
6199
6442
 
6200
6443
/** Copy result of functions to record in tmp_table. */
6201
 
bool copy_funcs(Item **func_ptr, const Session *session)
 
6444
void copy_funcs(Item **func_ptr)
6202
6445
{
6203
6446
  Item *func;
6204
6447
  for (; (func = *func_ptr) ; func_ptr++)
6205
 
  {
6206
6448
    func->save_in_result_field(1);
6207
 
    /*
6208
 
      Need to check the THD error state because Item::val_xxx() don't
6209
 
      return error code, but can generate errors
6210
 
      TODO: change it for a real status check when Item::val_xxx()
6211
 
      are extended to return status code.
6212
 
    */
6213
 
    if (session->is_error())
6214
 
      return true;
6215
 
  }
6216
 
  return false;
6217
6449
}
6218
6450
 
6219
6451
/**
6273
6505
  @retval
6274
6506
    1   on error
6275
6507
*/
6276
 
bool change_group_ref(Session *session, Item_func *expr, Order *group_list, bool *changed)
 
6508
bool change_group_ref(Session *session, Item_func *expr, order_st *group_list, bool *changed)
6277
6509
{
6278
6510
  if (expr->arg_count)
6279
6511
  {
6287
6519
      Item *item= *arg;
6288
6520
      if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM)
6289
6521
      {
6290
 
        Order *group_tmp;
 
6522
        order_st *group_tmp;
6291
6523
        for (group_tmp= group_list; group_tmp; group_tmp= group_tmp->next)
6292
6524
        {
6293
6525
          if (item->eq(*group_tmp->item,0))
6316
6548
  return 0;
6317
6549
}
6318
6550
 
 
6551
/**
 
6552
  EXPLAIN handling.
 
6553
 
 
6554
  Send a description about what how the select will be done to stdout.
 
6555
*/
 
6556
void select_describe(JOIN *join, bool need_tmp_table, bool need_order,
 
6557
                     bool distinct,const char *message)
 
6558
{
 
6559
  List<Item> field_list;
 
6560
  List<Item> item_list;
 
6561
  Session *session=join->session;
 
6562
  select_result *result=join->result;
 
6563
  Item *item_null= new Item_null();
 
6564
  const CHARSET_INFO * const cs= system_charset_info;
 
6565
  int quick_type;
 
6566
  /* Don't log this into the slow query log */
 
6567
  session->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED);
 
6568
  join->unit->offset_limit_cnt= 0;
 
6569
 
 
6570
  /*
 
6571
    NOTE: the number/types of items pushed into item_list must be in sync with
 
6572
    EXPLAIN column types as they're "defined" in Session::send_explain_fields()
 
6573
  */
 
6574
  if (message)
 
6575
  {
 
6576
    item_list.push_back(new Item_int((int32_t)
 
6577
                                     join->select_lex->select_number));
 
6578
    item_list.push_back(new Item_string(join->select_lex->type,
 
6579
                                        strlen(join->select_lex->type), cs));
 
6580
    for (uint32_t i=0 ; i < 7; i++)
 
6581
      item_list.push_back(item_null);
 
6582
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
6583
      item_list.push_back(item_null);
 
6584
 
 
6585
    item_list.push_back(new Item_string(message,strlen(message),cs));
 
6586
    if (result->send_data(item_list))
 
6587
      join->error= 1;
 
6588
  }
 
6589
  else if (join->select_lex == join->unit->fake_select_lex)
 
6590
  {
 
6591
    /*
 
6592
      here we assume that the query will return at least two rows, so we
 
6593
      show "filesort" in EXPLAIN. Of course, sometimes we'll be wrong
 
6594
      and no filesort will be actually done, but executing all selects in
 
6595
      the UNION to provide precise EXPLAIN information will hardly be
 
6596
      appreciated :)
 
6597
    */
 
6598
    char table_name_buffer[NAME_LEN];
 
6599
    item_list.empty();
 
6600
    /* id */
 
6601
    item_list.push_back(new Item_null);
 
6602
    /* select_type */
 
6603
    item_list.push_back(new Item_string(join->select_lex->type,
 
6604
                                        strlen(join->select_lex->type),
 
6605
                                        cs));
 
6606
    /* table */
 
6607
    {
 
6608
      Select_Lex *sl= join->unit->first_select();
 
6609
      uint32_t len= 6, lastop= 0;
 
6610
      memcpy(table_name_buffer, STRING_WITH_LEN("<union"));
 
6611
      for (; sl && len + lastop + 5 < NAME_LEN; sl= sl->next_select())
 
6612
      {
 
6613
        len+= lastop;
 
6614
        lastop= snprintf(table_name_buffer + len, NAME_LEN - len,
 
6615
                         "%u,", sl->select_number);
 
6616
      }
 
6617
      if (sl || len + lastop >= NAME_LEN)
 
6618
      {
 
6619
        memcpy(table_name_buffer + len, STRING_WITH_LEN("...>") + 1);
 
6620
        len+= 4;
 
6621
      }
 
6622
      else
 
6623
      {
 
6624
        len+= lastop;
 
6625
        table_name_buffer[len - 1]= '>';  // change ',' to '>'
 
6626
      }
 
6627
      item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
6628
    }
 
6629
    /* type */
 
6630
    item_list.push_back(new Item_string(access_method_str[AM_ALL].c_str(),
 
6631
                                        access_method_str[AM_ALL].length(),
 
6632
                                        cs));
 
6633
    /* possible_keys */
 
6634
    item_list.push_back(item_null);
 
6635
    /* key*/
 
6636
    item_list.push_back(item_null);
 
6637
    /* key_len */
 
6638
    item_list.push_back(item_null);
 
6639
    /* ref */
 
6640
    item_list.push_back(item_null);
 
6641
    /* in_rows */
 
6642
    if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
6643
      item_list.push_back(item_null);
 
6644
    /* rows */
 
6645
    item_list.push_back(item_null);
 
6646
    /* extra */
 
6647
    if (join->unit->global_parameters->order_list.first)
 
6648
      item_list.push_back(new Item_string("Using filesort",
 
6649
                                          14, cs));
 
6650
    else
 
6651
      item_list.push_back(new Item_string("", 0, cs));
 
6652
 
 
6653
    if (result->send_data(item_list))
 
6654
      join->error= 1;
 
6655
  }
 
6656
  else
 
6657
  {
 
6658
    table_map used_tables=0;
 
6659
    for (uint32_t i=0 ; i < join->tables ; i++)
 
6660
    {
 
6661
      JoinTable *tab=join->join_tab+i;
 
6662
      Table *table=tab->table;
 
6663
      TableList *table_list= tab->table->pos_in_table_list;
 
6664
      char buff[512];
 
6665
      char buff1[512], buff2[512], buff3[512];
 
6666
      char keylen_str_buf[64];
 
6667
      String extra(buff, sizeof(buff),cs);
 
6668
      char table_name_buffer[NAME_LEN];
 
6669
      String tmp1(buff1,sizeof(buff1),cs);
 
6670
      String tmp2(buff2,sizeof(buff2),cs);
 
6671
      String tmp3(buff3,sizeof(buff3),cs);
 
6672
      extra.length(0);
 
6673
      tmp1.length(0);
 
6674
      tmp2.length(0);
 
6675
      tmp3.length(0);
 
6676
 
 
6677
      quick_type= -1;
 
6678
      item_list.empty();
 
6679
      /* id */
 
6680
      item_list.push_back(new Item_uint((uint32_t)
 
6681
                                       join->select_lex->select_number));
 
6682
      /* select_type */
 
6683
      item_list.push_back(new Item_string(join->select_lex->type,
 
6684
                                          strlen(join->select_lex->type),
 
6685
                                          cs));
 
6686
      if (tab->type == AM_ALL && tab->select && tab->select->quick)
 
6687
      {
 
6688
        quick_type= tab->select->quick->get_type();
 
6689
        if ((quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE) ||
 
6690
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT) ||
 
6691
            (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION))
 
6692
          tab->type = AM_INDEX_MERGE;
 
6693
        else
 
6694
          tab->type = AM_RANGE;
 
6695
      }
 
6696
      /* table */
 
6697
      if (table->derived_select_number)
 
6698
      {
 
6699
        /* Derived table name generation */
 
6700
        int len= snprintf(table_name_buffer, sizeof(table_name_buffer)-1,
 
6701
                          "<derived%u>",
 
6702
                          table->derived_select_number);
 
6703
        item_list.push_back(new Item_string(table_name_buffer, len, cs));
 
6704
      }
 
6705
      else
 
6706
      {
 
6707
        TableList *real_table= table->pos_in_table_list;
 
6708
        item_list.push_back(new Item_string(real_table->alias,
 
6709
                                            strlen(real_table->alias),
 
6710
                                            cs));
 
6711
      }
 
6712
      /* "type" column */
 
6713
      item_list.push_back(new Item_string(access_method_str[tab->type].c_str(),
 
6714
                                          access_method_str[tab->type].length(),
 
6715
                                          cs));
 
6716
      /* Build "possible_keys" value and add it to item_list */
 
6717
      if (tab->keys.any())
 
6718
      {
 
6719
        uint32_t j;
 
6720
        for (j=0 ; j < table->s->keys ; j++)
 
6721
        {
 
6722
          if (tab->keys.test(j))
 
6723
          {
 
6724
            if (tmp1.length())
 
6725
              tmp1.append(',');
 
6726
            tmp1.append(table->key_info[j].name,
 
6727
                        strlen(table->key_info[j].name),
 
6728
                        system_charset_info);
 
6729
          }
 
6730
        }
 
6731
      }
 
6732
      if (tmp1.length())
 
6733
        item_list.push_back(new Item_string(tmp1.ptr(),tmp1.length(),cs));
 
6734
      else
 
6735
        item_list.push_back(item_null);
 
6736
 
 
6737
      /* Build "key", "key_len", and "ref" values and add them to item_list */
 
6738
      if (tab->ref.key_parts)
 
6739
      {
 
6740
        KEY *key_info=table->key_info+ tab->ref.key;
 
6741
        register uint32_t length;
 
6742
        item_list.push_back(new Item_string(key_info->name,
 
6743
                                            strlen(key_info->name),
 
6744
                                            system_charset_info));
 
6745
        length= int64_t2str(tab->ref.key_length, keylen_str_buf, 10) -
 
6746
                keylen_str_buf;
 
6747
        item_list.push_back(new Item_string(keylen_str_buf, length,
 
6748
                                            system_charset_info));
 
6749
        for (StoredKey **ref=tab->ref.key_copy ; *ref ; ref++)
 
6750
        {
 
6751
          if (tmp2.length())
 
6752
            tmp2.append(',');
 
6753
          tmp2.append((*ref)->name(), strlen((*ref)->name()),
 
6754
                      system_charset_info);
 
6755
        }
 
6756
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
6757
      }
 
6758
      else if (tab->type == AM_NEXT)
 
6759
      {
 
6760
        KEY *key_info=table->key_info+ tab->index;
 
6761
        register uint32_t length;
 
6762
        item_list.push_back(new Item_string(key_info->name,
 
6763
                                            strlen(key_info->name),cs));
 
6764
        length= int64_t2str(key_info->key_length, keylen_str_buf, 10) -
 
6765
                keylen_str_buf;
 
6766
        item_list.push_back(new Item_string(keylen_str_buf,
 
6767
                                            length,
 
6768
                                            system_charset_info));
 
6769
        item_list.push_back(item_null);
 
6770
      }
 
6771
      else if (tab->select && tab->select->quick)
 
6772
      {
 
6773
        tab->select->quick->add_keys_and_lengths(&tmp2, &tmp3);
 
6774
        item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
6775
        item_list.push_back(new Item_string(tmp3.ptr(),tmp3.length(),cs));
 
6776
        item_list.push_back(item_null);
 
6777
      }
 
6778
      else
 
6779
      {
 
6780
        if (table_list->schema_table && 
 
6781
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
6782
        {
 
6783
          if (table_list->has_db_lookup_value)
 
6784
          {
 
6785
            int f_idx= table_list->schema_table->getFirstColumnIndex();
 
6786
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
6787
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
6788
          }
 
6789
          if (table_list->has_table_lookup_value)
 
6790
          {
 
6791
            if (table_list->has_db_lookup_value)
 
6792
              tmp2.append(',');
 
6793
            int f_idx= table_list->schema_table->getSecondColumnIndex();
 
6794
            const string &tmp_buff= table_list->schema_table->getColumnName(f_idx);
 
6795
            tmp2.append(tmp_buff.c_str(), tmp_buff.length(), cs);
 
6796
          }
 
6797
          if (tmp2.length())
 
6798
            item_list.push_back(new Item_string(tmp2.ptr(),tmp2.length(),cs));
 
6799
          else
 
6800
            item_list.push_back(item_null);
 
6801
        }
 
6802
        else
 
6803
          item_list.push_back(item_null);
 
6804
        item_list.push_back(item_null);
 
6805
        item_list.push_back(item_null);
 
6806
      }
 
6807
 
 
6808
      /* Add "rows" field to item_list. */
 
6809
      if (table_list->schema_table)
 
6810
      {
 
6811
        /* in_rows */
 
6812
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
6813
          item_list.push_back(item_null);
 
6814
        /* rows */
 
6815
        item_list.push_back(item_null);
 
6816
      }
 
6817
      else
 
6818
      {
 
6819
        double examined_rows;
 
6820
        if (tab->select && tab->select->quick)
 
6821
          examined_rows= rows2double(tab->select->quick->records);
 
6822
        else if (tab->type == AM_NEXT || tab->type == AM_ALL)
 
6823
          examined_rows= rows2double(tab->limit ? tab->limit :
 
6824
                                     tab->table->cursor->records());
 
6825
        else
 
6826
        {
 
6827
          optimizer::Position cur_pos= join->getPosFromOptimalPlan(i);
 
6828
          examined_rows= cur_pos.getFanout();
 
6829
        }
 
6830
 
 
6831
        item_list.push_back(new Item_int((int64_t) (uint64_t) examined_rows,
 
6832
                                         MY_INT64_NUM_DECIMAL_DIGITS));
 
6833
 
 
6834
        /* Add "filtered" field to item_list. */
 
6835
        if (join->session->lex->describe & DESCRIBE_EXTENDED)
 
6836
        {
 
6837
          float f= 0.0;
 
6838
          if (examined_rows)
 
6839
          {
 
6840
            optimizer::Position cur_pos= join->getPosFromOptimalPlan(i);
 
6841
            f= (float) (100.0 * cur_pos.getFanout() /
 
6842
                        examined_rows);
 
6843
          }
 
6844
          item_list.push_back(new Item_float(f, 2));
 
6845
        }
 
6846
      }
 
6847
 
 
6848
      /* Build "Extra" field and add it to item_list. */
 
6849
      bool key_read=table->key_read;
 
6850
      if ((tab->type == AM_NEXT || tab->type == AM_CONST) &&
 
6851
          table->covering_keys.test(tab->index))
 
6852
        key_read=1;
 
6853
      if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT &&
 
6854
          !((QUICK_ROR_INTERSECT_SELECT*)tab->select->quick)->need_to_fetch_row)
 
6855
        key_read=1;
 
6856
 
 
6857
      if (tab->info)
 
6858
        item_list.push_back(new Item_string(tab->info,strlen(tab->info),cs));
 
6859
      else if (tab->packed_info & TAB_INFO_HAVE_VALUE)
 
6860
      {
 
6861
        if (tab->packed_info & TAB_INFO_USING_INDEX)
 
6862
          extra.append(STRING_WITH_LEN("; Using index"));
 
6863
        if (tab->packed_info & TAB_INFO_USING_WHERE)
 
6864
          extra.append(STRING_WITH_LEN("; Using where"));
 
6865
        if (tab->packed_info & TAB_INFO_FULL_SCAN_ON_NULL)
 
6866
          extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
6867
        /* Skip initial "; "*/
 
6868
        const char *str= extra.ptr();
 
6869
        uint32_t len= extra.length();
 
6870
        if (len)
 
6871
        {
 
6872
          str += 2;
 
6873
          len -= 2;
 
6874
        }
 
6875
        item_list.push_back(new Item_string(str, len, cs));
 
6876
      }
 
6877
      else
 
6878
      {
 
6879
        uint32_t keyno= MAX_KEY;
 
6880
        if (tab->ref.key_parts)
 
6881
          keyno= tab->ref.key;
 
6882
        else if (tab->select && tab->select->quick)
 
6883
          keyno = tab->select->quick->index;
 
6884
 
 
6885
        if (quick_type == QUICK_SELECT_I::QS_TYPE_ROR_UNION ||
 
6886
            quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
 
6887
            quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE)
 
6888
        {
 
6889
          extra.append(STRING_WITH_LEN("; Using "));
 
6890
          tab->select->quick->add_info_string(&extra);
 
6891
        }
 
6892
          if (tab->select)
 
6893
        {
 
6894
          if (tab->use_quick == 2)
 
6895
          {
 
6896
            /*
 
6897
             * To print out the bitset in tab->keys, we go through
 
6898
             * it 32 bits at a time. We need to do this to ensure
 
6899
             * that the to_ulong() method will not throw an
 
6900
             * out_of_range exception at runtime which would happen
 
6901
             * if the bitset we were working with was larger than 64
 
6902
             * bits on a 64-bit platform (for example).
 
6903
             */
 
6904
            stringstream s, w;
 
6905
            string str;
 
6906
            w << tab->keys;
 
6907
            w >> str;
 
6908
            for (uint32_t pos= 0; pos < tab->keys.size(); pos+= 32)
 
6909
            {
 
6910
              bitset<32> tmp(str, pos, 32);
 
6911
              if (tmp.any())
 
6912
                s << uppercase << hex << tmp.to_ulong();
 
6913
            }
 
6914
            extra.append(STRING_WITH_LEN("; Range checked for each "
 
6915
                                         "record (index map: 0x"));
 
6916
            extra.append(s.str().c_str());
 
6917
            extra.append(')');
 
6918
          }
 
6919
          else if (tab->select->cond)
 
6920
          {
 
6921
            extra.append(STRING_WITH_LEN("; Using where"));
 
6922
          }
 
6923
        }
 
6924
        if (key_read)
 
6925
        {
 
6926
          if (quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
 
6927
            extra.append(STRING_WITH_LEN("; Using index for group-by"));
 
6928
          else
 
6929
            extra.append(STRING_WITH_LEN("; Using index"));
 
6930
        }
 
6931
        if (table->reginfo.not_exists_optimize)
 
6932
          extra.append(STRING_WITH_LEN("; Not exists"));
 
6933
 
 
6934
        if (table_list->schema_table &&
 
6935
            table_list->schema_table->getRequestedObject() & OPTIMIZE_I_S_TABLE)
 
6936
        {
 
6937
          if (!table_list->table_open_method)
 
6938
            extra.append(STRING_WITH_LEN("; Skip_open_table"));
 
6939
          else if (table_list->table_open_method == OPEN_FRM_ONLY)
 
6940
            extra.append(STRING_WITH_LEN("; Open_frm_only"));
 
6941
          else
 
6942
            extra.append(STRING_WITH_LEN("; Open_full_table"));
 
6943
          if (table_list->has_db_lookup_value &&
 
6944
              table_list->has_table_lookup_value)
 
6945
            extra.append(STRING_WITH_LEN("; Scanned 0 databases"));
 
6946
          else if (table_list->has_db_lookup_value ||
 
6947
                   table_list->has_table_lookup_value)
 
6948
            extra.append(STRING_WITH_LEN("; Scanned 1 database"));
 
6949
          else
 
6950
            extra.append(STRING_WITH_LEN("; Scanned all databases"));
 
6951
        }
 
6952
        if (need_tmp_table)
 
6953
        {
 
6954
          need_tmp_table=0;
 
6955
          extra.append(STRING_WITH_LEN("; Using temporary"));
 
6956
        }
 
6957
        if (need_order)
 
6958
        {
 
6959
          need_order=0;
 
6960
          extra.append(STRING_WITH_LEN("; Using filesort"));
 
6961
        }
 
6962
        if (distinct & test_all_bits(used_tables,session->used_tables))
 
6963
          extra.append(STRING_WITH_LEN("; Distinct"));
 
6964
 
 
6965
        if (tab->insideout_match_tab)
 
6966
        {
 
6967
          extra.append(STRING_WITH_LEN("; LooseScan"));
 
6968
        }
 
6969
 
 
6970
        for (uint32_t part= 0; part < tab->ref.key_parts; part++)
 
6971
        {
 
6972
          if (tab->ref.cond_guards[part])
 
6973
          {
 
6974
            extra.append(STRING_WITH_LEN("; Full scan on NULL key"));
 
6975
            break;
 
6976
          }
 
6977
        }
 
6978
 
 
6979
        if (i > 0 && tab[-1].next_select == sub_select_cache)
 
6980
          extra.append(STRING_WITH_LEN("; Using join buffer"));
 
6981
 
 
6982
        /* Skip initial "; "*/
 
6983
        const char *str= extra.ptr();
 
6984
        uint32_t len= extra.length();
 
6985
        if (len)
 
6986
        {
 
6987
          str += 2;
 
6988
          len -= 2;
 
6989
        }
 
6990
        item_list.push_back(new Item_string(str, len, cs));
 
6991
      }
 
6992
      // For next iteration
 
6993
      used_tables|=table->map;
 
6994
      if (result->send_data(item_list))
 
6995
        join->error= 1;
 
6996
    }
 
6997
  }
 
6998
  for (Select_Lex_Unit *unit= join->select_lex->first_inner_unit();
 
6999
       unit;
 
7000
       unit= unit->next_unit())
 
7001
  {
 
7002
    if (mysql_explain_union(session, unit, result))
 
7003
      return;
 
7004
  }
 
7005
  return;
 
7006
}
 
7007
 
 
7008
bool mysql_explain_union(Session *session, Select_Lex_Unit *unit, select_result *result)
 
7009
{
 
7010
  bool res= false;
 
7011
  Select_Lex *first= unit->first_select();
 
7012
 
 
7013
  for (Select_Lex *sl= first;
 
7014
       sl;
 
7015
       sl= sl->next_select())
 
7016
  {
 
7017
    // drop UNCACHEABLE_EXPLAIN, because it is for internal usage only
 
7018
    uint8_t uncacheable= (sl->uncacheable & ~UNCACHEABLE_EXPLAIN);
 
7019
    sl->type= (((&session->lex->select_lex)==sl)?
 
7020
               (sl->first_inner_unit() || sl->next_select() ?
 
7021
                "PRIMARY" : "SIMPLE"):
 
7022
               ((sl == first)?
 
7023
                ((sl->linkage == DERIVED_TABLE_TYPE) ?
 
7024
                 "DERIVED":
 
7025
                 ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
7026
                  "DEPENDENT SUBQUERY":
 
7027
                  (uncacheable?"UNCACHEABLE SUBQUERY":
 
7028
                   "SUBQUERY"))):
 
7029
                ((uncacheable & UNCACHEABLE_DEPENDENT) ?
 
7030
                 "DEPENDENT UNION":
 
7031
                 uncacheable?"UNCACHEABLE UNION":
 
7032
                 "UNION")));
 
7033
    sl->options|= SELECT_DESCRIBE;
 
7034
  }
 
7035
  if (unit->is_union())
 
7036
  {
 
7037
    unit->fake_select_lex->select_number= UINT_MAX; // jost for initialization
 
7038
    unit->fake_select_lex->type= "UNION RESULT";
 
7039
    unit->fake_select_lex->options|= SELECT_DESCRIBE;
 
7040
    if (!(res= unit->prepare(session, result, SELECT_NO_UNLOCK | SELECT_DESCRIBE)))
 
7041
      res= unit->exec();
 
7042
    res|= unit->cleanup();
 
7043
  }
 
7044
  else
 
7045
  {
 
7046
    session->lex->current_select= first;
 
7047
    unit->set_limit(unit->global_parameters);
 
7048
    res= mysql_select(session, &first->ref_pointer_array,
 
7049
                        (TableList*) first->table_list.first,
 
7050
                        first->with_wild, first->item_list,
 
7051
                        first->where,
 
7052
                        first->order_list.elements +
 
7053
                        first->group_list.elements,
 
7054
                        (order_st*) first->order_list.first,
 
7055
                        (order_st*) first->group_list.first,
 
7056
                        first->having,
 
7057
                        first->options | session->options | SELECT_DESCRIBE,
 
7058
                        result, unit, first);
 
7059
  }
 
7060
  return(res || session->is_error());
 
7061
}
6319
7062
 
6320
7063
static void print_table_array(Session *session, String *str, TableList **table,
6321
7064
                              TableList **end)
6370
7113
void Select_Lex::print(Session *session, String *str, enum_query_type query_type)
6371
7114
{
6372
7115
  /* QQ: session may not be set for sub queries, but this should be fixed */
6373
 
  if(not session)
 
7116
  if (!session)
6374
7117
    session= current_session;
6375
7118
 
6376
 
 
6377
7119
  str->append(STRING_WITH_LEN("select "));
6378
7120
 
6379
7121
  /* First add options */
6439
7181
  if (group_list.elements)
6440
7182
  {
6441
7183
    str->append(STRING_WITH_LEN(" group by "));
6442
 
    print_order(str, (Order *) group_list.first, query_type);
 
7184
    print_order(str, (order_st *) group_list.first, query_type);
6443
7185
    switch (olap)
6444
7186
    {
6445
7187
      case CUBE_TYPE:
6470
7212
  if (order_list.elements)
6471
7213
  {
6472
7214
    str->append(STRING_WITH_LEN(" order by "));
6473
 
    print_order(str, (Order *) order_list.first, query_type);
 
7215
    print_order(str, (order_st *) order_list.first, query_type);
6474
7216
  }
6475
7217
 
6476
7218
  // limit
6482
7224
/**
6483
7225
  @} (end of group Query_Optimizer)
6484
7226
*/
6485
 
 
6486
 
} /* namespace drizzled */