~ubuntu-branches/ubuntu/saucy/drizzle/saucy-proposed

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Package Import Robot
  • Author(s): Clint Byrum
  • Date: 2012-06-19 10:46:49 UTC
  • mfrom: (1.1.6)
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20120619104649-e2l0ggd4oz3um0f4
Tags: upstream-7.1.36-stable
ImportĀ upstreamĀ versionĀ 7.1.36-stable

Show diffs side-by-side

added added

removed removed

Lines of Context:
87
87
                                     Item *cond,
88
88
                                     Item *field,
89
89
                                     Item *value);
90
 
static bool copy_blobs(Field **ptr);
 
90
static void copy_blobs(Field **ptr);
91
91
 
92
92
static bool eval_const_cond(COND *cond)
93
93
{
94
 
    return ((Item_func*) cond)->val_int() ? true : false;
 
94
  return ((Item_func*) cond)->val_int() ? true : false;
95
95
}
96
96
 
97
97
/*
99
99
  We limit semi-join InsideOut optimization to handling max 64 inequalities,
100
100
  The following variable occupies 64 addresses.
101
101
*/
102
 
const char *subq_sj_cond_name=
103
 
  "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
 
102
const char *subq_sj_cond_name= "0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef-sj-cond";
104
103
 
105
 
static bool copy_blobs(Field **ptr)
 
104
static void copy_blobs(Field **ptr)
106
105
{
107
106
  for (; *ptr ; ptr++)
108
107
  {
109
108
    if ((*ptr)->flags & BLOB_FLAG)
110
 
      if (((Field_blob *) (*ptr))->copy())
111
 
        return 1;                               // Error
 
109
    {
 
110
      ((Field_blob *) (*ptr))->copy();
 
111
    }
112
112
  }
113
 
  return 0;
114
113
}
115
114
 
116
115
/**
123
122
  Select_Lex *select_lex= &lex->select_lex;
124
123
  DRIZZLE_SELECT_START(session->getQueryString()->c_str());
125
124
 
126
 
  if (select_lex->master_unit()->is_union() ||
 
125
  if (select_lex->master_unit()->is_union() or
127
126
      select_lex->master_unit()->fake_select_lex)
128
127
  {
129
128
    res= drizzle_union(session, lex, result, &lex->unit,
134
133
    Select_Lex_Unit *unit= &lex->unit;
135
134
    unit->set_limit(unit->global_parameters);
136
135
    session->session_marker= 0;
 
136
 
137
137
    /*
138
138
      'options' of select_query will be set in JOIN, as far as JOIN for
139
139
      every PS/SP execution new, we will not need reset this flag if
155
155
                      result, unit, select_lex);
156
156
  }
157
157
  res|= session->is_error();
 
158
 
158
159
  if (unlikely(res))
 
160
  {
159
161
    result->abort();
 
162
  }
160
163
 
161
164
  DRIZZLE_SELECT_DONE(res, session->limit_found_rows);
162
165
  return res;
217
220
    Item *item= ref->outer_ref;
218
221
    Item **item_ref= ref->ref;
219
222
    Item_ref *new_ref;
 
223
 
220
224
    /*
221
225
      @todo this field item already might be present in the select list.
222
226
      In this case instead of adding new field item we could use an
240
244
    {
241
245
      Item_sum *sum_func;
242
246
      if (ref->in_sum_func->nest_level > select->nest_level)
 
247
      {
243
248
        direct_ref= true;
 
249
      }
244
250
      else
245
251
      {
246
252
        for (sum_func= ref->in_sum_func; sum_func &&
255
261
        }
256
262
      }
257
263
    }
 
264
 
258
265
    new_ref= direct_ref ?
259
266
              new Item_direct_ref(ref->context, item_ref, ref->table_name,
260
267
                          ref->field_name, ref->alias_name_used) :
261
268
              new Item_ref(ref->context, item_ref, ref->table_name,
262
269
                          ref->field_name, ref->alias_name_used);
263
 
    if (!new_ref)
264
 
      return true;
 
270
 
265
271
    ref->outer_ref= new_ref;
266
272
    ref->ref= &ref->outer_ref;
267
273
 
268
274
    if (!ref->fixed && ref->fix_fields(session, 0))
 
275
    {
269
276
      return true;
 
277
    }
270
278
    session->used_tables|= item->used_tables();
271
279
  }
272
280
  return res;
298
306
void save_index_subquery_explain_info(JoinTable *join_tab, Item* where)
299
307
{
300
308
  join_tab->packed_info= TAB_INFO_HAVE_VALUE;
 
309
 
301
310
  if (join_tab->table->covering_keys.test(join_tab->ref.key))
302
311
    join_tab->packed_info |= TAB_INFO_USING_INDEX;
 
312
 
303
313
  if (where)
304
314
    join_tab->packed_info |= TAB_INFO_USING_WHERE;
 
315
 
305
316
  for (uint32_t i = 0; i < join_tab->ref.key_parts; i++)
306
317
  {
307
318
    if (join_tab->ref.cond_guards[i])
389
400
        //here is EXPLAIN of subselect or derived table
390
401
        if (join->change_result(result))
391
402
        {
392
 
          return(true);
 
403
          return true;
393
404
        }
394
405
      }
395
406
      else
406
417
  }
407
418
  else
408
419
  {
409
 
    if (!(join= new Join(session, fields, select_options, result)))
410
 
      return(true);
 
420
    join= new Join(session, fields, select_options, result);
411
421
    session->set_proc_info("init");
412
422
    session->used_tables=0;                         // Updated by setup_fields
413
 
    if ((err= join->prepare(rref_pointer_array, tables, wild_num,
414
 
                           conds, og_num, order, group, having,
415
 
                           select_lex, unit)) == true)
 
423
    if ((err= join->prepare(rref_pointer_array, tables, wild_num, conds, og_num, order, group, having, select_lex, unit)))
416
424
    {
417
425
      goto err;
418
426
    }
431
439
  }
432
440
 
433
441
  if (session->is_error())
 
442
  {
434
443
    goto err;
 
444
  }
435
445
 
436
446
  join->exec();
437
447
 
464
474
{
465
475
  int error;
466
476
  if (check_stack_overrun(session, STACK_MIN_SIZE, NULL))
467
 
    return(0);                           // Fatal error flag is set
 
477
  {
 
478
    return 0;                           // Fatal error flag is set
 
479
  }
 
480
 
468
481
  if (select)
469
482
  {
470
483
    select->head=table;
471
484
    table->reginfo.impossible_range=0;
472
485
    if ((error= select->test_quick_select(session, *(key_map *)keys,(table_map) 0,
473
486
                                          limit, 0, false)) == 1)
 
487
    {
474
488
      return(select->quick->records);
 
489
    }
 
490
 
475
491
    if (error == -1)
476
492
    {
477
493
      table->reginfo.impossible_range=1;
478
 
      return(0);
 
494
      return 0;
479
495
    }
480
496
  }
 
497
 
481
498
  return(HA_POS_ERROR);                 /* This shouldn't happend */
482
499
}
483
500
 
499
516
{
500
517
  uint32_t found;
501
518
  for (found=0; bits & 1 ; found++,bits>>=1) ;
 
519
 
502
520
  return found;
503
521
}
504
522
 
507
525
  int res;
508
526
  if (a->getTable()->tablenr != b->getTable()->tablenr)
509
527
    return static_cast<int>((a->getTable()->tablenr - b->getTable()->tablenr));
 
528
 
510
529
  if (a->getKey() != b->getKey())
511
530
    return static_cast<int>((a->getKey() - b->getKey()));
 
531
 
512
532
  if (a->getKeypart() != b->getKeypart())
513
533
    return static_cast<int>((a->getKeypart() - b->getKeypart()));
 
534
 
514
535
  // Place const values before other ones
515
536
  if ((res= test((a->getUsedTables() & ~OUTER_REF_TABLE_BIT)) -
516
537
       test((b->getUsedTables() & ~OUTER_REF_TABLE_BIT))))
517
538
    return res;
 
539
 
518
540
  /* Place rows that are not 'OPTIMIZE_REF_OR_NULL' first */
519
541
  return static_cast<int>(((a->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL) -
520
542
                          (b->getOptimizeFlags() & KEY_OPTIMIZE_REF_OR_NULL)));
541
563
   @retval
542
564
     1  Out of memory.
543
565
*/
544
 
bool update_ref_and_keys(Session *session,
 
566
void update_ref_and_keys(Session *session,
545
567
                         DYNAMIC_ARRAY *keyuse,
546
568
                         JoinTable *join_tab,
547
569
                         uint32_t tables,
551
573
                         Select_Lex *select_lex,
552
574
                         vector<optimizer::SargableParam> &sargables)
553
575
{
554
 
  uint  and_level,found_eq_constant;
555
 
  optimizer::KeyField *key_fields, *end, *field;
556
 
  uint32_t sz;
557
576
  uint32_t m= max(select_lex->max_equal_elems,(uint32_t)1);
558
577
 
559
578
  /*
573
592
    can be not more than select_lex->max_equal_elems such
574
593
    substitutions.
575
594
  */
576
 
  sz= sizeof(optimizer::KeyField) *
577
 
      (((session->lex().current_select->cond_count+1)*2 +
578
 
        session->lex().current_select->between_count)*m+1);
579
 
  if (! (key_fields= (optimizer::KeyField*) session->getMemRoot()->allocate(sz)))
580
 
    return true;
581
 
  and_level= 0;
 
595
  optimizer::KeyField* key_fields= new (session->mem) optimizer::KeyField[((session->lex().current_select->cond_count+1)*2 + session->lex().current_select->between_count)*m+1];
 
596
  uint and_level= 0;
 
597
  optimizer::KeyField* end, *field;
582
598
  field= end= key_fields;
583
599
 
584
 
  if (my_init_dynamic_array(keyuse, sizeof(optimizer::KeyUse), 20, 64))
585
 
    return true;
 
600
  keyuse->init(sizeof(optimizer::KeyUse), 20, 64);
586
601
  if (cond)
587
602
  {
588
603
    add_key_fields(join_tab->join, &end, &and_level, cond, normal_tables,
652
667
 
653
668
    use= save_pos= (optimizer::KeyUse*)keyuse->buffer;
654
669
    prev= &key_end;
655
 
    found_eq_constant= 0;
 
670
    uint found_eq_constant= 0;
656
671
    {
657
 
      uint32_t i;
658
 
 
659
 
      for (i= 0; i < keyuse->size()-1; i++, use++)
 
672
      for (uint32_t i= 0; i < keyuse->size()-1; i++, use++)
660
673
      {
661
674
        if (! use->getUsedTables() && use->getOptimizeFlags() != KEY_OPTIMIZE_REF_OR_NULL)
662
675
          use->getTable()->const_key_parts[use->getKey()]|= use->getKeypartMap();
 
676
 
663
677
        if (use->getKey() == prev->getKey() && use->getTable() == prev->getTable())
664
678
        {
665
679
          if (prev->getKeypart() + 1 < use->getKeypart() ||
666
680
              ((prev->getKeypart() == use->getKeypart()) && found_eq_constant))
 
681
          {
667
682
            continue;                           /* remove */
 
683
          }
668
684
        }
669
685
        else if (use->getKeypart() != 0)                // First found must be 0
 
686
        {
670
687
          continue;
 
688
        }
671
689
 
672
690
#ifdef HAVE_VALGRIND
673
691
        /* Valgrind complains about overlapped memcpy when save_pos==use. */
678
696
        found_eq_constant= ! use->getUsedTables();
679
697
        /* Save ptr to first use */
680
698
        if (! use->getTable()->reginfo.join_tab->keyuse)
 
699
        {
681
700
          use->getTable()->reginfo.join_tab->keyuse= save_pos;
 
701
        }
682
702
        use->getTable()->reginfo.join_tab->checked_keys.set(use->getKey());
683
703
        save_pos++;
684
704
      }
685
 
      i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
 
705
 
 
706
      uint32_t i= (uint32_t) (save_pos - (optimizer::KeyUse*) keyuse->buffer);
686
707
      reinterpret_cast<optimizer::KeyUse*>(keyuse->buffer)[i] = key_end;
687
708
      keyuse->set_size(i);
688
709
    }
689
710
  }
690
 
  return false;
691
711
}
692
712
 
693
713
/**
708
728
      To avoid bad matches, we don't make ref_table_rows less than 100.
709
729
    */
710
730
    keyuse->setTableRows(~(ha_rows) 0); // If no ref
 
731
 
711
732
    if (keyuse->getUsedTables() & (map= (keyuse->getUsedTables() & ~join->const_table_map & ~OUTER_REF_TABLE_BIT)))
712
733
    {
713
734
      uint32_t tablenr;
718
739
        keyuse->setTableRows(max(tmp_table->cursor->stats.records, (ha_rows)100));
719
740
      }
720
741
    }
 
742
 
721
743
    /*
722
744
      Outer reference (external field) is constant for single executing
723
745
      of subquery
724
746
    */
725
747
    if (keyuse->getUsedTables() == OUTER_REF_TABLE_BIT)
 
748
    {
726
749
      keyuse->setTableRows(1);
 
750
    }
727
751
  }
728
752
}
729
753
 
756
780
  if (join->group_list)
757
781
  { /* Collect all query fields referenced in the GROUP clause. */
758
782
    for (cur_group= join->group_list; cur_group; cur_group= cur_group->next)
759
 
      (*cur_group->item)->walk(&Item::collect_item_field_processor, 0,
760
 
                               (unsigned char*) &indexed_fields);
 
783
    {
 
784
      (*cur_group->item)->walk(&Item::collect_item_field_processor, 0, (unsigned char*) &indexed_fields);
 
785
    }
761
786
  }
762
787
  else if (join->select_distinct)
763
788
  { /* Collect all query fields referenced in the SELECT clause. */
765
790
    List<Item>::iterator select_items_it(select_items.begin());
766
791
    Item *item;
767
792
    while ((item= select_items_it++))
768
 
      item->walk(&Item::collect_item_field_processor, 0,
769
 
                 (unsigned char*) &indexed_fields);
 
793
    {
 
794
      item->walk(&Item::collect_item_field_processor, 0, (unsigned char*) &indexed_fields);
 
795
    }
770
796
  }
771
797
  else
 
798
  {
772
799
    return;
 
800
  }
773
801
 
774
802
  if (indexed_fields.size() == 0)
 
803
  {
775
804
    return;
 
805
  }
776
806
 
777
807
  /* Intersect the keys of all group fields. */
778
808
  cur_item= indexed_fields_it++;
817
847
 
818
848
  if (jt1->dependent & jt2->table->map)
819
849
    return 1;
 
