MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
sql_tmp_table.cc
1 /* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software Foundation,
14  51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
15 
18 #include "sql_select.h"
19 #include "sql_tmp_table.h"
20 #include "sql_executor.h"
21 #include "sql_base.h"
22 #include "opt_trace.h"
23 #include "debug_sync.h"
24 #include "filesort.h" // filesort_free_buffers
25 
26 #include <algorithm>
27 using std::max;
28 using std::min;
29 
30 /****************************************************************************
31  Create internal temporary table
32 ****************************************************************************/
33 
54 Field *create_tmp_field_from_field(THD *thd, Field *org_field,
55  const char *name, TABLE *table,
56  Item_field *item)
57 {
58  Field *new_field;
59 
60  new_field= org_field->new_field(thd->mem_root, table,
61  table == org_field->table);
62  if (new_field)
63  {
64  new_field->init(table);
65  new_field->orig_table= org_field->orig_table;
66  if (item)
67  item->result_field= new_field;
68  else
69  new_field->field_name= name;
70  new_field->flags|= (org_field->flags & NO_DEFAULT_VALUE_FLAG);
71  if (org_field->maybe_null() || (item && item->maybe_null))
72  new_field->flags&= ~NOT_NULL_FLAG; // Because of outer join
73  if (org_field->type() == MYSQL_TYPE_VAR_STRING ||
74  org_field->type() == MYSQL_TYPE_VARCHAR)
75  table->s->db_create_options|= HA_OPTION_PACK_RECORD;
76  else if (org_field->type() == FIELD_TYPE_DOUBLE)
77  ((Field_double *) new_field)->not_fixed= TRUE;
78  }
79  return new_field;
80 }
81 
104 static Field *create_tmp_field_from_item(THD *thd, Item *item, TABLE *table,
105  Item ***copy_func, bool modify_item)
106 {
107  bool maybe_null= item->maybe_null;
108  Field *new_field;
109  LINT_INIT(new_field);
110 
111  switch (item->result_type()) {
112  case REAL_RESULT:
113  new_field= new Field_double(item->max_length, maybe_null,
114  item->item_name.ptr(), item->decimals, TRUE);
115  break;
116  case INT_RESULT:
117  /*
118  Select an integer type with the minimal fit precision.
119  MY_INT32_NUM_DECIMAL_DIGITS is sign inclusive, don't consider the sign.
120  Values with MY_INT32_NUM_DECIMAL_DIGITS digits may or may not fit into
121  Field_long : make them Field_longlong.
122  */
123  if (item->max_length >= (MY_INT32_NUM_DECIMAL_DIGITS - 1))
124  new_field=new Field_longlong(item->max_length, maybe_null,
125  item->item_name.ptr(), item->unsigned_flag);
126  else
127  new_field=new Field_long(item->max_length, maybe_null,
128  item->item_name.ptr(), item->unsigned_flag);
129  break;
130  case STRING_RESULT:
131  DBUG_ASSERT(item->collation.collation);
132 
133  /*
134  DATE/TIME and GEOMETRY fields have STRING_RESULT result type.
135  To preserve type they needed to be handled separately.
136  */
137  if (item->is_temporal() || item->field_type() == MYSQL_TYPE_GEOMETRY)
138  new_field= item->tmp_table_field_from_field_type(table, 1);
139  else
140  new_field= item->make_string_field(table);
141  new_field->set_derivation(item->collation.derivation);
142  break;
143  case DECIMAL_RESULT:
144  new_field= Field_new_decimal::create_from_item(item);
145  break;
146  case ROW_RESULT:
147  default:
148  // This case should never be choosen
149  DBUG_ASSERT(0);
150  new_field= 0;
151  break;
152  }
153  if (new_field)
154  new_field->init(table);
155 
156  /*
157  If the item is a function, a pointer to the item is stored in
158  copy_func. We separate fields from functions by checking if the
159  item is a result field item. The real_item() must be checked to
160  avoid falsely identifying Item_ref and its subclasses as functions
161  when they refer to field-like items, such as Item_copy and
162  subclasses. References to true fields have already been untangled
163  in the beginning of create_tmp_field().
164  */
165  if (copy_func && item->real_item()->is_result_field())
166  *((*copy_func)++) = item; // Save for copy_funcs
167  if (modify_item)
168  item->set_result_field(new_field);
169  if (item->type() == Item::NULL_ITEM)
170  new_field->is_created_from_null_item= TRUE;
171  return new_field;
172 }
173 
174 
188 static Field *create_tmp_field_for_schema(THD *thd, Item *item, TABLE *table)
189 {
190  if (item->field_type() == MYSQL_TYPE_VARCHAR)
191  {
192  Field *field;
193  if (item->max_length > MAX_FIELD_VARCHARLENGTH)
194  field= new Field_blob(item->max_length, item->maybe_null,
195  item->item_name.ptr(), item->collation.collation);
196  else
197  {
198  field= new Field_varstring(item->max_length, item->maybe_null,
199  item->item_name.ptr(),
200  table->s, item->collation.collation);
201  table->s->db_create_options|= HA_OPTION_PACK_RECORD;
202  }
203  if (field)
204  field->init(table);
205  return field;
206  }
207  return item->tmp_table_field_from_field_type(table, 0);
208 }
209 
210 
238 Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
239  Item ***copy_func, Field **from_field,
240  Field **default_field,
241  bool group, bool modify_item,
242  bool table_cant_handle_bit_fields,
243  bool make_copy_field)
244 {
245  Field *result= NULL;
246  Item::Type orig_type= type;
247  Item *orig_item= 0;
248 
249  if (type != Item::FIELD_ITEM &&
250  item->real_item()->type() == Item::FIELD_ITEM)
251  {
252  orig_item= item;
253  item= item->real_item();
254  type= Item::FIELD_ITEM;
255  }
256 
257  switch (type) {
258  case Item::SUM_FUNC_ITEM:
259  {
260  Item_sum *item_sum=(Item_sum*) item;
261  result= item_sum->create_tmp_field(group, table);
262  if (!result)
263  my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
264  break;
265  }
266  case Item::FIELD_ITEM:
267  case Item::DEFAULT_VALUE_ITEM:
268  {
269  Item_field *field= (Item_field*) item;
270  bool orig_modify= modify_item;
271  if (orig_type == Item::REF_ITEM)
272  modify_item= 0;
273  /*
274  If item have to be able to store NULLs but underlaid field can't do it,
275  create_tmp_field_from_field() can't be used for tmp field creation.
276  */
277  if (field->maybe_null && !field->field->maybe_null())
278  {
279  result= create_tmp_field_from_item(thd, item, table, NULL,
280  modify_item);
281  if (!result)
282  break;
283  *from_field= field->field;
284  if (modify_item)
285  field->result_field= result;
286  }
287  else if (table_cant_handle_bit_fields && field->field->type() ==
288  MYSQL_TYPE_BIT)
289  {
290  *from_field= field->field;
291  result= create_tmp_field_from_item(thd, item, table, copy_func,
292  modify_item);
293  if (!result)
294  break;
295  if (modify_item)
296  field->result_field= result;
297  }
298  else
299  {
300  result= create_tmp_field_from_field(thd, (*from_field= field->field),
301  orig_item ? orig_item->item_name.ptr() :
302  item->item_name.ptr(),
303  table,
304  modify_item ? field :
305  NULL);
306  if (!result)
307  break;
308  }
309  if (orig_type == Item::REF_ITEM && orig_modify)
310  ((Item_ref*)orig_item)->set_result_field(result);
311  /*
312  Fields that are used as arguments to the DEFAULT() function already have
313  their data pointers set to the default value during name resulotion. See
314  Item_default_value::fix_fields.
315  */
316  if (orig_type != Item::DEFAULT_VALUE_ITEM && field->field->eq_def(result))
317  *default_field= field->field;
318  break;
319  }
320  /* Fall through */
321  case Item::FUNC_ITEM:
322  if (((Item_func *) item)->functype() == Item_func::FUNC_SP)
323  {
324  Item_func_sp *item_func_sp= (Item_func_sp *) item;
325  Field *sp_result_field= item_func_sp->get_sp_result_field();
326 
327  if (make_copy_field)
328  {
329  DBUG_ASSERT(item_func_sp->result_field);
330  *from_field= item_func_sp->result_field;
331  }
332  else
333  {
334  *((*copy_func)++)= item;
335  }
336 
337  result= create_tmp_field_from_field(thd,
338  sp_result_field,
339  item_func_sp->item_name.ptr(),
340  table,
341  NULL);
342  if (!result)
343  break;
344  if (modify_item)
345  item->set_result_field(result);
346  break;
347  }
348 
349  /* Fall through */
350  case Item::COND_ITEM:
351  case Item::FIELD_AVG_ITEM:
352  case Item::FIELD_STD_ITEM:
353  case Item::FIELD_VARIANCE_ITEM:
354  case Item::SUBSELECT_ITEM:
355  /* The following can only happen with 'CREATE TABLE ... SELECT' */
356  case Item::PROC_ITEM:
357  case Item::INT_ITEM:
358  case Item::REAL_ITEM:
359  case Item::DECIMAL_ITEM:
360  case Item::STRING_ITEM:
361  case Item::REF_ITEM:
362  case Item::NULL_ITEM:
363  case Item::VARBIN_ITEM:
364  if (make_copy_field)
365  {
366  DBUG_ASSERT(((Item_result_field*)item)->result_field);
367  *from_field= ((Item_result_field*)item)->result_field;
368  }
369  result= create_tmp_field_from_item(thd, item, table,
370  (make_copy_field ? 0 : copy_func),
371  modify_item);
372  break;
373  case Item::TYPE_HOLDER:
374  result= ((Item_type_holder *)item)->make_field_by_type(table);
375  if (!result)
376  break;
377  result->set_derivation(item->collation.derivation);
378  break;
379  default: // Dosen't have to be stored
380  break;
381  }
382  return result;
383 }
384 
385 /*
386  Set up column usage bitmaps for a temporary table
387 
388  IMPLEMENTATION
389  For temporary tables, we need one bitmap with all columns set and
390  a tmp_set bitmap to be used by things like filesort.
391 */
392 
393 static void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps)
394 {
395  uint field_count= table->s->fields;
396  bitmap_init(&table->def_read_set, (my_bitmap_map*) bitmaps, field_count,
397  FALSE);
398  bitmap_init(&table->tmp_set,
399  (my_bitmap_map*) (bitmaps+ bitmap_buffer_size(field_count)),
400  field_count, FALSE);
401  /* write_set and all_set are copies of read_set */
402  table->def_write_set= table->def_read_set;
403  table->s->all_set= table->def_read_set;
404  bitmap_set_all(&table->s->all_set);
405  table->default_column_bitmaps();
406  table->s->column_bitmap_size= bitmap_buffer_size(field_count);
407 }
408 
409 
441 #define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128
442 #define AVG_STRING_LENGTH_TO_PACK_ROWS 64
443 #define RATIO_TO_PACK_ROWS 2
444 #define MIN_STRING_LENGTH_TO_PACK_ROWS 10
445 
446 TABLE *
447 create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
448  ORDER *group, bool distinct, bool save_sum_fields,
449  ulonglong select_options, ha_rows rows_limit,
450  const char *table_alias)
451 {
452  MEM_ROOT *mem_root_save, own_root;
453  TABLE *table;
454  TABLE_SHARE *share;
455  uint i,field_count,null_count,null_pack_length;
456  uint copy_func_count= param->func_count;
457  uint hidden_null_count, hidden_null_pack_length, hidden_field_count;
458  uint blob_count,group_null_items, string_count;
459  uint temp_pool_slot=MY_BIT_NONE;
460  uint fieldnr= 0;
461  ulong reclength, string_total_length;
462  bool using_unique_constraint= false;
463  bool use_packed_rows= false;
464  bool not_all_columns= !(select_options & TMP_TABLE_ALL_COLUMNS);
465  char *tmpname,path[FN_REFLEN];
466  uchar *pos, *group_buff, *bitmaps;
467  uchar *null_flags;
468  Field **reg_field, **from_field, **default_field;
469  uint *blob_field;
470  Copy_field *copy=0;
471  KEY *keyinfo;
472  KEY_PART_INFO *key_part_info;
473  Item **copy_func;
474  MI_COLUMNDEF *recinfo;
475  /*
476  total_uneven_bit_length is uneven bit length for visible fields
477  hidden_uneven_bit_length is uneven bit length for hidden fields
478  */
479  uint total_uneven_bit_length= 0, hidden_uneven_bit_length= 0;
480  bool force_copy_fields= param->force_copy_fields;
481  /* Treat sum functions as normal ones when loose index scan is used. */
482  save_sum_fields|= param->precomputed_group_by;
483  DBUG_ENTER("create_tmp_table");
484  DBUG_PRINT("enter",
485  ("distinct: %d save_sum_fields: %d rows_limit: %lu group: %d",
486  (int) distinct, (int) save_sum_fields,
487  (ulong) rows_limit,test(group)));
488 
489  thd->inc_status_created_tmp_tables();
490 
491  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
492  temp_pool_slot = bitmap_lock_set_next(&temp_pool);
493 
494  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
495  sprintf(path, "%s_%lx_%i", tmp_file_prefix,
496  current_pid, temp_pool_slot);
497  else
498  {
499  /* if we run out of slots or we are not using tempool */
500  sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
501  thd->thread_id, thd->tmp_table++);
502  }
503 
504  /*
505  No need to change table name to lower case as we are only creating
506  MyISAM or HEAP tables here
507  */
508  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
509 
510 
511  if (group)
512  {
513  if (!param->quick_group)
514  group=0; // Can't use group key
515  else for (ORDER *tmp=group ; tmp ; tmp=tmp->next)
516  {
517  /*
518  marker == 4 means two things:
519  - store NULLs in the key, and
520  - convert BIT fields to 64-bit long, needed because MEMORY tables
521  can't index BIT fields.
522  */
523  (*tmp->item)->marker= 4;
524  if ((*tmp->item)->max_length >= CONVERT_IF_BIGGER_TO_BLOB)
525  using_unique_constraint= true;
526  }
527  if (param->group_length >= MAX_BLOB_WIDTH)
528  using_unique_constraint= true;
529  if (group)
530  distinct=0; // Can't use distinct
531  }
532 
533  field_count=param->field_count+param->func_count+param->sum_func_count;
534  hidden_field_count=param->hidden_field_count;
535 
536  /*
537  When loose index scan is employed as access method, it already
538  computes all groups and the result of all aggregate functions. We
539  make space for the items of the aggregate function in the list of
540  functions TMP_TABLE_PARAM::items_to_copy, so that the values of
541  these items are stored in the temporary table.
542  */
543  if (param->precomputed_group_by)
544  copy_func_count+= param->sum_func_count;
545 
546  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
547 
548  if (!multi_alloc_root(&own_root,
549  &table, sizeof(*table),
550  &share, sizeof(*share),
551  &reg_field, sizeof(Field*) * (field_count+1),
552  &default_field, sizeof(Field*) * (field_count),
553  &blob_field, sizeof(uint)*(field_count+1),
554  &from_field, sizeof(Field*)*field_count,
555  &copy_func, sizeof(*copy_func)*(copy_func_count+1),
556  &param->keyinfo, sizeof(*param->keyinfo),
557  &key_part_info,
558  sizeof(*key_part_info)*(param->group_parts+1),
559  &param->start_recinfo,
560  sizeof(*param->recinfo)*(field_count*2+4),
561  &tmpname, (uint) strlen(path)+1,
562  &group_buff, (group && ! using_unique_constraint ?
563  param->group_length : 0),
564  &bitmaps, bitmap_buffer_size(field_count)*2,
565  NullS))
566  {
567  if (temp_pool_slot != MY_BIT_NONE)
568  bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
569  DBUG_RETURN(NULL); /* purecov: inspected */
570  }
571  /* Copy_field belongs to TMP_TABLE_PARAM, allocate it in THD mem_root */
572  if (!(param->copy_field= copy= new (thd->mem_root) Copy_field[field_count]))
573  {
574  if (temp_pool_slot != MY_BIT_NONE)
575  bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
576  free_root(&own_root, MYF(0)); /* purecov: inspected */
577  DBUG_RETURN(NULL); /* purecov: inspected */
578  }
579  param->items_to_copy= copy_func;
580  strmov(tmpname,path);
581  /* make table according to fields */
582 
583  memset(table, 0, sizeof(*table));
584  memset(reg_field, 0, sizeof(Field*)*(field_count+1));
585  memset(default_field, 0, sizeof(Field*) * (field_count));
586  memset(from_field, 0, sizeof(Field*)*field_count);
587 
588  table->mem_root= own_root;
589  mem_root_save= thd->mem_root;
590  thd->mem_root= &table->mem_root;
591 
592  table->field=reg_field;
593  table->alias= table_alias;
594  table->reginfo.lock_type=TL_WRITE; /* Will be updated */
595  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
596  table->map=1;
597  table->temp_pool_slot = temp_pool_slot;
598  table->copy_blobs= 1;
599  table->in_use= thd;
600  table->quick_keys.init();
601  table->possible_quick_keys.init();
602  table->covering_keys.init();
603  table->merge_keys.init();
604  table->keys_in_use_for_query.init();
605 
606  table->s= share;
607  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
608  share->blob_field= blob_field;
609  share->db_low_byte_first=1; // True for HEAP and MyISAM
610  share->table_charset= param->table_charset;
611  share->primary_key= MAX_KEY; // Indicate no primary key
612  share->keys_for_keyread.init();
613  share->keys_in_use.init();
614  if (param->schema_table)
615  share->db= INFORMATION_SCHEMA_NAME;
616 
617  /* Calculate which type of fields we will store in the temporary table */
618 
619  reclength= string_total_length= 0;
620  blob_count= string_count= null_count= hidden_null_count= group_null_items= 0;
621  param->using_outer_summary_function= 0;
622 
623  List_iterator_fast<Item> li(fields);
624  Item *item;
625  Field **tmp_from_field=from_field;
626  while ((item=li++))
627  {
628  Item::Type type= item->type();
629  if (type == Item::COPY_STR_ITEM)
630  {
631  item= ((Item_copy *)item)->get_item();
632  type= item->type();
633  }
634  if (not_all_columns)
635  {
636  if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
637  {
638  if (item->used_tables() & OUTER_REF_TABLE_BIT)
639  item->update_used_tables();
640  if (type == Item::SUBSELECT_ITEM ||
641  (item->used_tables() & ~OUTER_REF_TABLE_BIT))
642  {
643  /*
644  Mark that we have ignored an item that refers to a summary
645  function. We need to know this if someone is going to use
646  DISTINCT on the result.
647  */
648  param->using_outer_summary_function= 1;
649  goto update_hidden;
650  }
651  }
652  }
653  if (type == Item::SUM_FUNC_ITEM && !group && !save_sum_fields)
654  { /* Can't calc group yet */
655  Item_sum *sum_item= (Item_sum *) item;
656  sum_item->result_field=0;
657  for (i=0 ; i < sum_item->get_arg_count() ; i++)
658  {
659  Item *arg= sum_item->get_arg(i);
660  if (!arg->const_item())
661  {
662  Field *new_field=
663  create_tmp_field(thd, table, arg, arg->type(), &copy_func,
664  tmp_from_field, &default_field[fieldnr],
665  group != 0,not_all_columns,
666  distinct, false);
667  if (!new_field)
668  goto err; // Should be OOM
669  tmp_from_field++;
670  reclength+=new_field->pack_length();
671  if (new_field->flags & BLOB_FLAG)
672  {
673  *blob_field++= fieldnr;
674  blob_count++;
675  }
676  if (new_field->type() == MYSQL_TYPE_BIT)
677  total_uneven_bit_length+= new_field->field_length & 7;
678  *(reg_field++)= new_field;
679  if (new_field->real_type() == MYSQL_TYPE_STRING ||
680  new_field->real_type() == MYSQL_TYPE_VARCHAR)
681  {
682  string_count++;
683  string_total_length+= new_field->pack_length();
684  }
685  thd->mem_root= mem_root_save;
686  arg= sum_item->set_arg(i, thd, new Item_field(new_field));
687  thd->mem_root= &table->mem_root;
688  if (!(new_field->flags & NOT_NULL_FLAG))
689  {
690  null_count++;
691  /*
692  new_field->maybe_null() is still false, it will be
693  changed below. But we have to setup Item_field correctly
694  */
695  arg->maybe_null=1;
696  }
697  new_field->field_index= fieldnr++;
698  }
699  }
700  }
701  else
702  {
703  /*
704  The last parameter to create_tmp_field() is a bit tricky:
705 
706  We need to set it to 0 in union, to get fill_record() to modify the
707  temporary table.
708  We need to set it to 1 on multi-table-update and in select to
709  write rows to the temporary table.
710  We here distinguish between UNION and multi-table-updates by the fact
711  that in the later case group is set to the row pointer.
712  */
713  Field *new_field= (param->schema_table) ?
714  create_tmp_field_for_schema(thd, item, table) :
715  create_tmp_field(thd, table, item, type, &copy_func,
716  tmp_from_field, &default_field[fieldnr],
717  group != 0,
718  !force_copy_fields &&
719  (not_all_columns || group !=0),
720  /*
721  If item->marker == 4 then we force create_tmp_field
722  to create a 64-bit longs for BIT fields because HEAP
723  tables can't index BIT fields directly. We do the same
724  for distinct, as we want the distinct index to be
725  usable in this case too.
726  */
727  item->marker == 4 || param->bit_fields_as_long,
728  force_copy_fields);
729 
730  if (!new_field)
731  {
732  if (thd->is_fatal_error)
733  goto err; // Got OOM
734  goto update_hidden;
735  }
736  if (type == Item::SUM_FUNC_ITEM)
737  ((Item_sum *) item)->result_field= new_field;
738  tmp_from_field++;
739  reclength+=new_field->pack_length();
740  if (!(new_field->flags & NOT_NULL_FLAG))
741  null_count++;
742  if (new_field->type() == MYSQL_TYPE_BIT)
743  total_uneven_bit_length+= new_field->field_length & 7;
744  if (new_field->flags & BLOB_FLAG)
745  {
746  *blob_field++= fieldnr;
747  blob_count++;
748  }
749 
750  if (new_field->real_type() == MYSQL_TYPE_STRING ||
751  new_field->real_type() == MYSQL_TYPE_VARCHAR)
752  {
753  string_count++;
754  string_total_length+= new_field->pack_length();
755  }
756 
757  if (item->marker == 4 && item->maybe_null)
758  {
759  group_null_items++;
760  new_field->flags|= GROUP_FLAG;
761  }
762  new_field->field_index= fieldnr++;
763  *(reg_field++)= new_field;
764  }
765 
766 update_hidden:
767  if (!--hidden_field_count)
768  {
769  /*
770  This was the last hidden field; Remember how many hidden fields could
771  have null
772  */
773  hidden_null_count=null_count;
774  /*
775  We need to update hidden_field_count as we may have stored group
776  functions with constant arguments
777  */
778  param->hidden_field_count= fieldnr;
779  null_count= 0;
780  /*
781  On last hidden field we store uneven bit length in
782  hidden_uneven_bit_length and proceed calculation of
783  uneven bits for visible fields into
784  total_uneven_bit_length variable.
785  */
786  hidden_uneven_bit_length= total_uneven_bit_length;
787  total_uneven_bit_length= 0;
788  }
789  }
790  DBUG_ASSERT(fieldnr == (uint) (reg_field - table->field));
791  DBUG_ASSERT(field_count >= (uint) (reg_field - table->field));
792  field_count= fieldnr;
793  *reg_field= 0;
794  *blob_field= 0; // End marker
795  share->fields= field_count;
796 
797  /* If result table is small; use a heap */
798  /* future: storage engine selection can be made dynamic? */
799  if (blob_count || using_unique_constraint
800  || (thd->variables.big_tables && !(select_options & SELECT_SMALL_RESULT))
801  || (select_options & TMP_TABLE_FORCE_MYISAM))
802  {
803  share->db_plugin= ha_lock_engine(0, myisam_hton);
804  table->file= get_new_handler(share, &table->mem_root,
805  share->db_type());
806  if (group &&
807  (param->group_parts > table->file->max_key_parts() ||
808  param->group_length > table->file->max_key_length()))
809  using_unique_constraint= true;
810  }
811  else
812  {
813  share->db_plugin= ha_lock_engine(0, heap_hton);
814  table->file= get_new_handler(share, &table->mem_root,
815  share->db_type());
816  }
817  if (!table->file)
818  goto err;
819 
820  if (table->file->set_ha_share_ref(&share->ha_share))
821  {
822  delete table->file;
823  goto err;
824  }
825 
826  if (!using_unique_constraint)
827  reclength+= group_null_items; // null flag is stored separately
828 
829  share->blob_fields= blob_count;
830  if (blob_count == 0)
831  {
832  /* We need to ensure that first byte is not 0 for the delete link */
833  if (param->hidden_field_count)
834  hidden_null_count++;
835  else
836  null_count++;
837  }
838  hidden_null_pack_length= (hidden_null_count + 7 +
839  hidden_uneven_bit_length) / 8;
840  null_pack_length= (hidden_null_pack_length +
841  (null_count + total_uneven_bit_length + 7) / 8);
842  reclength+=null_pack_length;
843  if (!reclength)
844  reclength=1; // Dummy select
845  /* Use packed rows if there is blobs or a lot of space to gain */
846  if (blob_count ||
847  (string_total_length >= STRING_TOTAL_LENGTH_TO_PACK_ROWS &&
848  (reclength / string_total_length <= RATIO_TO_PACK_ROWS ||
849  string_total_length / string_count >= AVG_STRING_LENGTH_TO_PACK_ROWS)))
850  use_packed_rows= true;
851 
852  if (!use_packed_rows)
853  share->db_create_options&= ~HA_OPTION_PACK_RECORD;
854 
855  share->reclength= reclength;
856  {
857  uint alloc_length=ALIGN_SIZE(reclength+MI_UNIQUE_HASH_LENGTH+1);
858  share->rec_buff_length= alloc_length;
859  if (!(table->record[0]= (uchar*)
860  alloc_root(&table->mem_root, alloc_length*3)))
861  goto err;
862  table->record[1]= table->record[0]+alloc_length;
863  share->default_values= table->record[1]+alloc_length;
864  }
865  copy_func[0]=0; // End marker
866  param->func_count= copy_func - param->items_to_copy;
867 
868  setup_tmp_table_column_bitmaps(table, bitmaps);
869 
870  recinfo=param->start_recinfo;
871  null_flags=(uchar*) table->record[0];
872  pos=table->record[0]+ null_pack_length;
873  if (null_pack_length)
874  {
875  memset(recinfo, 0, sizeof(*recinfo));
876  recinfo->type=FIELD_NORMAL;
877  recinfo->length=null_pack_length;
878  recinfo++;
879  memset(null_flags, 255, null_pack_length); // Set null fields
880 
881  table->null_flags= (uchar*) table->record[0];
882  share->null_fields= null_count+ hidden_null_count;
883  share->null_bytes= null_pack_length;
884  }
885  null_count= (blob_count == 0) ? 1 : 0;
886  hidden_field_count=param->hidden_field_count;
887  for (i=0,reg_field=table->field; i < field_count; i++,reg_field++,recinfo++)
888  {
889  Field *field= *reg_field;
890  uint length;
891  memset(recinfo, 0, sizeof(*recinfo));
892 
893  if (!(field->flags & NOT_NULL_FLAG))
894  {
895  if (field->flags & GROUP_FLAG && !using_unique_constraint)
896  {
897  /*
898  We have to reserve one byte here for NULL bits,
899  as this is updated by 'end_update()'
900  */
901  *pos++=0; // Null is stored here
902  recinfo->length=1;
903  recinfo->type=FIELD_NORMAL;
904  recinfo++;
905  memset(recinfo, 0, sizeof(*recinfo));
906  }
907  else
908  {
909  recinfo->null_bit= (uint8)1 << (null_count & 7);
910  recinfo->null_pos= null_count/8;
911  }
912  field->move_field(pos,null_flags+null_count/8,
913  (uint8)1 << (null_count & 7));
914  null_count++;
915  }
916  else
917  field->move_field(pos,(uchar*) 0,0);
918  if (field->type() == MYSQL_TYPE_BIT)
919  {
920  /* We have to reserve place for extra bits among null bits */
921  ((Field_bit*) field)->set_bit_ptr(null_flags + null_count / 8,
922  null_count & 7);
923  null_count+= (field->field_length & 7);
924  }
925  field->reset();
926 
927  /*
928  Test if there is a default field value. The test for ->ptr is to skip
929  'offset' fields generated by initalize_tables
930  */
931  if (default_field[i] && default_field[i]->ptr)
932  {
933  /*
934  default_field[i] is set only in the cases when 'field' can
935  inherit the default value that is defined for the field referred
936  by the Item_field object from which 'field' has been created.
937  */
938  my_ptrdiff_t diff;
939  Field *orig_field= default_field[i];
940  /* Get the value from default_values */
941  diff= (my_ptrdiff_t) (orig_field->table->s->default_values-
942  orig_field->table->record[0]);
943  orig_field->move_field_offset(diff); // Points now at default_values
944  if (orig_field->is_real_null())
945  field->set_null();
946  else
947  {
948  field->set_notnull();
949  memcpy(field->ptr, orig_field->ptr, field->pack_length());
950  }
951  orig_field->move_field_offset(-diff); // Back to record[0]
952  }
953 
954  if (from_field[i])
955  { /* Not a table Item */
956  copy->set(field,from_field[i],save_sum_fields);
957  copy++;
958  }
959  length=field->pack_length();
960  pos+= length;
961 
962  /* Make entry for create table */
963  recinfo->length=length;
964  if (field->flags & BLOB_FLAG)
965  recinfo->type= (int) FIELD_BLOB;
966  else if (use_packed_rows &&
967  field->real_type() == MYSQL_TYPE_STRING &&
968  length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
969  recinfo->type=FIELD_SKIP_ENDSPACE;
970  else if (use_packed_rows &&
971  field->real_type() == MYSQL_TYPE_VARCHAR &&
972  length >= MIN_STRING_LENGTH_TO_PACK_ROWS)
973  recinfo->type= FIELD_VARCHAR;
974  else
975  recinfo->type=FIELD_NORMAL;
976  if (!--hidden_field_count)
977  null_count=(null_count+7) & ~7; // move to next byte
978 
979  // fix table name in field entry
980  field->table_name= &table->alias;
981  }
982 
983  param->copy_field_end=copy;
984  param->recinfo=recinfo;
985  store_record(table,s->default_values); // Make empty default record
986 
987  if (thd->variables.tmp_table_size == ~ (ulonglong) 0) // No limit
988  share->max_rows= ~(ha_rows) 0;
989  else
990  share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
991  min(thd->variables.tmp_table_size,
992  thd->variables.max_heap_table_size) :
993  thd->variables.tmp_table_size) /
994  share->reclength);
995  set_if_bigger(share->max_rows,1); // For dummy start options
996  /*
997  Push the LIMIT clause to the temporary table creation, so that we
998  materialize only up to 'rows_limit' records instead of all result records.
999  */
1000  set_if_smaller(share->max_rows, rows_limit);
1001  param->end_write_records= rows_limit;
1002 
1003  keyinfo= param->keyinfo;
1004  keyinfo->table= table;
1005 
1006  if (group)
1007  {
1008  DBUG_PRINT("info",("Creating group key in temporary table"));
1009  table->group=group; /* Table is grouped by key */
1010  param->group_buff=group_buff;
1011  share->keys=1;
1012  share->uniques= test(using_unique_constraint);
1013  table->key_info= share->key_info= keyinfo;
1014  keyinfo->key_part= key_part_info;
1015  keyinfo->flags=HA_NOSAME;
1016  keyinfo->usable_key_parts=keyinfo->user_defined_key_parts=
1017  param->group_parts;
1018  keyinfo->actual_key_parts= keyinfo->user_defined_key_parts;
1019  keyinfo->key_length=0;
1020  keyinfo->rec_per_key=0;
1021  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1022  keyinfo->name= (char*) "group_key";
1023  ORDER *cur_group= group;
1024  for (; cur_group ; cur_group= cur_group->next, key_part_info++)
1025  {
1026  Field *field=(*cur_group->item)->get_tmp_table_field();
1027  DBUG_ASSERT(field->table == table);
1028  bool maybe_null=(*cur_group->item)->maybe_null;
1029  key_part_info->init_from_field(field);
1030  if (!using_unique_constraint)
1031  {
1032  cur_group->buff=(char*) group_buff;
1033  cur_group->field= field->new_key_field(thd->mem_root, table,
1034  group_buff + test(maybe_null));
1035 
1036  if (!cur_group->field)
1037  goto err; /* purecov: inspected */
1038 
1039  if (maybe_null)
1040  {
1041  /*
1042  To be able to group on NULL, we reserved place in group_buff
1043  for the NULL flag just before the column. (see above).
1044  The field data is after this flag.
1045  The NULL flag is updated in 'end_update()' and 'end_write()'
1046  */
1047  keyinfo->flags|= HA_NULL_ARE_EQUAL; // def. that NULL == NULL
1048  cur_group->buff++; // Pointer to field data
1049  group_buff++; // Skipp null flag
1050  }
1051  /* In GROUP BY 'a' and 'a ' are equal for VARCHAR fields */
1052  key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL;
1053  group_buff+= cur_group->field->pack_length();
1054  }
1055  keyinfo->key_length+= key_part_info->store_length;
1056  }
1057  keyinfo->actual_flags= keyinfo->flags;
1058  }
1059 
1060  if (distinct && field_count != param->hidden_field_count)
1061  {
1062  /*
1063  Create an unique key or an unique constraint over all columns
1064  that should be in the result. In the temporary table, there are
1065  'param->hidden_field_count' extra columns, whose null bits are stored
1066  in the first 'hidden_null_pack_length' bytes of the row.
1067  */
1068  DBUG_PRINT("info",("hidden_field_count: %d", param->hidden_field_count));
1069 
1070  if (blob_count)
1071  {
1072  /*
1073  Special mode for index creation in MyISAM used to support unique
1074  indexes on blobs with arbitrary length. Such indexes cannot be
1075  used for lookups.
1076  */
1077  share->uniques= 1;
1078  }
1079  null_pack_length-=hidden_null_pack_length;
1080  keyinfo->user_defined_key_parts=
1081  ((field_count-param->hidden_field_count) +
1082  (share->uniques ? test(null_pack_length) : 0));
1083  keyinfo->actual_key_parts= keyinfo->user_defined_key_parts;
1084  table->distinct= 1;
1085  share->keys= 1;
1086  if (!(key_part_info= (KEY_PART_INFO*)
1087  alloc_root(&table->mem_root,
1088  keyinfo->user_defined_key_parts * sizeof(KEY_PART_INFO))))
1089  goto err;
1090  memset(key_part_info, 0, keyinfo->user_defined_key_parts *
1091  sizeof(KEY_PART_INFO));
1092  table->key_info= share->key_info= keyinfo;
1093  keyinfo->key_part= key_part_info;
1094  keyinfo->actual_flags= keyinfo->flags= HA_NOSAME | HA_NULL_ARE_EQUAL;
1095  keyinfo->key_length= 0; // Will compute the sum of the parts below.
1096  keyinfo->name= (char*) "<auto_key>";
1097  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1098  keyinfo->rec_per_key= 0;
1099 
1100  /*
1101  Create an extra field to hold NULL bits so that unique indexes on
1102  blobs can distinguish NULL from 0. This extra field is not needed
1103  when we do not use UNIQUE indexes for blobs.
1104  */
1105  if (null_pack_length && share->uniques)
1106  {
1107  key_part_info->null_bit=0;
1108  key_part_info->offset=hidden_null_pack_length;
1109  key_part_info->length=null_pack_length;
1110  key_part_info->field= new Field_string(table->record[0],
1111  (uint32) key_part_info->length,
1112  (uchar*) 0,
1113  (uint) 0,
1114  Field::NONE,
1115  NullS, &my_charset_bin);
1116  if (!key_part_info->field)
1117  goto err;
1118  key_part_info->field->init(table);
1119  key_part_info->key_type=FIELDFLAG_BINARY;
1120  key_part_info->type= HA_KEYTYPE_BINARY;
1121  key_part_info++;
1122  }
1123  /* Create a distinct key over the columns we are going to return */
1124  for (i=param->hidden_field_count, reg_field=table->field + i ;
1125  i < field_count;
1126  i++, reg_field++, key_part_info++)
1127  {
1128  key_part_info->init_from_field(*reg_field);
1129  keyinfo->key_length+= key_part_info->store_length;
1130  }
1131  }
1132 
1133  if (thd->is_fatal_error) // If end of memory
1134  goto err; /* purecov: inspected */
1135  share->db_record_offset= 1;
1136  if (!param->skip_create_table)
1137  {
1138  if (instantiate_tmp_table(table, param->keyinfo, param->start_recinfo,
1139  &param->recinfo, select_options,
1140  thd->variables.big_tables, &thd->opt_trace))
1141  goto err;
1142  }
1143 
1144  thd->mem_root= mem_root_save;
1145 
1146  DEBUG_SYNC(thd, "tmp_table_created");
1147 
1148  DBUG_RETURN(table);
1149 
1150 err:
1151  thd->mem_root= mem_root_save;
1152  free_tmp_table(thd,table); /* purecov: inspected */
1153  if (temp_pool_slot != MY_BIT_NONE)
1154  bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
1155  DBUG_RETURN(NULL); /* purecov: inspected */
1156 }
1157 
1158 /*
1159  Create a temporary table to weed out duplicate rowid combinations
1160 
1161  SYNOPSIS
1162 
1163  create_duplicate_weedout_tmp_table()
1164  thd Thread handle
1165  uniq_tuple_length_arg Length of the table's column
1166  sjtbl Update sjtbl->[start_]recinfo values which
1167  will be needed if we'll need to convert the
1168  created temptable from HEAP to MyISAM/Maria.
1169 
1170  DESCRIPTION
1171  Create a temporary table to weed out duplicate rowid combinations. The
1172  table has a single column that is a concatenation of all rowids in the
1173  combination.
1174 
1175  Depending on the needed length, there are two cases:
1176 
1177  1. When the length of the column < max_key_length:
1178 
1179  CREATE TABLE tmp (col VARBINARY(n) NOT NULL, UNIQUE KEY(col));
1180 
1181  2. Otherwise (not a valid SQL syntax but internally supported):
1182 
1183  CREATE TABLE tmp (col VARBINARY NOT NULL, UNIQUE CONSTRAINT(col));
1184 
1185  The code in this function was produced by extraction of relevant parts
1186  from create_tmp_table().
1187 
1188  RETURN
1189  created table
1190  NULL on error
1191 */
1192 
1193 TABLE *create_duplicate_weedout_tmp_table(THD *thd,
1194  uint uniq_tuple_length_arg,
1195  SJ_TMP_TABLE *sjtbl)
1196 {
1197  MEM_ROOT *mem_root_save, own_root;
1198  TABLE *table;
1199  TABLE_SHARE *share;
1200  uint temp_pool_slot=MY_BIT_NONE;
1201  char *tmpname,path[FN_REFLEN];
1202  Field **reg_field;
1203  KEY_PART_INFO *key_part_info;
1204  KEY *keyinfo;
1205  uchar *group_buff;
1206  uchar *bitmaps;
1207  uint *blob_field;
1208  MI_COLUMNDEF *recinfo, *start_recinfo;
1209  bool using_unique_constraint=false;
1210  Field *field, *key_field;
1211  uint null_pack_length, null_count;
1212  uchar *null_flags;
1213 
1214  DBUG_ENTER("create_duplicate_weedout_tmp_table");
1215  DBUG_ASSERT(!sjtbl->is_confluent);
1216  /*
1217  STEP 1: Get temporary table name
1218  */
1219  thd->inc_status_created_tmp_tables();
1220  if (use_temp_pool && !(test_flags & TEST_KEEP_TMP_TABLES))
1221  temp_pool_slot = bitmap_lock_set_next(&temp_pool);
1222 
1223  if (temp_pool_slot != MY_BIT_NONE) // we got a slot
1224  sprintf(path, "%s_%lx_%i", tmp_file_prefix,
1225  current_pid, temp_pool_slot);
1226  else
1227  {
1228  /* if we run out of slots or we are not using tempool */
1229  sprintf(path,"%s%lx_%lx_%x", tmp_file_prefix,current_pid,
1230  thd->thread_id, thd->tmp_table++);
1231  }
1232  fn_format(path, path, mysql_tmpdir, "", MY_REPLACE_EXT|MY_UNPACK_FILENAME);
1233 
1234  /* STEP 2: Figure if we'll be using a key or blob+constraint */
1235  if (uniq_tuple_length_arg >= CONVERT_IF_BIGGER_TO_BLOB)
1236  using_unique_constraint= true;
1237 
1238  /* STEP 3: Allocate memory for temptable description */
1239  init_sql_alloc(&own_root, TABLE_ALLOC_BLOCK_SIZE, 0);
1240  if (!multi_alloc_root(&own_root,
1241  &table, sizeof(*table),
1242  &share, sizeof(*share),
1243  &reg_field, sizeof(Field*) * (1+1),
1244  &blob_field, sizeof(uint)*2,
1245  &keyinfo, sizeof(*keyinfo),
1246  &key_part_info, sizeof(*key_part_info) * 2,
1247  &start_recinfo,
1248  sizeof(*recinfo)*(1*2+4),
1249  &tmpname, (uint) strlen(path)+1,
1250  &group_buff, (!using_unique_constraint ?
1251  uniq_tuple_length_arg : 0),
1252  &bitmaps, bitmap_buffer_size(1)*2,
1253  NullS))
1254  {
1255  if (temp_pool_slot != MY_BIT_NONE)
1256  bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
1257  DBUG_RETURN(NULL);
1258  }
1259  strmov(tmpname,path);
1260 
1261 
1262  /* STEP 4: Create TABLE description */
1263  memset(table, 0, sizeof(*table));
1264  memset(reg_field, 0, sizeof(Field*)*2);
1265 
1266  table->mem_root= own_root;
1267  mem_root_save= thd->mem_root;
1268  thd->mem_root= &table->mem_root;
1269 
1270  table->field=reg_field;
1271  table->alias= "weedout-tmp";
1272  table->reginfo.lock_type=TL_WRITE; /* Will be updated */
1273  table->db_stat=HA_OPEN_KEYFILE+HA_OPEN_RNDFILE;
1274  table->map=1;
1275  table->temp_pool_slot = temp_pool_slot;
1276  table->copy_blobs= 1;
1277  table->in_use= thd;
1278  table->quick_keys.init();
1279  table->possible_quick_keys.init();
1280  table->covering_keys.init();
1281  table->keys_in_use_for_query.init();
1282 
1283  table->s= share;
1284  init_tmp_table_share(thd, share, "", 0, tmpname, tmpname);
1285  share->blob_field= blob_field;
1286  share->db_low_byte_first=1; // True for HEAP and MyISAM
1287  share->table_charset= NULL;
1288  share->primary_key= MAX_KEY; // Indicate no primary key
1289  share->keys_for_keyread.init();
1290  share->keys_in_use.init();
1291 
1292  /* Create the field */
1293  {
1294  /*
1295  For the sake of uniformity, always use Field_varstring (altough we could
1296  use Field_string for shorter keys)
1297  */
1298  field= new Field_varstring(uniq_tuple_length_arg, FALSE, "rowids", share,
1299  &my_charset_bin);
1300  if (!field)
1301  DBUG_RETURN(0);
1302  field->table= table;
1303  field->unireg_check= Field::NONE;
1304  field->flags= (NOT_NULL_FLAG | BINARY_FLAG | NO_DEFAULT_VALUE_FLAG);
1305  field->reset_fields();
1306  field->init(table);
1307  field->orig_table= NULL;
1308 
1309  field->field_index= 0;
1310 
1311  *(reg_field++)= field;
1312  *blob_field= 0;
1313  *reg_field= 0;
1314 
1315  share->fields= 1;
1316  share->blob_fields= 0;
1317  }
1318 
1319  uint reclength= field->pack_length();
1320  if (using_unique_constraint)
1321  {
1322  share->db_plugin= ha_lock_engine(0, myisam_hton);
1323  table->file= get_new_handler(share, &table->mem_root,
1324  share->db_type());
1325  }
1326  else
1327  {
1328  share->db_plugin= ha_lock_engine(0, heap_hton);
1329  table->file= get_new_handler(share, &table->mem_root,
1330  share->db_type());
1331  }
1332  if (!table->file)
1333  goto err;
1334 
1335  if (table->file->set_ha_share_ref(&share->ha_share))
1336  {
1337  delete table->file;
1338  goto err;
1339  }
1340 
1341  null_count=1;
1342 
1343  null_pack_length= 1;
1344  reclength += null_pack_length;
1345 
1346  share->reclength= reclength;
1347  {
1348  uint alloc_length=ALIGN_SIZE(share->reclength + MI_UNIQUE_HASH_LENGTH+1);
1349  share->rec_buff_length= alloc_length;
1350  if (!(table->record[0]= (uchar*)
1351  alloc_root(&table->mem_root, alloc_length*3)))
1352  goto err;
1353  table->record[1]= table->record[0]+alloc_length;
1354  share->default_values= table->record[1]+alloc_length;
1355  }
1356  setup_tmp_table_column_bitmaps(table, bitmaps);
1357 
1358  recinfo= start_recinfo;
1359  null_flags=(uchar*) table->record[0];
1360 
1361  {
1362  /* Table description for the NULL bits */
1363  memset(recinfo, 0, sizeof(*recinfo));
1364  recinfo->type= FIELD_NORMAL;
1365  recinfo->length= null_pack_length;
1366  recinfo++;
1367  memset(null_flags, 255, null_pack_length); // Set null fields
1368 
1369  table->null_flags= (uchar*) table->record[0];
1370  share->null_fields= null_count;
1371  share->null_bytes= null_pack_length;
1372  }
1373  null_count=1;
1374 
1375  {
1376  /* Table description for the concatenated rowid column */
1377  memset(recinfo, 0, sizeof(*recinfo));
1378  /*
1379  Don't care about packing the VARCHAR since it's only a
1380  concatenation of rowids. @see create_tmp_table() for how
1381  packed VARCHARs can be achieved
1382  */
1383  recinfo->type= FIELD_NORMAL;
1384  recinfo->length= field->pack_length();
1385 
1386  field->move_field(table->record[0] + null_pack_length, 0, 0);
1387  field->reset();
1388  field->table_name= &table->alias;
1389  }
1390 
1391  if (thd->variables.tmp_table_size == ~ (ulonglong) 0) // No limit
1392  share->max_rows= ~(ha_rows) 0;
1393  else
1394  share->max_rows= (ha_rows) (((share->db_type() == heap_hton) ?
1395  min(thd->variables.tmp_table_size,
1396  thd->variables.max_heap_table_size) :
1397  thd->variables.tmp_table_size) /
1398  share->reclength);
1399  set_if_bigger(share->max_rows,1); // For dummy start options
1400 
1401 
1402  if (TRUE)
1403  {
1404  DBUG_PRINT("info",("Creating group key in temporary table"));
1405  share->keys=1;
1406  share->uniques= test(using_unique_constraint);
1407  table->key_info= table->s->key_info= keyinfo;
1408  keyinfo->key_part=key_part_info;
1409  keyinfo->actual_flags= keyinfo->flags= HA_NOSAME;
1410  keyinfo->usable_key_parts= keyinfo->user_defined_key_parts= 1;
1411  keyinfo->actual_key_parts= keyinfo->user_defined_key_parts;
1412  keyinfo->key_length=0;
1413  keyinfo->rec_per_key=0;
1414  keyinfo->algorithm= HA_KEY_ALG_UNDEF;
1415  keyinfo->name= (char*) "weedout_key";
1416  {
1417  key_part_info->null_bit=0;
1418  key_part_info->field= field;
1419  key_part_info->offset= field->offset(table->record[0]);
1420  key_part_info->length= (uint16) field->key_length();
1421  key_part_info->type= (uint8) field->key_type();
1422  key_part_info->key_type = FIELDFLAG_BINARY;
1423  if (!using_unique_constraint)
1424  {
1425  key_field= field->new_key_field(thd->mem_root, table, group_buff);
1426  if (!key_field)
1427  goto err;
1428  key_part_info->key_part_flag|= HA_END_SPACE_ARE_EQUAL; //todo need this?
1429  }
1430  keyinfo->key_length+= key_part_info->length;
1431  }
1432  }
1433 
1434  if (thd->is_fatal_error) // If end of memory
1435  goto err;
1436  share->db_record_offset= 1;
1437  if (share->db_type() == myisam_hton)
1438  recinfo++;
1439  if (instantiate_tmp_table(table, keyinfo, start_recinfo, &recinfo,
1440  0, 0, &thd->opt_trace))
1441  goto err;
1442 
1443  sjtbl->start_recinfo= start_recinfo;
1444  sjtbl->recinfo= recinfo;
1445 
1446  thd->mem_root= mem_root_save;
1447  DBUG_RETURN(table);
1448 
1449 err:
1450  thd->mem_root= mem_root_save;
1451  free_tmp_table(thd,table); /* purecov: inspected */
1452  if (temp_pool_slot != MY_BIT_NONE)
1453  bitmap_lock_clear_bit(&temp_pool, temp_pool_slot);
1454  DBUG_RETURN(NULL); /* purecov: inspected */
1455 }
1456 
1457 
1458 /****************************************************************************/
1459 
1479 TABLE *create_virtual_tmp_table(THD *thd, List<Create_field> &field_list)
1480 {
1481  uint field_count= field_list.elements;
1482  uint blob_count= 0;
1483  Field **field;
1484  Create_field *cdef; /* column definition */
1485  uint record_length= 0;
1486  uint null_count= 0; /* number of columns which may be null */
1487  uint null_pack_length; /* NULL representation array length */
1488  uint *blob_field;
1489  uchar *bitmaps;
1490  TABLE *table;
1491  TABLE_SHARE *share;
1492 
1493  if (!multi_alloc_root(thd->mem_root,
1494  &table, sizeof(*table),
1495  &share, sizeof(*share),
1496  &field, (field_count + 1) * sizeof(Field*),
1497  &blob_field, (field_count+1) *sizeof(uint),
1498  &bitmaps, bitmap_buffer_size(field_count)*2,
1499  NullS))
1500  return 0;
1501 
1502  memset(table, 0, sizeof(*table));
1503  memset(share, 0, sizeof(*share));
1504  table->field= field;
1505  table->s= share;
1506  table->temp_pool_slot= MY_BIT_NONE;
1507  share->blob_field= blob_field;
1508  share->fields= field_count;
1509  share->db_low_byte_first=1; // True for HEAP and MyISAM
1510  setup_tmp_table_column_bitmaps(table, bitmaps);
1511 
1512  /* Create all fields and calculate the total length of record */
1513  List_iterator_fast<Create_field> it(field_list);
1514  while ((cdef= it++))
1515  {
1516  *field= make_field(share, 0, cdef->length,
1517  (uchar*) (f_maybe_null(cdef->pack_flag) ? "" : 0),
1518  f_maybe_null(cdef->pack_flag) ? 1 : 0,
1519  cdef->pack_flag, cdef->sql_type, cdef->charset,
1520  cdef->geom_type, cdef->unireg_check,
1521  cdef->interval, cdef->field_name);
1522  if (!*field)
1523  goto error;
1524  (*field)->init(table);
1525  record_length+= (*field)->pack_length();
1526  if (! ((*field)->flags & NOT_NULL_FLAG))
1527  null_count++;
1528 
1529  if ((*field)->flags & BLOB_FLAG)
1530  share->blob_field[blob_count++]= (uint) (field - table->field);
1531 
1532  field++;
1533  }
1534  *field= NULL; /* mark the end of the list */
1535  share->blob_field[blob_count]= 0; /* mark the end of the list */
1536  share->blob_fields= blob_count;
1537 
1538  null_pack_length= (null_count + 7)/8;
1539  share->reclength= record_length + null_pack_length;
1540  share->rec_buff_length= ALIGN_SIZE(share->reclength + 1);
1541  table->record[0]= (uchar*) thd->alloc(share->rec_buff_length);
1542  if (!table->record[0])
1543  goto error;
1544 
1545  if (null_pack_length)
1546  {
1547  table->null_flags= (uchar*) table->record[0];
1548  share->null_fields= null_count;
1549  share->null_bytes= null_pack_length;
1550  }
1551 
1552  table->in_use= thd; /* field->reset() may access table->in_use */
1553  {
1554  /* Set up field pointers */
1555  uchar *null_pos= table->record[0];
1556  uchar *field_pos= null_pos + share->null_bytes;
1557  uint null_bit= 1;
1558 
1559  for (field= table->field; *field; ++field)
1560  {
1561  Field *cur_field= *field;
1562  if ((cur_field->flags & NOT_NULL_FLAG))
1563  cur_field->move_field(field_pos);
1564  else
1565  {
1566  cur_field->move_field(field_pos, (uchar*) null_pos, null_bit);
1567  null_bit<<= 1;
1568  if (null_bit == (uint8)1 << 8)
1569  {
1570  ++null_pos;
1571  null_bit= 1;
1572  }
1573  }
1574  if (cur_field->type() == MYSQL_TYPE_BIT &&
1575  cur_field->key_type() == HA_KEYTYPE_BIT)
1576  {
1577  /* This is a Field_bit since key_type is HA_KEYTYPE_BIT */
1578  static_cast<Field_bit*>(cur_field)->set_bit_ptr(null_pos, null_bit);
1579  null_bit+= cur_field->field_length & 7;
1580  if (null_bit > 7)
1581  {
1582  null_pos++;
1583  null_bit-= 8;
1584  }
1585  }
1586  cur_field->reset();
1587 
1588  field_pos+= cur_field->pack_length();
1589  }
1590  }
1591  return table;
1592 error:
1593  for (field= table->field; *field; ++field)
1594  delete *field; /* just invokes field destructor */
1595  return 0;
1596 }
1597 
1598 
1599 bool open_tmp_table(TABLE *table)
1600 {
1601  int error;
1602  if ((error=table->file->ha_open(table, table->s->table_name.str,O_RDWR,
1603  HA_OPEN_TMP_TABLE | HA_OPEN_INTERNAL_TABLE)))
1604  {
1605  table->file->print_error(error,MYF(0)); /* purecov: inspected */
1606  table->db_stat=0;
1607  return(1);
1608  }
1609  (void) table->file->extra(HA_EXTRA_QUICK); /* Faster */
1610 
1611  table->set_created();
1612 
1613  return false;
1614 }
1615 
1616 
1617 /*
1618  Create MyISAM temporary table
1619 
1620  SYNOPSIS
1621  create_myisam_tmp_table()
1622  table Table object that descrimes the table to be created
1623  keyinfo Description of the index (there is always one index)
1624  start_recinfo MyISAM's column descriptions
1625  recinfo INOUT End of MyISAM's column descriptions
1626  options Option bits
1627 
1628  DESCRIPTION
1629  Create a MyISAM temporary table according to passed description. The is
1630  assumed to have one unique index or constraint.
1631 
1632  The passed array or MI_COLUMNDEF structures must have this form:
1633 
1634  1. 1-byte column (afaiu for 'deleted' flag) (note maybe not 1-byte
1635  when there are many nullable columns)
1636  2. Table columns
1637  3. One free MI_COLUMNDEF element (*recinfo points here)
1638 
1639  This function may use the free element to create hash column for unique
1640  constraint.
1641 
1642  RETURN
1643  FALSE - OK
1644  TRUE - Error
1645 */
1646 
1647 bool create_myisam_tmp_table(TABLE *table, KEY *keyinfo,
1648  MI_COLUMNDEF *start_recinfo,
1649  MI_COLUMNDEF **recinfo,
1650  ulonglong options, my_bool big_tables)
1651 {
1652  int error;
1653  MI_KEYDEF keydef;
1654  MI_UNIQUEDEF uniquedef;
1655  TABLE_SHARE *share= table->s;
1656  DBUG_ENTER("create_myisam_tmp_table");
1657 
1658  if (share->keys)
1659  { // Get keys for ni_create
1660  bool using_unique_constraint=0;
1661  if (share->keys > 1)
1662  {
1663  DBUG_ASSERT(0); // This code can't handle more than 1 key
1664  share->keys= 1;
1665  }
1666  HA_KEYSEG *seg= (HA_KEYSEG*) alloc_root(&table->mem_root,
1667  sizeof(*seg) *
1668  keyinfo->user_defined_key_parts);
1669  if (!seg)
1670  goto err;
1671 
1672  memset(seg, 0, sizeof(*seg) * keyinfo->user_defined_key_parts);
1673  if (keyinfo->key_length >= table->file->max_key_length() ||
1674  keyinfo->user_defined_key_parts > table->file->max_key_parts() ||
1675  share->uniques)
1676  {
1677  /* Can't create a key; Make a unique constraint instead of a key */
1678  share->keys= 0;
1679  share->uniques= 1;
1680  using_unique_constraint=1;
1681  memset(&uniquedef, 0, sizeof(uniquedef));
1682  uniquedef.keysegs=keyinfo->user_defined_key_parts;
1683  uniquedef.seg=seg;
1684  uniquedef.null_are_equal=1;
1685 
1686  /* Create extra column for hash value */
1687  memset(*recinfo, 0, sizeof(**recinfo));
1688  (*recinfo)->type= FIELD_CHECK;
1689  (*recinfo)->length=MI_UNIQUE_HASH_LENGTH;
1690  (*recinfo)++;
1691  share->reclength+=MI_UNIQUE_HASH_LENGTH;
1692  }
1693  else
1694  {
1695  /* Create an unique key */
1696  memset(&keydef, 0, sizeof(keydef));
1697  keydef.flag= keyinfo->flags;
1698  keydef.keysegs= keyinfo->user_defined_key_parts;
1699  keydef.seg= seg;
1700  }
1701  for (uint i=0; i < keyinfo->user_defined_key_parts ; i++,seg++)
1702  {
1703  Field *field=keyinfo->key_part[i].field;
1704  seg->flag= 0;
1705  seg->language= field->charset()->number;
1706  seg->length= keyinfo->key_part[i].length;
1707  seg->start= keyinfo->key_part[i].offset;
1708  if (field->flags & BLOB_FLAG)
1709  {
1710  seg->type=
1711  ((keyinfo->key_part[i].key_type & FIELDFLAG_BINARY) ?
1712  HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2);
1713  seg->bit_start= (uint8)(field->pack_length() -
1714  portable_sizeof_char_ptr);
1715  seg->flag= HA_BLOB_PART;
1716  seg->length=0; // Whole blob in unique constraint
1717  }
1718  else
1719  {
1720  seg->type= keyinfo->key_part[i].type;
1721  /* Tell handler if it can do suffic space compression */
1722  if (field->real_type() == MYSQL_TYPE_STRING &&
1723  keyinfo->key_part[i].length > 4)
1724  seg->flag|= HA_SPACE_PACK;
1725  }
1726  if (!(field->flags & NOT_NULL_FLAG))
1727  {
1728  seg->null_bit= field->null_bit;
1729  seg->null_pos= field->null_offset();
1730  /*
1731  We are using a GROUP BY on something that contains NULL
1732  In this case we have to tell MyISAM that two NULL should
1733  on INSERT be regarded at the same value
1734  */
1735  if (!using_unique_constraint)
1736  keydef.flag|= HA_NULL_ARE_EQUAL;
1737  }
1738  }
1739  }
1740  MI_CREATE_INFO create_info;
1741  memset(&create_info, 0, sizeof(create_info));
1742 
1743  if (big_tables && !(options & SELECT_SMALL_RESULT))
1744  create_info.data_file_length= ~(ulonglong) 0;
1745 
1746  if ((error=mi_create(share->table_name.str, share->keys, &keydef,
1747  (uint) (*recinfo - start_recinfo),
1748  start_recinfo,
1749  share->uniques, &uniquedef,
1750  &create_info,
1751  HA_CREATE_TMP_TABLE | HA_CREATE_INTERNAL_TABLE |
1752  ((share->db_create_options & HA_OPTION_PACK_RECORD) ?
1753  HA_PACK_RECORD : 0)
1754  )))
1755  {
1756  table->file->print_error(error,MYF(0)); /* purecov: inspected */
1757  table->db_stat=0;
1758  goto err;
1759  }
1760  table->in_use->inc_status_created_tmp_disk_tables();
1761  share->db_record_offset= 1;
1762  DBUG_RETURN(0);
1763  err:
1764  DBUG_RETURN(1);
1765 }
1766 
1767 
1768 void trace_tmp_table(Opt_trace_context *trace, const TABLE *table)
1769 {
1770  Opt_trace_object trace_tmp(trace, "tmp_table_info");
1771  if (strlen(table->alias) != 0)
1772  trace_tmp.add_utf8_table(table);
1773  else
1774  trace_tmp.add_alnum("table", "intermediate_tmp_table");
1775 
1776  trace_tmp.add("row_length",table->s->reclength).
1777  add("key_length", table->s->key_info ?
1778  table->s->key_info->key_length : 0).
1779  add("unique_constraint", table->s->uniques ? true : false);
1780 
1781  if (table->s->db_type() == myisam_hton)
1782  {
1783  trace_tmp.add_alnum("location", "disk (MyISAM)");
1784  if (table->s->db_create_options & HA_OPTION_PACK_RECORD)
1785  trace_tmp.add_alnum("record_format", "packed");
1786  else
1787  trace_tmp.add_alnum("record_format", "fixed");
1788  }
1789  else
1790  {
1791  DBUG_ASSERT(table->s->db_type() == heap_hton);
1792  trace_tmp.add_alnum("location", "memory (heap)").
1793  add("row_limit_estimate", table->s->max_rows);
1794  }
1795 }
1796 
1817 bool instantiate_tmp_table(TABLE *table, KEY *keyinfo,
1818  MI_COLUMNDEF *start_recinfo,
1819  MI_COLUMNDEF **recinfo,
1820  ulonglong options, my_bool big_tables,
1821  Opt_trace_context *trace)
1822 {
1823  if (table->s->db_type() == myisam_hton)
1824  {
1825  if (create_myisam_tmp_table(table, keyinfo, start_recinfo, recinfo,
1826  options, big_tables))
1827  return TRUE;
1828  // Make empty record so random data is not written to disk
1829  empty_record(table);
1830  }
1831  if (open_tmp_table(table))
1832  return TRUE;
1833 
1834  if (unlikely(trace->is_started()))
1835  {
1836  Opt_trace_object wrapper(trace);
1837  Opt_trace_object convert(trace, "creating_tmp_table");
1838  trace_tmp_table(trace, table);
1839  }
1840  return FALSE;
1841 }
1842 
1843 void
1844 free_tmp_table(THD *thd, TABLE *entry)
1845 {
1846  MEM_ROOT own_root= entry->mem_root;
1847  const char *save_proc_info;
1848  DBUG_ENTER("free_tmp_table");
1849  DBUG_PRINT("enter",("table: %s",entry->alias));
1850 
1851  save_proc_info=thd->proc_info;
1852  THD_STAGE_INFO(thd, stage_removing_tmp_table);
1853 
1854  // Release latches since this can take a long time
1856 
1857  filesort_free_buffers(entry, true);
1858 
1859  if (entry->is_created())
1860  {
1861  if (entry->db_stat)
1862  entry->file->ha_drop_table(entry->s->table_name.str);
1863  else
1864  entry->file->ha_delete_table(entry->s->table_name.str);
1865  delete entry->file;
1866  entry->file= NULL;
1867 
1868  entry->set_deleted();
1869  }
1870  /* free blobs */
1871  for (Field **ptr=entry->field ; *ptr ; ptr++)
1872  (*ptr)->free();
1873  free_io_cache(entry);
1874 
1875  if (entry->temp_pool_slot != MY_BIT_NONE)
1876  bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot);
1877 
1878  plugin_unlock(0, entry->s->db_plugin);
1879 
1880  free_root(&own_root, MYF(0)); /* the table is allocated in its own root */
1881  thd_proc_info(thd, save_proc_info);
1882 
1883  DBUG_VOID_RETURN;
1884 }
1885 
1918 bool create_myisam_from_heap(THD *thd, TABLE *table,
1919  MI_COLUMNDEF *start_recinfo,
1920  MI_COLUMNDEF **recinfo,
1921  int error, bool ignore_last_dup,
1922  bool *is_duplicate)
1923 {
1924  TABLE new_table;
1925  TABLE_SHARE share;
1926  const char *save_proc_info;
1927  int write_err;
1928  DBUG_ENTER("create_myisam_from_heap");
1929 
1930  if (table->s->db_type() != heap_hton ||
1931  error != HA_ERR_RECORD_FILE_FULL)
1932  {
1933  /*
1934  We don't want this error to be converted to a warning, e.g. in case of
1935  INSERT IGNORE ... SELECT.
1936  */
1937  table->file->print_error(error, MYF(ME_FATALERROR));
1938  DBUG_RETURN(1);
1939  }
1940 
1941  // Release latches since this can take a long time
1943 
1944  new_table= *table;
1945  share= *table->s;
1946  share.ha_share= NULL;
1947  new_table.s= &share;
1948  new_table.s->db_plugin= ha_lock_engine(thd, myisam_hton);
1949  if (!(new_table.file= get_new_handler(&share, &new_table.mem_root,
1950  new_table.s->db_type())))
1951  DBUG_RETURN(1); // End of memory
1952  if (new_table.file->set_ha_share_ref(&share.ha_share))
1953  {
1954  delete new_table.file;
1955  DBUG_RETURN(1);
1956  }
1957  save_proc_info=thd->proc_info;
1958  THD_STAGE_INFO(thd, stage_converting_heap_to_myisam);
1959 
1960  if (create_myisam_tmp_table(&new_table, table->s->key_info,
1961  start_recinfo, recinfo,
1962  (thd->lex->select_lex.options |
1963  thd->variables.option_bits),
1964  thd->variables.big_tables))
1965  goto err2;
1966  if (open_tmp_table(&new_table))
1967  goto err1;
1968 
1969 
1970  if (unlikely(thd->opt_trace.is_started()))
1971  {
1972  Opt_trace_context * trace= &thd->opt_trace;
1973  Opt_trace_object wrapper(trace);
1974  Opt_trace_object convert(trace, "converting_tmp_table_to_myisam");
1975  DBUG_ASSERT(error == HA_ERR_RECORD_FILE_FULL);
1976  convert.add_alnum("cause", "memory_table_size_exceeded");
1977  trace_tmp_table(trace, &new_table);
1978  }
1979 
1980  if (table->file->indexes_are_disabled())
1981  new_table.file->ha_disable_indexes(HA_KEY_SWITCH_ALL);
1982  table->file->ha_index_or_rnd_end();
1983  if ((write_err= table->file->ha_rnd_init(1)))
1984  {
1985  table->file->print_error(write_err, MYF(ME_FATALERROR));
1986  write_err= 0;
1987  goto err;
1988  }
1989  if (table->no_rows)
1990  {
1991  new_table.file->extra(HA_EXTRA_NO_ROWS);
1992  new_table.no_rows=1;
1993  }
1994 
1995 #ifdef TO_BE_DONE_LATER_IN_4_1
1996  /*
1997  To use start_bulk_insert() (which is new in 4.1) we need to find
1998  all places where a corresponding end_bulk_insert() should be put.
1999  */
2000  table->file->info(HA_STATUS_VARIABLE); /* update table->file->stats.records */
2001  new_table.file->ha_start_bulk_insert(table->file->stats.records);
2002 #else
2003  /* HA_EXTRA_WRITE_CACHE can stay until close, no need to disable it */
2004  new_table.file->extra(HA_EXTRA_WRITE_CACHE);
2005 #endif
2006 
2007  /*
2008  copy all old rows from heap table to MyISAM table
2009  This is the only code that uses record[1] to read/write but this
2010  is safe as this is a temporary MyISAM table without timestamp/autoincrement
2011  or partitioning.
2012  */
2013  while (!table->file->ha_rnd_next(new_table.record[1]))
2014  {
2015  write_err= new_table.file->ha_write_row(new_table.record[1]);
2016  DBUG_EXECUTE_IF("raise_error", write_err= HA_ERR_FOUND_DUPP_KEY ;);
2017  if (write_err)
2018  goto err;
2019  }
2020  /* copy row that filled HEAP table */
2021  if ((write_err=new_table.file->ha_write_row(table->record[0])))
2022  {
2023  if (new_table.file->is_fatal_error(write_err, HA_CHECK_DUP) ||
2024  !ignore_last_dup)
2025  goto err;
2026  if (is_duplicate)
2027  *is_duplicate= TRUE;
2028  }
2029  else
2030  {
2031  if (is_duplicate)
2032  *is_duplicate= FALSE;
2033  }
2034 
2035  /* remove heap table and change to use myisam table */
2036  (void) table->file->ha_rnd_end();
2037  (void) table->file->ha_close(); // This deletes the table !
2038  delete table->file;
2039  table->file=0;
2040  plugin_unlock(0, table->s->db_plugin);
2041  share.db_plugin= my_plugin_lock(0, &share.db_plugin);
2042  new_table.s= table->s; // Keep old share
2043  *table= new_table;
2044  *table->s= share;
2045  /* Update quick select, if any. */
2046  {
2047  JOIN_TAB *tab= table->reginfo.join_tab;
2048  if (tab && tab->select && tab->select->quick)
2049  {
2050  /*
2051  This could happen only with result of derived table/view
2052  materialization.
2053  */
2054  DBUG_ASSERT(table->pos_in_table_list &&
2055  table->pos_in_table_list->uses_materialization());
2056  tab->select->quick->set_handler(table->file);
2057  }
2058  }
2059  table->file->change_table_ptr(table, table->s);
2060  table->use_all_columns();
2061  if (save_proc_info)
2062  thd_proc_info(thd, (!strcmp(save_proc_info,"Copying to tmp table") ?
2063  "Copying to tmp table on disk" : save_proc_info));
2064  DBUG_RETURN(0);
2065 
2066  err:
2067  if (write_err)
2068  {
2069  DBUG_PRINT("error",("Got error: %d",write_err));
2070  new_table.file->print_error(write_err, MYF(0));
2071  }
2072  if (table->file->inited)
2073  (void) table->file->ha_rnd_end();
2074  (void) new_table.file->ha_close();
2075  err1:
2076  new_table.file->ha_delete_table(new_table.s->table_name.str);
2077  err2:
2078  delete new_table.file;
2079  thd_proc_info(thd, save_proc_info);
2080  table->mem_root= new_table.mem_root;
2081  DBUG_RETURN(1);
2082 }
2083