~hartmut-php/drizzle/codestyle

« back to all changes in this revision

Viewing changes to drizzled/sql_select.cc

  • Committer: Monty Taylor
  • Date: 2008-08-18 23:04:17 UTC
  • mfrom: (327.1.12 drizzle)
  • Revision ID: monty@inaugust.com-20080818230417-442rhihpahnout34
MergedĀ fromĀ trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
*/
26
26
#include <drizzled/server_includes.h>
27
27
#include <drizzled/sql_select.h>
 
28
#include "sj_tmp_table.h"
28
29
 
29
30
#include <mysys/my_bit.h>
30
31
#include <drizzled/drizzled_error_messages.h>
80
81
                                KEYUSE *keyuse, table_map used_tables,
81
82
                                KEY_PART_INFO *key_part, uchar *key_buff,
82
83
                                uint maybe_null);
83
 
static bool make_simple_join(JOIN *join,TABLE *tmp_table);
 
84
static bool make_simple_join(JOIN *join,Table *tmp_table);
84
85
static void make_outerjoin_info(JOIN *join);
85
86
static bool make_join_select(JOIN *join,SQL_SELECT *select,COND *item);
86
87
static bool make_join_readinfo(JOIN *join, uint64_t options, uint no_jbuf_after);
117
118
                           List<TABLE_LIST> *join_list,
118
119
                           Item::cond_result *cond_value);
119
120
static bool const_expression_in_where(COND *conds,Item *item, Item **comp_item);
120
 
static bool open_tmp_table(TABLE *table);
121
 
static bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo, 
122
 
                                    MI_COLUMNDEF *start_recinfo,
123
 
                                    MI_COLUMNDEF **recinfo,
124
 
                                    uint64_t options);
125
 
static int do_select(JOIN *join,List<Item> *fields,TABLE *tmp_table);
 
121
static int do_select(JOIN *join,List<Item> *fields,Table *tmp_table);
126
122
 
127
123
static enum_nested_loop_state
128
124
evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
163
159
static COND *make_cond_for_table(COND *cond,table_map table,
164
160
                                 table_map used_table,
165
161
                                 bool exclude_expensive_cond);
166
 
static Item* part_of_refkey(TABLE *form,Field *field);
 
162
static Item* part_of_refkey(Table *form,Field *field);
167
163
static bool test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,
168
164
                                    ha_rows select_limit, bool no_changes,
169
165
                                    const key_map *map);
170
 
static bool list_contains_unique_index(TABLE *table,
 
166
static bool list_contains_unique_index(Table *table,
171
167
                          bool (*find_func) (Field *, void *), void *data);
172
168
static bool find_field_in_item_list (Field *field, void *data);
173
169
static bool find_field_in_order_list (Field *field, void *data);
174
170
static int create_sort_index(THD *thd, JOIN *join, ORDER *order,
175
171
                             ha_rows filesort_limit, ha_rows select_limit,
176
172
                             bool is_order_by);
177
 
static int remove_duplicates(JOIN *join,TABLE *entry,List<Item> &fields,
 
173
static int remove_duplicates(JOIN *join,Table *entry,List<Item> &fields,
178
174
                             Item *having);
179
 
static int remove_dup_with_compare(THD *thd, TABLE *entry, Field **field,
 
175
static int remove_dup_with_compare(THD *thd, Table *entry, Field **field,
180
176
                                   ulong offset,Item *having);
181
 
static int remove_dup_with_hash_index(THD *thd,TABLE *table,
 
177
static int remove_dup_with_hash_index(THD *thd,Table *table,
182
178
                                      uint field_count, Field **first_field,
183
179
 
184
180
                                      ulong key_length,Item *having);
194
190
                                    List<Item> &all_fields,
195
191
                                    bool *all_order_by_fields_used);
196
192
static bool test_if_subpart(ORDER *a,ORDER *b);
197
 
static TABLE *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
 
193
static Table *get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables);
198
194
static void calc_group_buffer(JOIN *join,ORDER *group);
199
195
static bool make_group_fields(JOIN *main_join, JOIN *curr_join);
200
196
static bool alloc_group_fields(JOIN *join,ORDER *group);
209
205
                                      List<Item> &new_list2,
210
206
                                      uint elements, List<Item> &items);
211
207
static void init_tmptable_sum_functions(Item_sum **func);
212
 
static void update_tmptable_sum_func(Item_sum **func,TABLE *tmp_table);
 
208
static void update_tmptable_sum_func(Item_sum **func,Table *tmp_table);
213
209
static void copy_sum_funcs(Item_sum **func_ptr, Item_sum **end);
214
210
static bool add_ref_to_table_cond(THD *thd, JOIN_TAB *join_tab);
215
211
static bool setup_sum_funcs(THD *thd, Item_sum **func_ptr);
848
844
}
849
845
 
850
846
 
851
 
TABLE *create_duplicate_weedout_tmp_table(THD *thd, uint uniq_tuple_length_arg,
852
 
                                          SJ_TMP_TABLE *sjtbl);
853
 
 
854
 
 
855
847
/*
856
848
  Setup the strategies to eliminate semi-join duplicates.
857
849
  
984
976
  for (i=join->const_tables ; i < join->tables ; i++)
985
977
  {
986
978
    JOIN_TAB *tab=join->join_tab+i;
987
 
    TABLE *table=tab->table;
 
979
    Table *table=tab->table;
988
980
    cur_map |= table->map;
989
981
 
990
982
    if (tab->emb_sj_nest) // Encountered an sj-inner table
1199
1191
  {
1200
1192
    if (sj_tbl->tmp_table)
1201
1193
    {
1202
 
      free_tmp_table(join->thd, sj_tbl->tmp_table);
 
1194
      sj_tbl->tmp_table->free_tmp_table(join->thd);
1203
1195
    }
1204
1196
  }
1205
1197
  join->sj_tmp_tables= NULL;
2133
2125
  JOIN *curr_join= this;
2134
2126
  List<Item> *curr_all_fields= &all_fields;
2135
2127
  List<Item> *curr_fields_list= &fields_list;
2136
 
  TABLE *curr_tmp_table= 0;
 
2128
  Table *curr_tmp_table= 0;
2137
2129
  /*
2138
2130
    Initialize examined rows here because the values from all join parts
2139
2131
    must be accumulated in examined_row_count. Hence every join
2563
2555
 
2564
2556
  cleanup(1);
2565
2557
  if (exec_tmp_table1)
2566
 
    free_tmp_table(thd, exec_tmp_table1);
 
2558
    exec_tmp_table1->free_tmp_table(thd);
2567
2559
  if (exec_tmp_table2)
2568
 
    free_tmp_table(thd, exec_tmp_table2);
 
2560
    exec_tmp_table2->free_tmp_table(thd);
2569
2561
  delete select;
2570
2562
  delete_dynamic(&keyuse);
2571
2563
  return(error);
3209
3201
    false - Otherwise
3210
3202
*/
3211
3203
 
3212
 
bool find_eq_ref_candidate(TABLE *table, table_map sj_inner_tables)
 