850
 
820
851
  if (jt2->dependent & jt1->table->map)
821
852
    return -1;
 
853
 
822
854
  if (jt1->found_records > jt2->found_records)
823
855
    return 1;
 
856
 
824
857
  if (jt1->found_records < jt2->found_records)
825
858
    return -1;
 
859
 
826
860
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
827
861
}
828
862
 
836
870
 
837
871
  if (jt1->dependent & jt2->table->map)
838
872
    return 1;
 
873
 
839
874
  if (jt2->dependent & jt1->table->map)
840
875
    return -1;
 
876
 
841
877
  return jt1 > jt2 ? 1 : (jt1 < jt2 ? -1 : 0);
842
878
}
843
879
 
857
893
      uint32_t flags=field->flags;
858
894
      fields++;
859
895
      rec_length+=field->pack_length();
 
896
 
860
897
      if (flags & BLOB_FLAG)
 
898
      {
861
899
        blobs++;
 
900
      }
 
901
 
862
902
      if (!(flags & NOT_NULL_FLAG))
 
903
      {
863
904
        null_fields++;
 
905
      }
864
906
    }
865
907
  }
 
908
 
866
909
  if (null_fields)
 
910
  {
867
911
    rec_length+=(join_tab->table->getNullFields() + 7)/8;
 
912
  }
 
913
 
868
914
  if (join_tab->table->maybe_null)
 
915
  {
869
916
    rec_length+=sizeof(bool);
 
917
  }
 
918
 
870
919
  if (blobs)
871
920
  {
872
921
    uint32_t blob_length=(uint32_t) (join_tab->table->cursor->stats.mean_rec_length-
946
995
{
947
996
  if (*e1)
948
997
  {
949
 
    Item *res;
950
 
    if ((res= new Item_cond_and(*e1, e2)))
951
 
    {
952
 
      *e1= res;
953
 
      res->quick_fix_field();
954
 
    }
 
998
    Item* res= new Item_cond_and(*e1, e2);
 
999
    *e1= res;
 
1000
    res->quick_fix_field();
955
1001
  }
956
1002
  else
 
1003
  {
957
1004
    *e1= e2;
 
1005
  }
958
1006
}
959
1007
 
960
1008
bool create_ref_for_key(Join *join,
1004
1052
  j->ref.key_parts=keyparts;
1005
1053
  j->ref.key_length=length;
1006
1054
  j->ref.key=(int) key;
1007
 
  if (!(j->ref.key_buff= (unsigned char*) session->calloc(ALIGN_SIZE(length)*2)) ||
1008
 
      !(j->ref.key_copy= (StoredKey**) session->getMemRoot()->allocate((sizeof(StoredKey*) *
1009
 
               (keyparts+1)))) ||
1010
 
      !(j->ref.items=    (Item**) session->getMemRoot()->allocate(sizeof(Item*)*keyparts)) ||
1011
 
      !(j->ref.cond_guards= (bool**) session->getMemRoot()->allocate(sizeof(uint*)*keyparts)))
1012
 
  {
1013
 
    return(true);
1014
 
  }
 
1055
  j->ref.key_buff= (unsigned char*) session->mem.calloc(ALIGN_SIZE(length)*2);
 
1056
  j->ref.key_copy= new (session->mem) StoredKey*[keyparts + 1];
 
1057
  j->ref.items= new (session->mem) Item*[keyparts];
 
1058
  j->ref.cond_guards= new (session->mem) bool*[keyparts];
1015
1059
  j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
1016
1060
  j->ref.key_err=1;
1017
1061
  j->ref.null_rejecting= 0;
1024
1068
  {
1025
1069
    for (uint32_t i= 0; i < keyparts; keyuse++, i++)
1026
1070
    {
1027
 
      while (keyuse->getKeypart() != i ||
1028
 
             ((~used_tables) & keyuse->getUsedTables()))
 
1071
      while (keyuse->getKeypart() != i or ((~used_tables) & keyuse->getUsedTables()))
 
1072
      {
1029
1073
        keyuse++;       /* Skip other parts */
 
1074
      }
1030
1075
 
1031
1076
      uint32_t maybe_null= test(keyinfo->key_part[i].null_bit);
1032
1077
      j->ref.items[i]= keyuse->getVal();    // Save for cond removal
1033
1078
      j->ref.cond_guards[i]= keyuse->getConditionalGuard();
1034
1079
      if (keyuse->isNullRejected())
 
1080
      {
1035
1081
        j->ref.null_rejecting |= 1 << i;
 
1082
      }
 
1083
 
1036
1084
      keyuse_uses_no_tables= keyuse_uses_no_tables && ! keyuse->getUsedTables();
1037
1085
      if (! keyuse->getUsedTables() &&  !(join->select_options & SELECT_DESCRIBE))
1038
1086
      {         // Compare against constant
1041
1089
                           maybe_null ?  key_buff : 0,
1042
1090
                           keyinfo->key_part[i].length, keyuse->getVal());
1043
1091
        if (session->is_fatal_error)
1044
 
          return(true);
 
1092
        {
 
1093
          return true;
 
1094
        }
1045
1095
        tmp.copy();
1046
1096
      }
1047
1097
      else
 
1098
      {
1048
1099
        *ref_key++= get_store_key(session,
1049
 
          keyuse,join->const_table_map,
1050
 
          &keyinfo->key_part[i],
1051
 
          key_buff, maybe_null);
 
1100
                                  keyuse,join->const_table_map,
 
1101
                                  &keyinfo->key_part[i],
 
1102
                                  key_buff, maybe_null);
 
1103
      }
 
1104
 
1052
1105
      /*
1053
1106
        Remember if we are going to use REF_OR_NULL
1054
1107
        But only if field _really_ can be null i.e. we force AM_REF
1061
1114
  }
1062
1115
  *ref_key= 0;       // end_marker
1063
1116
  if (j->type == AM_CONST)
 
1117
  {
1064
1118
    j->table->const_table= 1;
1065
 
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) ||
1066
 
           keyparts != keyinfo->key_parts || null_ref_key)
 
1119
  }
 
1120
  else if (((keyinfo->flags & (HA_NOSAME | HA_NULL_PART_KEY)) != HA_NOSAME) || keyparts != keyinfo->key_parts || null_ref_key)
1067
1121
  {
1068
1122
    /* Must read with repeat */
1069
1123
    j->type= null_ref_key ? AM_REF_OR_NULL : AM_REF;
1081
1135
    j->type= AM_CONST;
1082
1136
  }
1083
1137
  else
 
1138
  {
1084
1139
    j->type= AM_EQ_REF;
 
1140
  }
 
1141
 
1085
1142
  return 0;
1086
1143
}
1087
1144
 
1159
1216
            not_null_item is the t1.f1, but it's referred_tab is 0.
1160
1217
          */
1161
1218
          if (!referred_tab || referred_tab->join != join)
 
1219
          {
1162
1220
            continue;
1163
 
          if (!(notnull= new Item_func_isnotnull(not_null_item)))
1164
 
            return;
 
1221
          }
 
1222
          notnull= new Item_func_isnotnull(not_null_item);
 
1223
 
1165
1224
          /*
1166
1225
            We need to do full fix_fields() call here in order to have correct
1167
1226
            notnull->const_item(). This is needed e.g. by test_quick_select
1169
1228
            called.
1170
1229
          */
1171
1230
          if (notnull->fix_fields(join->session, &notnull))
 
1231
          {
1172
1232
            return;
 
1233
          }
 
1234
 
1173
1235
          add_cond_and_fix(&referred_tab->select_cond, notnull);
1174
1236
        }
1175
1237
      }
1176
1238
    }
1177
1239
  }
1178
 
  return;
1179
1240
}
1180
1241
 
1181
1242
/**
1209
1270
  return tmp;
1210
1271
}
1211
1272
 
1212
 
#define ICP_COND_USES_INDEX_ONLY 10
1213
 
 
1214
 
 
1215
1273
/**
1216
1274
  cleanup JoinTable.
1217
1275
*/
1250
1308
  for (JoinTable **tab=join->map2table ; tables ; tab++, tables>>=1)
1251
1309
  {
1252
1310
    if (tables & 1 && !eq_ref_table(join, order, *tab))
 
1311
    {
1253
1312
      return 0;
 
1313
    }
1254
1314
  }
1255
1315
  return 1;
1256
1316
}
1277
1337
bool eq_ref_table(Join *join, Order *start_order, JoinTable *tab)
1278
1338
{
1279
1339
  if (tab->cached_eq_ref_table)                 // If cached
 
1340
  {
1280
1341
    return tab->eq_ref_table;
 
1342
  }
 
1343
 
1281
1344
  tab->cached_eq_ref_table=1;
 
1345
 
1282
1346
  /* We can skip const tables only if not an outer table */
1283
1347
  if (tab->type == AM_CONST && !tab->first_inner)
 
1348
  {
1284
1349
    return (tab->eq_ref_table=1);
 
1350
  }
 
1351
 
1285
1352
  if (tab->type != AM_EQ_REF || tab->table->maybe_null)
 
1353
  {
1286
1354
    return (tab->eq_ref_table=0);               // We must use this
 
1355
  }
 
1356
 
1287
1357
  Item **ref_item=tab->ref.items;
1288
1358
  Item **end=ref_item+tab->ref.key_parts;
1289
1359
  uint32_t found=0;
1299
1369
        if ((*ref_item)->eq(order->item[0],0))
1300
1370
          break;
1301
1371
      }
 
1372
 
1302
1373
      if (order)
1303
1374
      {
1304
1375
        found++;
1306
1377
        order->used|=map;
1307
1378
        continue;                               // Used in order_st BY
1308
1379
      }
 
1380
 
1309
1381
      if (!only_eq_ref_tables(join,start_order, (*ref_item)->used_tables()))
 
1382
      {
1310
1383
        return (tab->eq_ref_table= 0);
 
1384
      }
1311
1385
    }
1312
1386
  }
1313
1387
  /* Check that there was no reference to table before sort order */
1352
1426
    while ((item= li++))
1353
1427
    {
1354
1428
      if (item->contains(field))
 
1429
      {
1355
1430
        goto finish;
 
1431
      }
1356
1432
    }
1357
1433
    in_upper_level= true;
1358
1434
    cond_equal= cond_equal->upper_levels;
1359
1435
  }
1360
1436
  in_upper_level= false;
 
1437
 
1361
1438
finish:
1362
1439
  *inherited_fl= in_upper_level;
1363
1440
  return item;
1492
1569
      left_item_equal= new Item_equal(left_item_equal);
1493
1570
      cond_equal->current_level.push_back(left_item_equal);
1494
1571
      if (copy_item_name)
 
1572
      {
1495
1573
        left_item_equal->name = item->name;
 
1574
      }
1496
1575
    }
1497
1576
    if (right_copyfl)
1498
1577
    {
1500
1579
      right_item_equal= new Item_equal(right_item_equal);
1501
1580
      cond_equal->current_level.push_back(right_item_equal);
1502
1581
      if (copy_item_name)
 
1582
      {
1503
1583
        right_item_equal->name = item->name;
 
1584
      }
1504
1585
    }
1505
1586
 
1506
1587
    if (left_item_equal)
1525
1606
      {
1526
1607
        right_item_equal->add((Item_field *) left_item);
1527
1608
        if (copy_item_name)
 
1609
        {
1528
1610
          right_item_equal->name = item->name;
 
1611
        }
1529
1612
      }
1530
1613
      else
1531
1614
      {
1534
1617
                                               (Item_field *) right_item);
1535
1618
        cond_equal->current_level.push_back(item_equal);
1536
1619
        if (copy_item_name)
 
1620
        {
1537
1621
          item_equal->name = item->name;
 
1622
        }
1538
1623
      }
1539
1624
    }
1540
1625
    return true;
1566
1651
 
1567
1652
      if (field_item->result_type() == STRING_RESULT)
1568
1653
      {
1569
 
        const CHARSET_INFO * const cs= ((Field_str*) field_item->field)->charset();
 
1654
        const charset_info_st * const cs= ((Field_str*) field_item->field)->charset();
1570
1655
        if (!item)
1571
1656
        {
1572
1657
          Item_func_eq *eq_item;
1573
 
          if ((eq_item= new Item_func_eq(left_item, right_item)))
1574
 
            return false;
 
1658
          eq_item= new Item_func_eq(left_item, right_item);
1575
1659
          eq_item->set_cmp_func();
1576
1660
          eq_item->quick_fix_field();
1577
1661
          item= eq_item;
1578
1662
        }
1579
 
        if ((cs != ((Item_func *) item)->compare_collation()) ||
1580
 
            !cs->coll->propagate(cs, 0, 0))
 
1663
 
 
1664
        if ((cs != ((Item_func *) item)->compare_collation()) || !cs->coll->propagate())
 
1665
        {
1581
1666
          return false;
 
1667
        }
1582
1668
      }
1583
1669
 
1584
1670
      Item_equal *item_equal = find_item_equal(cond_equal,
1605
1691
      return true;
1606
1692
    }
1607
1693
  }
 
1694
 
1608
1695
  return false;
1609
1696
}
1610
1697
 
1653
1740
                                       (Item_row *) right_item,
1654
1741
                                       cond_equal, eq_list);
1655
1742
      if (!is_converted)
 
1743
      {
1656
1744
        session->lex().current_select->cond_count++;
 
1745
      }
1657
1746
    }
1658
1747
    else
1659
1748
    {
1664
1753
    if (!is_converted)
1665
1754
    {
1666
1755
      Item_func_eq *eq_item;
1667
 
      if (!(eq_item= new Item_func_eq(left_item, right_item)))
1668
 
        return false;
 
1756
      eq_item= new Item_func_eq(left_item, right_item);
1669
1757
      eq_item->set_cmp_func();
1670
1758
      eq_item->quick_fix_field();
1671
1759
      eq_list->push_back(eq_item);
1721
1809
                                cond_equal, eq_list);
1722
1810
    }
1723
1811
    else
 
1812
    {
1724
1813
      return check_simple_equality(left_item, right_item, item, cond_equal);
 
1814
    }
1725
1815
  }
1726
1816
  return false;
1727
1817
}
1821
1911
          re-execution of any prepared statement/stored procedure.
1822
1912
        */
1823
1913
        if (check_equality(session, item, &cond_equal, &eq_list))
 
1914
        {
1824
1915
          li.remove();
 
1916
        }
1825
1917
      }
1826
1918
 
1827
1919
      List<Item_equal>::iterator it(cond_equal.current_level.begin());
1877
1969
    if (check_equality(session, cond, &cond_equal, &eq_list))