3204
bool find_eq_ref_candidate(Table *table, table_map sj_inner_tables)
3213
3205
{
3214
3206
  KEYUSE *keyuse= table->reginfo.join_tab->keyuse;
3215
3207
  uint key;
3377
3369
 
3378
3370
 
3379
3371
static ha_rows get_quick_record_count(THD *thd, SQL_SELECT *select,
3380
 
                                      TABLE *table,
 
3372
                                      Table *table,
3381
3373
                                      const key_map *keys,ha_rows limit)
3382
3374
{
3383
3375
  int error;
3427
3419
                     DYNAMIC_ARRAY *keyuse_array)
3428
3420
{
3429
3421
  int error;
3430
 
  TABLE *table;
 
3422
  Table *table;
3431
3423
  uint i,table_count,const_count,key;
3432
3424
  table_map found_const_table_map, all_table_map, found_ref, refs;
3433
3425
  key_map const_ref, eq_part;
3434
 
  TABLE **table_vector;
 
3426
  Table **table_vector;
3435
3427
  JOIN_TAB *stat,*stat_end,*s,**stat_ref;
3436
3428
  KEYUSE *keyuse,*start_keyuse;
3437
3429
  table_map outer_join=0;
3441
3433
  table_count=join->tables;
3442
3434
  stat=(JOIN_TAB*) join->thd->calloc(sizeof(JOIN_TAB)*table_count);
3443
3435
  stat_ref=(JOIN_TAB**) join->thd->alloc(sizeof(JOIN_TAB*)*MAX_TABLES);
3444
 
  table_vector=(TABLE**) join->thd->alloc(sizeof(TABLE*)*(table_count*2));
 
3436
  table_vector=(Table**) join->thd->alloc(sizeof(Table*)*(table_count*2));
3445
3437
  if (!stat || !stat_ref || !table_vector)
3446
3438
    return(1);                          // Eom /* purecov: inspected */
3447
3439
 
3515
3507
      while (embedding);
3516
3508
      continue;
3517
3509
    }
3518
 
    if ((table->s->system || table->file->stats.records <= 1) &&
 
3510
    if ((table->file->stats.records <= 1) &&
3519
3511
        !s->dependent &&
3520
3512
        (table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) && !join->no_const_tables)
3521
3513
    {
3916
3908
          The cause is as follows: Some of the tables are already known to be
3917
3909
          const tables (the detection code is in make_join_statistics(),
3918
3910
          above the update_ref_and_keys() call), but we didn't propagate 
3919
 
          information about this: TABLE::const_table is not set to true, and
 
3911
          information about this: Table::const_table is not set to true, and
3920
3912
          Item::update_used_tables() hasn't been called for each item.
3921
3913
          The result of this is that we're missing some 'ref' accesses.
3922
3914
          TODO: OptimizerTeam: Fix this
4436
4428
add_key_part(DYNAMIC_ARRAY *keyuse_array,KEY_FIELD *key_field)
4437
4429
{
4438
4430
  Field *field=key_field->field;
4439
 
  TABLE *form= field->table;
 
4431
  Table *form= field->table;
4440
4432
  KEYUSE keyuse;
4441
4433
 
4442
4434
  if (key_field->eq_func && !(key_field->optimize & KEY_OPTIMIZE_EXISTS))
4443
4435
  {
4444
 
    for (uint key=0 ; key < form->s->keys ; key++)
 
4436
    for (uint key= 0 ; key < form->sizeKeys() ; key++)
4445
4437
    {
4446
4438
      if (!(form->keys_in_use_for_query.is_set(key)))
4447
4439
        continue;
4757
4749
      for (tablenr=0 ; ! (map & 1) ; map>>=1, tablenr++) ;
4758
4750
      if (map == 1)                     // Only one table
4759
4751
      {
4760
 
        TABLE *tmp_table=join->all_tables[tablenr];
 
4752
        Table *tmp_table=join->all_tables[tablenr];
4761
4753
        keyuse->ref_table_rows= max(tmp_table->file->stats.records, (ha_rows)100);
4762
4754
      }
4763
4755
    }
4948
4940
 
4949
4941
  if (s->keyuse)
4950
4942
  {                                            /* Use key if possible */
4951
 
    TABLE *table= s->table;
 
4943
    Table *table= s->table;
4952
4944
    KEYUSE *keyuse,*start_key=0;
4953
4945
    double best_records= DBL_MAX;
4954
4946
    uint max_key_part=0;
5490
5482
    /*
5491
5483
      We estimate the cost of evaluating WHERE clause for found records
5492
5484
      as record_count * rnd_records / TIME_FOR_COMPARE. This cost plus
5493
 
      tmp give us total cost of using TABLE SCAN
 
5485
      tmp give us total cost of using Table SCAN
5494
5486
    */
5495
5487
    if (best == DBL_MAX ||
5496
5488
        (tmp  + record_count/(double) TIME_FOR_COMPARE*rnd_records <
5521
5513
      idx == join->const_tables &&
5522
5514
      s->table == join->sort_by_table &&
5523
5515
      join->unit->select_limit_cnt >= records)
5524
 
    join->sort_by_table= (TABLE*) 1;  // Must use temporary table
 
5516
    join->sort_by_table= (Table*) 1;  // Must use temporary table
5525
5517
 
5526
5518
  return;
5527
5519
}
6262
6254
    }
6263
6255
  }
6264
6256
  if (null_fields)
6265
 
    rec_length+=(join_tab->table->s->null_fields+7)/8;
 
6257
    rec_length+=(join_tab->table->getNullFields() + 7)/8;
6266
6258
  if (join_tab->table->maybe_null)
6267
6259
    rec_length+=sizeof(bool);
6268
6260
  if (blobs)
6269
6261
  {
6270
6262
    uint blob_length=(uint) (join_tab->table->file->stats.mean_rec_length-
6271
 
                             (join_tab->table->s->reclength- rec_length));
 
6263
                             (join_tab->table->getRecordLength()- rec_length));
6272
6264
    rec_length+=(uint) max((uint)4,blob_length);
6273
6265
  }
6274
6266
  join_tab->used_fields=fields;
6406
6398
  used_tables= OUTER_REF_TABLE_BIT;             // Outer row is already read
6407
6399
  for (j=join_tab, tablenr=0 ; tablenr < table_count ; tablenr++,j++)
6408
6400
  {
6409
 
    TABLE *form;
 
6401
    Table *form;
6410
6402
    *j= *join->best_positions[tablenr].table;
6411
6403
    form=join->table[tablenr]=j->table;
6412
6404
    used_tables|= form->map;
6444
6436
  KEYUSE *keyuse=org_keyuse;
6445
6437
  THD  *thd= join->thd;
6446
6438
  uint keyparts,length,key;
6447
 
  TABLE *table;
 
6439
  Table *table;
6448
6440
  KEY *keyinfo;
6449
6441
 
6450
6442
  /*  Use best key from find_best */
6611
6603
store_val_in_field(Field *field, Item *item, enum_check_fields check_flag)
6612
6604
{
6613
6605
  bool error;
6614
 
  TABLE *table= field->table;
 
6606
  Table *table= field->table;
6615
6607
  THD *thd= table->in_use;
6616
6608
  ha_rows cuted_fields=thd->cuted_fields;
6617
6609
  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table,
6632
6624
 
6633
6625
 
6634
6626
static bool
6635
 
make_simple_join(JOIN *join,TABLE *tmp_table)
 
6627
make_simple_join(JOIN *join,Table *tmp_table)
6636
6628
{
6637
 
  TABLE **tableptr;
 
6629
  Table **tableptr;
6638
6630
  JOIN_TAB *join_tab;
6639
6631
 
6640
6632
  /*
6641
 
    Reuse TABLE * and JOIN_TAB if already allocated by a previous call
 
6633
    Reuse Table * and JOIN_TAB if already allocated by a previous call
6642
6634
    to this function through JOIN::exec (may happen for sub-queries).
6643
6635
  */
6644
6636
  if (!join->table_reexec)
6645
6637
  {
6646
 
    if (!(join->table_reexec= (TABLE**) join->thd->alloc(sizeof(TABLE*))))
 
6638
    if (!(join->table_reexec= (Table**) join->thd->alloc(sizeof(Table*))))
6647
6639
      return(true);                        /* purecov: inspected */
6648
6640
    if (join->tmp_join)
6649
6641
      join->tmp_join->table_reexec= join->table_reexec;
6891
6883
  for (uint i=join->const_tables ; i < join->tables ; i++)
6892
6884
  {
6893
6885
    JOIN_TAB *tab=join->join_tab+i;
6894
 
    TABLE *table=tab->table;
 
6886
    Table *table=tab->table;
6895
6887
    TABLE_LIST *tbl= table->pos_in_table_list;
6896
6888
    TABLE_LIST *embedding= tbl->embedding;
6897
6889
 
7324
7316
    false  No
7325
7317
*/
7326
7318
 
7327
 
bool uses_index_fields_only(Item *item, TABLE *tbl, uint keyno, 
 
7319
bool uses_index_fields_only(Item *item, Table *tbl, uint keyno, 
7328
7320
                            bool other_tbls_ok)
7329
7321
{
7330
7322
  if (item->const_item())
7419
7411
    Index condition, or NULL if no condition could be inferred.
7420
7412
*/
7421
7413
 
7422
 
Item *make_cond_for_index(Item *cond, TABLE *table, uint keyno,
 
7414
Item *make_cond_for_index(Item *cond, Table *table, uint keyno,
7423
7415
                          bool other_tbls_ok)
7424
7416
{
7425
7417
  if (!cond)
7629
7621
  for (i=join->const_tables ; i < join->tables ; i++)
7630
7622
  {
7631
7623
    JOIN_TAB *tab=join->join_tab+i;
7632
 
    TABLE *table=tab->table;
 
7624
    Table *table=tab->table;
7633
7625
    if ((table == join->sort_by_table && 
7634
7626
         (!join->order || join->skip_sort_order)) ||
7635
 
        (join->sort_by_table == (TABLE *) 1 && i != join->const_tables))
 
7627
        (join->sort_by_table == (Table *) 1 && i != join->const_tables))
7636
7628
    {
7637
7629
      break;
7638
7630
    }
7673
7665
  for (i=join->const_tables ; i < join->tables ; i++)
7674
7666
  {
7675
7667
    JOIN_TAB *tab=join->join_tab+i;
7676
 
    TABLE *table=tab->table;
 
7668
    Table *table=tab->table;
7677
7669
    bool using_join_cache;
7678
7670
    tab->read_record.table= table;
7679
7671
    tab->read_record.file=table->file;
9456
9448
        */  
9457
9449
        if (!possible_keys.is_clear_all())
9458
9450
        {
9459
 
          TABLE *tab= field->table;
 
9451
          Table *tab= field->table;
9460
9452
          KEYUSE *use;
9461
9453
          for (use= stat->keyuse; use && use->table == tab; use++)
9462
9454
            if (possible_keys.is_set(use->key) && 
10523
10515
  return 0;
10524
10516
}
10525
10517
 
10526
 
/****************************************************************************
10527
 
  Create internal temporary table
10528
 
****************************************************************************/
10529
 
 
10530
 
/**
10531
 
  Create field for temporary table from given field.
10532
 
 
10533
 
  @param thd           Thread handler
10534
 
  @param org_field    field from which new field will be created
10535
 
  @param name         New field name
10536
 
  @param table         Temporary table
10537
 
  @param item          !=NULL if item->result_field should point to new field.
10538
 
                      This is relevant for how fill_record() is going to work:
10539
 
                      If item != NULL then fill_record() will update
10540
 
                      the record in the original table.
10541
 
                      If item == NULL then fill_record() will update
10542
 
                      the temporary table
10543
 
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
10544
 
                               field instead of blob.
10545
 
 
10546
 
  @retval
10547
 
    NULL                on error
10548
 
  @retval
10549
 
    new_created field
10550
 
*/
10551
 
 
10552
 
Field *create_tmp_field_from_field(THD *thd, Field *org_field,
10553
 
                                   const char *name, TABLE *table,
10554
 
                                   Item_field *item, uint convert_blob_length)
10555
 
{
10556
 
  Field *new_field;
10557
 
 
10558
 
  /* 
10559
 
    Make sure that the blob fits into a Field_varstring which has 
10560
 
    2-byte lenght. 
10561
 
  */
10562
 
  if (convert_blob_length && convert_blob_length <= Field_varstring::MAX_SIZE &&
10563
 
      (org_field->flags & BLOB_FLAG))
10564
 
    new_field= new Field_varstring(convert_blob_length,
10565
 
                                   org_field->maybe_null(),
10566
 
                                   org_field->field_name, table->s,
10567
 
                                   org_field->charset());
10568
 
  else
10569
 
    new_field= org_field->new_field(thd->mem_root, table,
10570
 
                                    table == org_field->table);
10571
 
  if (new_field)
10572
 
  {
10573
 
    new_field->init(table);
10574
 
    new_field->orig_table= org_field->orig_table;
10575
 
    if (item)
10576
 
      item->result_field= new_field;
10577
 
    else
10578
 
      new_field->field_name= name;
10579
 
    new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
10580
 
    if (org_field->maybe_null() || (item && item->maybe_null))
10581
 
      new_field->flags&= ~NOT_NULL_FLAG;        // Because of outer join
10582
 
    if (org_field->type() == DRIZZLE_TYPE_VARCHAR)
10583
 
      table->s->db_create_options|= HA_OPTION_PACK_RECORD;
10584
 
    else if (org_field->type() == DRIZZLE_TYPE_DOUBLE)
10585
 
      ((Field_double *) new_field)->not_fixed= true;
10586
 
  }
10587
 
  return new_field;
10588
 
}
10589
 
 
10590
 
/**
10591
 
  Create field for temporary table using type of given item.
10592
 
 
10593
 
  @param thd                   Thread handler
10594
 
  @param item                  Item to create a field for
10595
 
  @param table                 Temporary table
10596
 
  @param copy_func             If set and item is a function, store copy of
10597
 
                               item in this array
10598
 
  @param modify_item           1 if item->result_field should point to new
10599
 
                               item. This is relevent for how fill_record()
10600
 
                               is going to work:
10601
 
                               If modify_item is 1 then fill_record() will
10602
 
                               update the record in the original table.
10603
 
                               If modify_item is 0 then fill_record() will
10604
 
                               update the temporary table
10605
 
  @param convert_blob_length   If >0 create a varstring(convert_blob_length)
10606
 
                               field instead of blob.
10607
 
 
10608
 
  @retval
10609
 
    0  on error
10610
 
  @retval
10611
 
    new_created field
10612
 
*/
10613
 
 
10614
 
static Field *create_tmp_field_from_item(THD *thd __attribute__((unused)),
10615
 
                                         Item *item, TABLE *table,
10616
 
                                         Item ***copy_func, bool modify_item,
10617
 
                                         uint convert_blob_length)
10618
 
{
10619
 
  bool maybe_null= item->maybe_null;
10620
 
  Field *new_field;
10621
 
 
10622
 
  switch (item->result_type()) {
10623
 
  case REAL_RESULT:
10624
 
    new_field= new Field_double(item->max_length, maybe_null,
10625
 
                                item->name, item->decimals, true);
10626
 
    break;
10627
 
  case INT_RESULT:
10628
 
    /* 
10629
 
      Select an integer type with the minimal fit precision.
10630
 
      MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
10631
 
      Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into 
10632
 
      Field_long : make them Field_int64_t.  
10633
 
    */
10634
 
    if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
10635
 
      new_field=new Field_int64_t(item->max_length, maybe_null,
10636
 
                                   item->name, item->unsigned_flag);
10637
 
    else
10638
 
      new_field=new Field_long(item->max_length, maybe_null,
10639
 
                               item->name, item->unsigned_flag);
10640
 
    break;
10641
 
  case STRING_RESULT:
10642
 
    assert(item->collation.collation);
10643
 
  
10644
 
    enum enum_field_types type;
10645
 
    /*
10646
 
      DATE/TIME fields have STRING_RESULT result type. 
10647
 
      To preserve type they needed to be handled separately.
10648
 
    */
10649
 
    if ((type= item->field_type()) == DRIZZLE_TYPE_DATETIME ||
10650
 
        type == DRIZZLE_TYPE_TIME || type == DRIZZLE_TYPE_NEWDATE ||
10651
 
        type == DRIZZLE_TYPE_TIMESTAMP)
10652
 
      new_field= item->tmp_table_field_from_field_type(table, 1);
10653
 
    /* 
10654
 
      Make sure that the blob fits into a Field_varstring which has 
10655
 
      2-byte lenght. 
10656
 
    */
10657
 
    else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
10658
 
             convert_blob_length <= Field_varstring::MAX_SIZE && 
10659
 
             convert_blob_length)
10660
 
      new_field= new Field_varstring(convert_blob_length, maybe_null,
10661
 
                                     item->name, table->s,
10662
 
                                     item->collation.collation);
10663
 
    else
10664
 
      new_field= item->make_string_field(table);
10665
 
    new_field->set_derivation(item->collation.derivation);
10666
 
    break;
10667
 
  case DECIMAL_RESULT:
10668
 
  {
10669
 
    uint8_t dec= item->decimals;
10670
 
    uint8_t intg= ((Item_decimal *) item)->decimal_precision() - dec;
10671
 
    uint32_t len= item->max_length;
10672
 
 
10673
 
    /*
10674
 
      Trying to put too many digits overall in a DECIMAL(prec,dec)
10675
 
      will always throw a warning. We must limit dec to
10676
 
      DECIMAL_MAX_SCALE however to prevent an assert() later.
10677
 
    */
10678
 
 
10679
 
    if (dec > 0)
10680
 
    {
10681
 
      signed int overflow;
10682
 
 
10683
 
      dec= min(dec, (uint8_t)DECIMAL_MAX_SCALE);
10684
 
 
10685
 
      /*
10686
 
        If the value still overflows the field with the corrected dec,
10687
 
        we'll throw out decimals rather than integers. This is still
10688
 
        bad and of course throws a truncation warning.
10689
 
        +1: for decimal point
10690
 
      */
10691
 
 
10692
 
      overflow= my_decimal_precision_to_length(intg + dec, dec,
10693
 
                                               item->unsigned_flag) - len;
10694
 
 
10695
 
      if (overflow > 0)
10696
 
        dec= max(0, dec - overflow);            // too long, discard fract
10697
 
      else
10698
 
        len -= item->decimals - dec;            // corrected value fits
10699
 
    }
10700
 
 
10701
 
    new_field= new Field_new_decimal(len, maybe_null, item->name,
10702
 
                                     dec, item->unsigned_flag);
10703
 
    break;
10704
 
  }
10705
 
  case ROW_RESULT:
10706
 
  default:
10707
 
    // This case should never be choosen
10708
 
    assert(0);
10709
 
    new_field= 0;
10710
 
    break;
10711
 
  }
10712
 
  if (new_field)
10713
 
    new_field->init(table);
10714
 
    
10715
 
  if (copy_func && item->is_result_field())
10716
 
    *((*copy_func)++) = item;                   // Save for copy_funcs
10717
 
  if (modify_item)
10718
 
    item->set_result_field(new_field);
10719
 
  if (item->type() == Item::NULL_ITEM)
10720
 
    new_field->is_created_from_null_item= true;
10721
 
  return new_field;
10722
 
}
10723
 
 
10724
 
 
10725
 
/**
10726
 
  Create field for information schema table.
10727
 
 
10728
 
  @param thd            Thread handler
10729
 
  @param table          Temporary table
10730
 
  @param item           Item to create a field for
10731
 
 
10732
 
  @retval
10733
 
    0                   on error
10734
 
  @retval
10735
 
    new_created field
10736
 
*/
10737
 
 
10738
 
Field *create_tmp_field_for_schema(THD *thd __attribute__((unused)),
10739
 
                                   Item *item, TABLE *table)
10740
 
{
10741
 
  if (item->field_type() == DRIZZLE_TYPE_VARCHAR)
10742
 
  {
10743
 
    Field *field;
10744
 
    if (item->max_length > MAX_FIELD_VARCHARLENGTH)
10745
 
      field= new Field_blob(item->max_length, item->maybe_null,
10746
 
                            item->name, item->collation.collation);
10747
 
    else
10748
 
      field= new Field_varstring(item->max_length, item->maybe_null,
10749
 
                                 item->name,
10750
 
                                 table->s, item->collation.collation);
10751
 
    if (field)
10752
 
      field->init(table);
10753
 
    return field;
10754
 
  }
10755
 
  return item->tmp_table_field_from_field_type(table, 0);
10756
 
}
10757
 
 
10758
 
 
10759
 
/**
10760
 
  Create field for temporary table.
10761
 
 
10762
 
  @param thd            Thread handler
10763
 
  @param table          Temporary table
10764
 
  @param item           Item to create a field for
10765
 
  @param type           Type of item (normally item->type)
10766
 
  @param copy_func      If set and item is a function, store copy of item
10767
 
                       in this array
10768
 
  @param from_field    if field will be created using other field as example,
10769
 
                       pointer example field will be written here
10770
 
  @param default_field  If field has a default value field, store it here
10771
 
  @param group          1 if we are going to do a relative group by on result
10772
 
  @param modify_item    1 if item->result_field should point to new item.
10773
 
                       This is relevent for how fill_record() is going to
10774
 
                       work:
10775
 
                       If modify_item is 1 then fill_record() will update
10776
 
                       the record in the original table.
10777
 
                       If modify_item is 0 then fill_record() will update
10778
 
                       the temporary table
10779
 
  @param convert_blob_length If >0 create a varstring(convert_blob_length)
10780
 
                             field instead of blob.
10781
 
 
10782
 
  @retval
10783
 
    0                   on error
10784
 
  @retval
10785
 
    new_created field
10786
 
*/
10787
 
 
10788
 
Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
10789
 
                        Item ***copy_func, Field **from_field,
10790
 
                        Field **default_field,
10791
 
                        bool group, bool modify_item,
10792
 
                        bool table_cant_handle_bit_fields __attribute__((unused)),
10793
 
                        bool make_copy_field,
10794
 
                        uint convert_blob_length)
10795
 
{
10796
 
  Field *result;
10797
 
  Item::Type orig_type= type;
10798
 
  Item *orig_item= 0;
10799
 
 
10800
 
  if (type != Item::FIELD_ITEM &&
10801
 
      item->real_item()->type() == Item::FIELD_ITEM)
10802
 
  {
10803
 
    orig_item= item;
10804
 
    item= item->real_item();
10805
 
    type= Item::FIELD_ITEM;
10806
 
  }
10807
 
 
10808
 
  switch (type) {
10809
 
  case Item::SUM_FUNC_ITEM:
10810
 
  {
10811
 
    Item_sum *item_sum=(Item_sum*) item;
10812
 
    result= item_sum->create_tmp_field(group, table, convert_blob_length);
10813
 
    if (!result)
10814
 
      my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
10815
 
    return result;
10816
 
  }
10817
 
  case Item::FIELD_ITEM:
10818
 
  case Item::DEFAULT_VALUE_ITEM:
10819
 
  {
10820
 
    Item_field *field= (Item_field*) item;
10821
 
    bool orig_modify= modify_item;
10822
 
    if (orig_type == Item::REF_ITEM)
10823
 
      modify_item= 0;
10824
 
    /*
10825
 
      If item have to be able to store NULLs but underlaid field can't do it,
10826
 
      create_tmp_field_from_field() can't be used for tmp field creation.
10827
 
    */
10828
 
    if (field->maybe_null && !field->field->maybe_null())
10829
 
    {
10830
 
      result= create_tmp_field_from_item(thd, item, table, NULL,
10831
 
                                         modify_item, convert_blob_length);
10832
 
      *from_field= field->field;
10833
 
      if (result && modify_item)
10834
 
        field->result_field= result;
10835
 
    } 
10836
 
    else
10837
 
      result= create_tmp_field_from_field(thd, (*from_field= field->field),
10838
 
                                          orig_item ? orig_item->name :
10839
 
                                          item->name,
10840
 
                                          table,
10841
 
                                          modify_item ? field :
10842
 
                                          NULL,
10843
 
                                          convert_blob_length);
10844
 
    if (orig_type == Item::REF_ITEM && orig_modify)
10845
 
      ((Item_ref*)orig_item)->set_result_field(result);
10846
 
    if (field->field->eq_def(result))
10847
 
      *default_field= field->field;
10848
 
    return result;
10849
 
  }
10850
 
  /* Fall through */
10851
 
  case Item::FUNC_ITEM:
10852
 
    /* Fall through */
10853
 
  case Item::COND_ITEM:
10854
 
  case Item::FIELD_AVG_ITEM:
10855
 
  case Item::FIELD_STD_ITEM:
10856
 
  case Item::SUBSELECT_ITEM:
10857
 
    /* The following can only happen with 'CREATE TABLE ... SELECT' */
10858
 
  case Item::PROC_ITEM:
10859
 
  case Item::INT_ITEM:
10860
 
  case Item::REAL_ITEM:
10861
 
  case Item::DECIMAL_ITEM:
10862
 
  case Item::STRING_ITEM:
10863
 
  case Item::REF_ITEM:
10864
 
  case Item::NULL_ITEM:
10865
 
  case Item::VARBIN_ITEM:
10866
 
    if (make_copy_field)
10867
 
    {
10868
 
      assert(((Item_result_field*)item)->result_field);
10869
 
      *from_field= ((Item_result_field*)item)->result_field;
10870
 
    }
10871
 
    return create_tmp_field_from_item(thd, item, table,
10872
 
                                      (make_copy_field ? 0 : copy_func),
10873
 
                                       modify_item, convert_blob_length);
10874
 
  case Item::TYPE_HOLDER:  
10875
 
    result= ((Item_type_holder *)item)->make_field_by_type(table);
10876
 
    result->set_derivation(item->collation.derivation);
10877
 
    return result;
10878
 
  default:                                      // Dosen't have to be stored
10879
 
    return 0;
10880
 
  }
10881
 
}
10882
 
 
10883
 
/*
10884
 
  Set up column usage bitmaps for a temporary table
10885
 
 
10886
 
  IMPLEMENTATION
10887
 
    For temporary tables, we need one bitmap with all columns set and
10888
 
    a tmp_set bitmap to be used by things like filesort.
10889
 
*/
10890
 
 
10891
 
void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps)
10892
 
{
10893
 
  uint field_count= table->s->fields;
10894
 
  bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count,
10895
 
              false);
10896
 
  bitmap_init(&table->tmp_set,
10897
 
              (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)),
10898
 
              field_count, false);
10899
 
  /* write_set and all_set are copies of read_set */
10900
 
  table->def_write_set= table->def_read_set;
10901
 
  table->s->all_set= table->def_read_set;
10902
 
  bitmap_set_all(&table->s->all_set);
10903
 
  table->default_column_bitmaps();
10904
 
}
10905
 
 
10906
 
 
10907
 
/**
10908
 
  Create a temp table according to a field list.
10909
 
 
10910
 
  Given field pointers are changed to point at tmp_table for
10911
 
  send_fields. The table object is self contained: it's
10912
 
  allocated in its own memory root, as well as Field objects
10913
 
  created for table columns.
10914
 
  This function will replace Item_sum items in 'fields' list with
10915
 
  corresponding Item_field items, pointing at the fields in the
10916
 
  temporary table, unless this was prohibited by true
10917
 
  value of argument save_sum_fields. The Item_field objects
10918
 
  are created in THD memory root.
10919
 
 
10920
 
  @param thd                  thread handle
10921
 
  @param param                a description used as input to create the table
10922
 
  @param fields               list of items that will be used to define
10923
 
                              column types of the table (also see NOTES)
10924
 
  @param group                TODO document
10925
 
  @param distinct             should table rows be distinct
10926
 
  @param save_sum_fields      see NOTES
10927
 
  @param select_options
10928
 
  @param rows_limit
10929
 
  @param table_alias          possible name of the temporary table that can
10930
 
                              be used for name resolving; can be "".
10931
 
*/
10932
 
 
10933
 
#define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
10934
 
#define AVG_STRING_LENGTH_TO_PACK_ROWS   64
10935
 
#define RATIO_TO_PACK_ROWS             2
10936
 
#define MIN_STRING_LENGTH_TO_PACK_ROWS   10
10937
 
 
10938
 
TABLE *
10939
 
create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
10940
 
                 ORDER *group, bool distinct, bool save_sum_fields,
10941
 
                 uint64_t select_options, ha_rows rows_limit,
10942
 
                 char *table_alias)
10943
 
{
10944
 
  MEM_ROOT *mem_root_save, own_root;
10945
 
  TABLE *table;
10946
 
  TABLE_SHARE *share;
10947
 
  uint  i,field_count,null_count,null_pack_length;
10948
 
  uint  copy_func_count= param->func_count;
10949
 
  uint  hidden_null_count, hidden_null_pack_length, hidden_field_count;
10950
 
  uint  blob_count,group_null_items, string_count;
10951
 
  uint  temp_pool_slot=MY_BIT_NONE;
10952
 
  uint fieldnr= 0;
10953
 
  ulong reclength, string_total_length;
10954
 
  bool  using_unique_constraint= 0;
10955
 
  bool  use_packed_rows= 0;
10956
 
  bool  not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
10957
 
  char  *tmpname,path[FN_REFLEN];
10958
 
  uchar *pos, *group_buff, *bitmaps;
10959
 
  uchar *null_flags;
10960
 
  Field **reg_field, **from_field, **default_field;
10961
 
  uint *blob_field;
10962
 
  Copy_field *copy=0;
10963
 
  KEY *keyinfo;
10964
 
  KEY_PART_INFO *key_part_info;
10965
 
  Item **copy_func;
10966
 
  MI_COLUMNDEF *recinfo;
10967
 
  uint total_uneven_bit_length= 0;
10968
 
  bool force_copy_fields= param->force_copy_fields;
10969
 
 
10970
 
  status_var_increment(thd->status_var.created_tmp_tables);
10971
 
 
10972
 
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
10973
 
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
10974
 
 
10975
 
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
10976
 
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
10977
 
            current_pid, temp_pool_slot);
10978
 
  else
10979
 
  {
10980
 
    /* if we run out of slots or we are not using tempool */
10981
 
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
10982
 
            thd->thread_id, thd->tmp_table++);
10983
 
  }
10984
 
 
10985
 
  /*
10986
 
    No need to change table name to lower case as we are only creating
10987
 
    MyISAM or HEAP tables here
10988
 
  */
10989
 
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
10990
 
 
10991
 
 
10992
 
  if (group)
10993
 
  {
10994
 
    if (!param->quick_group)
10995
 
      group=0;                                  // Can't use group key
10996
 
    else for (ORDER *tmp=group ; tmp ; tmp=tmp->next)
10997
 
    {
10998
 
      /*
10999
 
        marker == 4 means two things:
11000
 
        - store NULLs in the key, and
11001
 
        - convert BIT fields to 64-bit long, needed because MEMORY tables
11002
 
          can't index BIT fields.
11003
 
      */
11004
 
      (*tmp->item)->marker= 4;
11005
 
      if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
11006
 
        using_unique_constraint=1;
11007
 
    }
11008
 
    if (param->group_length >= MAX_BLOB_WIDTH)
11009
 
      using_unique_constraint=1;
11010
 
    if (group)
11011
 
      distinct=0;                               // Can't use distinct
11012
 
  }
11013
 
 
11014
 
  field_count=param->field_count+param->func_count+param->sum_func_count;
11015
 
  hidden_field_count=param->hidden_field_count;
11016
 
 
11017
 
  /*
11018
 
    When loose index scan is employed as access method, it already
11019
 
    computes all groups and the result of all aggregate functions. We
11020
 
    make space for the items of the aggregate function in the list of
11021
 
    functions TMP_TABLE_PARAM::items_to_copy, so that the values of
11022
 
    these items are stored in the temporary table.
11023
 
  */
11024
 
  if (param->precomputed_group_by)
11025
 
    copy_func_count+= param->sum_func_count;
11026
 
  
11027
 
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
11028
 
 
11029
 
  if (!multi_alloc_root(&own_root,
11030
 
                        &table, sizeof(*table),
11031
 
                        &share, sizeof(*share),
11032
 
                        &reg_field, sizeof(Field*) * (field_count+1),
11033
 
                        &default_field, sizeof(Field*) * (field_count),
11034
 
                        &blob_field, sizeof(uint)*(field_count+1),
11035
 
                        &from_field, sizeof(Field*)*field_count,
11036
 
                        &copy_func, sizeof(*copy_func)*(copy_func_count+1),
11037
 
                        &param->keyinfo, sizeof(*param->keyinfo),
11038
 
                        &key_part_info,
11039
 
                        sizeof(*key_part_info)*(param->group_parts+1),
11040
 
                        &param->start_recinfo,
11041
 
                        sizeof(*param->recinfo)*(field_count*2+4),
11042
 
                        &tmpname, (uint) strlen(path)+1,
11043
 
                        &group_buff, (group && ! using_unique_constraint ?
11044
 
                                      param->group_length : 0),
11045
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
11046
 
                        NullS))
11047
 
  {
11048
 
    if (temp_pool_slot != MY_BIT_NONE)
11049
 
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
11050
 
    return(NULL);                               /* purecov: inspected */
11051
 
  }
11052
 
  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
11053
 
  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
11054
 
  {
11055
 
    if (temp_pool_slot != MY_BIT_NONE)
11056
 
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
11057
 
    free_root(&own_root, MYF(0));               /* purecov: inspected */
11058
 
    return(NULL);                               /* purecov: inspected */
11059
 
  }
11060
 
  param->items_to_copy= copy_func;
11061
 
  stpcpy(tmpname,path);
11062
 
  /* make table according to fields */
11063
 
 
11064
 
  memset(table, 0, sizeof(*table));
11065
 
  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
11066
 
  memset(default_field, 0, sizeof(Field*) * (field_count));
11067
 
  memset(from_field, 0, sizeof(Field*)*field_count);
11068
 
 
11069
 
  table->mem_root= own_root;
11070
 
  mem_root_save= thd->mem_root;
11071
 
  thd->mem_root= &table->mem_root;
11072
 
 
11073
 
  table->field=reg_field;
11074
 
  table->alias= table_alias;
11075
 
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
11076
 
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
11077
 
  table->map=1;
11078
 
  table->temp_pool_slot = temp_pool_slot;
11079
 
  table->copy_blobs= 1;
11080
 
  table->in_use= thd;
11081
 
  table->quick_keys.init();
11082
 
  table->covering_keys.init();
11083
 
  table->keys_in_use_for_query.init();
11084
 
 
11085
 
  table->s= share;
11086
 
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
11087
 
  share->blob_field= blob_field;
11088
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
11089
 
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
11090
 
  share->table_charset= param->table_charset;
11091
 
  share->primary_key= MAX_KEY;               // Indicate no primary key
11092
 
  share->keys_for_keyread.init();
11093
 
  share->keys_in_use.init();
11094
 
 
11095
 
  /* Calculate which type of fields we will store in the temporary table */
11096
 
 
11097
 
  reclength= string_total_length= 0;
11098
 
  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
11099
 
  param->using_indirect_summary_function=0;
11100
 
 
11101
 
  List_iterator_fast<Item> li(fields);
11102
 
  Item *item;
11103
 
  Field **tmp_from_field=from_field;
11104
 
  while ((item=li++))
11105
 
  {
11106
 
    Item::Type type=item->type();
11107
 
    if (not_all_columns)
11108
 
    {
11109
 
      if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
11110
 
      {
11111
 
        if (item->used_tables() & OUTER_REF_TABLE_BIT)
11112
 
          item->update_used_tables();
11113
 
        if (type == Item::SUBSELECT_ITEM ||
11114
 
            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
11115
 
        {
11116
 
          /*
11117
 
            Mark that the we have ignored an item that refers to a summary
11118
 
            function. We need to know this if someone is going to use
11119
 
            DISTINCT on the result.
11120
 
          */
11121
 
          param->using_indirect_summary_function=1;
11122
 
          continue;
11123
 
        }
11124
 
      }
11125
 
      if (item->const_item() && (int) hidden_field_count <= 0)
11126
 
        continue; // We don't have to store this
11127
 
    }
11128
 
    if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
11129
 
    {                                           /* Can't calc group yet */
11130
 
      ((Item_sum*) item)->result_field=0;
11131
 
      for (i=0 ; i < ((Item_sum*) item)->arg_count ; i++)
11132
 
      {
11133
 
        Item **argp= ((Item_sum*) item)->args + i;
11134
 
        Item *arg= *argp;
11135
 
        if (!arg->const_item())
11136
 
        {
11137
 
          Field *new_field=
11138
 
            create_tmp_field(thd, table, arg, arg->type(), &copy_func,
11139
 
                             tmp_from_field, &default_field[fieldnr],
11140
 
                             group != 0,not_all_columns,
11141
 
                             distinct, 0,
11142
 
                             param->convert_blob_length);
11143
 
          if (!new_field)
11144
 
            goto err;                                   // Should be OOM
11145
 
          tmp_from_field++;
11146
 
          reclength+=new_field->pack_length();
11147
 
          if (new_field->flags & BLOB_FLAG)
11148
 
          {
11149
 
            *blob_field++= fieldnr;
11150
 
            blob_count++;
11151
 
          }
11152
 
          *(reg_field++)= new_field;
11153
 
          if (new_field->real_type() == DRIZZLE_TYPE_VARCHAR)
11154
 
          {
11155
 
            string_count++;
11156
 
            string_total_length+= new_field->pack_length();
11157
 
          }
11158
 
          thd->mem_root= mem_root_save;
11159
 
          thd->change_item_tree(argp, new Item_field(new_field));
11160
 
          thd->mem_root= &table->mem_root;
11161
 
          if (!(new_field->flags & NOT_NULL_FLAG))
11162
 
          {
11163
 
            null_count++;
11164
 
            /*
11165
 
              new_field->maybe_null() is still false, it will be
11166
 
              changed below. But we have to setup Item_field correctly
11167
 
            */
11168
 
            (*argp)->maybe_null=1;
11169
 
          }
11170
 
          new_field->field_index= fieldnr++;
11171
 
        }
11172
 
      }
11173
 
    }
11174
 
    else
11175
 
    {
11176
 
      /*
11177
 
        The last parameter to create_tmp_field() is a bit tricky:
11178
 
 
11179
 
        We need to set it to 0 in union, to get fill_record() to modify the
11180
 
        temporary table.
11181
 
        We need to set it to 1 on multi-table-update and in select to
11182
 
        write rows to the temporary table.
11183
 
        We here distinguish between UNION and multi-table-updates by the fact
11184
 
        that in the later case group is set to the row pointer.
11185
 
      */
11186
 
      Field *new_field= (param->schema_table) ?
11187
 
        create_tmp_field_for_schema(thd, item, table) :
11188
 
        create_tmp_field(thd, table, item, type, &copy_func,
11189
 
                         tmp_from_field, &default_field[fieldnr],
11190
 
                         group != 0,
11191
 
                         !force_copy_fields &&
11192
 
                           (not_all_columns || group !=0),
11193
 
                         /*
11194
 
                           If item->marker == 4 then we force create_tmp_field
11195
 
                           to create a 64-bit longs for BIT fields because HEAP
11196
 
                           tables can't index BIT fields directly. We do the same
11197
 
                           for distinct, as we want the distinct index to be
11198
 
                           usable in this case too.
11199
 
                         */
11200
 
                         item->marker == 4 || param->bit_fields_as_long,
11201
 
                         force_copy_fields,
11202
 
                         param->convert_blob_length);
11203
 
 
11204
 
      if (!new_field)
11205
 
      {
11206
 
        if (thd->is_fatal_error)
11207
 
          goto err;                             // Got OOM
11208
 
        continue;                               // Some kindf of const item
11209
 
      }
11210
 
      if (type == Item::SUM_FUNC_ITEM)
11211
 
        ((Item_sum *) item)->result_field= new_field;
11212
 
      tmp_from_field++;
11213
 
      reclength+=new_field->pack_length();
11214
 
      if (!(new_field->flags & NOT_NULL_FLAG))
11215
 
        null_count++;
11216
 
      if (new_field->flags & BLOB_FLAG)
11217
 
      {
11218
 
        *blob_field++= fieldnr;
11219
 
        blob_count++;
11220
 
      }
11221
 
      if (item->marker == 4 && item->maybe_null)
11222
 
      {
11223
 
        group_null_items++;
11224
 
        new_field->flags|= GROUP_FLAG;
11225
 
      }
11226
 
      new_field->field_index= fieldnr++;
11227
 
      *(reg_field++)= new_field;
11228
 
    }
11229
 
    if (!--hidden_field_count)
11230
 
    {
11231
 
      /*
11232
 
        This was the last hidden field; Remember how many hidden fields could
11233
 
        have null
11234
 
      */
11235
 
      hidden_null_count=null_count;
11236
 
      /*
11237
 
        We need to update hidden_field_count as we may have stored group
11238
 
        functions with constant arguments
11239
 
      */
11240
 
      param->hidden_field_count= fieldnr;
11241
 
      null_count= 0;
11242
 
    }
11243
 
  }
11244
 
  assert(fieldnr == (uint) (reg_field - table->field));
11245
 
  assert(field_count >= (uint) (reg_field - table->field));
11246
 
  field_count= fieldnr;
11247
 
  *reg_field= 0;
11248
 
  *blob_field= 0;                               // End marker
11249
 
  share->fields= field_count;
11250
 
 
11251
 
  /* If result table is small; use a heap */
11252
 
  /* future: storage engine selection can be made dynamic? */
11253
 
  if (blob_count || using_unique_constraint ||
11254
 
      (select_options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
11255
 
      OPTION_BIG_TABLES || (select_options & TMP_TABLE_FORCE_MYISAM))
11256
 
  {
11257
 
    share->db_plugin= ha_lock_engine(0, myisam_hton);
11258
 
    table->file= get_new_handler(share, &table->mem_root,
11259
 
                                 share->db_type());
11260
 
    if (group &&
11261
 
        (param->group_parts > table->file->max_key_parts() ||
11262
 
         param->group_length > table->file->max_key_length()))
11263
 
      using_unique_constraint=1;
11264
 
  }
11265
 
  else
11266
 
  {
11267
 
    share->db_plugin= ha_lock_engine(0, heap_hton);
11268
 
    table->file= get_new_handler(share, &table->mem_root,
11269
 
                                 share->db_type());
11270
 
  }
11271
 
  if (!table->file)
11272
 
    goto err;
11273
 
 
11274
 
 
11275
 
  if (!using_unique_constraint)
11276
 
    reclength+= group_null_items;       // null flag is stored separately
11277
 
 
11278
 
  share->blob_fields= blob_count;
11279
 
  if (blob_count == 0)
11280
 
  {
11281
 
    /* We need to ensure that first byte is not 0 for the delete link */
11282
 
    if (param->hidden_field_count)
11283
 
      hidden_null_count++;
11284
 
    else
11285
 
      null_count++;
11286
 
  }
11287
 
  hidden_null_pack_length=(hidden_null_count+7)/8;
11288
 
  null_pack_length= (hidden_null_pack_length +
11289
 
                     (null_count + total_uneven_bit_length + 7) / 8);
11290
 
  reclength+=null_pack_length;
11291
 
  if (!reclength)
11292
 
    reclength=1;                                // Dummy select
11293
 
  /* Use packed rows if there is blobs or a lot of space to gain */
11294
 
  if (blob_count || ((string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS) && (reclength / string_total_length <= RATIO_TO_PACK_ROWS || (string_total_length / string_count) >= AVG_STRING_LENGTH_TO_PACK_ROWS)))
11295
 
    use_packed_rows= 1;
11296
 
 
11297
 
  share->reclength= reclength;
11298
 
  {
11299
 
    uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
11300
 
    share->rec_buff_length= alloc_length;
11301
 
    if (!(table->record[0]= (uchar*)
11302
 
                            alloc_root(&table->mem_root, alloc_length*3)))
11303
 
      goto err;
11304
 
    table->record[1]= table->record[0]+alloc_length;
11305
 
    share->default_values= table->record[1]+alloc_length;
11306
 
  }
11307
 
  copy_func[0]=0;                               // End marker
11308
 
  param->func_count= copy_func - param->items_to_copy; 
11309
 
 
11310
 
  setup_tmp_table_column_bitmaps(table, bitmaps);
11311
 
 
11312
 
  recinfo=param->start_recinfo;
11313
 
  null_flags=(uchar*) table->record[0];
11314
 
  pos=table->record[0]+ null_pack_length;
11315
 
  if (null_pack_length)
11316
 
  {
11317
 
    memset(recinfo, 0, sizeof(*recinfo));
11318
 
    recinfo->type=FIELD_NORMAL;
11319
 
    recinfo->length=null_pack_length;
11320
 
    recinfo++;
11321
 
    memset(null_flags, 255, null_pack_length);  // Set null fields
11322
 
 
11323
 
    table->null_flags= (uchar*) table->record[0];
11324
 
    share->null_fields= null_count+ hidden_null_count;
11325
 
    share->null_bytes= null_pack_length;
11326
 
  }
11327
 
  null_count= (blob_count == 0) ? 1 : 0;
11328
 
  hidden_field_count=param->hidden_field_count;
11329
 
  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
11330
 
  {
11331
 
    Field *field= *reg_field;
11332
 
    uint length;
11333
 
    memset(recinfo, 0, sizeof(*recinfo));
11334
 
 
11335
 
    if (!(field->flags & NOT_NULL_FLAG))
11336
 
    {
11337
 
      if (field->flags & GROUP_FLAG && !using_unique_constraint)
11338
 
      {
11339
 
        /*
11340
 
          We have to reserve one byte here for NULL bits,
11341
 
          as this is updated by 'end_update()'
11342
 
        */
11343
 
        *pos++=0;                               // Null is stored here
11344
 
        recinfo->length=1;
11345
 
        recinfo->type=FIELD_NORMAL;
11346
 
        recinfo++;
11347
 
        memset(recinfo, 0, sizeof(*recinfo));
11348
 
      }
11349
 
      else
11350
 
      {
11351
 
        recinfo->null_bit= 1 << (null_count & 7);
11352
 
        recinfo->null_pos= null_count/8;
11353
 
      }
11354
 
      field->move_field(pos,null_flags+null_count/8,
11355
 
                        1 << (null_count & 7));
11356
 
      null_count++;
11357
 
    }
11358
 
    else
11359
 
      field->move_field(pos,(uchar*) 0,0);
11360
 
    field->reset();
11361
 
 
11362
 
    /*
11363
 
      Test if there is a default field value. The test for ->ptr is to skip
11364
 
      'offset' fields generated by initalize_tables
11365
 
    */
11366
 
    if (default_field[i] && default_field[i]->ptr)
11367
 
    {
11368
 
      /* 
11369
 
         default_field[i] is set only in the cases  when 'field' can
11370
 
         inherit the default value that is defined for the field referred
11371
 
         by the Item_field object from which 'field' has been created.
11372
 
      */
11373
 
      my_ptrdiff_t diff;
11374
 
      Field *orig_field= default_field[i];
11375
 
      /* Get the value from default_values */
11376
 
      diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
11377
 
                            orig_field->table->record[0]);
11378
 
      orig_field->move_field_offset(diff);      // Points now at default_values
11379
 
      if (orig_field->is_real_null())
11380
 
        field->set_null();
11381
 
      else
11382
 
      {
11383
 
        field->set_notnull();
11384
 
        memcpy(field->ptr, orig_field->ptr, field->pack_length());
11385
 
      }
11386
 
      orig_field->move_field_offset(-diff);     // Back to record[0]
11387
 
    } 
11388
 
 
11389
 
    if (from_field[i])
11390
 
    {                                           /* Not a table Item */
11391
 
      copy->set(field,from_field[i],save_sum_fields);
11392
 
      copy++;
11393
 
    }
11394
 
    length=field->pack_length();
11395
 
    pos+= length;
11396
 
 
11397
 
    /* Make entry for create table */
11398
 
    recinfo->length=length;
11399
 
    if (field->flags & BLOB_FLAG)
11400
 
      recinfo->type= (int) FIELD_BLOB;
11401
 
    else
11402
 
      recinfo->type=FIELD_NORMAL;
11403
 
    if (!--hidden_field_count)
11404
 
      null_count=(null_count+7) & ~7;           // move to next byte
11405
 
 
11406
 
    // fix table name in field entry
11407
 
    field->table_name= &table->alias;
11408
 
  }
11409
 
 
11410
 
  param->copy_field_end=copy;
11411
 
  param->recinfo=recinfo;
11412
 
  store_record(table,s->default_values);        // Make empty default record
11413
 
 
11414
 
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
11415
 
    share->max_rows= ~(ha_rows) 0;
11416
 
  else
11417
 
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
11418
 
                                 min(thd->variables.tmp_table_size,
11419
 
                                     thd->variables.max_heap_table_size) :
11420
 
                                 thd->variables.tmp_table_size) /
11421
 
                                 share->reclength);
11422
 
  set_if_bigger(share->max_rows,1);             // For dummy start options
11423
 
  /*
11424
 
    Push the LIMIT clause to the temporary table creation, so that we
11425
 
    materialize only up to 'rows_limit' records instead of all result records.
11426
 
  */
11427
 
  set_if_smaller(share->max_rows, rows_limit);
11428
 
  param->end_write_records= rows_limit;
11429
 
 
11430
 
  keyinfo= param->keyinfo;
11431
 
 
11432
 
  if (group)
11433
 
  {
11434
 
    table->group=group;                         /* Table is grouped by key */
11435
 
    param->group_buff=group_buff;
11436
 
    share->keys=1;
11437
 
    share->uniques= test(using_unique_constraint);
11438
 
    table->key_info=keyinfo;
11439
 
    keyinfo->key_part=key_part_info;
11440
 
    keyinfo->flags=HA_NOSAME;
11441
 
    keyinfo->usable_key_parts=keyinfo->key_parts= param->group_parts;
11442
 
    keyinfo->key_length=0;
11443
 
    keyinfo->rec_per_key=0;
11444
 
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
11445
 
    keyinfo->name= (char*) "group_key";
11446
 
    ORDER *cur_group= group;
11447
 
    for (; cur_group ; cur_group= cur_group->next, key_part_info++)
11448
 
    {
11449
 
      Field *field=(*cur_group->item)->get_tmp_table_field();
11450
 
      bool maybe_null=(*cur_group->item)->maybe_null;
11451
 
      key_part_info->null_bit=0;
11452
 
      key_part_info->field=  field;
11453
 
      key_part_info->offset= field->offset(table->record[0]);
11454
 
      key_part_info->length= (uint16_t) field->key_length();
11455
 
      key_part_info->type=   (uint8_t) field->key_type();
11456
 
      key_part_info->key_type =
11457
 
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
11458
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
11459
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
11460
 
        0 : FIELDFLAG_BINARY;
11461
 
      if (!using_unique_constraint)
11462
 
      {
11463
 
        cur_group->buff=(char*) group_buff;
11464
 
        if (!(cur_group->field= field->new_key_field(thd->mem_root,table,
11465
 
                                                     group_buff +
11466
 
                                                     test(maybe_null),
11467
 
                                                     field->null_ptr,
11468
 
                                                     field->null_bit)))
11469
 
          goto err; /* purecov: inspected */
11470
 
        if (maybe_null)
11471
 
        {
11472
 
          /*
11473
 
            To be able to group on NULL, we reserved place in group_buff
11474
 
            for the NULL flag just before the column. (see above).
11475
 
            The field data is after this flag.
11476
 
            The NULL flag is updated in 'end_update()' and 'end_write()'
11477
 
          */
11478
 
          keyinfo->flags|= HA_NULL_ARE_EQUAL;   // def. that NULL == NULL
11479
 
          key_part_info->null_bit=field->null_bit;
11480
 
          key_part_info->null_offset= (uint) (field->null_ptr -
11481
 
                                              (uchar*) table->record[0]);
11482
 
          cur_group->buff++;                        // Pointer to field data
11483
 
          group_buff++;                         // Skipp null flag
11484
 
        }
11485
 
        /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
11486
 
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
11487
 
        group_buff+= cur_group->field->pack_length();
11488
 
      }
11489
 
      keyinfo->key_length+=  key_part_info->length;
11490
 
    }
11491
 
  }
11492
 
 
11493
 
  if (distinct && field_count != param->hidden_field_count)
11494
 
  {
11495
 
    /*
11496
 
      Create an unique key or an unique constraint over all columns
11497
 
      that should be in the result.  In the temporary table, there are
11498
 
      'param->hidden_field_count' extra columns, whose null bits are stored
11499
 
      in the first 'hidden_null_pack_length' bytes of the row.
11500
 
    */
11501
 
    if (blob_count)
11502
 
    {
11503
 
      /*
11504
 
        Special mode for index creation in MyISAM used to support unique
11505
 
        indexes on blobs with arbitrary length. Such indexes cannot be
11506
 
        used for lookups.
11507
 
      */
11508
 
      share->uniques= 1;
11509
 
    }
11510
 
    null_pack_length-=hidden_null_pack_length;
11511
 
    keyinfo->key_parts= ((field_count-param->hidden_field_count)+
11512
 
                         (share->uniques ? test(null_pack_length) : 0));
11513
 
    table->distinct= 1;
11514
 
    share->keys= 1;
11515
 
    if (!(key_part_info= (KEY_PART_INFO*)
11516
 
          alloc_root(&table->mem_root,
11517
 
                     keyinfo->key_parts * sizeof(KEY_PART_INFO))))
11518
 
      goto err;
11519
 
    memset(key_part_info, 0, keyinfo->key_parts * sizeof(KEY_PART_INFO));
11520
 
    table->key_info=keyinfo;
11521
 
    keyinfo->key_part=key_part_info;
11522
 
    keyinfo->flags=HA_NOSAME | HA_NULL_ARE_EQUAL;
11523
 
    keyinfo->key_length=(uint16_t) reclength;
11524
 
    keyinfo->name= (char*) "distinct_key";
11525
 
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
11526
 
    keyinfo->rec_per_key=0;
11527
 
 
11528
 
    /*
11529
 
      Create an extra field to hold NULL bits so that unique indexes on
11530
 
      blobs can distinguish NULL from 0. This extra field is not needed
11531
 
      when we do not use UNIQUE indexes for blobs.
11532
 
    */
11533
 
    if (null_pack_length && share->uniques)
11534
 
    {
11535
 
      key_part_info->null_bit=0;
11536
 
      key_part_info->offset=hidden_null_pack_length;
11537
 
      key_part_info->length=null_pack_length;
11538
 
      key_part_info->field= new Field_varstring(table->record[0],
11539
 
                                                (uint32_t) key_part_info->length,
11540
 
                                                0,
11541
 
                                                (uchar*) 0,
11542
 
                                                (uint) 0,
11543
 
                                                Field::NONE,
11544
 
                                                NullS, 
11545
 
                                                table->s,
11546
 
                                                &my_charset_bin);
11547
 
      if (!key_part_info->field)
11548
 
        goto err;
11549
 
      key_part_info->field->init(table);
11550
 
      key_part_info->key_type=FIELDFLAG_BINARY;
11551
 
      key_part_info->type=    HA_KEYTYPE_BINARY;
11552
 
      key_part_info++;
11553
 
    }
11554
 
    /* Create a distinct key over the columns we are going to return */
11555
 
    for (i=param->hidden_field_count, reg_field=table->field + i ;
11556
 
         i < field_count;
11557
 
         i++, reg_field++, key_part_info++)
11558
 
    {
11559
 
      key_part_info->null_bit=0;
11560
 
      key_part_info->field=    *reg_field;
11561
 
      key_part_info->offset=   (*reg_field)->offset(table->record[0]);
11562
 
      key_part_info->length=   (uint16_t) (*reg_field)->pack_length();
11563
 
      /* TODO:
11564
 
        The below method of computing the key format length of the
11565
 
        key part is a copy/paste from opt_range.cc, and table.cc.
11566
 
        This should be factored out, e.g. as a method of Field.
11567
 
        In addition it is not clear if any of the Field::*_length
11568
 
        methods is supposed to compute the same length. If so, it
11569
 
        might be reused.
11570
 
      */
11571
 
      key_part_info->store_length= key_part_info->length;
11572
 
 
11573
 
      if ((*reg_field)->real_maybe_null())
11574
 
        key_part_info->store_length+= HA_KEY_NULL_LENGTH;
11575
 
      if ((*reg_field)->type() == DRIZZLE_TYPE_BLOB || 
11576
 
          (*reg_field)->real_type() == DRIZZLE_TYPE_VARCHAR)
11577
 
        key_part_info->store_length+= HA_KEY_BLOB_LENGTH;
11578
 
 
11579
 
      key_part_info->type=     (uint8_t) (*reg_field)->key_type();
11580
 
      key_part_info->key_type =
11581
 
        ((ha_base_keytype) key_part_info->type == HA_KEYTYPE_TEXT ||
11582
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
11583
 
         (ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
11584
 
        0 : FIELDFLAG_BINARY;
11585
 
    }
11586
 
  }
11587
 
 
11588
 
  if (thd->is_fatal_error)                              // If end of memory
11589
 
    goto err;                                    /* purecov: inspected */
11590
 
  share->db_record_offset= 1;
11591
 
  if (share->db_type() == myisam_hton)
11592
 
  {
11593
 
    if (create_myisam_tmp_table(table, param->keyinfo, param->start_recinfo,
11594
 
                                &param->recinfo, select_options))
11595
 
      goto err;
11596
 
  }
11597
 
  if (open_tmp_table(table))
11598
 
    goto err;
11599
 
 
11600
 
  thd->mem_root= mem_root_save;
11601
 
 
11602
 
  return(table);
11603
 
 
11604
 
err:
11605
 
  thd->mem_root= mem_root_save;
11606
 
  free_tmp_table(thd,table);                    /* purecov: inspected */
11607
 
  if (temp_pool_slot != MY_BIT_NONE)
11608
 
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
11609
 
  return(NULL);                         /* purecov: inspected */
11610
 
}
11611
 
 
11612
 
 
11613
 
 
11614
 
 
11615
 
/*
11616
 
  Create a temporary table to weed out duplicate rowid combinations
11617
 
 
11618
 
  SYNOPSIS
11619
 
 
11620
 
    create_duplicate_weedout_tmp_table()
11621
 
      thd
11622
 
      uniq_tuple_length_arg
11623
 
      SJ_TMP_TABLE 
11624
 
 
11625
 
  DESCRIPTION
11626
 
    Create a temporary table to weed out duplicate rowid combinations. The
11627
 
    table has a single column that is a concatenation of all rowids in the
11628
 
    combination. 
11629
 
 
11630
 
    Depending on the needed length, there are two cases:
11631
 
 
11632
 
    1. When the length of the column < max_key_length:
11633
 
 
11634
 
      CREATE TABLE tmp (col VARBINARY(n) NOT NULL, UNIQUE KEY(col));
11635
 
 
11636
 
    2. Otherwise (not a valid SQL syntax but internally supported):
11637
 
 
11638
 
      CREATE TABLE tmp (col VARBINARY NOT NULL, UNIQUE CONSTRAINT(col));
11639
 
 
11640
 
    The code in this function was produced by extraction of relevant parts
11641
 
    from create_tmp_table().
11642
 
 
11643
 
  RETURN
11644
 
    created table
11645
 
    NULL on error
11646
 
*/
11647
 
 
11648
 
TABLE *create_duplicate_weedout_tmp_table(THD *thd, 
11649
 
                                          uint uniq_tuple_length_arg,
11650
 
                                          SJ_TMP_TABLE *sjtbl)
11651
 
{
11652
 
  MEM_ROOT *mem_root_save, own_root;
11653
 
  TABLE *table;
11654
 
  TABLE_SHARE *share;
11655
 
  uint  temp_pool_slot=MY_BIT_NONE;
11656
 
  char  *tmpname,path[FN_REFLEN];
11657
 
  Field **reg_field;
11658
 
  KEY_PART_INFO *key_part_info;
11659
 
  KEY *keyinfo;
11660
 
  uchar *group_buff;
11661
 
  uchar *bitmaps;
11662
 
  uint *blob_field;
11663
 
  MI_COLUMNDEF *recinfo, *start_recinfo;
11664
 
  bool using_unique_constraint=false;
11665
 
  Field *field, *key_field;
11666
 
  uint blob_count, null_pack_length, null_count;
11667
 
  uchar *null_flags;
11668
 
  uchar *pos;
11669
 
  
11670
 
  /*
11671
 
    STEP 1: Get temporary table name
11672
 
  */
11673
 
  statistic_increment(thd->status_var.created_tmp_tables, &LOCK_status);
11674
 
  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
11675
 
    temp_pool_slot = bitmap_lock_set_next(&temp_pool);
11676
 
 
11677
 
  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
11678
 
    sprintf(path, "%s_%lx_%i", tmp_file_prefix,
11679
 
            current_pid, temp_pool_slot);
11680
 
  else
11681
 
  {
11682
 
    /* if we run out of slots or we are not using tempool */
11683
 
    sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
11684
 
            thd->thread_id, thd->tmp_table++);
11685
 
  }
11686
 
  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
11687
 
 
11688
 
  /* STEP 2: Figure if we'll be using a key or blob+constraint */
11689
 
  if (uniq_tuple_length_arg >= CONVERT_IF_BIGGER_TO_BLOB)
11690
 
    using_unique_constraint= true;
11691
 
 
11692
 
  /* STEP 3: Allocate memory for temptable description */
11693
 
  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
11694
 
  if (!multi_alloc_root(&own_root,
11695
 
                        &table, sizeof(*table),
11696
 
                        &share, sizeof(*share),
11697
 
                        &reg_field, sizeof(Field*) * (1+1),
11698
 
                        &blob_field, sizeof(uint)*2,
11699
 
                        &keyinfo, sizeof(*keyinfo),
11700
 
                        &key_part_info, sizeof(*key_part_info) * 2,
11701
 
                        &start_recinfo,
11702
 
                        sizeof(*recinfo)*(1*2+4),
11703
 
                        &tmpname, (uint) strlen(path)+1,
11704
 
                        &group_buff, (!using_unique_constraint ?
11705
 
                                      uniq_tuple_length_arg : 0),
11706
 
                        &bitmaps, bitmap_buffer_size(1)*2,
11707
 
                        NullS))
11708
 
  {
11709
 
    if (temp_pool_slot != MY_BIT_NONE)
11710
 
      bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
11711
 
    return(NULL);
11712
 
  }
11713
 
  stpcpy(tmpname,path);
11714
 
  
11715
 
 
11716
 
  /* STEP 4: Create TABLE description */
11717
 
  memset(table, 0, sizeof(*table));
11718
 
  memset(reg_field, 0, sizeof(Field*)*2);
11719
 
 
11720
 
  table->mem_root= own_root;
11721
 
  mem_root_save= thd->mem_root;
11722
 
  thd->mem_root= &table->mem_root;
11723
 
 
11724
 
  table->field=reg_field;
11725
 
  table->alias= "weedout-tmp";
11726
 
  table->reginfo.lock_type=TL_WRITE;    /* Will be updated */
11727
 
  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
11728
 
  table->map=1;
11729
 
  table->temp_pool_slot = temp_pool_slot;
11730
 
  table->copy_blobs= 1;
11731
 
  table->in_use= thd;
11732
 
  table->quick_keys.init();
11733
 
  table->covering_keys.init();
11734
 
  table->keys_in_use_for_query.init();
11735
 
 
11736
 
  table->s= share;
11737
 
  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
11738
 
  share->blob_field= blob_field;
11739
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
11740
 
  share->db_low_byte_first=1;                // True for HEAP and MyISAM
11741
 
  share->table_charset= NULL;
11742
 
  share->primary_key= MAX_KEY;               // Indicate no primary key
11743
 
  share->keys_for_keyread.init();
11744
 
  share->keys_in_use.init();
11745
 
 
11746
 
  blob_count= 0;
11747
 
 
11748
 
  /* Create the field */
11749
 
  {
11750
 
    /*
11751
 
      For the sake of uniformity, always use Field_varstring.
11752
 
    */
11753
 
    field= new Field_varstring(uniq_tuple_length_arg, false, "rowids", share,
11754
 
                               &my_charset_bin);
11755
 
    if (!field)
11756
 
      return(0);
11757
 
    field->table= table;
11758
 
    field->key_start.init(0);
11759
 
    field->part_of_key.init(0);
11760
 
    field->part_of_sortkey.init(0);
11761
 
    field->unireg_check= Field::NONE;
11762
 
    field->flags= (NOT_NULL_FLAG | BINARY_FLAG | NO_DEFAULT_VALUE_FLAG);
11763
 
    field->reset_fields();
11764
 
    field->init(table);
11765
 
    field->orig_table= NULL;
11766
 
     
11767
 
    field->field_index= 0;
11768
 
    
11769
 
    *(reg_field++)= field;
11770
 
    *blob_field= 0;
11771
 
    *reg_field= 0;
11772
 
 
11773
 
    share->fields= 1;
11774
 
    share->blob_fields= 0;
11775
 
  }
11776
 
 
11777
 
  uint reclength= field->pack_length();
11778
 
  if (using_unique_constraint)
11779
 
  { 
11780
 
    share->db_plugin= ha_lock_engine(0, myisam_hton);
11781
 
    table->file= get_new_handler(share, &table->mem_root,
11782
 
                                 share->db_type());
11783
 
    assert(uniq_tuple_length_arg <= table->file->max_key_length());
11784
 
  }
11785
 
  else
11786
 
  {
11787
 
    share->db_plugin= ha_lock_engine(0, heap_hton);
11788
 
    table->file= get_new_handler(share, &table->mem_root,
11789
 
                                 share->db_type());
11790
 
  }
11791
 
  if (!table->file)
11792
 
    goto err;
11793
 
 
11794
 
  null_count=1;
11795
 
  
11796
 
  null_pack_length= 1;
11797
 
  reclength += null_pack_length;
11798
 
 
11799
 
  share->reclength= reclength;
11800
 
  {
11801
 
    uint alloc_length=ALIGN_SIZE(share->reclength + MI_UNIQUE_HASH_LENGTH+1);
11802
 
    share->rec_buff_length= alloc_length;
11803
 
    if (!(table->record[0]= (uchar*)
11804
 
                            alloc_root(&table->mem_root, alloc_length*3)))
11805
 
      goto err;
11806
 
    table->record[1]= table->record[0]+alloc_length;
11807
 
    share->default_values= table->record[1]+alloc_length;
11808
 
  }
11809
 
  setup_tmp_table_column_bitmaps(table, bitmaps);
11810
 
 
11811
 
  recinfo= start_recinfo;
11812
 
  null_flags=(uchar*) table->record[0];
11813
 
  pos=table->record[0]+ null_pack_length;
11814
 
  if (null_pack_length)
11815
 
  {
11816
 
    memset(recinfo, 0, sizeof(*recinfo));
11817
 
    recinfo->type=FIELD_NORMAL;
11818
 
    recinfo->length=null_pack_length;
11819
 
    recinfo++;
11820
 
    memset(null_flags, 255, null_pack_length);  // Set null fields
11821
 
 
11822
 
    table->null_flags= (uchar*) table->record[0];
11823
 
    share->null_fields= null_count;
11824
 
    share->null_bytes= null_pack_length;
11825
 
  }
11826
 
  null_count=1;
11827
 
 
11828
 
  {
11829
 
    //Field *field= *reg_field;
11830
 
    uint length;
11831
 
    memset(recinfo, 0, sizeof(*recinfo));
11832
 
    field->move_field(pos,(uchar*) 0,0);
11833
 
 
11834
 
    field->reset();
11835
 
    /*
11836
 
      Test if there is a default field value. The test for ->ptr is to skip
11837
 
      'offset' fields generated by initalize_tables
11838
 
    */
11839
 
    // Initialize the table field:
11840
 
    memset(field->ptr, 0, field->pack_length());
11841
 
 
11842
 
    length=field->pack_length();
11843
 
    pos+= length;
11844
 
 
11845
 
    /* Make entry for create table */
11846
 
    recinfo->length=length;
11847
 
    if (field->flags & BLOB_FLAG)
11848
 
      recinfo->type= (int) FIELD_BLOB;
11849
 
    else
11850
 
      recinfo->type=FIELD_NORMAL;
11851
 
 
11852
 
    field->table_name= &table->alias;
11853
 
  }
11854
 
 
11855
 
  //param->recinfo=recinfo;
11856
 
  //store_record(table,s->default_values);        // Make empty default record
11857
 
 
11858
 
  if (thd->variables.tmp_table_size == ~ (uint64_t) 0)          // No limit
11859
 
    share->max_rows= ~(ha_rows) 0;
11860
 
  else
11861
 
    share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
11862
 
                                 min(thd->variables.tmp_table_size,
11863
 
                                     thd->variables.max_heap_table_size) :
11864
 
                                 thd->variables.tmp_table_size) /
11865
 
                                 share->reclength);
11866
 
  set_if_bigger(share->max_rows,1);             // For dummy start options
11867
 
 
11868
 
 
11869
 
  //// keyinfo= param->keyinfo;
11870
 
  if (true)
11871
 
  {
11872
 
    share->keys=1;
11873
 
    share->uniques= test(using_unique_constraint);
11874
 
    table->key_info=keyinfo;
11875
 
    keyinfo->key_part=key_part_info;
11876
 
    keyinfo->flags=HA_NOSAME;
11877
 
    keyinfo->usable_key_parts= keyinfo->key_parts= 1;
11878
 
    keyinfo->key_length=0;
11879
 
    keyinfo->rec_per_key=0;
11880
 
    keyinfo->algorithm= HA_KEY_ALG_UNDEF;
11881
 
    keyinfo->name= (char*) "weedout_key";
11882
 
    {
11883
 
      key_part_info->null_bit=0;
11884
 
      key_part_info->field=  field;
11885
 
      key_part_info->offset= field->offset(table->record[0]);
11886
 
      key_part_info->length= (uint16_t) field->key_length();
11887
 
      key_part_info->type=   (uint8_t) field->key_type();
11888
 
      key_part_info->key_type = FIELDFLAG_BINARY;
11889
 
      if (!using_unique_constraint)
11890
 
      {
11891
 
        if (!(key_field= field->new_key_field(thd->mem_root, table,
11892
 
                                              group_buff,
11893
 
                                              field->null_ptr,
11894
 
                                              field->null_bit)))
11895
 
          goto err;
11896
 
        key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL; //todo need this?
11897
 
      }
11898
 
      keyinfo->key_length+=  key_part_info->length;
11899
 
    }
11900
 
  }
11901
 
 
11902
 
  if (thd->is_fatal_error)                              // If end of memory
11903
 
    goto err;
11904
 
  share->db_record_offset= 1;
11905
 
  if (share->db_type() == myisam_hton)
11906
 
  {
11907
 
    recinfo++;
11908
 
    if (create_myisam_tmp_table(table, keyinfo, start_recinfo, &recinfo, 0))
11909
 
      goto err;
11910
 
  }
11911
 
  sjtbl->start_recinfo= start_recinfo;
11912
 
  sjtbl->recinfo=       recinfo;
11913
 
  if (open_tmp_table(table))
11914
 
    goto err;
11915
 
 
11916
 
  thd->mem_root= mem_root_save;
11917
 
  return(table);
11918
 
 
11919
 
err:
11920
 
  thd->mem_root= mem_root_save;
11921
 
  free_tmp_table(thd,table);                    /* purecov: inspected */
11922
 
  if (temp_pool_slot != MY_BIT_NONE)
11923
 
    bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
11924
 
  return(NULL);                         /* purecov: inspected */
11925
 
}
11926
 
 
11927
 
/****************************************************************************/
11928
 
 
11929
 
/**
11930
 
  Create a reduced TABLE object with properly set up Field list from a
11931
 
  list of field definitions.
11932
 
 
11933
 
    The created table doesn't have a table handler associated with
11934
 
    it, has no keys, no group/distinct, no copy_funcs array.
11935
 
    The sole purpose of this TABLE object is to use the power of Field
11936
 
    class to read/write data to/from table->record[0]. Then one can store
11937
 
    the record in any container (RB tree, hash, etc).
11938
 
    The table is created in THD mem_root, so are the table's fields.
11939
 
    Consequently, if you don't BLOB fields, you don't need to free it.
11940
 
 
11941
 
  @param thd         connection handle
11942
 
  @param field_list  list of column definitions
11943
 
 
11944
 
  @return
11945
 
    0 if out of memory, TABLE object in case of success
11946
 
*/
11947
 
 
11948
 
TABLE *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
11949
 
{
11950
 
  uint field_count= field_list.elements;
11951
 
  uint blob_count= 0;
11952
 
  Field **field;
11953
 
  Create_field *cdef;                           /* column definition */
11954
 
  uint record_length= 0;
11955
 
  uint null_count= 0;                 /* number of columns which may be null */
11956
 
  uint null_pack_length;              /* NULL representation array length */
11957
 
  uint *blob_field;
11958
 
  uchar *bitmaps;
11959
 
  TABLE *table;
11960
 
  TABLE_SHARE *share;
11961
 
 
11962
 
  if (!multi_alloc_root(thd->mem_root,
11963
 
                        &table, sizeof(*table),
11964
 
                        &share, sizeof(*share),
11965
 
                        &field, (field_count + 1) * sizeof(Field*),
11966
 
                        &blob_field, (field_count+1) *sizeof(uint),
11967
 
                        &bitmaps, bitmap_buffer_size(field_count)*2,
11968
 
                        NullS))
11969
 
    return 0;
11970
 
 
11971
 
  memset(table, 0, sizeof(*table));
11972
 
  memset(share, 0, sizeof(*share));
11973
 
  table->field= field;
11974
 
  table->s= share;
11975
 
  share->blob_field= blob_field;
11976
 
  share->fields= field_count;
11977
 
  share->blob_ptr_size= portable_sizeof_char_ptr;
11978
 
  setup_tmp_table_column_bitmaps(table, bitmaps);
11979
 
 
11980
 
  /* Create all fields and calculate the total length of record */
11981
 
  List_iterator_fast<Create_field> it(field_list);
11982
 
  while ((cdef= it++))
11983
 
  {
11984
 
    *field= make_field(share, 0, cdef->length,
11985
 
                       (uchar*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
11986
 
                       f_maybe_null(cdef->pack_flag) ? 1 : 0,
11987
 
                       cdef->pack_flag, cdef->sql_type, cdef->charset,
11988
 
                       cdef->unireg_check,
11989
 
                       cdef->interval, cdef->field_name);
11990
 
    if (!*field)
11991
 
      goto error;
11992
 
    (*field)->init(table);
11993
 
    record_length+= (*field)->pack_length();
11994
 
    if (! ((*field)->flags & NOT_NULL_FLAG))
11995
 
      null_count++;
11996
 
 
11997
 
    if ((*field)->flags & BLOB_FLAG)
11998
 
      share->blob_field[blob_count++]= (uint) (field - table->field);
11999
 
 
12000
 
    field++;
12001
 
  }
12002
 
  *field= NULL;                             /* mark the end of the list */
12003
 
  share->blob_field[blob_count]= 0;            /* mark the end of the list */
12004
 
  share->blob_fields= blob_count;
12005
 
 
12006
 
  null_pack_length= (null_count + 7)/8;
12007
 
  share->reclength= record_length + null_pack_length;
12008
 
  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
12009
 
  table->record[0]= (uchar*) thd->alloc(share->rec_buff_length);
12010
 
  if (!table->record[0])
12011
 
    goto error;
12012
 
 
12013
 
  if (null_pack_length)
12014
 
  {
12015
 
    table->null_flags= (uchar*) table->record[0];
12016
 
    share->null_fields= null_count;
12017
 
    share->null_bytes= null_pack_length;
12018
 
  }
12019
 
 
12020
 
  table->in_use= thd;           /* field->reset() may access table->in_use */
12021
 
  {
12022
 
    /* Set up field pointers */
12023
 
    uchar *null_pos= table->record[0];
12024
 
    uchar *field_pos= null_pos + share->null_bytes;
12025
 
    uint null_bit= 1;
12026
 
 
12027
 
    for (field= table->field; *field; ++field)
12028
 
    {
12029
 
      Field *cur_field= *field;
12030
 
      if ((cur_field->flags & NOT_NULL_FLAG))
12031
 
        cur_field->move_field(field_pos);
12032
 
      else
12033
 
      {
12034
 
        cur_field->move_field(field_pos, (uchar*) null_pos, null_bit);
12035
 
        null_bit<<= 1;
12036
 
        if (null_bit == (1 << 8))
12037
 
        {
12038
 
          ++null_pos;
12039
 
          null_bit= 1;
12040
 
        }
12041
 
      }
12042
 
      cur_field->reset();
12043
 
 
12044
 
      field_pos+= cur_field->pack_length();
12045
 
    }
12046
 
  }
12047
 
  return table;
12048
 
error:
12049
 
  for (field= table->field; *field; ++field)
12050
 
    delete *field;                         /* just invokes field destructor */
12051
 
  return 0;
12052
 
}
12053
 
 
12054
 
 
12055
 
static bool open_tmp_table(TABLE *table)
12056
 
{
12057
 
  int error;
12058
 
  if ((error=table->file->ha_open(table, table->s->table_name.str,O_RDWR,
12059
 
                                  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
12060
 
  {
12061
 
    table->file->print_error(error,MYF(0)); /* purecov: inspected */
12062
 
    table->db_stat=0;
12063
 
    return(1);
12064
 
  }
12065
 
  (void) table->file->extra(HA_EXTRA_QUICK);            /* Faster */
12066
 
  return(0);
12067
 
}
12068
 
 
12069
 
 
12070
 
/*
12071
 
  Create MyISAM temporary table
12072
 
 
12073
 
  SYNOPSIS
12074
 
    create_myisam_tmp_table()
12075
 
      table           Table object that descrimes the table to be created
12076
 
      keyinfo         Description of the index (there is always one index)
12077
 
      start_recinfo   MyISAM's column descriptions
12078
 
      recinfo INOUT   End of MyISAM's column descriptions
12079
 
      options         Option bits
12080
 
   
12081
 
  DESCRIPTION
12082
 
    Create a MyISAM temporary table according to passed description. The is
12083
 
    assumed to have one unique index or constraint.
12084
 
 
12085
 
    The passed array or MI_COLUMNDEF structures must have this form:
12086
 
 
12087
 
      1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
12088
 
         when there are many nullable columns)
12089
 
      2. Table columns
12090
 
      3. One free MI_COLUMNDEF element (*recinfo points here)
12091
 
   
12092
 
    This function may use the free element to create hash column for unique
12093
 
    constraint.
12094
 
 
12095
 
   RETURN
12096
 
     false - OK
12097
 
     true  - Error
12098
 
*/
12099
 
 
12100
 
static bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo, 
12101
 
                                    MI_COLUMNDEF *start_recinfo,
12102
 
                                    MI_COLUMNDEF **recinfo, 
12103
 
                                    uint64_t options)
12104
 
{
12105
 
  int error;
12106
 
  MI_KEYDEF keydef;
12107
 
  MI_UNIQUEDEF uniquedef;
12108
 
  TABLE_SHARE *share= table->s;
12109
 
 
12110
 
  if (share->keys)
12111
 
  {                                             // Get keys for ni_create
12112
 
    bool using_unique_constraint=0;
12113
 
    HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&table->mem_root,
12114
 
                                            sizeof(*seg) * keyinfo->key_parts);
12115
 
    if (!seg)
12116
 
      goto err;
12117
 
 
12118
 
    memset(seg, 0, sizeof(*seg) * keyinfo->key_parts);
12119
 
    if (keyinfo->key_length >= table->file->max_key_length() ||
12120
 
        keyinfo->key_parts > table->file->max_key_parts() ||
12121
 
        share->uniques)
12122
 
    {
12123
 
      /* Can't create a key; Make a unique constraint instead of a key */
12124
 
      share->keys=    0;
12125
 
      share->uniques= 1;
12126
 
      using_unique_constraint=1;
12127
 
      memset(&uniquedef, 0, sizeof(uniquedef));
12128
 
      uniquedef.keysegs=keyinfo->key_parts;
12129
 
      uniquedef.seg=seg;
12130
 
      uniquedef.null_are_equal=1;
12131
 
 
12132
 
      /* Create extra column for hash value */
12133
 
      memset(*recinfo, 0, sizeof(**recinfo));
12134
 
      (*recinfo)->type= FIELD_CHECK;
12135
 
      (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
12136
 
      (*recinfo)++;
12137
 
      share->reclength+=MI_UNIQUE_HASH_LENGTH;
12138
 
    }
12139
 
    else
12140
 
    {
12141
 
      /* Create an unique key */
12142
 
      memset(&keydef, 0, sizeof(keydef));
12143
 
      keydef.flag=HA_NOSAME | HA_BINARY_PACK_KEY | HA_PACK_KEY;
12144
 
      keydef.keysegs=  keyinfo->key_parts;
12145
 
      keydef.seg= seg;
12146
 
    }
12147
 
    for (uint i=0; i < keyinfo->key_parts ; i++,seg++)
12148
 
    {
12149
 
      Field *field=keyinfo->key_part[i].field;
12150
 
      seg->flag=     0;
12151
 
      seg->language= field->charset()->number;
12152
 
      seg->length=   keyinfo->key_part[i].length;
12153
 
      seg->start=    keyinfo->key_part[i].offset;
12154
 
      if (field->flags & BLOB_FLAG)
12155
 
      {
12156
 
        seg->type=
12157
 
        ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
12158
 
         HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
12159
 
        seg->bit_start= (uint8_t)(field->pack_length() - share->blob_ptr_size);
12160
 
        seg->flag= HA_BLOB_PART;
12161
 
        seg->length=0;                  // Whole blob in unique constraint
12162
 
      }
12163
 
      else
12164
 
      {
12165
 
        seg->type= keyinfo->key_part[i].type;
12166
 
      }
12167
 
      if (!(field->flags & NOT_NULL_FLAG))
12168
 
      {
12169
 
        seg->null_bit= field->null_bit;
12170
 
        seg->null_pos= (uint) (field->null_ptr - (uchar*) table->record[0]);
12171
 
        /*
12172
 
          We are using a GROUP BY on something that contains NULL
12173
 
          In this case we have to tell MyISAM that two NULL should
12174
 
          on INSERT be regarded at the same value
12175
 
        */
12176
 
        if (!using_unique_constraint)
12177
 
          keydef.flag|= HA_NULL_ARE_EQUAL;
12178
 
      }
12179
 
    }
12180
 
  }
12181
 
  MI_CREATE_INFO create_info;
12182
 
  memset(&create_info, 0, sizeof(create_info));
12183
 
 
12184
 
  if ((options & (OPTION_BIG_TABLES | SELECT_SMALL_RESULT)) ==
12185
 
      OPTION_BIG_TABLES)
12186
 
    create_info.data_file_length= ~(uint64_t) 0;
12187
 
 
12188
 
  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
12189
 
                       (uint) (*recinfo-start_recinfo),
12190
 
                       start_recinfo,
12191
 
                       share->uniques, &uniquedef,
12192
 
                       &create_info,
12193
 
                       HA_CREATE_TMP_TABLE)))
12194
 
  {
12195
 
    table->file->print_error(error,MYF(0));     /* purecov: inspected */
12196
 
    table->db_stat=0;
12197
 
    goto err;
12198
 
  }
12199
 
  status_var_increment(table->in_use->status_var.created_tmp_disk_tables);
12200
 
  share->db_record_offset= 1;
12201
 
  return(0);
12202
 
 err:
12203
 
  return(1);
12204
 
}
12205
 
 
12206
 
 
12207
 
void
12208
 
free_tmp_table(THD *thd, TABLE *entry)
12209
 
{
12210
 
  MEM_ROOT own_root= entry->mem_root;
12211
 
  const char *save_proc_info;
12212
 
 
12213
 
  save_proc_info=thd->proc_info;
12214
 
  thd_proc_info(thd, "removing tmp table");
12215
 
 
12216
 
  if (entry->file)
12217
 
  {
12218
 
    if (entry->db_stat)
12219
 
      entry->file->ha_drop_table(entry->s->table_name.str);
12220
 
    else
12221
 
      entry->file->ha_delete_table(entry->s->table_name.str);
12222
 
    delete entry->file;
12223
 
  }
12224
 
 
12225
 
  /* free blobs */
12226
 
  for (Field **ptr=entry->field ; *ptr ; ptr++)
12227
 
    (*ptr)->free();
12228
 
  free_io_cache(entry);
12229
 
 
12230
 
  if (entry->temp_pool_slot != MY_BIT_NONE)
12231
 
    bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot);
12232
 
 
12233
 
  plugin_unlock(0, entry->s->db_plugin);
12234
 
 
12235
 
  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
12236
 
  thd_proc_info(thd, save_proc_info);
12237
 
 
12238
 
  return;
12239
 
}
12240
 
 
12241
 
/**
12242
 
  If a HEAP table gets full, create a MyISAM table and copy all rows
12243
 
  to this.
12244
 
*/
12245
 
 
12246
 
bool create_myisam_from_heap(THD *thd, TABLE *table,
12247
 
                             MI_COLUMNDEF *start_recinfo,
12248
 
                             MI_COLUMNDEF **recinfo, 
12249
 
                             int error, bool ignore_last_dupp_key_error)
12250
 
{
12251
 
  TABLE new_table;
12252
 
  TABLE_SHARE share;
12253
 
  const char *save_proc_info;
12254
 
  int write_err;
12255
 
 
12256
 
  if (table->s->db_type() != heap_hton || 
12257
 
      error != HA_ERR_RECORD_FILE_FULL)
12258
 
  {
12259
 
    table->file->print_error(error,MYF(0));
12260
 
    return(1);
12261
 
  }
12262
 
  new_table= *table;
12263
 
  share= *table->s;
12264
 
  new_table.s= &share;
12265
 
  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
12266
 
  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
12267
 
                                        new_table.s->db_type())))
12268
 
    return(1);                          // End of memory
12269
 
 
12270
 
  save_proc_info=thd->proc_info;
12271
 
  thd_proc_info(thd, "converting HEAP to MyISAM");
12272
 
 
12273
 
  if (create_myisam_tmp_table(&new_table, table->key_info, start_recinfo,
12274
 
                              recinfo, thd->lex->select_lex.options | 
12275
 
                                               thd->options))
12276
 
    goto err2;
12277
 
  if (open_tmp_table(&new_table))
12278
 
    goto err1;
12279
 
  if (table->file->indexes_are_disabled())
12280
 
    new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
12281
 
  table->file->ha_index_or_rnd_end();
12282
 
  table->file->ha_rnd_init(1);
12283
 
  if (table->no_rows)
12284
 
  {
12285
 
    new_table.file->extra(HA_EXTRA_NO_ROWS);
12286
 
    new_table.no_rows=1;
12287
 
  }
12288
 
 
12289
 
#ifdef TO_BE_DONE_LATER_IN_4_1
12290
 
  /*
12291
 
    To use start_bulk_insert() (which is new in 4.1) we need to find
12292
 
    all places where a corresponding end_bulk_insert() should be put.
12293
 
  */
12294
 
  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
12295
 
  new_table.file->ha_start_bulk_insert(table->file->stats.records);
12296
 
#else
12297
 
  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
12298
 
  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
12299
 
#endif
12300
 
 
12301
 
  /*
12302
 
    copy all old rows from heap table to MyISAM table
12303
 
    This is the only code that uses record[1] to read/write but this
12304
 
    is safe as this is a temporary MyISAM table without timestamp/autoincrement.
12305
 
  */
12306
 
  while (!table->file->rnd_next(new_table.record[1]))
12307
 
  {
12308
 
    write_err= new_table.file->ha_write_row(new_table.record[1]);
12309
 
    if (write_err)
12310
 
      goto err;
12311
 
  }
12312
 
  /* copy row that filled HEAP table */
12313
 
  if ((write_err=new_table.file->ha_write_row(table->record[0])))
12314
 
  {
12315
 
    if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
12316
 
        !ignore_last_dupp_key_error)
12317
 
      goto err;
12318
 
  }