1878
1970
    {
1879
1971
      int n= cond_equal.current_level.size() + eq_list.size();
 
1972
 
1880
1973
      if (n == 0)
 
1974
      {
1881
1975
        return new Item_int((int64_t) 1,1);
 
1976
      }
1882
1977
      else if (n == 1)
1883
1978
      {
1884
1979
        if ((item_equal= cond_equal.current_level.pop()))
1887
1982
          item_equal->update_used_tables();
1888
1983
        }
1889
1984
        else
 
1985
        {
1890
1986
          item_equal= (Item_equal *) eq_list.pop();
 
1987
        }
1891
1988
        set_if_bigger(session->lex().current_select->max_equal_elems,
1892
1989
                      item_equal->members());
1893
1990
        return item_equal;
2007
2104
  {
2008
2105
    cond= build_equal_items_for_cond(session, cond, inherited);
2009
2106
    cond->update_used_tables();
2010
 
    if (cond->type() == Item::COND_ITEM &&
2011
 
        ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
2107
 
 
2108
    if (cond->type() == Item::COND_ITEM && ((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
 
2109
    {
2012
2110
      cond_equal= &((Item_cond_and*) cond)->cond_equal;
 
2111
    }
2013
2112
    else if (cond->type() == Item::FUNC_ITEM &&
2014
2113
             ((Item_cond*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)
2015
2114
    {
2079
2178
    outer_ref= 1;
2080
2179
    cmp= -1;
2081
2180
  }
 
2181
 
2082
2182
  if (field2->used_tables() & OUTER_REF_TABLE_BIT)
2083
2183
  {
2084
2184
    outer_ref= 1;
2085
2185
    cmp++;
2086
2186
  }
 
2187
 
2087
2188
  if (outer_ref)
 
2189
  {
2088
2190
    return cmp;
 
2191
  }
 
2192
 
2089
2193
  JoinTable **idx= (JoinTable **) table_join_idx;
2090
2194
  cmp= idx[field2->field->getTable()->tablenr]-idx[field1->field->getTable()->tablenr];
 
2195
 
2091
2196
  return cmp < 0 ? -1 : (cmp ? 1 : 0);
2092
2197
}
2093
2198
 
2140
2245
  Item_equal_iterator it(item_equal->begin());
2141
2246
  Item *head;
2142
2247
  if (item_const)
 
2248
  {
2143
2249
    head= item_const;
 
2250
  }
2144
2251
  else
2145
2252
  {
2146
2253
    head= item_equal->get_first();
2154
2261
    if (upper)
2155
2262
    {
2156
2263
      if (item_const && upper->get_const())
 
2264
      {
2157
2265
        item= 0;
 
2266
      }
2158
2267
      else
2159
2268
      {
2160
2269
        Item_equal_iterator li(item_equal->begin());
2161
2270
        while ((item= li++) != item_field)
2162
2271
        {
2163
2272
          if (item->find_item_equal(upper_levels) == upper)
 
2273
          {
2164
2274
            break;
 
2275
          }
2165
2276
        }
2166
2277
      }
2167
2278
    }
2168
2279
    if (item == item_field)
2169
2280
    {
2170
2281
      if (eq_item)
 
2282
      {
2171
2283
        eq_list.push_back(eq_item);
 
2284
      }
 
2285
 
2172
2286
      eq_item= new Item_func_eq(item_field, head);
 
2287
 
2173
2288
      if (!eq_item)
 
2289
      {
2174
2290
        return 0;
 
2291
      }
2175
2292
      eq_item->set_cmp_func();
2176
2293
      eq_item->quick_fix_field();
2177
2294
   }
2180
2297
  if (!cond && !&eq_list.front())
2181
2298
  {
2182
2299
    if (!eq_item)
 
2300
    {
2183
2301
      return new Item_int((int64_t) 1,1);
 
2302
    }
2184
2303
    return eq_item;
2185
2304
  }
2186
2305
 
2187
2306
  if (eq_item)
 
2307
  {
2188
2308
    eq_list.push_back(eq_item);
 
2309
  }
 
2310
 
2189
2311
  if (!cond)
 
2312
  {
2190
2313
    cond= new Item_cond_and(eq_list);
 
2314
  }
2191
2315
  else
2192
2316
  {
2193
2317
    assert(cond->type() == Item::COND_ITEM);
2276
2400
          break;
2277
2401
      }
2278
2402
    }
2279
 
    if (cond->type() == Item::COND_ITEM &&
2280
 
        !((Item_cond*)cond)->argument_list()->size())
 
2403
 
 
2404
    if (cond->type() == Item::COND_ITEM && !((Item_cond*)cond)->argument_list()->size())
 
2405
    {
2281
2406
      cond= new Item_int((int32_t)cond->val_bool());
 
2407
    }
2282
2408
 
2283
2409
  }
2284
2410
  else if (cond->type() == Item::FUNC_ITEM &&
2287
2413
    item_equal= (Item_equal *) cond;
2288
2414
    item_equal->sort(&compare_fields_by_table_order, table_join_idx);
2289
2415
    if (cond_equal && &cond_equal->current_level.front() == item_equal)
 
2416
    {
2290
2417
      cond_equal= 0;
 
2418
    }
 
2419
 
2291
2420
    return eliminate_item_equal(0, cond_equal, item_equal);
2292
2421
  }
2293
2422
  else
 
2423
  {
2294
2424
    cond->transform(&Item::replace_equal_field, 0);
 
2425
  }
 
2426
 
2295
2427
  return cond;
2296
2428
}
2297
2429
 
2380
2512
 
2381
2513
    return;
2382
2514
  }
 
2515
 
2383
2516
  if (cond->eq_cmp_result() == Item::COND_OK)
 
2517
  {
2384
2518
    return;                                     // Not a boolean function
 
2519
  }
2385
2520
 
2386
2521
  Item_bool_func2 *func=  (Item_bool_func2*) cond;
2387
2522
  Item **args= func->arguments();
2449
2584
Item *remove_additional_cond(Item* conds)
2450
2585
{
2451
2586
  if (conds->name == in_additional_cond)
 
2587
  {
2452
2588
    return 0;
 
2589
  }
 
2590
 
2453
2591
  if (conds->type() == Item::COND_ITEM)
2454
2592
  {
2455
2593
    Item_cond *cnd= (Item_cond*) conds;
2461
2599
      {
2462
2600
        li.remove();
2463
2601
        if (cnd->argument_list()->size() == 1)
 
2602
        {
2464
2603
          return &cnd->argument_list()->front();
 
2604
        }
 
2605
 
2465
2606
        return conds;
2466
2607
      }
2467
2608
    }
2508
2649
      Item **args= func->arguments();
2509
2650
      bool left_const= args[0]->const_item();
2510
2651
      bool right_const= args[1]->const_item();
2511
 
      if (!(left_const && right_const) &&
2512
 
          args[0]->result_type() == args[1]->result_type())
 
2652
      if (!(left_const && right_const) && args[0]->result_type() == args[1]->result_type())
2513
2653
      {
2514
2654
        if (right_const)
2515
2655
        {
2516
 
                resolve_const_item(session, &args[1], args[0]);
 
2656
          resolve_const_item(session, &args[1], args[0]);
2517
2657
          func->update_used_tables();
2518
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2519
 
                                        args[0], args[1]);
 
2658
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
2659
                                   args[0], args[1]);
2520
2660
        }
2521
2661
        else if (left_const)
2522
2662
        {
2523
 
                resolve_const_item(session, &args[0], args[1]);
 
2663
          resolve_const_item(session, &args[0], args[1]);
2524
2664
          func->update_used_tables();
2525
 
                change_cond_ref_to_const(session, save_list, and_father, and_father,
2526
 
                                        args[1], args[0]);
 
2665
          change_cond_ref_to_const(session, save_list, and_father, and_father,
 
2666
                                   args[1], args[0]);
2527
2667
        }
2528
2668
      }
2529
2669
    }
2651
2791
      join->cur_embedding_map |= next_emb->getNestedJoin()->nj_map;
2652
2792
    }
2653
2793
 
2654
 
    if (next_emb->getNestedJoin()->join_list.size() !=
2655
 
        next_emb->getNestedJoin()->counter_)
 
2794
    if (next_emb->getNestedJoin()->join_list.size() != next_emb->getNestedJoin()->counter_)
 
2795
    {
2656
2796
      break;
 
2797
    }
2657
2798
 
2658
2799
    /*
2659
2800
      We're currently at Y or Z-bracket as depicted in the above picture.
2668
2809
{
2669
2810
  Session *session= join->session;
2670
2811
 
2671
 
  if (!conds)
 
2812
  if (conds == NULL)
 
2813
  {
2672
2814
    *cond_value= Item::COND_TRUE;
 
2815
  }
2673
2816
  else
2674
2817
  {
2675
2818
    /*
2721
2864
    {
2722
2865
      Item *new_item= remove_eq_conds(session, item, &tmp_cond_value);
2723
2866
      if (! new_item)
2724
 
              li.remove();
 
2867
      {
 
2868
        li.remove();
 
2869
      }
2725
2870
      else if (item != new_item)
2726
2871
      {
2727
2872
        li.replace(new_item);
2728
2873
        should_fix_fields= true;
2729
2874
      }
 
2875
 
2730
2876
      if (*cond_value == Item::COND_UNDEF)
2731
 
              *cond_value= tmp_cond_value;
 
2877
      {
 
2878
        *cond_value= tmp_cond_value;
 
2879
      }
2732
2880
 
2733
2881
      switch (tmp_cond_value)
2734
2882
      {
2756
2904
    }
2757
2905
 
2758
2906
    if (should_fix_fields)
 
2907
    {
2759
2908
      cond->update_used_tables();
 
2909
    }
2760
2910
 
2761
2911
    if (! ((Item_cond*) cond)->argument_list()->size() || *cond_value != Item::COND_OK)
 
2912
    {
2762
2913
      return (COND*) NULL;
 
2914
    }
2763
2915
 
2764
2916
    if (((Item_cond*) cond)->argument_list()->size() == 1)
2765
2917
    {
2766
2918
      /* Argument list contains only one element, so reduce it so a single item, then remove list */
2767
2919
      item= &((Item_cond*) cond)->argument_list()->front();
2768
2920
      ((Item_cond*) cond)->argument_list()->clear();
 
2921
 
2769
2922
      return item;
2770
2923
    }
2771
2924
  }
2795
2948
            )
2796
2949
          )
2797
2950
      {
2798
 
        COND *new_cond;
2799
 
        if ((new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()",
2800
 
                                                          session->read_first_successful_insert_id_in_prev_stmt(),
2801
 
                                                          MY_INT64_NUM_DECIMAL_DIGITS))))
2802
 
        {
2803
 
          cond= new_cond;
2804
 
          /*
2805
 
            Item_func_eq can't be fixed after creation so we do not check
2806
 
            cond->fixed, also it do not need tables so we use 0 as second
2807
 
            argument.
2808
 
          */
2809
 
          cond->fix_fields(session, &cond);
2810
 
        }
 
2951
        COND *new_cond= new Item_func_eq(args[0], new Item_int("last_insert_id()", 
 
2952
          session->read_first_successful_insert_id_in_prev_stmt(), MY_INT64_NUM_DECIMAL_DIGITS));
 
2953
        cond= new_cond;
 
2954
        /*
 
2955
        Item_func_eq can't be fixed after creation so we do not check
 
2956
        cond->fixed, also it do not need tables so we use 0 as second
 
2957
        argument.
 
2958
        */
 
2959
        cond->fix_fields(session, &cond);
2811
2960
        /*
2812
2961
          IS NULL should be mapped to LAST_INSERT_ID only for first row, so
2813
2962
          clear for next row
2821
2970
          && (field->flags & NOT_NULL_FLAG)
2822
2971
          && ! field->table->maybe_null)
2823
2972
      {
2824
 
        COND *new_cond;
2825
 
        if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
2826
 
        {
2827
 
          cond= new_cond;
2828
 
          /*
2829
 
            Item_func_eq can't be fixed after creation so we do not check
2830
 
            cond->fixed, also it do not need tables so we use 0 as second
2831
 
            argument.
2832
 
          */
2833
 
          cond->fix_fields(session, &cond);
2834
 
        }
 
2973
        COND* new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2));
 
2974
        cond= new_cond;
 
2975
        /*
 
2976
        Item_func_eq can't be fixed after creation so we do not check
 
2977
        cond->fixed, also it do not need tables so we use 0 as second
 
2978
        argument.
 
2979
        */
 
2980
        cond->fix_fields(session, &cond);
2835
2981
      }
2836
2982
#endif /* NOTDEFINED */
2837
2983
    }
2864
3010
    if (left_item->eq(right_item,1))
2865
3011
    {
2866
3012
      if (!left_item->maybe_null || ((Item_func*) cond)->functype() == Item_func::EQUAL_FUNC)
2867
 
              return (COND*) NULL;                      /* Comparison of identical items */
 
3013
      {
 
3014
        return (COND*) NULL;                    /* Comparison of identical items */
 
3015
      }
2868
3016
    }
2869
3017
  }
2870
3018
  *cond_value= Item::COND_OK;
2913
3061
{
2914
3062
  if (cond->type() == Item::COND_ITEM)
2915
3063
  {
2916
 
    bool and_level= (((Item_cond*) cond)->functype()
2917
 
                     == Item_func::COND_AND_FUNC);
 
3064
    bool and_level= (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC);
2918
3065
    List<Item>::iterator li(((Item_cond*) cond)->argument_list()->begin());
 
3066
 
2919
3067
    Item *item;
2920
3068
    while ((item=li++))
2921
3069
    {
2923
3071
      if (res)                                  // Is a const value
2924
3072
      {
2925
3073
        if (and_level)
2926
 
          return 1;
2927
 
      }
2928
 
      else if (!and_level)
2929
 
        return 0;
 
3074
        {
 
3075
          return true;
 
3076
        }
 
3077
      }
 
3078
      else if (and_level == false)
 
3079
      {
 
3080
        return false;
 
3081
      }
2930
3082
    }
2931
 
    return and_level ? 0 : 1;
 
3083
    return and_level ? false : true;
2932
3084
  }
2933
3085
  else if (cond->eq_cmp_result() != Item::COND_OK)