12319
 
 
12320
 
  /* remove heap table and change to use myisam table */
12321
 
  (void) table->file->ha_rnd_end();
12322
 
  (void) table->file->close();                  // This deletes the table !
12323
 
  delete table->file;
12324
 
  table->file=0;
12325
 
  plugin_unlock(0, table->s->db_plugin);
12326
 
  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
12327
 
  new_table.s= table->s;                       // Keep old share
12328
 
  *table= new_table;
12329
 
  *table->s= share;
12330
 
  
12331
 
  table->file->change_table_ptr(table, table->s);
12332
 
  table->use_all_columns();
12333
 
  if (save_proc_info)
12334
 
  {
12335
 
    const char *new_proc_info=
12336
 
      (!strcmp(save_proc_info,"Copying to tmp table") ?
12337
 
      "Copying to tmp table on disk" : save_proc_info);
12338
 
    thd_proc_info(thd, new_proc_info);
12339
 
  }
12340
 
  return(0);
12341
 
 
12342
 
 err:
12343
 
  table->file->print_error(write_err, MYF(0));
12344
 
  (void) table->file->ha_rnd_end();
12345
 
  (void) new_table.file->close();
12346
 
 err1:
12347
 
  new_table.file->ha_delete_table(new_table.s->table_name.str);