2934
3086
  {                                             // boolan compare function
2935
3087
    Item_func* func= (Item_func*) cond;
2936
3088
    if (func->functype() != Item_func::EQUAL_FUNC &&
2937
3089
              func->functype() != Item_func::EQ_FUNC)
2938
 
      return 0;
 
3090
    {
 
3091
      return false;
 
3092
    }
 
3093
 
2939
3094
    Item *left_item=    ((Item_func*) cond)->arguments()[0];
2940
3095
    Item *right_item= ((Item_func*) cond)->arguments()[1];
 
3096
 
2941
3097
    if (left_item->eq(comp_item,1))
2942
3098
    {
2943
3099
      if (test_if_equality_guarantees_uniqueness (left_item, right_item))
2944
3100
      {
2945
3101
        if (*const_item)
 
3102
        {
2946
3103
          return right_item->eq(*const_item, 1);
 
3104
        }
2947
3105
        *const_item=right_item;
2948
 
        return 1;
 
3106
        return true;
2949
3107
      }
2950
3108
    }
2951
3109
    else if (right_item->eq(comp_item,1))
2953
3111
      if (test_if_equality_guarantees_uniqueness (right_item, left_item))
2954
3112
      {
2955
3113
        if (*const_item)
 
3114
        {
2956
3115
          return left_item->eq(*const_item, 1);
 
3116
        }
2957
3117
        *const_item=left_item;
2958
 
        return 1;
 
3118
        return true;
2959
3119
      }
2960
3120
    }
2961
3121
  }
2962
 
  return 0;
 
3122
 
 
3123
  return false;
2963
3124
}
2964
3125
 
2965
3126
/**
3019
3180
  }
3020
3181
  else
3021
3182
  {
3022
 
    if ((join->sort_and_group) &&
3023
 
        !tmp_tbl->precomputed_group_by)
 
3183
    if ((join->sort_and_group) && !tmp_tbl->precomputed_group_by)
 
3184
    {
3024
3185
      end_select= end_send_group;
 
3186
    }
3025
3187
    else
 
3188
    {
3026
3189
      end_select= end_send;
 
3190
    }
3027
3191
  }
 
3192
 
3028
3193
  return end_select;
3029
3194
}
3030
3195
 
3063
3228
      }
3064
3229
    }
3065
3230
  }
 
3231
 
3066
3232
  /* Set up select_end */
3067
3233
  Next_select_func end_select= setup_end_select_func(join);
3068
3234
  if (join->tables)
3071
3237
 
3072
3238
    join_tab=join->join_tab+join->const_tables;
3073
3239
  }
 
3240
 
3074
3241
  join->send_records=0;
3075
3242
  if (join->tables == join->const_tables)
3076
3243
  {
3104
3271
    assert(join->tables);
3105
3272
    error= sub_select(join,join_tab,0);
3106
3273
    if (error == NESTED_LOOP_OK || error == NESTED_LOOP_NO_MORE_ROWS)
 
3274
    {
3107
3275
      error= sub_select(join,join_tab,1);
 
3276
    }
 
3277
 
3108
3278
    if (error == NESTED_LOOP_QUERY_LIMIT)
 
3279
    {
3109
3280
      error= NESTED_LOOP_OK;                    /* select_limit used */
 
3281
    }
3110
3282
  }
 
3283
 
3111
3284
  if (error == NESTED_LOOP_NO_MORE_ROWS)
 
3285
  {
3112
3286
    error= NESTED_LOOP_OK;
 
3287
  }
3113
3288
 
3114
3289
  if (error == NESTED_LOOP_OK)
3115
3290
  {
3125
3300
      */
3126
3301
      join->join_free();                        // Unlock all cursors
3127
3302
      if (join->result->send_eof())
 
3303
      {
3128
3304
        rc= 1;                                  // Don't send error
 
3305
      }
3129
3306
    }
3130
3307
  }
3131
3308
  else
 
3309
  {
3132
3310
    rc= -1;
 
3311
  }
 
3312
 
3133
3313
  if (table)
3134
3314
  {
3135
3315
    int tmp, new_errno= 0;
3137
3317
    {
3138
3318
      new_errno= tmp;
3139
3319
    }
 
3320
 
3140
3321
    if ((tmp=table->cursor->ha_index_or_rnd_end()))
3141
3322
    {
3142
3323
      new_errno= tmp;
3143
3324
    }
 
3325
 
3144
3326
    if (new_errno)
 
3327
    {
3145
3328
      table->print_error(new_errno,MYF(0));
 
3329
    }
3146
3330
  }
3147
3331
  return(join->session->is_error() ? -1 : rc);
3148
3332
}
3158
3342
      rc= sub_select(join,join_tab,end_of_records);
3159
3343
    return rc;
3160
3344
  }
 
3345
 
3161
3346
  if (join->session->getKilled())               // If aborted by user
3162
3347
  {
3163
3348
    join->session->send_kill_message();
3164
3349
    return NESTED_LOOP_KILLED;
3165
3350
  }
 
3351
 
3166
3352
  if (join_tab->use_quick != 2 || test_if_quick_select(join_tab) <= 0)
3167
3353
  {
3168
3354
    if (! join_tab->cache.store_record_in_cache())
3171
3357
  }
3172
3358
  rc= flush_cached_records(join, join_tab, true);
3173
3359
  if (rc == NESTED_LOOP_OK || rc == NESTED_LOOP_NO_MORE_ROWS)
 
3360
  {
3174
3361
    rc= sub_select(join, join_tab, end_of_records);
 
3362
  }
 
3363
 
3175
3364
  return rc;
3176
3365
}
3177
3366
 
3298
3487
{
3299
3488
  join_tab->table->null_row=0;
3300
3489
  if (end_of_records)
 
3490
  {
3301
3491
    return (*join_tab->next_select)(join,join_tab+1,end_of_records);
 
3492
  }
3302
3493
 
3303
3494
  int error;
3304
3495
  enum_nested_loop_state rc;
3308
3499
  {
3309
3500
    /* If not the last table, plunge down the nested loop */
3310
3501
    if (join_tab < join->join_tab + join->tables - 1)
 
3502
    {
3311
3503
      rc= (*join_tab->next_select)(join, join_tab + 1, 0);
 
3504
    }
3312
3505
    else
3313
3506
    {
3314
3507
      join->resume_nested_loop= false;
3346
3539
    rc= evaluate_join_record(join, join_tab, error);
3347
3540
  }
3348
3541
 
3349
 
  if (rc == NESTED_LOOP_NO_MORE_ROWS &&
3350
 
      join_tab->last_inner && !join_tab->found)
 
3542
  if (rc == NESTED_LOOP_NO_MORE_ROWS and join_tab->last_inner && !join_tab->found)
 
3543
  {
3351
3544
    rc= evaluate_null_complemented_join_record(join, join_tab);
 
3545
  }
3352
3546
 
3353
3547
  if (rc == NESTED_LOOP_NO_MORE_ROWS)
 
3548
  {
3354
3549
    rc= NESTED_LOOP_OK;
 
3550
  }
 
3551
 
3355
3552
  return rc;
3356
3553
}
3357
3554
 
3387
3584
  {
3388
3585
    table->status= 0;
3389
3586
    if (cp_buffer_from_ref(tab->join->session, &tab->ref))
 
3587
    {
3390
3588
      error= HA_ERR_KEY_NOT_FOUND;
 
3589
    }
3391
3590
    else
3392
3591
    {
3393
3592
      error=table->cursor->index_read_idx_map(table->getInsertRecord(),tab->ref.key,
3401
3600
      tab->table->mark_as_null_row();
3402
3601
      table->emptyRecord();
3403
3602
      if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
 
3603
      {
3404
3604
        return table->report_error(error);
 
3605
      }
3405
3606
      return -1;
3406
3607
    }
3407
3608
    table->storeRecord();
3459
3660
                                      make_prev_keypart_map(tab->ref.key_parts),
3460
3661
                                      HA_READ_KEY_EXACT);
3461
3662
    if (error && error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
 
3663
    {
3462
3664
      return table->report_error(error);
 
3665
    }
3463
3666
  }
3464
3667
  table->null_row=0;
3465
3668
  return table->status ? -1 : 0;
3493
3696
  {
3494
3697
    error= table->cursor->startIndexScan(tab->ref.key, tab->sorted);
3495
3698
    if (error != 0)
 
3699
    {
3496
3700
      return table->report_error(error);
 
3701
    }
3497
3702
  }
3498
3703
 
3499
3704
  /* Perform "Late NULLs Filtering" (see internals manual for explanations) */
3500
3705
  for (uint32_t i= 0 ; i < tab->ref.key_parts ; i++)
3501
3706
  {
3502
3707
    if ((tab->ref.null_rejecting & 1 << i) && tab->ref.items[i]->is_null())
3503
 
        return -1;
 
3708
    {
 
3709
      return -1;
 
3710
    }
3504
3711
  }
3505
3712
 
3506
3713
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
 
3714
  {
3507
3715
    return -1;
 
3716
  }
 
3717
 
3508
3718
  if ((error=table->cursor->index_read_map(table->getInsertRecord(),
3509
3719
                                         tab->ref.key_buff,
3510
3720
                                         make_prev_keypart_map(tab->ref.key_parts),
3511
3721
                                         HA_READ_KEY_EXACT)))
3512
3722
  {
3513
3723
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
 
3724
    {
3514
3725
      return table->report_error(error);
 
3726
    }
3515
3727
    return -1;
3516
3728
  }
3517
3729
 
3533
3745
    if (error != 0)
3534
3746
      return table->report_error(error);
3535
3747
  }
 
3748
 
3536
3749
  if (cp_buffer_from_ref(tab->join->session, &tab->ref))
 
3750
  {
3537
3751
    return -1;
 
3752
  }
 
3753
 
3538
3754
  if ((error=table->cursor->index_read_last_map(table->getInsertRecord(),
3539
3755
                                              tab->ref.key_buff,
3540
3756
                                              make_prev_keypart_map(tab->ref.key_parts))))
3541
3757
  {
3542
3758
    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
 
3759
    {
3543
3760
      return table->report_error(error);
 
3761
    }
3544
3762
    return -1;
3545
3763
  }
 
3764
 
3546
3765
  return 0;
3547
3766
}
3548
3767
 
3579
3798
    return 0;
3580
3799
  }
3581
3800
  else
 
3801
  {
3582
3802
    return join_read_next_same(info);
 
3803
  }
3583
3804
}
3584
3805
 
3585
3806
int join_read_next_same(ReadRecord *info)
3608
3829
  JoinTable *tab=table->reginfo.join_tab;
3609
3830
 
3610
3831
  if ((error=table->cursor->index_prev(table->getInsertRecord())))
 
3832
  {
3611
3833
    return table->report_error(error);
 
3834
  }
 
3835
 
3612
3836
  if (key_cmp_if_same(table, tab->ref.key_buff, tab->ref.key,
3613
3837
                      tab->ref.key_length))
3614
3838
  {
3615
3839
    table->status=STATUS_NOT_FOUND;
3616
3840
    error= -1;
3617
3841
  }
 
3842
 
3618
3843
  return error;
3619
3844
}
3620
3845
 
3621
3846
int join_init_quick_read_record(JoinTable *tab)
3622
3847
{
3623
3848
  if (test_if_quick_select(tab) == -1)
 
3849
  {
3624
3850
    return -1;                                  /* No possible records */
 
3851
  }
 
3852
 
3625
3853
  return join_init_read_record(tab);
3626
3854
}
3627
3855
 
3630
3858
  tab->read_record.init_reard_record_sequential();
3631
3859
 
3632
3860
  if (tab->read_record.cursor->startTableScan(1))
 
3861
  {
3633
3862
    return 1;
 
3863
  }
3634
3864
  return (*tab->read_record.read_record)(&tab->read_record);
3635
3865
}
3636
3866
 
3645
3875
int join_init_read_record(JoinTable *tab)
3646
3876
{
3647
3877
  if (tab->select && tab->select->quick && tab->select->quick->reset())
 
3878
  {
3648
3879
    return 1;
 
3880
  }
3649
3881
 
3650
3882
  if (tab->read_record.init_read_record(tab->join->session, tab->table, tab->select, 1, true))
 
3883
  {
3651
3884
    return 1;
 
3885
  }
3652
3886
 
3653
3887
  return (*tab->read_record.read_record)(&tab->read_record);
3654
3888
}
3712
3946
      key_copy(tab->insideout_buf, info->record, key, 0);
3713
3947
 
3714
3948
      if ((error=info->cursor->index_next(info->record)))
 
3949
      {
3715
3950
        return info->table->report_error(error);
 
3951
      }
3716
3952
    } while (!key_cmp(tab->table->key_info[tab->index].key_part,
3717
3953
                      tab->insideout_buf, key->key_length));
3718
3954
    tab->insideout_match_tab->found_match= 0;
3719
3955
    return 0;
3720
3956
  }
3721
3957
  else
 
3958
  {
3722
3959
    return join_read_next(info);
 
3960
  }
3723
3961
}
3724
3962
 
3725
3963
int join_read_next(ReadRecord *info)
3726
3964
{
3727
3965
  int error;
3728
3966
  if ((error=info->cursor->index_next(info->record)))
 
3967
  {
3729
3968
    return info->table->report_error(error);
 
3969
  }
3730
3970
  return 0;
3731
3971
}
3732
3972
 
3746
3986
  tab->read_record.cursor=table->cursor;
3747
3987
  tab->read_record.index=tab->index;
3748
3988
  tab->read_record.record=table->getInsertRecord();
 
3989
 
3749
3990
  if (!table->cursor->inited)
3750
3991
  {
3751
3992
    error= table->cursor->startIndexScan(tab->index, 1);
3752
3993
    if (error != 0)
 
3994
    {
3753
3995
      return table->report_error(error);
 
3996
    }
3754
3997
  }
 
3998
 
3755
3999
  if ((error= tab->table->cursor->index_last(tab->table->getInsertRecord())))
 
4000
  {
3756
4001
    return table->report_error(error);
 
4002
  }
3757
4003
 
3758
4004
  return 0;
3759
4005
}
3762
4008
{
3763
4009
  int error;
3764
4010
  if ((error= info->cursor->index_prev(info->record)))
 
4011
  {
3765
4012
    return info->table->report_error(error);
 
4013
  }
3766
4014
 
3767
4015
  return 0;
3768
4016
}
3777
4025
  /* First read according to key which is NOT NULL */
3778
4026
  *tab->ref.null_ref_key= 0;                    // Clear null byte
3779
4027
  if ((res= join_read_always_key(tab)) >= 0)
 
4028
  {
3780
4029
    return res;
 
4030
  }
3781
4031
 
3782
4032
  /* Then read key with null value */
3783
4033
  *tab->ref.null_ref_key= 1;                    // Set null byte
3788
4038
{
3789
4039
  int error;
3790
4040
  if ((error= join_read_next_same(info)) >= 0)
 
4041
  {
3791
4042
    return error;
 
4043
  }
3792
4044
  JoinTable *tab= info->table->reginfo.join_tab;
3793
4045
 
3794
4046
  /* Test if we have already done a read after null key */
3795
4047
  if (*tab->ref.null_ref_key)
 
4048
  {
3796
4049
    return -1;                                  // All keys read
 
4050
  }
 
4051
 
3797
4052
  *tab->ref.null_ref_key= 1;                    // Set null byte
 
4053
 
3798
4054
  return safe_index_read(tab);                  // then read null keys
3799
4055
}
3800
4056
 
3803
4059
  int idx= -1;
3804
4060
  enum_nested_loop_state ok_code= NESTED_LOOP_OK;
3805
4061
 
3806
 
  if (!join->first_record || end_of_records ||
3807
 
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
 
4062
  if (!join->first_record or end_of_records or (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
3808
4063
  {
3809
 
    if (join->first_record ||
 
4064
    if (join->first_record or
3810
4065
        (end_of_records && !join->group && !join->group_optimized_away))
3811
4066
    {
3812
4067
      if (idx < (int) join->send_group_parts)
3821
4076
            join->clear();
3822
4077
 
3823
4078
            while ((item= it++))
 
4079
            {
3824
4080
              item->no_rows_in_result();
 
4081
            }
3825
4082
          }
3826
4083
          if (join->having && join->having->val_int() == 0)
 
4084
          {
3827
4085
            error= -1;                          // Didn't satisfy having
 
4086
          }
3828
4087
          else
3829
4088
          {
3830
4089
            if (join->do_send_rows)
3837
4096
              error= 1;
3838
4097
          }
3839
4098
        }
 
4099
 
3840
4100
        if (error > 0)
 
4101
        {
3841
4102
          return(NESTED_LOOP_ERROR);
 
4103
        }
 
4104
 
3842
4105
        if (end_of_records)
 
4106
        {
3843
4107
          return(NESTED_LOOP_OK);
 
4108
        }
 
4109
 
3844
4110
        if (join->send_records >= join->unit->select_limit_cnt &&
3845
4111
            join->do_send_rows)
3846
4112
        {
3847
4113
          if (!(join->select_options & OPTION_FOUND_ROWS))
 
4114
          {
3848
4115
            return(NESTED_LOOP_QUERY_LIMIT); // Abort nicely
 
4116
          }
3849
4117
          join->do_send_rows=0;
3850
4118
          join->unit->select_limit_cnt = HA_POS_ERROR;
3851
4119
        }
3866
4134
    else
3867
4135
    {
3868
4136
      if (end_of_records)
 
4137
      {
3869
4138
        return(NESTED_LOOP_OK);
 
4139
      }
3870
4140
      join->first_record=1;
3871
4141
      test_if_item_cache_changed(join->group_fields);
3872
4142
    }
3878
4148
      */
3879
4149
      copy_fields(&join->tmp_table_param);
3880
4150
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
 
4151
      {
3881
4152
        return(NESTED_LOOP_ERROR);
 
4153
      }
3882
4154
      return(ok_code);
3883
4155
    }
3884
4156
  }
3897
4169
    join->session->send_kill_message();
3898
4170
    return NESTED_LOOP_KILLED;
3899
4171
  }
3900
 
  if (!join->first_record || end_of_records ||
3901
 
      (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
 
4172
 
 
4173
  if (!join->first_record or end_of_records or (idx=test_if_item_cache_changed(join->group_fields)) >= 0)
3902
4174
  {
3903
 
    if (join->first_record || (end_of_records && !join->group))
 
4175
    if (join->first_record or (end_of_records && !join->group))
3904
4176
    {
3905
4177
      int send_group_parts= join->send_group_parts;
3906
4178
      if (idx < send_group_parts)
3910
4182
          /* No matching rows for group function */
3911
4183
          join->clear();
3912
4184
        }
 
4185
 
3913
4186
        copy_sum_funcs(join->sum_funcs, join->sum_funcs_end[send_group_parts]);
 
4187
 
3914
4188
        if (!join->having || join->having->val_int())
3915
4189
        {
3916
4190
          int error= table->cursor->insertRecord(table->getInsertRecord());
3921
4195
            return NESTED_LOOP_ERROR;
3922
4196
          }
3923
4197
        }
 
4198
 
3924
4199
        if (join->rollup.getState() != Rollup::STATE_NONE)
3925
4200
        {
3926
4201
          if (join->rollup_write_data((uint32_t) (idx+1), table))
 
4202
          {
3927
4203
            return NESTED_LOOP_ERROR;
 
4204
          }
3928
4205
        }
 
4206
 
3929
4207
        if (end_of_records)
 
4208
        {
3930
4209
          return NESTED_LOOP_OK;
 
4210
        }
3931
4211
      }
3932
4212
    }
3933
4213
    else
3934
4214
    {
3935
4215
      if (end_of_records)
 
4216
      {
3936
4217
        return NESTED_LOOP_OK;
 
4218
      }
3937
4219
      join->first_record=1;
3938
4220
      test_if_item_cache_changed(join->group_fields);
3939
4221
    }
3941
4223
    {
3942
4224
      copy_fields(&join->tmp_table_param);
3943
4225
      if (copy_funcs(join->tmp_table_param.items_to_copy, join->session))
 
4226
      {
3944
4227
        return NESTED_LOOP_ERROR;
 
4228
      }
 
4229
 
3945
4230
      if (init_sum_functions(join->sum_funcs, join->sum_funcs_end[idx+1]))
 
4231
      {
3946
4232
        return NESTED_LOOP_ERROR;
 
4233
      }
 
4234
 
3947
4235
      return NESTED_LOOP_OK;
3948
4236
    }
3949
4237
  }
 
4238
 
3950
4239
  if (update_sum_func(join->sum_funcs))
 
4240
  {
3951
4241
    return NESTED_LOOP_ERROR;
 
4242
  }
 
4243
 
3952
4244
  return NESTED_LOOP_OK;
3953
4245
}
3954
4246
 
4045
4337
      and will be checked at execution time, attached to the first table.
4046
4338
    */
4047
4339
    !((used_table & 1) && cond->is_expensive()))
 
4340
  {
4048
4341
    return (COND*) 0;                           // Already checked
 
4342
  }
 
4343
 
4049
4344
  if (cond->type() == Item::COND_ITEM)
4050
4345
  {
4051
4346
    if (((Item_cond*) cond)->functype() == Item_func::COND_AND_FUNC)
4052
4347
    {
4053
4348
      /* Create new top level AND item */
4054
4349
      Item_cond_and *new_cond=new Item_cond_and;
4055
 
      if (!new_cond)
 
4350
      if (new_cond == NULL)
 
4351
      {
4056
4352
        return (COND*) 0;
 
4353
      }
4057
4354
      List<Item>::iterator li(((Item_cond*) cond)->argument_list()->begin());
4058
4355
      Item *item;
4059
4356
      while ((item=li++))
4061
4358
        Item *fix= make_cond_for_table(item,tables,used_table,
4062
4359
                                            exclude_expensive_cond);
4063
4360
        if (fix)
 
4361
        {
4064
4362
          new_cond->argument_list()->push_back(fix);
 
4363
        }
4065
4364
      }
4066
4365
      switch (new_cond->argument_list()->size())
4067
4366
      {
4068
4367
        case 0:
4069
4368
          return (COND*) 0;                     // Always true
 
4369
 
4070
4370
        case 1:
4071
4371
          return &new_cond->argument_list()->front();
 
4372
 
4072
4373
        default:
4073
4374
          /*
4074
4375
            Item_cond_and do not need fix_fields for execution, its parameters
4082
4383
    else
4083
4384
    {                                           // Or list
4084
4385
      Item_cond_or *new_cond=new Item_cond_or;
4085
 
      if (!new_cond)
 
4386
      if (new_cond == NULL)
 
4387
      {
4086
4388
        return (COND*) 0;
 
4389
      }
4087
4390
      List<Item>::iterator li(((Item_cond*) cond)->argument_list()->begin());
4088
4391
      Item *item;
4089
4392
      while ((item=li++))
4090
4393
      {
4091
4394
        Item *fix= make_cond_for_table(item,tables,0L, exclude_expensive_cond);
4092
4395
        if (!fix)
 
4396
        {
4093
4397
          return (COND*) 0;                     // Always true
 
4398
        }
4094
4399
        new_cond->argument_list()->push_back(fix);
4095
4400
      }
4096
4401
      /*
4100
4405
      new_cond->quick_fix_field();
4101
4406
      new_cond->used_tables_cache= ((Item_cond_or*) cond)->used_tables_cache;
4102
4407
      new_cond->top_level_item();
 
4408
 
4103
4409
      return new_cond;
4104
4410
    }
4105
4411
  }
4116
4422
        non-constant, so that they are not evaluated at optimization time.
4117
4423
      */
4118
4424
      (!used_table && exclude_expensive_cond && cond->is_expensive()))
 
4425
  {
4119
4426
    return (COND*) 0;                           // Can't check this yet
 
4427
  }
 
4428
 
4120
4429
  if (cond->marker == 2 || cond->eq_cmp_result() == Item::COND_OK)
 
4430
  {
4121
4431
    return cond;                                // Not boolean op
 
4432
  }
4122
4433
 
4123
4434
  /*
4124
4435
    Remove equalities that are guaranteed to be true by use of 'ref' access
4146
4457
static Item *part_of_refkey(Table *table,Field *field)
4147
4458
{
4148
4459
  if (!table->reginfo.join_tab)
 
4460
  {
4149
4461
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
 
4462
  }
4150
4463
 
4151
4464
  uint32_t ref_parts=table->reginfo.join_tab->ref.key_parts;
4152
4465
  if (ref_parts)
4158
4471
    for (part=0 ; part < ref_parts ; part++)
4159
4472
    {
4160
4473
      if (table->reginfo.join_tab->ref.cond_guards[part])
 
4474
      {
4161
4475
        return 0;
 
4476
      }
4162
4477
    }
4163
4478
 
4164
4479
    for (part=0 ; part < ref_parts ; part++,key_part++)
4173
4488
      }
4174
4489
    }
4175
4490
  }
 
4491
 
4176
4492
  return (Item*) 0;
4177
4493
}
4178
4494
 
4179
4495
/**
4180
4496
  Test if one can use the key to resolve order_st BY.
4181
4497
 
 
4498
  used_key_parts is set to correct key parts used if return value != 0
 
4499
  (On other cases, used_key_part may be changed).
 
4500
  Note that the value may actually be greater than the number of index
 
4501
  key parts. This can happen for storage engines that have the primary
 
4502
  key parts as a suffix for every secondary key.
 
4503
 
4182
4504
  @param order                 Sort order
4183
4505
  @param table                 Table to sort
4184
4506
  @param idx                   Index to check
4216
4538
      These are already skipped in the ORDER BY by const_expression_in_where()
4217
4539
    */
4218
4540
    for (; const_key_parts & 1 ; const_key_parts>>= 1)
 
4541
    {
4219
4542
      key_part++;
 
4543
    }
4220
4544
 
4221
4545
    if (key_part == key_part_end)
4222
4546
    {
4235
4559
        const_key_parts=table->const_key_parts[table->getShare()->getPrimaryKey()];
4236
4560
 
4237
4561
        for (; const_key_parts & 1 ; const_key_parts>>= 1)
 
4562
        {
4238
4563
          key_part++;
 
4564
        }
 
4565
 
4239
4566
        /*
4240
4567
         The primary and secondary key parts were all const (i.e. there's
4241
4568
         one row).  The sorting doesn't matter.
4242
4569
        */
4243
4570
        if (key_part == key_part_end && reverse == 0)
4244
 
          return(1);
 
4571
        {
 
4572
          return 1;
 
4573
        }
4245
4574
      }
4246
4575
      else
4247
 
        return(0);
 
4576
      {
 
4577
        return 0;
 
4578
      }
4248
4579
    }
4249
4580
 
4250
4581
    if (key_part->field != field)
4251
 
      return(0);
 
4582
    {
 
4583
      return 0;
 
4584
    }
4252
4585
 
4253
4586
    /* set flag to 1 if we can use read-next on key, else to -1 */
4254
4587
    flag= ((order->asc == !(key_part->key_part_flag & HA_REVERSE_SORT)) ?
4255
4588
           1 : -1);
4256
4589
    if (reverse && flag != reverse)
4257
 
      return(0);
 
4590
    {
 
4591
      return 0;
 
4592
    }
4258
4593
    reverse=flag;                               // Remember if reverse
4259
4594
    key_part++;
4260
4595
  }
4261
 
  *used_key_parts= on_primary_key ? table->key_info[idx].key_parts :
4262
 
    (uint32_t) (key_part - table->key_info[idx].key_part);
4263
 
  if (reverse == -1 && !(table->index_flags(idx) &
4264
 
                         HA_READ_PREV))
4265
 
    reverse= 0;                                 // Index can't be used
 
4596
  if (on_primary_key)
 
4597
  {
 
4598
    uint32_t used_key_parts_secondary= table->key_info[idx].key_parts;
 
4599
    uint32_t used_key_parts_pk= (uint32_t) (key_part - table->key_info[table->getShare()->getPrimaryKey()].key_part);
 
4600
    *used_key_parts= used_key_parts_pk + used_key_parts_secondary;
 
4601
 
 
4602
    if (reverse == -1 &&
 
4603
        (!(table->index_flags(idx) &
 
4604
           HA_READ_PREV) ||
 
4605
         !(table->index_flags(table->getShare()->getPrimaryKey()) &
 
4606
           HA_READ_PREV)))
 
4607
      reverse= 0;                               // Index can't be used
 
4608
  }
 
4609
  else
 
4610
  {
 
4611
    *used_key_parts= (uint32_t) (key_part - table->key_info[idx].key_part);
 
4612
    if (reverse == -1 &&
 
4613
        !(table->index_flags(idx) & HA_READ_PREV))
 
4614
      reverse= 0;                               // Index can't be used
 
4615
  }
4266
4616
  return(reverse);
4267
4617
}
4268
4618
 
4286
4636
                      KeyPartInfo *ref_key_part_end)
4287
4637
{
4288
4638
  for (; ref_key_part < ref_key_part_end; key_part++, ref_key_part++)
 
4639
  {
4289
4640
    if (! key_part->field->eq(ref_key_part->field))
 
4641
    {
4290
4642
      return 0;
 
4643
    }
 
4644
  }
 
4645
 
4291
4646
  return 1;
4292
4647
}
4293
4648
 
4378
4733
           key_part < key_part_end;
4379
4734
           key_part++)
4380
4735
      {
4381
 
        if (key_part->field->maybe_null() ||
4382
 
            ! find_func(key_part->field, data))
 
4736
        if (key_part->field->maybe_null() || ! find_func(key_part->field, data))
 
4737
        {
4383
4738
          break;
 
4739
        }
4384
4740
      }
 