12348
 
 err2:
12349
 
  delete new_table.file;
12350
 
  thd_proc_info(thd, save_proc_info);
12351
 
  table->mem_root= new_table.mem_root;
12352
 
  return(1);
12353
 
}
12354
 
 
12355
10518
 
12356
10519
/**
12357
10520
  @details
12367
10530
 
12368
10531
Next_select_func setup_end_select_func(JOIN *join)
12369
10532
{
12370
 
  TABLE *table= join->tmp_table;
 
10533
  Table *table= join->tmp_table;
12371
10534
  TMP_TABLE_PARAM *tmp_tbl= &join->tmp_table_param;
12372
10535
  Next_select_func end_select;
12373
10536
 
12433
10596
*/
12434
10597
 
12435
10598
static int
12436
 
do_select(JOIN *join,List<Item> *fields,TABLE *table)
 
10599
do_select(JOIN *join,List<Item> *fields,Table *table)
12437
10600
{
12438
10601
  int rc= 0;
12439
10602
  enum_nested_loop_state error= NESTED_LOOP_OK;
13141
11304
 
13142
11305
/** Help function when we get some an error from the table handler. */
13143
11306
 
13144
 
int report_error(TABLE *table, int error)
 
11307
int report_error(Table *table, int error)
13145
11308
{
13146
11309
  if (error == HA_ERR_END_OF_FILE || error == HA_ERR_KEY_NOT_FOUND)
13147
11310
  {
13163
11326
int safe_index_read(JOIN_TAB *tab)
13164
11327
{
13165
11328
  int error;
13166
 
  TABLE *table= tab->table;
 
11329
  Table *table= tab->table;
13167
11330
  if ((error=table->file->index_read_map(table->record[0],
13168
11331
                                         tab->ref.key_buff,
13169
11332
                                         make_prev_keypart_map(tab->ref.key_parts),
13177
11340
join_read_const_table(JOIN_TAB *tab, POSITION *pos)
13178
11341
{
13179
11342
  int error;
13180
 
  TABLE *table=tab->table;
 
11343
  Table *table=tab->table;
13181
11344
  table->const_table=1;
13182
11345
  table->null_row=0;
13183
11346
  table->status=STATUS_NO_RECORD;
13255
11418
static int
13256
11419
join_read_system(JOIN_TAB *tab)
13257
11420
{
13258
 
  TABLE *table= tab->table;
 
11421
  Table *table= tab->table;
13259
11422
  int error;
13260
11423
  if (table->status & STATUS_GARBAGE)           // If first read
13261
11424
  {
13294
11457
join_read_const(JOIN_TAB *tab)
13295
11458
{
13296
11459
  int error;
13297
 
  TABLE *table= tab->table;
 
11460
  Table *table= tab->table;
13298
11461
  if (table->status & STATUS_GARBAGE)           // If first read
13299
11462
  {
13300
11463
    table->status= 0;
13349
11512
join_read_key(JOIN_TAB *tab)
13350
11513
{
13351
11514
  int error;
13352
 
  TABLE *table= tab->table;
 
11515
  Table *table= tab->table;
13353
11516
 
13354
11517
  if (!table->file->inited)
13355
11518
  {
13400
11563
join_read_always_key(JOIN_TAB *tab)
13401
11564
{
13402
11565
  int error;
13403
 
  TABLE *table= tab->table;
 
11566
  Table *table= tab->table;
13404
11567
 
13405
11568
  /* Initialize the index first */
13406
11569
  if (!table->file->inited)
13437
11600
join_read_last_key(JOIN_TAB *tab)
13438
11601
{
13439
11602
  int error;
13440
 
  TABLE *table= tab->table;
 
11603
  Table *table= tab->table;
13441
11604
 
13442
11605
  if (!table->file->inited)
13443
11606
    table->file->ha_index_init(tab->ref.key, tab->sorted);
13465
11628
static int
13466
11629
join_read_next_same_diff(READ_RECORD *info)
13467
11630
{
13468
 
  TABLE *table= info->table;
 
11631
  Table *table= info->table;
13469
11632
  JOIN_TAB *tab=table->reginfo.join_tab;
13470
11633
  if (tab->insideout_match_tab->found_match)
13471
11634
  {
13498
11661
join_read_next_same(READ_RECORD *info)
13499
11662
{
13500
11663
  int error;
13501
 
  TABLE *table= info->table;
 
11664
  Table *table= info->table;
13502
11665
  JOIN_TAB *tab=table->reginfo.join_tab;
13503
11666
 
13504
11667
  if ((error=table->file->index_next_same(table->record[0],
13518
11681
join_read_prev_same(READ_RECORD *info)
13519
11682
{
13520
11683
  int error;
13521
 
  TABLE *table= info->table;
 
11684
  Table *table= info->table;
13522
11685
  JOIN_TAB *tab=table->reginfo.join_tab;
13523
11686
 
13524
11687
  if ((error=table->file->index_prev(table->record[0])))
13577
11740
join_read_first(JOIN_TAB *tab)
13578
11741
{
13579
11742
  int error;
13580
 
  TABLE *table=tab->table;
 
11743
  Table *table=tab->table;
13581
11744
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
13582
11745
      !table->no_keyread)
13583
11746
  {
13652
11815
static int
13653
11816
join_read_last(JOIN_TAB *tab)
13654
11817
{
13655
 
  TABLE *table=tab->table;
 
11818
  Table *table=tab->table;
13656
11819
  int error;
13657
11820
  if (!table->key_read && table->covering_keys.is_set(tab->index) &&
13658
11821
      !table->no_keyread)
13772
11935
            (jt->ref.key < 0))
13773
11936
        {
13774
11937
          /* Join over all rows in table;  Return number of found rows */
13775
 
          TABLE *table=jt->table;
 
11938
          Table *table=jt->table;
13776
11939
 
13777
11940
          join->select_options ^= OPTION_FOUND_ROWS;
13778
11941
          if (table->sort.record_pointers ||
13909
12072
end_write(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
13910
12073
          bool end_of_records)
13911
12074
{
13912
 
  TABLE *table=join->tmp_table;
 
12075
  Table *table=join->tmp_table;
13913
12076
 
13914
12077
  if (join->thd->killed)                        // Aborted by user
13915
12078
  {
13973
12136
end_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
13974
12137
           bool end_of_records)
13975
12138
{
13976
 
  TABLE *table=join->tmp_table;
 
12139
  Table *table=join->tmp_table;
13977
12140
  ORDER   *group;
13978
12141
  int     error;
13979
12142
 
14049
12212
end_unique_update(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
14050
12213
                  bool end_of_records)
14051
12214
{
14052
 
  TABLE *table=join->tmp_table;
 
12215
  Table *table=join->tmp_table;
14053
12216
  int     error;
14054
12217
 
14055
12218
  if (end_of_records)
14096
12259
end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
14097
12260
                bool end_of_records)
14098
12261
{
14099
 
  TABLE *table=join->tmp_table;
 
12262
  Table *table=join->tmp_table;
14100
12263
  int     idx= -1;
14101
12264
 
14102
12265
  if (join->thd->killed)
14404
12567
 
14405
12568
 
14406
12569
static Item *
14407
 
part_of_refkey(TABLE *table,Field *field)
 
12570
part_of_refkey(Table *table,Field *field)
14408
12571
{
14409
12572
  if (!table->reginfo.join_tab)
14410
12573
    return (Item*) 0;             // field from outer non-select (UPDATE,...)
14452
12615
    -1   Reverse key can be used
14453
12616
*/
14454
12617
 
14455
 
static int test_if_order_by_key(ORDER *order, TABLE *table, uint idx,
 
12618
static int test_if_order_by_key(ORDER *order, Table *table, uint idx,
14456
12619
                                uint *used_key_parts)
14457
12620
{
14458
12621
  KEY_PART_INFO *key_part,*key_part_end;
14523
12686
}
14524
12687
 
14525
12688
 
14526
 
uint find_shortest_key(TABLE *table, const key_map *usable_keys)
 
12689
uint find_shortest_key(Table *table, const key_map *usable_keys)
14527
12690
{
14528
12691
  uint min_length= (uint) ~0;
14529
12692
  uint best= MAX_KEY;
14583
12746
*/
14584
12747
 
14585
12748
static uint
14586
 
test_if_subkey(ORDER *order, TABLE *table, uint ref, uint ref_key_parts,
 
12749
test_if_subkey(ORDER *order, Table *table, uint ref, uint ref_key_parts,
14587
12750
               const key_map *usable_keys)
14588
12751
{
14589
12752
  uint nr;
14643
12806
*/
14644
12807
 
14645
12808
static bool
14646
 
list_contains_unique_index(TABLE *table,
 
12809
list_contains_unique_index(Table *table,
14647
12810
                          bool (*find_func) (Field *, void *), void *data)
14648
12811
{
14649
12812
  for (uint keynr= 0; keynr < table->s->keys; keynr++)
14773
12936
  uint ref_key_parts;
14774
12937
  int order_direction;
14775
12938
  uint used_key_parts;
14776
 
  TABLE *table=tab->table;
 
12939
  Table *table=tab->table;
14777
12940
  SQL_SELECT *select=tab->select;
14778
12941
  key_map usable_keys;
14779
12942
  QUICK_SELECT_I *save_quick= 0;
14780
12943
 
14781
12944
  /*
14782
 
    Keys disabled by ALTER TABLE ... DISABLE KEYS should have already
 
12945
    Keys disabled by ALTER Table ... DISABLE KEYS should have already
14783
12946
    been taken into account.
14784
12947
  */
14785
12948
  usable_keys= *map;
15216
13379
{
15217
13380
  uint length= 0;
15218
13381
  ha_rows examined_rows;
15219
 
  TABLE *table;
 
13382
  Table *table;
15220
13383
  SQL_SELECT *select;
15221
13384
  JOIN_TAB *tab;
15222
13385
 
15320
13483
  fields is the number of fields to check (from the end)
15321
13484
*****************************************************************************/
15322
13485
 
15323
 
static bool compare_record(TABLE *table, Field **ptr)
 
13486
static bool compare_record(Table *table, Field **ptr)
15324
13487
{
15325
13488
  for (; *ptr ; ptr++)
15326
13489
  {
15352
13515
 
15353
13516
 
15354
13517
static int
15355
 
remove_duplicates(JOIN *join, TABLE *entry,List<Item> &fields, Item *having)
 
13518
remove_duplicates(JOIN *join, Table *entry,List<Item> &fields, Item *having)
15356
13519
{
15357
13520
  int error;
15358
13521
  ulong reclength,offset;
15400
13563
}
15401
13564
 
15402
13565
 
15403
 
static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field,
 
13566
static int remove_dup_with_compare(THD *thd, Table *table, Field **first_field,
15404
13567
                                   ulong offset, Item *having)
15405
13568
{
15406
13569
  handler *file=table->file;
15491
13654
    Note that this will not work on tables with blobs!
15492
13655
*/
15493
13656
 
15494
 
static int remove_dup_with_hash_index(THD *thd, TABLE *table,
 
13657
static int remove_dup_with_hash_index(THD *thd, Table *table,
15495
13658
                                      uint field_count,
15496
13659
                                      Field **first_field,
15497
13660
                                      ulong key_length,
15685
13848
  length=0;
15686
13849
  for (i=0 ; i < table_count ; i++)
15687
13850
  {
15688
 
    uint null_fields=0,used_fields;
 
13851
    uint null_fields=0, used_fields;
15689
13852
    Field **f_ptr,*field;
15690
13853
    MY_BITMAP *read_set= tables[i].table->read_set;
15691
13854
    for (f_ptr=tables[i].table->field,used_fields=tables[i].used_fields ;
15706
13869
      }
15707
13870
    }
15708
13871
    /* Copy null bits from table */
15709
 
    if (null_fields && tables[i].table->s->null_fields)
 
13872
    if (null_fields && tables[i].table->getNullFields())
15710
13873
    {                                           /* must copy null bits */
15711
13874
      copy->str= tables[i].table->null_flags;
15712
13875
      copy->length= tables[i].table->s->null_bytes;
15949
14112
 
15950
14113
 
15951
14114
bool
15952
 
cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref)
 
14115
cp_buffer_from_ref(THD *thd, Table *table, TABLE_REF *ref)
15953
14116
{
15954
14117
  enum enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
15955
14118
  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
16424
14587
  and group and order is compatible, else return 0.
16425
14588
*/
16426
14589
 
16427
 
static TABLE *
 
14590
static Table *
16428
14591
get_sort_by_table(ORDER *a,ORDER *b,TABLE_LIST *tables)
16429
14592
{
16430
14593
  table_map map= (table_map) 0;
17063
15226
 
17064
15227
static void
17065
15228
update_tmptable_sum_func(Item_sum **func_ptr,
17066
 
                         TABLE *tmp_table __attribute__((unused)))
 
15229
                         Table *tmp_table __attribute__((unused)))
17067
15230
{
17068
15231
  Item_sum *func;
17069
15232
  while ((func= *(func_ptr++)))
17132
15295
    return(false);
17133
15296
 
17134
15297
  Item_cond_and *cond=new Item_cond_and();
17135
 
  TABLE *table=join_tab->table;
 
15298
  Table *table=join_tab->table;
17136
15299
  int error;
17137
15300
  if (!cond)
17138
15301
    return(true);
17561
15724
    1   if write_data_failed()
17562
15725
*/
17563
15726
 
17564
 
int JOIN::rollup_write_data(uint idx, TABLE *table_arg)
 
15727
int JOIN::rollup_write_data(uint idx, Table *table_arg)
17565
15728
{
17566
15729
  uint i;
17567
15730
  for (i= send_group_parts ; i-- > idx ; )
17725
15888
    for (uint i=0 ; i < join->tables ; i++)
17726
15889
    {
17727
15890
      JOIN_TAB *tab=join->join_tab+i;
17728
 
      TABLE *table=tab->table;
 
15891
      Table *table=tab->table;
17729
15892
      TABLE_LIST *table_list= tab->table->pos_in_table_list;
17730
15893
      char buff[512]; 
17731
15894
      char buff1[512], buff2[512], buff3[512];
18044
16207
        else if (tab->do_firstmatch)
18045
16208
        {
18046
16209
          extra.append(STRING_WITH_LEN("; FirstMatch("));
18047
 
          TABLE *prev_table=tab->do_firstmatch->table;
 
16210
          Table *prev_table=tab->do_firstmatch->table;
18048
16211
          if (prev_table->derived_select_number)
18049
16212
          {
18050
16213
            char namebuf[NAME_LEN];