4741
 
4385
4742
      if (key_part == key_part_end)
 
4743
      {
4386
4744
        return 1;
 
4745
      }
4387
4746
    }
4388
4747
  }
4389
4748
  return 0;
4499
4858
    if (item->type() != Item::FIELD_ITEM)
4500
4859
    {
4501
4860
      usable_keys.reset();
4502
 
      return(0);
 
4861
      return 0;
4503
4862
    }
4504
4863
    usable_keys&= ((Item_field*) item)->field->part_of_sortkey;
4505
4864
    if (usable_keys.none())
4506
 
      return(0);                                        // No usable keys
 
4865
    {
 
4866
      return 0;                                 // No usable keys
 
4867
    }
4507
4868
  }
4508
4869
 
4509
4870
  ref_key= -1;
4513
4874
    ref_key=       tab->ref.key;
4514
4875
    ref_key_parts= tab->ref.key_parts;
4515
4876
    if (tab->type == AM_REF_OR_NULL)
4516
 
      return(0);
 
4877
    {
 
4878
      return 0;
 
4879
    }
4517
4880
  }
4518
4881
  else if (select && select->quick)             // Range found by optimizer/range
4519
4882
  {
4528
4891
    if (quick_type == optimizer::QuickSelectInterface::QS_TYPE_INDEX_MERGE ||
4529
4892
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_UNION ||
4530
4893
        quick_type == optimizer::QuickSelectInterface::QS_TYPE_ROR_INTERSECT)
4531
 
      return(0);
 
4894
    {
 
4895
      return 0;
 
4896
    }
4532
4897
    ref_key=       select->quick->index;
4533
4898
    ref_key_parts= select->quick->used_key_parts;
4534
4899
  }
4550
4915
      */
4551
4916
      if (table->covering_keys.test(ref_key))
4552
4917
        usable_keys&= table->covering_keys;
 
4918
 
4553
4919
      if (tab->pre_idx_push_select_cond)
4554
4920
        tab->select_cond= tab->select->cond= tab->pre_idx_push_select_cond;
 
4921
 
4555
4922
      if ((new_ref_key= test_if_subkey(order, table, ref_key, ref_key_parts,
4556
4923
                                       &usable_keys)) < MAX_KEY)
4557
4924
      {
4570
4937
          while (keyuse->getKey() != new_ref_key && keyuse->getTable() == tab->table)
4571
4938
            keyuse++;
4572
4939
 
4573
 
          if (create_ref_for_key(tab->join, tab, keyuse,
4574
 
                                 tab->join->const_table_map))
4575
 
            return(0);
 
4940
          if (create_ref_for_key(tab->join, tab, keyuse, tab->join->const_table_map))
 
4941
          {
 
4942
            return 0;
 
4943
          }
4576
4944
        }
4577
4945
        else
4578
4946
        {
4595
4963
                                        tab->join->unit->select_limit_cnt,0,
4596
4964
                                        true) <=
4597
4965
              0)
4598
 
            return(0);
 
4966
          {
 
4967
            return 0;
 
4968
          }
4599
4969
        }
4600
4970
        ref_key= new_ref_key;
4601
4971
      }
4640
5010
        index order and not using join cache
4641
5011
        */
4642
5012
      if (tab->type == AM_ALL && tab->join->tables > tab->join->const_tables + 1)
4643
 
        return(0);
 
5013
      {
 
5014
        return 0;
 
5015
      }
4644
5016
      keys= *table->cursor->keys_to_use_for_scanning();
4645
5017
      keys|= table->covering_keys;
4646
5018
 
4650
5022
        This is to allow users to use index in order_st BY.
4651
5023
      */
4652
5024
      if (table->force_index)
 
5025
      {
4653
5026
        keys|= (group ? table->keys_in_use_for_group_by :
4654
5027
                                table->keys_in_use_for_order_by);
 
5028
      }
4655
5029
      keys&= usable_keys;
4656
5030
    }
4657
5031
    else
 
5032
    {
4658
5033
      keys= usable_keys;
 
5034
    }
4659
5035
 
4660
5036
    cur_pos= join->getPosFromOptimalPlan(tablenr);
4661
5037
    read_time= cur_pos.getCost();
 
5038
 
4662
5039
    for (uint32_t i= tablenr+1; i < join->tables; i++)
4663
5040
    {
4664
5041
      cur_pos= join->getPosFromOptimalPlan(i);
4690
5067
          double index_scan_time;
4691
5068
          KeyInfo *keyinfo= tab->table->key_info+nr;
4692
5069
          if (select_limit == HA_POS_ERROR)
 
5070
          {
4693
5071
            select_limit= table_records;
 
5072
          }
 
5073
 
4694
5074
          if (group)
4695
5075
          {
4696
5076
            rec_per_key= keyinfo->rec_per_key[used_key_parts-1];
4701
5081
              be included into the result set.
4702
5082
            */
4703
5083
            if (select_limit > table_records/rec_per_key)
4704
 
                select_limit= table_records;
 
5084
            {
 
5085
              select_limit= table_records;
 
5086
            }
4705
5087
            else
 
5088
            {
4706
5089
              select_limit= (ha_rows) (select_limit*rec_per_key);
 
5090
            }
4707
5091
          }
4708
5092
          /*
4709
5093
            If tab=tk is not the last joined table tn then to get first
4728
5112
            <=> N > table->quick_condition_rows.
4729
5113
          */
4730
5114
          if (select_limit > table->quick_condition_rows)
 
5115
          {
4731
5116
            select_limit= table_records;
 
5117
          }
4732
5118
          else
 
5119
          {
4733
5120
            select_limit= (ha_rows) (select_limit *
4734
5121
                                     (double) table_records /
4735
 
                                      table->quick_condition_rows);
 
5122
                                     table->quick_condition_rows);
 
5123
          }
4736
5124
          rec_per_key= keyinfo->rec_per_key[keyinfo->key_parts-1];
4737
5125
          set_if_bigger(rec_per_key, 1.0);
4738
5126
          /*
4746
5134
            to calculate the cost of accessing data rows for one
4747
5135
            index entry.
4748
5136
          */
4749
 
          index_scan_time= select_limit/rec_per_key *
4750
 
                           min(rec_per_key, table->cursor->scan_time());
4751
 
          if (is_covering || (ref_key < 0 && (group || table->force_index)) ||
4752
 
              index_scan_time < read_time)
 
5137
          index_scan_time= select_limit/rec_per_key * min(rec_per_key, table->cursor->scan_time());
 
5138
 
 
5139
          if (is_covering || (ref_key < 0 && (group || table->force_index)) || index_scan_time < read_time)
4753
5140
          {
4754
5141
            ha_rows quick_records= table_records;
4755
5142
            if (is_best_covering && !is_covering)
 
5143
            {
4756
5144
              continue;
 
5145
            }
 
5146
 
4757
5147
            if (table->quick_keys.test(nr))
 
5148
            {
4758
5149
              quick_records= table->quick_rows[nr];
 
5150
            }
 
5151
 
4759
5152
            if (best_key < 0 ||
4760
5153
                (select_limit <= min(quick_records,best_records) ?
4761
5154
                 keyinfo->key_parts < best_key_parts :
4771
5164
        }
4772
5165
      }
4773
5166
    }
 
5167
 
4774
5168
    if (best_key >= 0)
4775
5169
    {
4776
5170
      bool quick_created= false;
4786
5180
                                    join->unit->select_limit_cnt,
4787
5181
                                    true, false) > 0;
4788
5182
      }
4789
 
      if (!no_changes)
 
5183
      if (no_changes == false)
4790
5184
      {
4791
5185
        if (!quick_created)
4792
5186
        {
4793
5187
          tab->index= best_key;
4794
5188
          tab->read_first_record= best_key_direction > 0 ?
4795
 
                                  join_read_first:join_read_last;
 
5189
                                  join_read_first : join_read_last;
4796
5190
          tab->type= AM_NEXT;           // Read with index_first(), index_next()
4797
5191
          if (select && select->quick)
4798
5192
          {
4831
5225
      order_direction= best_key_direction;
4832
5226
    }
4833
5227
    else
4834
 
      return(0);
 
5228
    {
 
5229
      return 0;
 
5230
    }
4835
5231
  }
4836
5232
 
4837
5233
check_reverse_order:
4886
5282
    }
4887
5283
  }
4888
5284
  else if (select && select->quick)
 
5285
  {
4889
5286
    select->quick->sorted= 1;
 
5287
  }
 
5288
 
4890
5289
  return 1;
4891
5290
}
4892
5291
 
4927
5326
  JoinTable *tab;
4928
5327
 
4929
5328
  if (join->tables == join->const_tables)
4930
 
    return(0);                          // One row, no need to sort
 
5329
    return 0;                           // One row, no need to sort
4931
5330
  tab=    join->join_tab + join->const_tables;
4932
5331
  table=  tab->table;
4933
5332
  select= tab->select;
4944
5343
      test_if_skip_sort_order(tab,order,select_limit,0,
4945
5344
                              is_order_by ?  &table->keys_in_use_for_order_by :
4946
5345
                              &table->keys_in_use_for_group_by))
4947
 
    return(0);
 
5346
  {
 
5347
    return 0;
 
5348
  }
 
5349
 
4948
5350
  for (Order *ord= join->order; ord; ord= ord->next)
 
5351
  {
4949
5352
    length++;
4950
 
  if (!(join->sortorder= make_unireg_sortorder(order, &length, join->sortorder)))
4951
 
  {
4952
 
    return(-1);
4953
5353
  }
4954
5354
 
4955
 
  table->sort.io_cache= new internal::IO_CACHE;
 
5355
  join->sortorder= make_unireg_sortorder(order, &length, join->sortorder);
 
5356
  table->sort.io_cache= new internal::io_cache_st;
4956
5357
  table->status=0;                              // May be wrong if quick_select
4957
5358
 
4958
5359
  // If table has a range, move it to select
5044
5445
    if (error)
5045
5446
    {
5046
5447
      if (error == HA_ERR_RECORD_DELETED)
 
5448
      {
5047
5449
        continue;
 
5450
      }
5048
5451
      if (error == HA_ERR_END_OF_FILE)
 
5452
      {
5049
5453
        break;
 
5454
      }
5050
5455
      goto err;
5051
5456
    }
5052
5457
    if (having && !having->val_int())
5053
5458
    {
5054
5459
      if ((error=cursor->deleteRecord(record)))
 
5460
      {
5055
5461
        goto err;
 
5462
      }
5056
5463
      error=cursor->rnd_next(record);
5057
5464
      continue;
5058
5465
    }
5059
 
    if (copy_blobs(first_field))
5060
 
    {
5061
 
      my_message(ER_OUTOFMEMORY, ER(ER_OUTOFMEMORY), MYF(0));
5062
 
      error=0;
5063
 
      goto err;
5064
 
    }
 
5466
    copy_blobs(first_field);
5065
5467
    memcpy(new_record,org_record,reclength);
5066
5468
 
5067
5469
    /* Read through rest of cursor and mark duplicated rows deleted */
5071
5473
      if ((error=cursor->rnd_next(record)))
5072
5474
      {
5073
5475
        if (error == HA_ERR_RECORD_DELETED)
 
5476
        {
5074
5477
          continue;
 
5478
        }
5075
5479
        if (error == HA_ERR_END_OF_FILE)
 
5480
        {
5076
5481
          break;
 
5482
        }
 
5483
 
5077
5484
        goto err;
5078
5485
      }
5079
5486
      if (table->compare_record(first_field) == 0)
5080
5487
      {
5081
5488
        if ((error=cursor->deleteRecord(record)))
 
5489
        {
5082
5490
          goto err;
 
5491
        }
5083
5492
      }
5084
5493
      else if (!found)
5085
5494
      {
5088
5497
      }
5089
5498
    }
5090
5499
    if (!found)
 
5500
    {
5091
5501
      break;                                    // End of cursor
 
5502
    }
5092
5503
    /* Move current position to the next row */
5093
5504
    error= cursor->rnd_pos(record, cursor->ref);
5094
5505
  }
5095
5506
 
5096
5507
  cursor->extra(HA_EXTRA_NO_CACHE);
5097
 
  return(0);
 
5508
  return 0;
5098
5509
err:
5099
5510
  cursor->extra(HA_EXTRA_NO_CACHE);
5100
5511
  if (error)
 
5512
  {
5101
5513
    table->print_error(error,MYF(0));
5102
 
  return(1);
 
5514
  }
 
5515
  return 1;
5103
5516
}
5104
5517
 
5105
5518
/**
5139
5552
    extra_length= ALIGN_SIZE(key_length)-key_length;
5140
5553
  }
5141
5554
 
5142
 
  if (hash_init(&hash, &my_charset_bin, (uint32_t) cursor.stats.records, 0, key_length, (hash_get_key) 0, 0, 0))
5143
 
    return 1;
 
5555
  hash_init(&hash, &my_charset_bin, (uint32_t) cursor.stats.records, 0, key_length, (hash_get_key) 0, 0, 0);
5144
5556
 
5145
5557
  if ((error= cursor.startTableScan(1)))
 
5558
  {
5146
5559
    goto err;
 
5560
  }
5147
5561
 
5148
5562
  key_pos= &key_buffer[0];
5149
5563
  for (;;)
5157
5571
    if ((error=cursor.rnd_next(record)))
5158
5572
    {
5159
5573
      if (error == HA_ERR_RECORD_DELETED)
 
5574
      {
5160
5575
        continue;
 
5576
      }
 
5577
 
5161
5578
      if (error == HA_ERR_END_OF_FILE)
 
5579
      {
5162
5580
        break;
 
5581
      }
 
5582
 
5163
5583
      goto err;
5164
5584
    }
5165
5585
    if (having && !having->val_int())
5166
5586
    {
5167
5587
      if ((error=cursor.deleteRecord(record)))
 
5588
      {
5168
5589
        goto err;
 
5590
      }
5169
5591
      continue;
5170
5592
    }
5171
5593
 
5185
5607
        goto err;
5186
5608
    }
5187
5609
    else
 
5610
    {
5188
5611
      (void) my_hash_insert(&hash, org_key_pos);
 
5612
    }
5189
5613
    key_pos+=extra_length;
5190
5614
  }
5191
5615
  hash_free(&hash);
5198
5622
  cursor.extra(HA_EXTRA_NO_CACHE);
5199
5623
  (void) cursor.endTableScan();
5200
5624
  if (error)
 
5625
  {
5201
5626
    table->print_error(error,MYF(0));
 
5627
  }
 
5628
 
5202
5629
  return 1;
5203
5630
}
5204
5631
 
5205
 
SortField *make_unireg_sortorder(Order *order, uint32_t *length, SortField *sortorder)
 
5632
SortField* make_unireg_sortorder(Order* order, uint32_t* length, SortField* sortorder)
5206
5633
{
5207
 
  uint32_t count;
5208
5634
  SortField *sort,*pos;
5209
5635
 
5210
 
  count=0;
 
5636
  uint32_t count= 0;
5211
5637
  for (Order *tmp = order; tmp; tmp=tmp->next)
5212
5638
    count++;
5213
 
  if (!sortorder)
5214
 
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) *
5215
 
                                       (max(count, *length) + 1));
 
5639
  if (not sortorder)
 
5640
    sortorder= (SortField*) memory::sql_alloc(sizeof(SortField) * (max(count, *length) + 1));
5216
5641
  pos= sort= sortorder;
5217
5642
 
5218
 
  if (!pos)
5219
 
    return 0;
5220
 
 
5221
 
  for (;order;order=order->next,pos++)
 
5643
  for (; order; order= order->next,pos++)
5222
5644
  {
5223
5645
    Item *item= order->item[0]->real_item();
5224
5646
    pos->field= 0; pos->item= 0;
 
5647
 
5225
5648
    if (item->type() == Item::FIELD_ITEM)
 
5649
    {
5226
5650
      pos->field= ((Item_field*) item)->field;
 
5651
    }
5227
5652
    else if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
 
5653
    {
5228
5654
      pos->field= ((Item_sum*) item)->get_tmp_table_field();
 
5655
    }
5229
5656
    else if (item->type() == Item::COPY_STR_ITEM)
5230
5657
    {                                           // Blob patch
5231
5658
      pos->item= ((Item_copy_string*) item)->item;
5232
5659
    }
5233
5660
    else
 
5661
    {
5234
5662
      pos->item= *order->item;
 
5663
    }
 
5664
 
5235
5665
    pos->reverse=! order->asc;
5236
5666
  }
5237
5667
  *length=count;
5238
 
  return(sort);
 
5668
  return sort;
5239
5669
}
5240
5670
 
5241
5671
/*
5268
5698
    }
5269
5699
  }
5270
5700
  else
 
5701
  {
5271
5702
    no_prev_key= true;
5272
 
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->session, &tab->ref)) ||
5273
 
      no_prev_key)
 
5703
  }
 
5704
 
 
5705
  if ((tab->ref.key_err= cp_buffer_from_ref(tab->join->session, &tab->ref)) || no_prev_key)
 
5706
  {
5274
5707
    return 1;
5275
 
  return memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length)
5276
 
    != 0;
 
5708
  }
 
5709
  return (memcmp(tab->ref.key_buff2, tab->ref.key_buff, tab->ref.key_length) != 0);
5277
5710
}
5278
5711
 
5279
5712
bool cp_buffer_from_ref(Session *session, table_reference_st *ref)
5354
5787
    uint32_t count= (uint32_t) order_item->val_int();
5355
5788
    if (!count || count > fields.size())
5356
5789
    {
5357
 
      my_error(ER_BAD_FIELD_ERROR, MYF(0),
5358
 
               order_item->full_name(), session->where());
 
5790
      my_error(ER_BAD_FIELD_ERROR, MYF(0), order_item->full_name(), session->where());
5359
5791
      return true;
5360
5792
    }
5361
5793
    order->item= ref_pointer_array + count - 1;
5365
5797
    return false;
5366
5798
  }
5367
5799
  /* Lookup the current GROUP/order_st field in the SELECT clause. */
5368
 
  select_item= find_item_in_list(session, order_item, fields, &counter,
5369
 
                                 REPORT_EXCEPT_NOT_FOUND, &resolution);
 
5800
  select_item= find_item_in_list(session, order_item, fields, &counter, REPORT_EXCEPT_NOT_FOUND, &resolution);
5370
5801
  if (!select_item)
 
5802
  {
5371
5803
    return true; /* The item is not unique, or some other error occured. */
 
5804
  }
5372
5805
 
5373
5806
 
5374
5807
  /* Check whether the resolved field is not ambiguos. */
5380
5813
      original field name, we should additionaly check if we have conflict
5381
5814
      for this name (in case if we would perform lookup in all tables).
5382
5815
    */
5383
 
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed &&
5384
 
        order_item->fix_fields(session, order->item))
 
5816
    if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed && order_item->fix_fields(session, order->item))
 
5817
    {
5385
5818
      return true;
 
5819
    }
5386
5820
 
5387
5821
    /* Lookup the current GROUP field in the FROM clause. */
5388
5822
    order_item_type= order_item->type();
5393
5827
      from_field= find_field_in_tables(session, (Item_ident*) order_item, tables,
5394
5828
                                       NULL, &view_ref, IGNORE_ERRORS, false);
5395
5829
      if (!from_field)
 
5830
      {
5396
5831
        from_field= (Field*) not_found_field;
 
5832
      }
5397
5833
    }
5398
5834
 
5399
5835
    if (from_field == not_found_field ||
5452
5888
      (order_item->fix_fields(session, order->item) ||
5453
5889
       (order_item= *order->item)->check_cols(1) ||
5454
5890
       session->is_fatal_error))
 
5891
  {
5455
5892
    return true; /* Wrong field. */
 
5893
  }
5456
5894
 
5457
5895
  uint32_t el= all_fields.size();
5458
5896
  all_fields.push_front(order_item); /* Add new field to field list. */
5475
5913
                Order *order)
5476
5914
{
5477
5915
  session->setWhere("order clause");
5478
 
  for (; order; order=order->next)
 
5916
  for (; order; order= order->next)
5479
5917
  {
5480
 
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields,
5481
 
                           all_fields, false))
 
5918
    if (find_order_in_list(session, ref_pointer_array, tables, order, fields, all_fields, false))
 
5919
    {
5482
5920
      return 1;
 
5921
    }
5483
5922
  }
5484
5923
  return 0;
5485
5924
}
5518
5957
                      bool *hidden_group_fields)
5519
5958
{
5520
5959
  *hidden_group_fields=0;
5521
 
  Order *ord;
5522
5960
 
5523
 
  if (!order)
 
5961
  if (order == NULL)
 
5962
  {
5524
5963
    return 0;                           /* Everything is ok */
 
5964
  }
5525
5965
 
5526
5966
  uint32_t org_fields=all_fields.size();
5527
5967
 
5528
5968
  session->setWhere("group statement");
5529
 
  for (ord= order; ord; ord= ord->next)
 
5969
  for (Order *ord= order; ord; ord= ord->next)
5530
5970
  {
5531
5971
    if (find_order_in_list(session, ref_pointer_array, tables, ord, fields,
5532
5972
                           all_fields, true))
 
5973
    {
5533
5974
      return 1;
 
5975
    }
5534
5976
    (*ord->item)->marker= UNDEF_POS;            /* Mark found */
5535
5977
    if ((*ord->item)->with_sum_func)
5536
5978
    {
5538
5980
      return 1;
5539
5981
    }
5540
5982
  }
 
5983
 
5541
5984
  /* MODE_ONLY_FULL_GROUP_BY */
5542
5985
  {
5543
5986
    /*
5573
6016
        {
5574
6017
          /* Skip fields from previous expressions. */
5575
6018
          if (field->marker < cur_pos_in_select_list)
 
6019
          {
5576
6020
            goto next_field;
 
6021
          }
 
6022
 
5577
6023
          /* Found a field from the next expression. */
5578
6024
          if (field->marker > cur_pos_in_select_list)
 
6025
          {
5579
6026
            break;
 
6027
          }
 
6028
 
5580
6029
          /*
5581
6030
            Check whether the field occur in the GROUP BY list.
5582
6031
            Throw the error later if the field isn't found.
5583
6032
          */
5584
 
          for (ord= order; ord; ord= ord->next)
 
6033
          for (Order *ord= order; ord; ord= ord->next)
 
6034
          {
5585
6035
            if ((*ord->item)->eq((Item*)field, 0))
 
6036
            {
5586
6037
              goto next_field;
 
6038
            }
 
6039
          }
 
6040
 
5587
6041
          /*
5588
6042
            @todo change ER_WRONG_FIELD_WITH_GROUP to more detailed ER_NON_GROUPING_FIELD_USED
5589
6043
          */
5596
6050
      cur_pos_in_select_list++;
5597
6051
    }
5598
6052
  }
 
6053
 
5599
6054
  if (org_fields != all_fields.size())
 
6055
  {
5600
6056
    *hidden_group_fields=1;                     // group fields is not used
 
6057
  }
 
6058
 
5601
6059
  return 0;
5602
6060
}
5603
6061
 
5615
6073
                                bool *all_order_by_fields_used)
5616
6074
{
5617
6075
  List<Item>::iterator li(fields.begin());
5618
 
  Item *item;
5619
6076
  Order *order,*group,**prev;
5620
6077
 
5621
6078
  *all_order_by_fields_used= 1;
5622
 
  while ((item=li++))
 
6079
  while (Item* item=li++)
 
6080
  {
5623
6081
    item->marker=0;                     /* Marker that field is not used */
 
6082
  }
5624
6083
 
5625
6084
  prev= &group;  group=0;
5626
6085
  for (order=order_list ; order; order=order->next)
5627
6086
  {
5628
6087
    if (order->in_field_list)
5629
6088
    {
5630
 
      Order *ord=(Order*) session->getMemRoot()->duplicate((char*) order,sizeof(Order));
5631
 
      if (!ord)
5632
 
        return 0;
 
6089
      Order *ord=(Order*) session->mem.memdup(order,sizeof(Order));
5633
6090
      *prev=ord;
5634
6091
      prev= &ord->next;
5635
6092
      (*ord->item)->marker=1;
5636
6093
    }
5637
6094
    else
 
6095
    {
5638
6096
      *all_order_by_fields_used= 0;
 
6097
    }
5639
6098
  }
5640
6099
 
5641
6100
  li= fields.begin();
5642
 
  while ((item=li++))
 
6101
  while (Item* item=li++)
5643
6102
  {
5644
6103
    if (!item->const_item() && !item->with_sum_func && !item->marker)
5645
6104
    {
5649
6108
      */
5650
6109
      Order *ord_iter;
5651
6110
      for (ord_iter= group; ord_iter; ord_iter= ord_iter->next)
 
6111
      {
5652
6112
        if ((*ord_iter->item)->eq(item, 1))
 
6113
        {
5653
6114
          goto next_item;
 
6115
        }
 
6116
      }
5654
6117
 
5655
 
      Order *ord=(Order*) session->calloc(sizeof(Order));
5656
 
      if (!ord)
5657
 
        return 0;
 
6118
      Order *ord=(Order*) session->mem.calloc(sizeof(Order));
5658
6119
 
5659
6120
      /*
5660
6121
        We have here only field_list (not all_field_list), so we can use
5681
6142
  List<Item>::iterator li(fields.begin());
5682
6143
  Item *field;
5683
6144
 
5684
 
  param->field_count=param->sum_func_count=param->func_count=
5685
 
    param->hidden_field_count=0;
 
6145
  param->field_count=param->sum_func_count=param->func_count= param->hidden_field_count=0;
5686
6146
  param->quick_group=1;
 
6147
 
5687
6148
  while ((field=li++))
5688
6149
  {
5689
6150
    Item::Type real_type= field->real_item()->type();
5690
6151
    if (real_type == Item::FIELD_ITEM)
 
6152
    {
5691
6153
      param->field_count++;
 
6154
    }
5692
6155
    else if (real_type == Item::SUM_FUNC_ITEM)
5693
6156
    {
5694
6157
      if (! field->const_item())
5698
6161
            sum_item->depended_from() == select_lex)
5699
6162
        {
5700
6163
          if (!sum_item->quick_group)
 
6164
          {
5701
6165
            param->quick_group=0;                       // UDF SUM function
 
6166
          }
5702
6167
          param->sum_func_count++;
5703
6168
 
5704
6169
          for (uint32_t i=0 ; i < sum_item->arg_count ; i++)
5716
6181
    {
5717
6182
      param->func_count++;
5718
6183
      if (reset_with_sum_func)
5719
 
        field->with_sum_func=0;
 
6184
      {
 
6185
        field->with_sum_func= 0;
 
6186
      }
5720
6187
    }
5721
6188
  }
5722
6189
}
5736
6203
int test_if_item_cache_changed(List<Cached_item> &list)
5737
6204
{
5738
6205
  List<Cached_item>::iterator li(list.begin());
5739
 
  int idx= -1,i;
 
6206
  int idx= -1;
5740
6207
  Cached_item *buff;
5741
6208
 
5742
 
  for (i=(int) list.size()-1 ; (buff=li++) ; i--)
 
6209
  for (int i=(int) list.size()-1 ; (buff=li++) ; i--)
5743
6210
  {
5744
6211
    if (buff->cmp())
5745
 
      idx=i;
 
6212
      idx= i;
5746
6213
  }
5747
 
  return(idx);
 
6214
  return idx;
5748
6215
}
5749
6216
 
5750
6217
/**
5790
6257
  res_all_fields.clear();
5791
6258
  List<Item>::iterator itr(res_all_fields.begin());
5792
6259
  List<Item> extra_funcs;
5793
 
  uint32_t i, border= all_fields.size() - elements;
 
6260
  uint32_t border= all_fields.size() - elements;
5794
6261
 
5795
6262
  if (param->field_count &&
5796
 
      !(copy=param->copy_field= new CopyField[param->field_count]))
5797
 
    goto err2;
 
6263
      !(copy= param->copy_field= new CopyField[param->field_count]))
 
6264
  {
 
6265
    return true;
 
6266
  }
5798
6267
 
5799
6268
  param->copy_funcs.clear();
5800
 
  for (i= 0; (pos= li++); i++)
 
6269
  for (uint32_t i= 0; (pos= li++); i++)
5801
6270
  {
5802
6271
    Field *field;
5803
6272
    unsigned char *tmp;
5804
6273
    Item *real_pos= pos->real_item();
5805
6274
    if (real_pos->type() == Item::FIELD_ITEM)
5806
6275
    {
5807
 
      Item_field *item;
5808
 
      if (!(item= new Item_field(session, ((Item_field*) real_pos))))
5809
 
        goto err;
 
6276
      Item_field* item= new Item_field(session, ((Item_field*) real_pos));
5810
6277
      if (pos->type() == Item::REF_ITEM)
5811
6278
      {
5812
6279
        /* preserve the names of the ref when dereferncing */
5816
6283
        item->name= ref->name;
5817
6284
      }
5818
6285
      pos= item;
 
6286
 
5819
6287
      if (item->field->flags & BLOB_FLAG)
5820
6288
      {
5821
 
        if (!(pos= new Item_copy_string(pos)))
5822
 
          goto err;
 
6289
        pos= new Item_copy_string(pos);
5823
6290
            /*
5824
6291
              Item_copy_string::copy for function can call
5825
6292
              Item_copy_string::val_int for blob via Item_ref.
5829
6296
              copy_funcs
5830
6297
              (to see full test case look at having.test, BUG #4358)
5831
6298
            */
5832
 
        if (param->copy_funcs.push_front(pos))
5833
 
          goto err;
 
6299
        param->copy_funcs.push_front(pos);
5834
6300
      }
5835
6301
      else
5836
6302
      {
5846
6312
                Field_varstring::val_int
5847
6313
              */
5848
6314
        if (!(tmp= (unsigned char*) memory::sql_alloc(field->pack_length()+2)))
 
6315
        {
5849
6316
          goto err;
 
6317
        }
 
6318
 
5850
6319
        if (copy)
5851
6320
        {
5852
6321
          copy->set(tmp, item->result_field);
5871
6340
        on how the value is to be used: In some cases this may be an
5872
6341
        argument in a group function, like: IF(ISNULL(col),0,COUNT(*))
5873
6342
      */
5874
 
      if (!(pos=new Item_copy_string(pos)))
5875
 
        goto err;
 
6343
      pos=new Item_copy_string(pos);
5876
6344
      if (i < border)                           // HAVING, order_st and GROUP BY
5877
6345
      {
5878
 
        if (extra_funcs.push_back(pos))
5879
 
          goto err;
5880
 
      }
5881
 
      else if (param->copy_funcs.push_back(pos))
5882
 
        goto err;
 
6346
        extra_funcs.push_back(pos);
 
6347
      }
 
6348
      else 
 
6349
      {
 
6350
        param->copy_funcs.push_back(pos);
 
6351
      }
5883
6352
    }
5884
6353
    res_all_fields.push_back(pos);
5885
6354
    ref_pointer_array[((i < border)? all_fields.size()-i-1 : i-border)]=
5887
6356
  }
5888
6357
  param->copy_field_end= copy;
5889
6358
 
5890
 
  for (i= 0; i < border; i++)
 
6359
  for (uint32_t i= 0; i < border; i++)
 
6360
  {
5891
6361
    itr++;
 
6362
  }
5892
6363
  itr.sublist(res_selected_fields, elements);
5893
6364
  /*
5894
6365
    Put elements from HAVING, ORDER BY and GROUP BY last to ensure that any
5896
6367
  */
5897
6368
  param->copy_funcs.concat(&extra_funcs);
5898
6369
 
5899
 
  return(0);
 
6370
  return 0;
5900
6371
 
5901
6372
err:
5902
6373
  if (copy)
5903
 
    delete [] param->copy_field;                        // This is never 0
 
6374
  {
 
6375
    delete[] param->copy_field;
 
6376
  }
5904
6377
  param->copy_field=0;
5905
 
err2:
5906
 
  return(true);
 
6378
  return true;
5907
6379
}
5908
6380
 
5909
6381
/**
5914
6386
*/
5915
6387
void copy_fields(Tmp_Table_Param *param)
5916
6388
{
5917
 
  CopyField *ptr= param->copy_field;
5918
 
  CopyField *end= param->copy_field_end;
5919
 
 
5920
 
  for (; ptr != end; ptr++)
 
6389
  for (CopyField *ptr= param->copy_field; ptr != param->copy_field_end; ptr++)
 
6390
  {
5921
6391
    (*ptr->do_copy)(ptr);
 
6392
  }
5922
6393
 
5923
6394
  List<Item>::iterator it(param->copy_funcs.begin());
5924
6395
  Item_copy_string *item;
5925
6396
  while ((item = (Item_copy_string*) it++))
 
6397
  {
5926
6398
    item->copy();
 
6399
  }
5927
6400
}
5928
6401
 
5929
6402
/**
5960
6433
  {
5961
6434
    Field *field;
5962
6435
 
5963
 
    if ((item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) ||
5964
 
        (item->type() == Item::FUNC_ITEM &&
5965
 
         ((Item_func*)item)->functype() == Item_func::SUSERVAR_FUNC))
 
6436
    if ((item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) or
 
6437
        (item->type() == Item::FUNC_ITEM and ((Item_func*)item)->functype() == Item_func::SUSERVAR_FUNC))
 
6438
    {
5966
6439
      item_field= item;
 
6440
    }
5967
6441
    else
5968
6442
    {
5969
6443
      if (item->type() == Item::FIELD_ITEM)
5973
6447
      else if ((field= item->get_tmp_table_field()))
5974
6448
      {
5975
6449
        if (item->type() == Item::SUM_FUNC_ITEM && field->getTable()->group)
 
6450
        {
5976
6451
          item_field= ((Item_sum*) item)->result_item(field);
 
6452
        }
5977
6453
        else
 
6454
        {
5978
6455
          item_field= (Item*) new Item_field(field);
5979
 
        if (!item_field)
5980
 
          return(true);                    // Fatal error
 
6456
        }
 
6457
 
 
6458
        if (item_field == NULL)
 
6459
        {
 
6460
          return true;                    // Fatal error
 
6461
        }
5981
6462
 
5982
6463
        if (item->real_item()->type() != Item::FIELD_ITEM)
 
6464
        {
5983
6465
          field->orig_table= 0;
 
6466
        }
 
6467
 
5984
6468
        item_field->name= item->name;
 
6469
 
5985
6470
        if (item->type() == Item::REF_ITEM)
5986
6471
        {
5987
6472
          Item_field *ifield= (Item_field *) item_field;
5991
6476
        }
5992
6477
      }
5993
6478
      else
 
6479
      {
5994
6480
        item_field= item;
 
6481
      }
5995
6482
    }
5996
6483
    res_all_fields.push_back(item_field);
5997
 
    ref_pointer_array[((i < border)? all_fields.size()-i-1 : i-border)]=
5998
 
      item_field;
 
6484
    ref_pointer_array[((i < border)? all_fields.size()-i-1 : i-border)]= item_field;
5999
6485
  }
6000
6486
 
6001
6487
  List<Item>::iterator itr(res_all_fields.begin());
6002
6488
  for (i= 0; i < border; i++)
6003
6489
    itr++;
6004
6490
  itr.sublist(res_selected_fields, elements);
6005
 
  return(false);
 
6491
  return false;
6006
6492
}
6007
6493
 
6008
6494
/**
6043
6529
 
6044
6530
  List<Item>::iterator itr(res_all_fields.begin());
6045
6531
  for (i= 0; i < border; i++)
 
6532
  {
6046
6533
    itr++;
 
6534
  }
6047
6535
  itr.sublist(res_selected_fields, elements);
6048
6536
 
6049
6537
  return session->is_fatal_error;
6070
6558
  while ((func= *(func_ptr++)))
6071
6559
  {
6072
6560
    if (func->setup(session))
6073
 
      return(true);
 
6561
    {
 
6562
      return true;
 
6563
    }
6074
6564
  }
6075
 
  return(false);
 
6565
  return false;
6076
6566
}
6077
6567
 
6078
6568
void init_tmptable_sum_functions(Item_sum **func_ptr)
6079
6569
{
6080
6570
  Item_sum *func;
6081
6571
  while ((func= *(func_ptr++)))
 
6572
  {
6082
6573
    func->reset_field();
 
6574
  }
6083
6575
}
6084
6576
 
6085
6577
/** Update record 0 in tmp_table from record 1. */
6087
6579
{
6088
6580
  Item_sum *func;
6089
6581
  while ((func= *(func_ptr++)))
 
6582
  {
6090
6583
    func->update_field();
 
6584
  }
6091
6585
}
6092
6586
 
6093
6587
/** Copy result of sum functions to record in tmp_table. */
6094
6588
void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end_ptr)
6095
6589
{
6096
6590
  for (; func_ptr != end_ptr ; func_ptr++)
 
6591
  {
6097
6592
    (void) (*func_ptr)->save_in_result_field(1);
6098
 
  return;
 
6593
  }
6099
6594
}
6100
6595
 
6101
6596
bool init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
6105
6600
    if ((*func_ptr)->reset())
6106
6601
      return 1;
6107
6602
  }
 
6603
 
6108
6604
  /* If rollup, calculate the upper sum levels */
6109
6605
  for ( ; *func_ptr ; func_ptr++)
6110
6606
  {
6111
6607
    if ((*func_ptr)->add())
 
6608
    {
6112
6609
      return 1;
 
6610
    }
6113
6611
  }
6114
6612
  return 0;
6115
6613
}
6118
6616
{
6119
6617
  Item_sum *func;
6120
6618
  for (; (func= (Item_sum*) *func_ptr) ; func_ptr++)
 
6619
  {
6121
6620
    if (func->add())
 
6621
    {
6122
6622
      return 1;
 
6623
    }
 
6624
  }
6123
6625
  return 0;
6124
6626
}
6125
6627
 
6137
6639
      are extended to return status code.
6138
6640
    */
6139
6641
    if (session->is_error())
 
6642
    {
6140
6643
      return true;
 
6644
    }
6141
6645
  }
6142
6646
  return false;
6143
6647
}
6218
6722
        {
6219
6723
          if (item->eq(*group_tmp->item,0))
6220
6724
          {
6221
 
            Item *new_item;
6222
 
            if (!(new_item= new Item_ref(context, group_tmp->item, 0,
6223
 
                                        item->name)))
6224
 
              return 1;                                 // fatal_error is set
 
6725
            Item* new_item= new Item_ref(context, group_tmp->item, 0, item->name);
6225
6726
            *arg= new_item;
6226
6727
            arg_changed= true;
6227
6728
          }
6230
6731
      else if (item->type() == Item::FUNC_ITEM)
6231
6732
      {
6232
6733
        if (change_group_ref(session, (Item_func *) item, group_list, &arg_changed))
 
6734
        {
6233
6735
          return 1;
 
6736
        }
6234
6737
      }
6235
6738
    }
 
6739
 
6236
6740
    if (arg_changed)
6237
6741
    {
6238
6742
      expr->maybe_null= 1;
6257
6761
      str->append(STRING_WITH_LEN(" left join "));
6258
6762
    }
6259
6763
    else if (curr->straight)
 
6764
    {
6260
6765
      str->append(STRING_WITH_LEN(" straight_join "));
 
6766
    }
6261
6767
    else
 
6768
    {
6262
6769
      str->append(STRING_WITH_LEN(" join "));
 
6770
    }
6263
6771
    curr->print(session, str);
6264
6772
    if (curr->on_expr)
6265
6773
    {
6281
6789
{
6282
6790
  /* List is reversed => we should reverse it before using */
6283
6791
  List<TableList>::iterator ti(tables->begin());
6284
 
  TableList **table= (TableList **)session->getMemRoot()->allocate(sizeof(TableList*) *
6285
 
                                                tables->size());
6286
 
  if (table == 0)
6287
 
    return;  // out of memory
 
6792
  TableList **table= new (session->mem) TableList*[tables->size()];
6288
6793
 
6289
6794
  for (TableList **t= table + (tables->size() - 1); t >= table; t--)
 
6795
  {
6290
6796
    *t= ti++;
 
6797
  }
6291
6798
  assert(tables->size() >= 1);
6292
6799
  print_table_array(session, str, table, table + tables->size());
6293
6800
}
6295
6802
void Select_Lex::print(Session *session, String *str)
6296
6803
{
6297
6804
  /* QQ: session may not be set for sub queries, but this should be fixed */
6298
 
  if(not session)
 
6805
  if (not session)
 
6806
  {
6299
6807
    session= current_session;
 
6808
  }
6300
6809
 
6301
6810
 
6302
6811
  str->append(STRING_WITH_LEN("select "));
6304
6813
  /* First add options */
6305
6814
  if (options & SELECT_STRAIGHT_JOIN)
6306
6815
    str->append(STRING_WITH_LEN("straight_join "));
 
6816
 
6307
6817
  if (options & SELECT_DISTINCT)
6308
6818
    str->append(STRING_WITH_LEN("distinct "));
 
6819
 
6309
6820
  if (options & SELECT_SMALL_RESULT)
6310
6821
    str->append(STRING_WITH_LEN("sql_small_result "));
 
6822
 
6311
6823
  if (options & SELECT_BIG_RESULT)
6312
6824
    str->append(STRING_WITH_LEN("sql_big_result "));
 
6825
 
6313
6826
  if (options & OPTION_BUFFER_RESULT)
6314
6827
    str->append(STRING_WITH_LEN("sql_buffer_result "));
 
6828
 
6315
6829
  if (options & OPTION_FOUND_ROWS)
6316
6830
    str->append(STRING_WITH_LEN("sql_calc_found_rows "));
6317
6831
 
6322
6836
  while ((item= it++))
6323
6837
  {
6324
6838
    if (first)
 
6839
    {
6325
6840
      first= 0;
 
6841
    }
6326
6842
    else
 
6843
    {
6327
6844
      str->append(',');
 
6845
    }
6328
6846
    item->print_item_w_name(str);
6329
6847
  }
6330
6848
 
6355
6873
  {
6356
6874
    str->append(STRING_WITH_LEN(" where "));
6357
6875
    if (cur_where)
 
6876
    {
6358
6877
      cur_where->print(str);
 
6878
    }
6359
6879
    else
6360
 
      str->append(cond_value != Item::COND_FALSE ? "1" : "0");
 
6880
    {
 
6881
      if (cond_value != Item::COND_FALSE)
 
6882
      {
 
6883
        str->append(STRING_WITH_LEN("1"));
 
6884
      }
 
6885
      else
 
6886
      {
 
6887
        str->append(STRING_WITH_LEN("0"));
 
6888
      }
 
6889
    }
6361
6890
  }
6362
6891
 
6363
6892
  // group by & olap
6387
6916
  {
6388
6917
    str->append(STRING_WITH_LEN(" having "));
6389
6918
    if (cur_having)
 
6919
    {
6390
6920
      cur_having->print(str);
 
6921
    }
6391
6922
    else
6392
 
      str->append(having_value != Item::COND_FALSE ? "1" : "0");
 
6923
    {
 
6924
      if (having_value != Item::COND_FALSE)
 
6925
      {
 
6926
        str->append(STRING_WITH_LEN("1"));
 
6927
      }
 
6928
      else
 
6929
      {
 
6930
        str->append(STRING_WITH_LEN("0"));
 
6931
      }
 
6932
    }
6393
6933
  }
6394
6934
 
6395
6935
  if (order_list.size())