MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
item_sum.cc
Go to the documentation of this file.
1 /* Copyright (c) 2000, 2013 Oracle and/or its affiliates. All
2  rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16 
17 
25 #include "sql_priv.h"
26 #include "sql_select.h"
27 #include "sql_tmp_table.h" // create_tmp_table
28 #include "sql_resolver.h" // setup_order, fix_inner_refs
29 #include "sql_optimizer.h" // JOIN
30 
31 using std::min;
32 using std::max;
33 
39 ulonglong Item_sum::ram_limitation(THD *thd)
40 {
41  return min(thd->variables.tmp_table_size,
42  thd->variables.max_heap_table_size);
43 }
44 
45 
69 {
70  if (!thd->lex->allow_sum_func)
71  {
72  my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE),
73  MYF(0));
74  return TRUE;
75  }
76  /* Set a reference to the nesting set function if there is any */
77  in_sum_func= thd->lex->in_sum_func;
78  /* Save a pointer to object to be used in items for nested set functions */
79  thd->lex->in_sum_func= this;
80  nest_level= thd->lex->current_select->nest_level;
81  ref_by= 0;
82  aggr_level= -1;
83  aggr_sel= NULL;
84  max_arg_level= -1;
85  max_sum_func_level= -1;
86  outer_fields.empty();
87  return FALSE;
88 }
89 
139 bool Item_sum::check_sum_func(THD *thd, Item **ref)
140 {
141  bool invalid= FALSE;
142  nesting_map allow_sum_func= thd->lex->allow_sum_func;
143  /*
144  The value of max_arg_level is updated if an argument of the set function
145  contains a column reference resolved against a subquery whose level is
146  greater than the current value of max_arg_level.
147  max_arg_level cannot be greater than nest level.
148  nest level is always >= 0
149  */
150  if (nest_level == max_arg_level)
151  {
152  /*
153  The function must be aggregated in the current subquery,
154  If it is there under a construct where it is not allowed
155  we report an error.
156  */
157  invalid= !(allow_sum_func & ((nesting_map)1 << max_arg_level));
158  }
159  else if (max_arg_level >= 0 ||
160  !(allow_sum_func & ((nesting_map)1 << nest_level)))
161  {
162  /*
163  The set function can be aggregated only in outer subqueries.
164  Try to find a subquery where it can be aggregated;
165  If we fail to find such a subquery report an error.
166  */
167  if (register_sum_func(thd, ref))
168  return TRUE;
169  invalid= aggr_level < 0 &&
170  !(allow_sum_func & ((nesting_map)1 << nest_level));
171  if (!invalid && thd->variables.sql_mode & MODE_ANSI)
172  invalid= aggr_level < 0 && max_arg_level < nest_level;
173  }
174  if (!invalid && aggr_level < 0)
175  {
176  aggr_level= nest_level;
177  aggr_sel= thd->lex->current_select;
178  }
179  /*
180  By this moment we either found a subquery where the set function is
181  to be aggregated and assigned a value that is >= 0 to aggr_level,
182  or set the value of 'invalid' to TRUE to report later an error.
183  */
184  /*
185  Additionally we have to check whether possible nested set functions
186  are acceptable here: they are not, if the level of aggregation of
187  some of them is less than aggr_level.
188  */
189  if (!invalid)
190  invalid= aggr_level <= max_sum_func_level;
191  if (invalid)
192  {
193  my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE),
194  MYF(0));
195  return TRUE;
196  }
197 
198  if (in_sum_func)
199  {
200  /*
201  If the set function is nested adjust the value of
202  max_sum_func_level for the nesting set function.
203  We take into account only enclosed set functions that are to be
204  aggregated on the same level or above of the nest level of
205  the enclosing set function.
206  But we must always pass up the max_sum_func_level because it is
207  the maximum nested level of all directly and indirectly enclosed
208  set functions. We must do that even for set functions that are
209  aggregated inside of their enclosing set function's nest level
210  because the enclosing function may contain another enclosing
211  function that is to be aggregated outside or on the same level
212  as its parent's nest level.
213  */
214  if (in_sum_func->nest_level >= aggr_level)
215  set_if_bigger(in_sum_func->max_sum_func_level, aggr_level);
216  set_if_bigger(in_sum_func->max_sum_func_level, max_sum_func_level);
217  }
218 
219  /*
220  Check that non-aggregated fields and sum functions aren't mixed in the
221  same select in the ONLY_FULL_GROUP_BY mode.
222  */
223  if (outer_fields.elements)
224  {
225  Item_field *field;
226  /*
227  Here we compare the nesting level of the select to which an outer field
228  belongs to with the aggregation level of the sum function. All fields in
229  the outer_fields list are checked.
230 
231  If the nesting level is equal to the aggregation level then the field is
232  aggregated by this sum function.
233  If the nesting level is less than the aggregation level then the field
234  belongs to an outer select. In this case if there is an embedding sum
235  function add current field to functions outer_fields list. If there is
236  no embedding function then the current field treated as non aggregated
237  and the select it belongs to is marked accordingly.
238  If the nesting level is greater than the aggregation level then it means
239  that this field was added by an inner sum function.
240  Consider an example:
241 
242  select avg ( <-- we are here, checking outer.f1
243  select (
244  select sum(outer.f1 + inner.f1) from inner
245  ) from outer)
246  from most_outer;
247 
248  In this case we check that no aggregate functions are used in the
249  select the field belongs to. If there are some then an error is
250  raised.
251  */
252  List_iterator<Item_field> of(outer_fields);
253  while ((field= of++))
254  {
255  SELECT_LEX *sel= field->cached_table->select_lex;
256  if (sel->nest_level < aggr_level)
257  {
258  if (in_sum_func)
259  {
260  /*
261  Let upper function decide whether this field is a non
262  aggregated one.
263  */
264  in_sum_func->outer_fields.push_back(field);
265  }
266  else
267  sel->set_non_agg_field_used(true);
268  }
269  if (sel->nest_level > aggr_level &&
270  (sel->agg_func_used()) &&
271  !sel->group_list.elements)
272  {
273  my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
274  ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
275  return TRUE;
276  }
277  }
278  }
279  aggr_sel->set_agg_func_used(true);
280  update_used_tables();
281  thd->lex->in_sum_func= in_sum_func;
282  return FALSE;
283 }
284 
310 bool Item_sum::register_sum_func(THD *thd, Item **ref)
311 {
312  nesting_map allow_sum_func= thd->lex->allow_sum_func;
313 
314  // Find the outer-most query block where this function can be aggregated.
315 
316  for (SELECT_LEX *sl= thd->lex->current_select->outer_select();
317  sl && sl->nest_level >= max_arg_level;
318  sl= sl->outer_select())
319  {
320  if (allow_sum_func & ((nesting_map)1 << sl->nest_level))
321  {
322  aggr_level= sl->nest_level;
323  aggr_sel= sl;
324  }
325  }
326 
327  if (aggr_level >= 0)
328  {
329  ref_by= ref;
330  /* Add the object to the list of registered objects assigned to aggr_sel */
331  if (!aggr_sel->inner_sum_func_list)
332  next= this;
333  else
334  {
335  next= aggr_sel->inner_sum_func_list->next;
336  aggr_sel->inner_sum_func_list->next= this;
337  }
338  aggr_sel->inner_sum_func_list= this;
339  aggr_sel->with_sum_func= true;
340 
341  /*
342  Mark Item_subselect(s) as containing aggregate function all the way up
343  to aggregate function's calculation context.
344  Note that we must not mark the Item of calculation context itself
345  because with_sum_func on the calculation context st_select_lex is
346  already set above.
347 
348  with_sum_func being set for an Item means that this Item refers
349  (somewhere in it, e.g. one of its arguments if it's a function) directly
350  or through intermediate items to an aggregate function that is calculated
351  in a context "outside" of the Item (e.g. in the current or outer select).
352 
353  with_sum_func being set for an st_select_lex means that this query block
354  has aggregate functions directly referenced (i.e. not through a subquery).
355  */
356  for (SELECT_LEX *sl= thd->lex->current_select;
357  sl && sl != aggr_sel && sl->master_unit()->item;
358  sl= sl->outer_select())
359  sl->master_unit()->item->with_sum_func= true;
360  }
361  thd->lex->current_select->mark_as_dependent(aggr_sel);
362  return false;
363 }
364 
365 
366 Item_sum::Item_sum(List<Item> &list) :next(NULL), arg_count(list.elements),
367  forced_const(FALSE)
368 {
369  if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
370  {
371  uint i=0;
372  List_iterator_fast<Item> li(list);
373  Item *item;
374 
375  while ((item=li++))
376  {
377  args[i++]= item;
378  }
379  }
380  if (!(orig_args= (Item **) sql_alloc(sizeof(Item *) * arg_count)))
381  {
382  args= NULL;
383  }
384  mark_as_sum_func();
385  init_aggregator();
386  list.empty(); // Fields are used
387 }
388 
389 
394 Item_sum::Item_sum(THD *thd, Item_sum *item):
395  Item_result_field(thd, item),
396  next(NULL),
397  aggr_sel(item->aggr_sel),
398  nest_level(item->nest_level), aggr_level(item->aggr_level),
399  quick_group(item->quick_group),
400  arg_count(item->arg_count), orig_args(NULL),
401  used_tables_cache(item->used_tables_cache),
402  forced_const(item->forced_const)
403 {
404  if (arg_count <= 2)
405  {
406  args=tmp_args;
407  orig_args=tmp_orig_args;
408  }
409  else
410  {
411  if (!(args= (Item**) thd->alloc(sizeof(Item*)*arg_count)))
412  return;
413  if (!(orig_args= (Item**) thd->alloc(sizeof(Item*)*arg_count)))
414  return;
415  }
416  memcpy(args, item->args, sizeof(Item*)*arg_count);
417  memcpy(orig_args, item->orig_args, sizeof(Item*)*arg_count);
418  init_aggregator();
419  with_distinct= item->with_distinct;
420  if (item->aggr)
421  set_aggregator(item->aggr->Aggrtype());
422 }
423 
424 
425 void Item_sum::mark_as_sum_func()
426 {
427  SELECT_LEX *cur_select= current_thd->lex->current_select;
428  cur_select->n_sum_items++;
429  cur_select->with_sum_func= 1;
430  with_sum_func= 1;
431 }
432 
433 
434 void Item_sum::print(String *str, enum_query_type query_type)
435 {
436  /* orig_args is not filled with valid values until fix_fields() */
437  Item **pargs= fixed ? orig_args : args;
438  str->append(func_name());
439  for (uint i=0 ; i < arg_count ; i++)
440  {
441  if (i)
442  str->append(',');
443  pargs[i]->print(str, query_type);
444  }
445  str->append(')');
446 }
447 
448 void Item_sum::fix_num_length_and_dec()
449 {
450  decimals=0;
451  for (uint i=0 ; i < arg_count ; i++)
452  set_if_bigger(decimals,args[i]->decimals);
453  max_length=float_length(decimals);
454 }
455 
456 Item *Item_sum::get_tmp_table_item(THD *thd)
457 {
458  Item_sum* sum_item= (Item_sum *) copy_or_same(thd);
459  if (sum_item && sum_item->result_field) // If not a const sum func
460  {
461  Field *result_field_tmp= sum_item->result_field;
462  for (uint i=0 ; i < sum_item->arg_count ; i++)
463  {
464  Item *arg= sum_item->args[i];
465  if (!arg->const_item())
466  {
467  if (arg->type() == Item::FIELD_ITEM)
468  ((Item_field*) arg)->field= result_field_tmp++;
469  else
470  sum_item->args[i]= new Item_field(result_field_tmp++);
471  }
472  }
473  }
474  return sum_item;
475 }
476 
477 
478 bool Item_sum::walk (Item_processor processor, bool walk_subquery,
479  uchar *argument)
480 {
481  if (arg_count)
482  {
483  Item **arg,**arg_end;
484  for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
485  {
486  if ((*arg)->walk(processor, walk_subquery, argument))
487  return 1;
488  }
489  }
490  return (this->*processor)(argument);
491 }
492 
493 
513 {
514  /*
515  Don't do anything if
516  1) this is an unresolved item (This may happen if an
517  expression occurs twice in the same query. In that case, the
518  whole item tree for the second occurence is replaced by the
519  item tree for the first occurence, without calling fix_fields()
520  on the second tree. Therefore there's nothing to clean up.), or
521  2) there is no inner_sum_func_list, or
522  3) the item is not an element in the inner_sum_func_list.
523  */
524  if (!fixed || // 1
525  aggr_sel == NULL || aggr_sel->inner_sum_func_list == NULL || // 2
526  next == NULL) // 3
527  return false;
528 
529  if (next == this)
530  aggr_sel->inner_sum_func_list= NULL;
531  else
532  {
533  Item_sum *prev;
534  for (prev= this; prev->next != this; prev= prev->next)
535  ;
536  prev->next= next;
537  if (aggr_sel->inner_sum_func_list == this)
538  aggr_sel->inner_sum_func_list= prev;
539  }
540 
541  return false;
542 }
543 
544 
545 Field *Item_sum::create_tmp_field(bool group, TABLE *table)
546 {
547  Field *field;
548  switch (result_type()) {
549  case REAL_RESULT:
550  field= new Field_double(max_length, maybe_null, item_name.ptr(), decimals, TRUE);
551  break;
552  case INT_RESULT:
553  field= new Field_longlong(max_length, maybe_null, item_name.ptr(), unsigned_flag);
554  break;
555  case STRING_RESULT:
556  return make_string_field(table);
557  case DECIMAL_RESULT:
558  field= Field_new_decimal::create_from_item(this);
559  break;
560  case ROW_RESULT:
561  default:
562  // This case should never be choosen
563  DBUG_ASSERT(0);
564  return 0;
565  }
566  if (field)
567  field->init(table);
568  return field;
569 }
570 
571 
572 void Item_sum::update_used_tables ()
573 {
574  if (!forced_const)
575  {
576  used_tables_cache= 0;
577  with_subselect= false;
578  with_stored_program= false;
579  for (uint i=0 ; i < arg_count ; i++)
580  {
581  args[i]->update_used_tables();
582  used_tables_cache|= args[i]->used_tables();
583  with_subselect|= args[i]->has_subquery();
584  with_stored_program|= args[i]->has_stored_program();
585  }
586 
587  used_tables_cache&= PSEUDO_TABLE_BITS;
588 
589  /* the aggregate function is aggregated into its local context */
590  used_tables_cache|= ((table_map)1 << aggr_sel->join->tables) - 1;
591  }
592 }
593 
594 
595 Item *Item_sum::set_arg(uint i, THD *thd, Item *new_val)
596 {
597  thd->change_item_tree(args + i, new_val);
598  return new_val;
599 }
600 
601 
602 int Item_sum::set_aggregator(Aggregator::Aggregator_type aggregator)
603 {
604  /*
605  Dependent subselects may be executed multiple times, making
606  set_aggregator to be called multiple times. The aggregator type
607  will be the same, but it needs to be reset so that it is
608  reevaluated with the new dependent data.
609  This function may also be called multiple times during query optimization.
610  In this case, the type may change, so we delete the old aggregator,
611  and create a new one.
612  */
613  if (aggr && aggregator == aggr->Aggrtype())
614  {
615  aggr->clear();
616  return FALSE;
617  }
618 
619  delete aggr;
620  switch (aggregator)
621  {
622  case Aggregator::DISTINCT_AGGREGATOR:
623  aggr= new Aggregator_distinct(this);
624  break;
625  case Aggregator::SIMPLE_AGGREGATOR:
626  aggr= new Aggregator_simple(this);
627  break;
628  };
629  return aggr ? FALSE : TRUE;
630 }
631 
632 
633 void Item_sum::cleanup()
634 {
635  if (aggr)
636  {
637  delete aggr;
638  aggr= NULL;
639  }
640  Item_result_field::cleanup();
641  forced_const= FALSE;
642 }
643 
644 
660 static int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2)
661 {
662  Field *f= (Field*) arg;
663  return f->cmp(key1, key2);
664 }
665 
666 
682 int Aggregator_distinct::composite_key_cmp(void* arg, uchar* key1, uchar* key2)
683 {
685  Field **field = aggr->table->field;
686  Field **field_end= field + aggr->table->s->fields;
687  uint32 *lengths=aggr->field_lengths;
688  for (; field < field_end; ++field)
689  {
690  Field* f = *field;
691  int len = *lengths++;
692  int res = f->cmp(key1, key2);
693  if (res)
694  return res;
695  key1 += len;
696  key2 += len;
697  }
698  return 0;
699 }
700 
701 
702 static enum enum_field_types
703 calc_tmp_field_type(enum enum_field_types table_field_type,
704  Item_result result_type)
705 {
706  /* Adjust tmp table type according to the chosen aggregation type */
707  switch (result_type) {
708  case STRING_RESULT:
709  case REAL_RESULT:
710  if (table_field_type != MYSQL_TYPE_FLOAT)
711  table_field_type= MYSQL_TYPE_DOUBLE;
712  break;
713  case INT_RESULT:
714  table_field_type= MYSQL_TYPE_LONGLONG;
715  /* fallthrough */
716  case DECIMAL_RESULT:
717  if (table_field_type != MYSQL_TYPE_LONGLONG)
718  table_field_type= MYSQL_TYPE_NEWDECIMAL;
719  break;
720  case ROW_RESULT:
721  default:
722  DBUG_ASSERT(0);
723  }
724  return table_field_type;
725 }
726 
727 
728 /***************************************************************************/
729 
730 C_MODE_START
731 
732 /* Declarations for auxilary C-callbacks */
733 
734 static int simple_raw_key_cmp(const void* arg,
735  const void* key1, const void* key2)
736 {
737  return memcmp(key1, key2, *(const uint *) arg);
738 }
739 
740 
741 static int item_sum_distinct_walk(void *element, element_count num_of_dups,
742  void *item)
743 {
744  return ((Aggregator_distinct*) (item))->unique_walk_function(element);
745 }
746 
747 C_MODE_END
748 
749 /***************************************************************************/
765 {
766  endup_done= FALSE;
767  /*
768  Setup can be called twice for ROLLUP items. This is a bug.
769  Please add DBUG_ASSERT(tree == 0) here when it's fixed.
770  */
771  if (tree || table || tmp_table_param)
772  return FALSE;
773 
774  if (item_sum->setup(thd))
775  return TRUE;
776  if (item_sum->sum_func() == Item_sum::COUNT_FUNC ||
777  item_sum->sum_func() == Item_sum::COUNT_DISTINCT_FUNC)
778  {
779  List<Item> list;
780  SELECT_LEX *select_lex= thd->lex->current_select;
781 
782  if (!(tmp_table_param= new TMP_TABLE_PARAM))
783  return TRUE;
784 
785  /* Create a table with an unique key over all parameters */
786  for (uint i=0; i < item_sum->get_arg_count() ; i++)
787  {
788  Item *item=item_sum->get_arg(i);
789  if (list.push_back(item))
790  return TRUE; // End of memory
791  if (item->const_item() && item->is_null())
792  always_null= true;
793  }
794  if (always_null)
795  return FALSE;
796  count_field_types(select_lex, tmp_table_param, list, 0);
797  tmp_table_param->force_copy_fields= item_sum->has_force_copy_fields();
798  DBUG_ASSERT(table == 0);
799  /*
800  Make create_tmp_table() convert BIT columns to BIGINT.
801  This is needed because BIT fields store parts of their data in table's
802  null bits, and we don't have methods to compare two table records, which
803  is needed by Unique which is used when HEAP table is used.
804  */
805  {
806  List_iterator_fast<Item> li(list);
807  Item *item;
808  while ((item= li++))
809  {
810  if (item->type() == Item::FIELD_ITEM &&
811  ((Item_field*)item)->field->type() == FIELD_TYPE_BIT)
812  item->marker=4;
813  }
814  }
815  if (!(table= create_tmp_table(thd, tmp_table_param, list, (ORDER*) 0, 1,
816  0,
817  (select_lex->options | thd->variables.option_bits),
818  HA_POS_ERROR, "")))
819  return TRUE;
820  table->file->extra(HA_EXTRA_NO_ROWS); // Don't update rows
821  table->no_rows=1;
822 
823  if (table->s->db_type() == heap_hton)
824  {
825  /*
826  No blobs, otherwise it would have been MyISAM: set up a compare
827  function and its arguments to use with Unique.
828  */
829  qsort_cmp2 compare_key;
830  void* cmp_arg;
831  Field **field= table->field;
832  Field **field_end= field + table->s->fields;
833  bool all_binary= TRUE;
834 
835  for (tree_key_length= 0; field < field_end; ++field)
836  {
837  Field *f= *field;
838  enum enum_field_types type= f->type();
839  tree_key_length+= f->pack_length();
840  if ((type == MYSQL_TYPE_VARCHAR) ||
841  (!f->binary() && (type == MYSQL_TYPE_STRING ||
842  type == MYSQL_TYPE_VAR_STRING)))
843  {
844  all_binary= FALSE;
845  break;
846  }
847  }
848  if (all_binary)
849  {
850  cmp_arg= (void*) &tree_key_length;
851  compare_key= (qsort_cmp2) simple_raw_key_cmp;
852  }
853  else
854  {
855  if (table->s->fields == 1)
856  {
857  /*
858  If we have only one field, which is the most common use of
859  count(distinct), it is much faster to use a simpler key
860  compare method that can take advantage of not having to worry
861  about other fields.
862  */
863  compare_key= (qsort_cmp2) simple_str_key_cmp;
864  cmp_arg= (void*) table->field[0];
865  /* tree_key_length has been set already */
866  }
867  else
868  {
869  uint32 *length;
870  compare_key= (qsort_cmp2) composite_key_cmp;
871  cmp_arg= (void*) this;
872  field_lengths= (uint32*) thd->alloc(table->s->fields * sizeof(uint32));
873  for (tree_key_length= 0, length= field_lengths, field= table->field;
874  field < field_end; ++field, ++length)
875  {
876  *length= (*field)->pack_length();
877  tree_key_length+= *length;
878  }
879  }
880  }
881  DBUG_ASSERT(tree == 0);
882  tree= new Unique(compare_key, cmp_arg, tree_key_length,
883  item_sum->ram_limitation(thd));
884  /*
885  The only time tree_key_length could be 0 is if someone does
886  count(distinct) on a char(0) field - stupid thing to do,
887  but this has to be handled - otherwise someone can crash
888  the server with a DoS attack
889  */
890  if (! tree)
891  return TRUE;
892  }
893  return FALSE;
894  }
895  else
896  {
897  List<Create_field> field_list;
898  Create_field field_def; /* field definition */
899  Item *arg;
900  DBUG_ENTER("Aggregator_distinct::setup");
901  /* It's legal to call setup() more than once when in a subquery */
902  if (tree)
903  DBUG_RETURN(FALSE);
904 
905  /*
906  Virtual table and the tree are created anew on each re-execution of
907  PS/SP. Hence all further allocations are performed in the runtime
908  mem_root.
909  */
910  if (field_list.push_back(&field_def))
911  DBUG_RETURN(TRUE);
912 
913  item_sum->null_value= item_sum->maybe_null= 1;
914  item_sum->quick_group= 0;
915 
916  DBUG_ASSERT(item_sum->get_arg(0)->fixed);
917 
918  arg= item_sum->get_arg(0);
919  if (arg->const_item())
920  {
921  (void) arg->val_int();
922  if (arg->null_value)
923  always_null= true;
924  }
925 
926  if (always_null)
927  DBUG_RETURN(FALSE);
928 
929  enum enum_field_types field_type;
930 
931  field_type= calc_tmp_field_type(arg->field_type(),
932  arg->result_type());
933  field_def.init_for_tmp_table(field_type,
934  arg->max_length,
935  arg->decimals,
936  arg->maybe_null,
937  arg->unsigned_flag);
938 
939  if (! (table= create_virtual_tmp_table(thd, field_list)))
940  DBUG_RETURN(TRUE);
941 
942  /* XXX: check that the case of CHAR(0) works OK */
943  tree_key_length= table->s->reclength - table->s->null_bytes;
944 
945  /*
946  Unique handles all unique elements in a tree until they can't fit
947  in. Then the tree is dumped to the temporary file. We can use
948  simple_raw_key_cmp because the table contains numbers only; decimals
949  are converted to binary representation as well.
950  */
951  tree= new Unique(simple_raw_key_cmp, &tree_key_length, tree_key_length,
952  item_sum->ram_limitation(thd));
953 
954  DBUG_RETURN(tree == 0);
955  }
956 }
957 
958 
967 {
968  endup_done= FALSE;
969  item_sum->clear();
970  if (tree)
971  tree->reset();
972  /* tree and table can be both null only if always_null */
973  if (item_sum->sum_func() == Item_sum::COUNT_FUNC ||
974  item_sum->sum_func() == Item_sum::COUNT_DISTINCT_FUNC)
975  {
976  if (!tree && table)
977  {
978  table->file->extra(HA_EXTRA_NO_CACHE);
979  table->file->ha_delete_all_rows();
980  table->file->extra(HA_EXTRA_WRITE_CACHE);
981  }
982  }
983  else
984  {
985  item_sum->null_value= 1;
986  }
987 }
988 
989 
1007 {
1008  if (always_null)
1009  return 0;
1010 
1011  if (item_sum->sum_func() == Item_sum::COUNT_FUNC ||
1012  item_sum->sum_func() == Item_sum::COUNT_DISTINCT_FUNC)
1013  {
1014  int error;
1015  copy_fields(tmp_table_param);
1016  if (copy_funcs(tmp_table_param->items_to_copy, table->in_use))
1017  return TRUE;
1018 
1019  for (Field **field=table->field ; *field ; field++)
1020  if ((*field)->is_real_null(0))
1021  return 0; // Don't count NULL
1022 
1023  if (tree)
1024  {
1025  /*
1026  The first few bytes of record (at least one) are just markers
1027  for deleted and NULLs. We want to skip them since they will
1028  bloat the tree without providing any valuable info. Besides,
1029  key_length used to initialize the tree didn't include space for them.
1030  */
1031  return tree->unique_add(table->record[0] + table->s->null_bytes);
1032  }
1033  if ((error= table->file->ha_write_row(table->record[0])) &&
1034  table->file->is_fatal_error(error, HA_CHECK_DUP))
1035  return TRUE;
1036  return FALSE;
1037  }
1038  else
1039  {
1040  item_sum->get_arg(0)->save_in_field(table->field[0], FALSE);
1041  if (table->field[0]->is_null())
1042  return 0;
1043  DBUG_ASSERT(tree);
1044  item_sum->null_value= 0;
1045  /*
1046  '0' values are also stored in the tree. This doesn't matter
1047  for SUM(DISTINCT), but is important for AVG(DISTINCT)
1048  */
1049  return tree->unique_add(table->field[0]->ptr);
1050  }
1051 }
1052 
1053 
1066 {
1067  /* prevent consecutive recalculations */
1068  if (endup_done)
1069  return;
1070 
1071  /* we are going to calculate the aggregate value afresh */
1072  item_sum->clear();
1073 
1074  /* The result will definitely be null : no more calculations needed */
1075  if (always_null)
1076  return;
1077 
1078  if (item_sum->sum_func() == Item_sum::COUNT_FUNC ||
1079  item_sum->sum_func() == Item_sum::COUNT_DISTINCT_FUNC)
1080  {
1081  DBUG_ASSERT(item_sum->fixed == 1);
1082  Item_sum_count *sum= (Item_sum_count *)item_sum;
1083  if (tree && tree->elements == 0)
1084  {
1085  /* everything fits in memory */
1086  sum->count= (longlong) tree->elements_in_tree();
1087  endup_done= TRUE;
1088  }
1089  if (!tree)
1090  {
1091  /* there were blobs */
1092  table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
1093  sum->count= table->file->stats.records;
1094  endup_done= TRUE;
1095  }
1096  }
1097  else
1098  {
1099  /*
1100  We don't have a tree only if 'setup()' hasn't been called;
1101  this is the case of sql_executor.cc:return_zero_rows.
1102  */
1103  if (tree)
1104  table->field[0]->set_notnull();
1105  }
1106 
1107  if (tree && !endup_done)
1108  {
1109  /* go over the tree of distinct keys and calculate the aggregate value */
1110  use_distinct_values= TRUE;
1111  tree->walk(item_sum_distinct_walk, (void*) this);
1112  use_distinct_values= FALSE;
1113  }
1114  /* prevent consecutive recalculations */
1115  endup_done= TRUE;
1116 }
1117 
1118 
1119 String *
1120 Item_sum_num::val_str(String *str)
1121 {
1122  return val_string_from_real(str);
1123 }
1124 
1125 
1126 my_decimal *Item_sum_num::val_decimal(my_decimal *decimal_value)
1127 {
1128  return val_decimal_from_real(decimal_value);
1129 }
1130 
1131 
1132 String *
1133 Item_sum_int::val_str(String *str)
1134 {
1135  return val_string_from_int(str);
1136 }
1137 
1138 
1139 my_decimal *Item_sum_int::val_decimal(my_decimal *decimal_value)
1140 {
1141  return val_decimal_from_int(decimal_value);
1142 }
1143 
1144 
1145 bool
1146 Item_sum_num::fix_fields(THD *thd, Item **ref)
1147 {
1148  DBUG_ASSERT(fixed == 0);
1149 
1150  if (init_sum_func_check(thd))
1151  return TRUE;
1152 
1153  decimals=0;
1154  maybe_null=0;
1155  for (uint i=0 ; i < arg_count ; i++)
1156  {
1157  if ((!args[i]->fixed && args[i]->fix_fields(thd, args + i)) ||
1158  args[i]->check_cols(1))
1159  return TRUE;
1160  set_if_bigger(decimals, args[i]->decimals);
1161  maybe_null |= args[i]->maybe_null;
1162  }
1163  result_field=0;
1164  max_length=float_length(decimals);
1165  null_value=1;
1166  fix_length_and_dec();
1167 
1168  if (check_sum_func(thd, ref))
1169  return TRUE;
1170 
1171  memcpy (orig_args, args, sizeof (Item *) * arg_count);
1172  fixed= 1;
1173  return FALSE;
1174 }
1175 
1176 
1177 bool
1178 Item_sum_hybrid::fix_fields(THD *thd, Item **ref)
1179 {
1180  DBUG_ASSERT(fixed == 0);
1181 
1182  Item *item= args[0];
1183 
1184  if (init_sum_func_check(thd))
1185  return TRUE;
1186 
1187  // 'item' can be changed during fix_fields
1188  if ((!item->fixed && item->fix_fields(thd, args)) ||
1189  (item= args[0])->check_cols(1))
1190  return TRUE;
1191  decimals=item->decimals;
1192 
1193  switch (hybrid_type= item->result_type()) {
1194  case INT_RESULT:
1195  case DECIMAL_RESULT:
1196  case STRING_RESULT:
1197  max_length= item->max_length;
1198  break;
1199  case REAL_RESULT:
1200  max_length= float_length(decimals);
1201  break;
1202  case ROW_RESULT:
1203  default:
1204  DBUG_ASSERT(0);
1205  };
1206  setup_hybrid(args[0], NULL);
1207  /* MIN/MAX can return NULL for empty set indepedent of the used column */
1208  maybe_null= 1;
1209  unsigned_flag=item->unsigned_flag;
1210  result_field=0;
1211  null_value=1;
1212  fix_length_and_dec();
1213  item= item->real_item();
1214  if (item->type() == Item::FIELD_ITEM)
1215  hybrid_field_type= ((Item_field*) item)->field->type();
1216  else
1217  hybrid_field_type= Item::field_type();
1218 
1219  if (check_sum_func(thd, ref))
1220  return TRUE;
1221 
1222  orig_args[0]= args[0];
1223  fixed= 1;
1224  return FALSE;
1225 }
1226 
1227 
1240 void Item_sum_hybrid::setup_hybrid(Item *item, Item *value_arg)
1241 {
1242  value= Item_cache::get_cache(item);
1243  value->setup(item);
1244  value->store(value_arg);
1245  arg_cache= Item_cache::get_cache(item);
1246  arg_cache->setup(item);
1247  cmp= new Arg_comparator();
1248  cmp->set_cmp_func(this, (Item**)&arg_cache, (Item**)&value, FALSE);
1249  collation.set(item->collation);
1250 }
1251 
1252 
1253 Field *Item_sum_hybrid::create_tmp_field(bool group, TABLE *table)
1254 {
1255  Field *field;
1256  if (args[0]->type() == Item::FIELD_ITEM)
1257  {
1258  field= ((Item_field*) args[0])->field;
1259 
1260  if ((field= create_tmp_field_from_field(current_thd, field, item_name.ptr(),
1261  table, NULL)))
1262  field->flags&= ~NOT_NULL_FLAG;
1263  return field;
1264  }
1265  /*
1266  DATE/TIME fields have STRING_RESULT result types.
1267  In order to preserve field type, it's needed to handle DATE/TIME
1268  fields creations separately.
1269  */
1270  switch (args[0]->field_type()) {
1271  case MYSQL_TYPE_DATE:
1272  field= new Field_newdate(maybe_null, item_name.ptr());
1273  break;
1274  case MYSQL_TYPE_TIME:
1275  field= new Field_timef(maybe_null, item_name.ptr(), decimals);
1276  break;
1277  case MYSQL_TYPE_TIMESTAMP:
1278  case MYSQL_TYPE_DATETIME:
1279  field= new Field_datetimef(maybe_null, item_name.ptr(), decimals);
1280  break;
1281  default:
1282  return Item_sum::create_tmp_field(group, table);
1283  }
1284  if (field)
1285  field->init(table);
1286  return field;
1287 }
1288 
1289 
1290 /***********************************************************************
1291 ** reset and add of sum_func
1292 ***********************************************************************/
1293 
1298 Item_sum_sum::Item_sum_sum(THD *thd, Item_sum_sum *item)
1299  :Item_sum_num(thd, item), hybrid_type(item->hybrid_type),
1300  curr_dec_buff(item->curr_dec_buff)
1301 {
1302  /* TODO: check if the following assignments are really needed */
1303  if (hybrid_type == DECIMAL_RESULT)
1304  {
1305  my_decimal2decimal(item->dec_buffs, dec_buffs);
1306  my_decimal2decimal(item->dec_buffs + 1, dec_buffs + 1);
1307  }
1308  else
1309  sum= item->sum;
1310 }
1311 
1312 Item *Item_sum_sum::copy_or_same(THD* thd)
1313 {
1314  return new (thd->mem_root) Item_sum_sum(thd, this);
1315 }
1316 
1317 
1318 void Item_sum_sum::clear()
1319 {
1320  DBUG_ENTER("Item_sum_sum::clear");
1321  null_value=1;
1322  if (hybrid_type == DECIMAL_RESULT)
1323  {
1324  curr_dec_buff= 0;
1325  my_decimal_set_zero(dec_buffs);
1326  }
1327  else
1328  sum= 0.0;
1329  DBUG_VOID_RETURN;
1330 }
1331 
1332 
1333 void Item_sum_sum::fix_length_and_dec()
1334 {
1335  DBUG_ENTER("Item_sum_sum::fix_length_and_dec");
1336  maybe_null=null_value=1;
1337  decimals= args[0]->decimals;
1338  switch (args[0]->numeric_context_result_type()) {
1339  case REAL_RESULT:
1340  hybrid_type= REAL_RESULT;
1341  sum= 0.0;
1342  break;
1343  case INT_RESULT:
1344  case DECIMAL_RESULT:
1345  {
1346  /* SUM result can't be longer than length(arg) + length(MAX_ROWS) */
1347  int precision= args[0]->decimal_precision() + DECIMAL_LONGLONG_DIGITS;
1348  max_length= my_decimal_precision_to_length_no_truncation(precision,
1349  decimals,
1350  unsigned_flag);
1351  curr_dec_buff= 0;
1352  hybrid_type= DECIMAL_RESULT;
1353  my_decimal_set_zero(dec_buffs);
1354  break;
1355  }
1356  case STRING_RESULT:
1357  case ROW_RESULT:
1358  default:
1359  DBUG_ASSERT(0);
1360  }
1361  DBUG_PRINT("info", ("Type: %s (%d, %d)",
1362  (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
1363  hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
1364  hybrid_type == INT_RESULT ? "INT_RESULT" :
1365  "--ILLEGAL!!!--"),
1366  max_length,
1367  (int)decimals));
1368  DBUG_VOID_RETURN;
1369 }
1370 
1371 
1372 bool Item_sum_sum::add()
1373 {
1374  DBUG_ENTER("Item_sum_sum::add");
1375  if (hybrid_type == DECIMAL_RESULT)
1376  {
1377  my_decimal value;
1378  const my_decimal *val= aggr->arg_val_decimal(&value);
1379  if (!aggr->arg_is_null())
1380  {
1381  my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs + (curr_dec_buff^1),
1382  val, dec_buffs + curr_dec_buff);
1383  curr_dec_buff^= 1;
1384  null_value= 0;
1385  }
1386  }
1387  else
1388  {
1389  sum+= aggr->arg_val_real();
1390  if (!aggr->arg_is_null())
1391  null_value= 0;
1392  }
1393  DBUG_RETURN(0);
1394 }
1395 
1396 
1397 longlong Item_sum_sum::val_int()
1398 {
1399  DBUG_ASSERT(fixed == 1);
1400  if (aggr)
1401  aggr->endup();
1402  if (hybrid_type == DECIMAL_RESULT)
1403  {
1404  longlong result;
1405  my_decimal2int(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, unsigned_flag,
1406  &result);
1407  return result;
1408  }
1409  return (longlong) rint(val_real());
1410 }
1411 
1412 
1413 double Item_sum_sum::val_real()
1414 {
1415  DBUG_ASSERT(fixed == 1);
1416  if (aggr)
1417  aggr->endup();
1418  if (hybrid_type == DECIMAL_RESULT)
1419  my_decimal2double(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, &sum);
1420  return sum;
1421 }
1422 
1423 
1424 String *Item_sum_sum::val_str(String *str)
1425 {
1426  if (aggr)
1427  aggr->endup();
1428  if (hybrid_type == DECIMAL_RESULT)
1429  return val_string_from_decimal(str);
1430  return val_string_from_real(str);
1431 }
1432 
1433 
1434 my_decimal *Item_sum_sum::val_decimal(my_decimal *val)
1435 {
1436  if (aggr)
1437  aggr->endup();
1438  if (hybrid_type == DECIMAL_RESULT)
1439  return (dec_buffs + curr_dec_buff);
1440  return val_decimal_from_real(val);
1441 }
1442 
1461 {
1462  memcpy(table->field[0]->ptr, element, tree_key_length);
1463  item_sum->add();
1464  return 0;
1465 }
1466 
1467 
1468 Aggregator_distinct::~Aggregator_distinct()
1469 {
1470  if (tree)
1471  {
1472  delete tree;
1473  tree= NULL;
1474  }
1475  if (table)
1476  {
1477  free_tmp_table(table->in_use, table);
1478  table=NULL;
1479  }
1480  if (tmp_table_param)
1481  {
1482  delete tmp_table_param;
1483  tmp_table_param= NULL;
1484  }
1485 }
1486 
1487 
1489 {
1490  return item_sum->args[0]->val_decimal(value);
1491 }
1492 
1493 
1495 {
1496  return item_sum->args[0]->val_real();
1497 }
1498 
1499 
1501 {
1502  return item_sum->args[0]->null_value;
1503 }
1504 
1505 
1507 {
1508  return use_distinct_values ? table->field[0]->val_decimal(value) :
1509  item_sum->args[0]->val_decimal(value);
1510 }
1511 
1512 
1514 {
1515  return use_distinct_values ? table->field[0]->val_real() :
1516  item_sum->args[0]->val_real();
1517 }
1518 
1519 
1521 {
1522  return use_distinct_values ? table->field[0]->is_null() :
1523  item_sum->args[0]->null_value;
1524 }
1525 
1526 
1527 Item *Item_sum_count::copy_or_same(THD* thd)
1528 {
1529  return new (thd->mem_root) Item_sum_count(thd, this);
1530 }
1531 
1532 
1533 void Item_sum_count::clear()
1534 {
1535  count= 0;
1536 }
1537 
1538 
1539 bool Item_sum_count::add()
1540 {
1541  if (!args[0]->maybe_null || !args[0]->is_null())
1542  count++;
1543  return 0;
1544 }
1545 
1546 longlong Item_sum_count::val_int()
1547 {
1548  DBUG_ASSERT(fixed == 1);
1549  if (aggr)
1550  aggr->endup();
1551  return (longlong) count;
1552 }
1553 
1554 
1555 void Item_sum_count::cleanup()
1556 {
1557  DBUG_ENTER("Item_sum_count::cleanup");
1558  count= 0;
1559  Item_sum_int::cleanup();
1560  DBUG_VOID_RETURN;
1561 }
1562 
1563 
1564 /*
1565  Avgerage
1566 */
1567 void Item_sum_avg::fix_length_and_dec()
1568 {
1569  Item_sum_sum::fix_length_and_dec();
1570  maybe_null=null_value=1;
1571  prec_increment= current_thd->variables.div_precincrement;
1572  if (hybrid_type == DECIMAL_RESULT)
1573  {
1574  int precision= args[0]->decimal_precision() + prec_increment;
1575  decimals= min<uint>(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
1576  max_length= my_decimal_precision_to_length_no_truncation(precision,
1577  decimals,
1578  unsigned_flag);
1579  f_precision= min(precision+DECIMAL_LONGLONG_DIGITS, DECIMAL_MAX_PRECISION);
1580  f_scale= args[0]->decimals;
1581  dec_bin_size= my_decimal_get_binary_size(f_precision, f_scale);
1582  }
1583  else {
1584  decimals= min<uint>(args[0]->decimals + prec_increment, NOT_FIXED_DEC);
1585  max_length= args[0]->max_length + prec_increment;
1586  }
1587 }
1588 
1589 
1590 Item *Item_sum_avg::copy_or_same(THD* thd)
1591 {
1592  return new (thd->mem_root) Item_sum_avg(thd, this);
1593 }
1594 
1595 
1596 Field *Item_sum_avg::create_tmp_field(bool group, TABLE *table)
1597 {
1598  Field *field;
1599  if (group)
1600  {
1601  /*
1602  We must store both value and counter in the temporary table in one field.
1603  The easiest way is to do this is to store both value in a string
1604  and unpack on access.
1605  */
1606  field= new Field_string(((hybrid_type == DECIMAL_RESULT) ?
1607  dec_bin_size : sizeof(double)) + sizeof(longlong),
1608  0, item_name.ptr(), &my_charset_bin);
1609  }
1610  else if (hybrid_type == DECIMAL_RESULT)
1611  field= Field_new_decimal::create_from_item(this);
1612  else
1613  field= new Field_double(max_length, maybe_null, item_name.ptr(), decimals, TRUE);
1614  if (field)
1615  field->init(table);
1616  return field;
1617 }
1618 
1619 
1620 void Item_sum_avg::clear()
1621 {
1622  Item_sum_sum::clear();
1623  count=0;
1624 }
1625 
1626 
1627 bool Item_sum_avg::add()
1628 {
1629  if (Item_sum_sum::add())
1630  return TRUE;
1631  if (!aggr->arg_is_null())
1632  count++;
1633  return FALSE;
1634 }
1635 
1636 double Item_sum_avg::val_real()
1637 {
1638  DBUG_ASSERT(fixed == 1);
1639  if (aggr)
1640  aggr->endup();
1641  if (!count)
1642  {
1643  null_value=1;
1644  return 0.0;
1645  }
1646  return Item_sum_sum::val_real() / ulonglong2double(count);
1647 }
1648 
1649 
1650 my_decimal *Item_sum_avg::val_decimal(my_decimal *val)
1651 {
1652  my_decimal sum_buff, cnt;
1653  const my_decimal *sum_dec;
1654  DBUG_ASSERT(fixed == 1);
1655  if (aggr)
1656  aggr->endup();
1657  if (!count)
1658  {
1659  null_value=1;
1660  return NULL;
1661  }
1662 
1663  /*
1664  For non-DECIMAL hybrid_type the division will be done in
1665  Item_sum_avg::val_real().
1666  */
1667  if (hybrid_type != DECIMAL_RESULT)
1668  return val_decimal_from_real(val);
1669 
1670  sum_dec= dec_buffs + curr_dec_buff;
1671  int2my_decimal(E_DEC_FATAL_ERROR, count, 0, &cnt);
1672  my_decimal_div(E_DEC_FATAL_ERROR, val, sum_dec, &cnt, prec_increment);
1673  return val;
1674 }
1675 
1676 
1677 String *Item_sum_avg::val_str(String *str)
1678 {
1679  if (aggr)
1680  aggr->endup();
1681  if (hybrid_type == DECIMAL_RESULT)
1682  return val_string_from_decimal(str);
1683  return val_string_from_real(str);
1684 }
1685 
1686 
1687 /*
1688  Standard deviation
1689 */
1690 
1691 double Item_sum_std::val_real()
1692 {
1693  DBUG_ASSERT(fixed == 1);
1694  double nr= Item_sum_variance::val_real();
1695  DBUG_ASSERT(nr >= 0.0);
1696  return sqrt(nr);
1697 }
1698 
1699 Item *Item_sum_std::copy_or_same(THD* thd)
1700 {
1701  return new (thd->mem_root) Item_sum_std(thd, this);
1702 }
1703 
1704 
1705 /*
1706  Variance
1707 */
1708 
1709 
1716 /*
1717  These two functions are used by the Item_sum_variance and the
1718  Item_variance_field classes, which are unrelated, and each need to calculate
1719  variance. The difference between the two classes is that the first is used
1720  for a mundane SELECT, while the latter is used in a GROUPing SELECT.
1721 */
1722 static void variance_fp_recurrence_next(double *m, double *s, ulonglong *count, double nr)
1723 {
1724  *count += 1;
1725 
1726  if (*count == 1)
1727  {
1728  *m= nr;
1729  *s= 0;
1730  }
1731  else
1732  {
1733  double m_kminusone= *m;
1734  *m= m_kminusone + (nr - m_kminusone) / (double) *count;
1735  *s= *s + (nr - m_kminusone) * (nr - *m);
1736  }
1737 }
1738 
1739 
1740 static double variance_fp_recurrence_result(double s, ulonglong count, bool is_sample_variance)
1741 {
1742  if (count == 1)
1743  return 0.0;
1744 
1745  if (is_sample_variance)
1746  return s / (count - 1);
1747 
1748  /* else, is a population variance */
1749  return s / count;
1750 }
1751 
1752 
1753 Item_sum_variance::Item_sum_variance(THD *thd, Item_sum_variance *item):
1754  Item_sum_num(thd, item), hybrid_type(item->hybrid_type),
1755  count(item->count), sample(item->sample),
1756  prec_increment(item->prec_increment)
1757 {
1758  recurrence_m= item->recurrence_m;
1759  recurrence_s= item->recurrence_s;
1760 }
1761 
1762 
1763 void Item_sum_variance::fix_length_and_dec()
1764 {
1765  DBUG_ENTER("Item_sum_variance::fix_length_and_dec");
1766  maybe_null= null_value= 1;
1767 
1768  /*
1769  According to the SQL2003 standard (Part 2, Foundations; sec 10.9,
1770  aggregate function; paragraph 7h of Syntax Rules), "the declared
1771  type of the result is an implementation-defined aproximate numeric
1772  type.
1773  */
1774  hybrid_type= REAL_RESULT;
1775  decimals= NOT_FIXED_DEC;
1776  max_length= float_length(decimals);
1777 
1778  DBUG_PRINT("info", ("Type: REAL_RESULT (%d, %d)", max_length, (int)decimals));
1779  DBUG_VOID_RETURN;
1780 }
1781 
1782 
1783 Item *Item_sum_variance::copy_or_same(THD* thd)
1784 {
1785  return new (thd->mem_root) Item_sum_variance(thd, this);
1786 }
1787 
1788 
1795 {
1796  Field *field;
1797  if (group)
1798  {
1799  /*
1800  We must store both value and counter in the temporary table in one field.
1801  The easiest way is to do this is to store both value in a string
1802  and unpack on access.
1803  */
1804  field= new Field_string(sizeof(double)*2 + sizeof(longlong), 0, item_name.ptr(), &my_charset_bin);
1805  }
1806  else
1807  field= new Field_double(max_length, maybe_null, item_name.ptr(), decimals, TRUE);
1808 
1809  if (field != NULL)
1810  field->init(table);
1811 
1812  return field;
1813 }
1814 
1815 
1816 void Item_sum_variance::clear()
1817 {
1818  count= 0;
1819 }
1820 
1821 bool Item_sum_variance::add()
1822 {
1823  /*
1824  Why use a temporary variable? We don't know if it is null until we
1825  evaluate it, which has the side-effect of setting null_value .
1826  */
1827  double nr= args[0]->val_real();
1828 
1829  if (!args[0]->null_value)
1830  variance_fp_recurrence_next(&recurrence_m, &recurrence_s, &count, nr);
1831  return 0;
1832 }
1833 
1834 double Item_sum_variance::val_real()
1835 {
1836  DBUG_ASSERT(fixed == 1);
1837 
1838  /*
1839  'sample' is a 1/0 boolean value. If it is 1/true, id est this is a sample
1840  variance call, then we should set nullness when the count of the items
1841  is one or zero. If it's zero, i.e. a population variance, then we only
1842  set nullness when the count is zero.
1843 
1844  Another way to read it is that 'sample' is the numerical threshhold, at and
1845  below which a 'count' number of items is called NULL.
1846  */
1847  DBUG_ASSERT((sample == 0) || (sample == 1));
1848  if (count <= sample)
1849  {
1850  null_value=1;
1851  return 0.0;
1852  }
1853 
1854  null_value=0;
1855  return variance_fp_recurrence_result(recurrence_s, count, sample);
1856 }
1857 
1858 
1859 my_decimal *Item_sum_variance::val_decimal(my_decimal *dec_buf)
1860 {
1861  DBUG_ASSERT(fixed == 1);
1862  return val_decimal_from_real(dec_buf);
1863 }
1864 
1865 
1866 void Item_sum_variance::reset_field()
1867 {
1868  double nr;
1869  uchar *res= result_field->ptr;
1870 
1871  nr= args[0]->val_real(); /* sets null_value as side-effect */
1872 
1873  if (args[0]->null_value)
1874  memset(res, 0, sizeof(double)*2+sizeof(longlong));
1875  else
1876  {
1877  /* Serialize format is (double)m, (double)s, (longlong)count */
1878  ulonglong tmp_count;
1879  double tmp_s;
1880  float8store(res, nr); /* recurrence variable m */
1881  tmp_s= 0.0;
1882  float8store(res + sizeof(double), tmp_s);
1883  tmp_count= 1;
1884  int8store(res + sizeof(double)*2, tmp_count);
1885  }
1886 }
1887 
1888 
1889 void Item_sum_variance::update_field()
1890 {
1891  ulonglong field_count;
1892  uchar *res=result_field->ptr;
1893 
1894  double nr= args[0]->val_real(); /* sets null_value as side-effect */
1895 
1896  if (args[0]->null_value)
1897  return;
1898 
1899  /* Serialize format is (double)m, (double)s, (longlong)count */
1900  double field_recurrence_m, field_recurrence_s;
1901  float8get(field_recurrence_m, res);
1902  float8get(field_recurrence_s, res + sizeof(double));
1903  field_count=sint8korr(res+sizeof(double)*2);
1904 
1905  variance_fp_recurrence_next(&field_recurrence_m, &field_recurrence_s, &field_count, nr);
1906 
1907  float8store(res, field_recurrence_m);
1908  float8store(res + sizeof(double), field_recurrence_s);
1909  res+= sizeof(double)*2;
1910  int8store(res,field_count);
1911 }
1912 
1913 
1914 /* min & max */
1915 
1916 void Item_sum_hybrid::clear()
1917 {
1918  value->clear();
1919  null_value= 1;
1920 }
1921 
1922 double Item_sum_hybrid::val_real()
1923 {
1924  DBUG_ASSERT(fixed == 1);
1925  if (null_value)
1926  return 0.0;
1927  double retval= value->val_real();
1928  if ((null_value= value->null_value))
1929  DBUG_ASSERT(retval == 0.0);
1930  return retval;
1931 }
1932 
1933 longlong Item_sum_hybrid::val_int()
1934 {
1935  DBUG_ASSERT(fixed == 1);
1936  if (null_value)
1937  return 0;
1938  longlong retval= value->val_int();
1939  if ((null_value= value->null_value))
1940  DBUG_ASSERT(retval == 0);
1941  return retval;
1942 }
1943 
1944 
1946 {
1947  DBUG_ASSERT(fixed == 1);
1948  if (null_value)
1949  return 0;
1950  longlong retval= value->val_time_temporal();
1951  if ((null_value= value->null_value))
1952  DBUG_ASSERT(retval == 0);
1953  return retval;
1954 }
1955 
1956 
1958 {
1959  DBUG_ASSERT(fixed == 1);
1960  if (null_value)
1961  return 0;
1962  longlong retval= value->val_date_temporal();
1963  if ((null_value= value->null_value))
1964  DBUG_ASSERT(retval == 0);
1965  return retval;
1966 }
1967 
1968 
1969 my_decimal *Item_sum_hybrid::val_decimal(my_decimal *val)
1970 {
1971  DBUG_ASSERT(fixed == 1);
1972  if (null_value)
1973  return 0;
1974  my_decimal *retval= value->val_decimal(val);
1975  if ((null_value= value->null_value))
1976  DBUG_ASSERT(retval == NULL);
1977  return retval;
1978 }
1979 
1980 
1981 bool Item_sum_hybrid::get_date(MYSQL_TIME *ltime, uint fuzzydate)
1982 {
1983  DBUG_ASSERT(fixed == 1);
1984  if (null_value)
1985  return true;
1986  return (null_value= value->get_date(ltime, fuzzydate));
1987 }
1988 
1989 
1990 bool Item_sum_hybrid::get_time(MYSQL_TIME *ltime)
1991 {
1992  DBUG_ASSERT(fixed == 1);
1993  if (null_value)
1994  return true;
1995  return (null_value= value->get_time(ltime));
1996 }
1997 
1998 
1999 String *
2000 Item_sum_hybrid::val_str(String *str)
2001 {
2002  DBUG_ASSERT(fixed == 1);
2003  if (null_value)
2004  return 0;
2005  String *retval= value->val_str(str);
2006  if ((null_value= value->null_value))
2007  DBUG_ASSERT(retval == NULL);
2008  return retval;
2009 }
2010 
2011 
2012 void Item_sum_hybrid::cleanup()
2013 {
2014  DBUG_ENTER("Item_sum_hybrid::cleanup");
2015  Item_sum::cleanup();
2016  forced_const= FALSE;
2017  if (cmp)
2018  delete cmp;
2019  cmp= 0;
2020  /*
2021  by default it is TRUE to avoid TRUE reporting by
2022  Item_func_not_all/Item_func_nop_all if this item was never called.
2023 
2024  no_rows_in_result() set it to FALSE if was not results found.
2025  If some results found it will be left unchanged.
2026  */
2027  was_values= TRUE;
2028  DBUG_VOID_RETURN;
2029 }
2030 
2032 {
2033  was_values= FALSE;
2034  clear();
2035 }
2036 
2037 
2038 Item *Item_sum_min::copy_or_same(THD* thd)
2039 {
2040  Item_sum_min *item= new (thd->mem_root) Item_sum_min(thd, this);
2041  item->setup_hybrid(args[0], value);
2042  return item;
2043 }
2044 
2045 
2046 bool Item_sum_min::add()
2047 {
2048  /* args[0] < value */
2049  arg_cache->cache_value();
2050  if (!arg_cache->null_value &&
2051  (null_value || cmp->compare() < 0))
2052  {
2053  value->store(arg_cache);
2054  value->cache_value();
2055  null_value= 0;
2056  }
2057  return 0;
2058 }
2059 
2060 
2061 Item *Item_sum_max::copy_or_same(THD* thd)
2062 {
2063  Item_sum_max *item= new (thd->mem_root) Item_sum_max(thd, this);
2064  item->setup_hybrid(args[0], value);
2065  return item;
2066 }
2067 
2068 
2069 bool Item_sum_max::add()
2070 {
2071  /* args[0] > value */
2072  arg_cache->cache_value();
2073  if (!arg_cache->null_value &&
2074  (null_value || cmp->compare() > 0))
2075  {
2076  value->store(arg_cache);
2077  value->cache_value();
2078  null_value= 0;
2079  }
2080  return 0;
2081 }
2082 
2083 
2084 /* bit_or and bit_and */
2085 
2086 longlong Item_sum_bit::val_int()
2087 {
2088  DBUG_ASSERT(fixed == 1);
2089  return (longlong) bits;
2090 }
2091 
2092 
2093 void Item_sum_bit::clear()
2094 {
2095  bits= reset_bits;
2096 }
2097 
2098 Item *Item_sum_or::copy_or_same(THD* thd)
2099 {
2100  return new (thd->mem_root) Item_sum_or(thd, this);
2101 }
2102 
2103 
2104 bool Item_sum_or::add()
2105 {
2106  ulonglong value= (ulonglong) args[0]->val_int();
2107  if (!args[0]->null_value)
2108  bits|=value;
2109  return 0;
2110 }
2111 
2112 Item *Item_sum_xor::copy_or_same(THD* thd)
2113 {
2114  return new (thd->mem_root) Item_sum_xor(thd, this);
2115 }
2116 
2117 
2118 bool Item_sum_xor::add()
2119 {
2120  ulonglong value= (ulonglong) args[0]->val_int();
2121  if (!args[0]->null_value)
2122  bits^=value;
2123  return 0;
2124 }
2125 
2126 Item *Item_sum_and::copy_or_same(THD* thd)
2127 {
2128  return new (thd->mem_root) Item_sum_and(thd, this);
2129 }
2130 
2131 
2132 bool Item_sum_and::add()
2133 {
2134  ulonglong value= (ulonglong) args[0]->val_int();
2135  if (!args[0]->null_value)
2136  bits&=value;
2137  return 0;
2138 }
2139 
2140 /************************************************************************
2141 ** reset result of a Item_sum with is saved in a tmp_table
2142 *************************************************************************/
2143 
2144 void Item_sum_num::reset_field()
2145 {
2146  double nr= args[0]->val_real();
2147  uchar *res=result_field->ptr;
2148 
2149  if (maybe_null)
2150  {
2151  if (args[0]->null_value)
2152  {
2153  nr=0.0;
2154  result_field->set_null();
2155  }
2156  else
2157  result_field->set_notnull();
2158  }
2159  float8store(res,nr);
2160 }
2161 
2162 
2163 void Item_sum_hybrid::reset_field()
2164 {
2165  switch(hybrid_type) {
2166  case STRING_RESULT:
2167  {
2168  if (args[0]->is_temporal())
2169  {
2170  longlong nr= args[0]->val_temporal_by_field_type();
2171  if (maybe_null)
2172  {
2173  if (args[0]->null_value)
2174  {
2175  nr= 0;
2176  result_field->set_null();
2177  }
2178  else
2179  result_field->set_notnull();
2180  }
2181  result_field->store_packed(nr);
2182  break;
2183  }
2184 
2185  char buff[MAX_FIELD_WIDTH];
2186  String tmp(buff,sizeof(buff),result_field->charset()),*res;
2187 
2188  res=args[0]->val_str(&tmp);
2189  if (args[0]->null_value)
2190  {
2191  result_field->set_null();
2192  result_field->reset();
2193  }
2194  else
2195  {
2196  result_field->set_notnull();
2197  result_field->store(res->ptr(),res->length(),tmp.charset());
2198  }
2199  break;
2200  }
2201  case INT_RESULT:
2202  {
2203  longlong nr=args[0]->val_int();
2204 
2205  if (maybe_null)
2206  {
2207  if (args[0]->null_value)
2208  {
2209  nr=0;
2210  result_field->set_null();
2211  }
2212  else
2213  result_field->set_notnull();
2214  }
2215  result_field->store(nr, unsigned_flag);
2216  break;
2217  }
2218  case REAL_RESULT:
2219  {
2220  double nr= args[0]->val_real();
2221 
2222  if (maybe_null)
2223  {
2224  if (args[0]->null_value)
2225  {
2226  nr=0.0;
2227  result_field->set_null();
2228  }
2229  else
2230  result_field->set_notnull();
2231  }
2232  result_field->store(nr);
2233  break;
2234  }
2235  case DECIMAL_RESULT:
2236  {
2237  my_decimal value_buff, *arg_dec= args[0]->val_decimal(&value_buff);
2238 
2239  if (maybe_null)
2240  {
2241  if (args[0]->null_value)
2242  result_field->set_null();
2243  else
2244  result_field->set_notnull();
2245  }
2246  /*
2247  We must store zero in the field as we will use the field value in
2248  add()
2249  */
2250  if (!arg_dec) // Null
2251  arg_dec= &decimal_zero;
2252  result_field->store_decimal(arg_dec);
2253  break;
2254  }
2255  case ROW_RESULT:
2256  default:
2257  DBUG_ASSERT(0);
2258  }
2259 }
2260 
2261 
2262 void Item_sum_sum::reset_field()
2263 {
2264  DBUG_ASSERT (aggr->Aggrtype() != Aggregator::DISTINCT_AGGREGATOR);
2265  if (hybrid_type == DECIMAL_RESULT)
2266  {
2267  my_decimal value, *arg_val= args[0]->val_decimal(&value);
2268  if (!arg_val) // Null
2269  arg_val= &decimal_zero;
2270  result_field->store_decimal(arg_val);
2271  }
2272  else
2273  {
2274  DBUG_ASSERT(hybrid_type == REAL_RESULT);
2275  double nr= args[0]->val_real(); // Nulls also return 0
2276  float8store(result_field->ptr, nr);
2277  }
2278  if (args[0]->null_value)
2279  result_field->set_null();
2280  else
2281  result_field->set_notnull();
2282 }
2283 
2284 
2285 void Item_sum_count::reset_field()
2286 {
2287  uchar *res=result_field->ptr;
2288  longlong nr=0;
2289  DBUG_ASSERT (aggr->Aggrtype() != Aggregator::DISTINCT_AGGREGATOR);
2290 
2291  if (!args[0]->maybe_null || !args[0]->is_null())
2292  nr=1;
2293  int8store(res,nr);
2294 }
2295 
2296 
2297 void Item_sum_avg::reset_field()
2298 {
2299  uchar *res=result_field->ptr;
2300  DBUG_ASSERT (aggr->Aggrtype() != Aggregator::DISTINCT_AGGREGATOR);
2301  if (hybrid_type == DECIMAL_RESULT)
2302  {
2303  longlong tmp;
2304  my_decimal value, *arg_dec= args[0]->val_decimal(&value);
2305  if (args[0]->null_value)
2306  {
2307  arg_dec= &decimal_zero;
2308  tmp= 0;
2309  }
2310  else
2311  tmp= 1;
2312  my_decimal2binary(E_DEC_FATAL_ERROR, arg_dec, res, f_precision, f_scale);
2313  res+= dec_bin_size;
2314  int8store(res, tmp);
2315  }
2316  else
2317  {
2318  double nr= args[0]->val_real();
2319 
2320  if (args[0]->null_value)
2321  memset(res, 0, sizeof(double)+sizeof(longlong));
2322  else
2323  {
2324  longlong tmp= 1;
2325  float8store(res,nr);
2326  res+=sizeof(double);
2327  int8store(res,tmp);
2328  }
2329  }
2330 }
2331 
2332 
2333 void Item_sum_bit::reset_field()
2334 {
2335  reset_and_add();
2336  int8store(result_field->ptr, bits);
2337 }
2338 
2339 void Item_sum_bit::update_field()
2340 {
2341  uchar *res=result_field->ptr;
2342  bits= uint8korr(res);
2343  add();
2344  int8store(res, bits);
2345 }
2346 
2347 
2353 {
2354  DBUG_ASSERT (aggr->Aggrtype() != Aggregator::DISTINCT_AGGREGATOR);
2355  if (hybrid_type == DECIMAL_RESULT)
2356  {
2357  my_decimal value, *arg_val= args[0]->val_decimal(&value);
2358  if (!args[0]->null_value)
2359  {
2360  if (!result_field->is_null())
2361  {
2362  my_decimal field_value,
2363  *field_val= result_field->val_decimal(&field_value);
2364  my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs, arg_val, field_val);
2365  result_field->store_decimal(dec_buffs);
2366  }
2367  else
2368  {
2369  result_field->store_decimal(arg_val);
2370  result_field->set_notnull();
2371  }
2372  }
2373  }
2374  else
2375  {
2376  double old_nr,nr;
2377  uchar *res=result_field->ptr;
2378 
2379  float8get(old_nr,res);
2380  nr= args[0]->val_real();
2381  if (!args[0]->null_value)
2382  {
2383  old_nr+=nr;
2384  result_field->set_notnull();
2385  }
2386  float8store(res,old_nr);
2387  }
2388 }
2389 
2390 
2391 void Item_sum_count::update_field()
2392 {
2393  longlong nr;
2394  uchar *res=result_field->ptr;
2395 
2396  nr=sint8korr(res);
2397  if (!args[0]->maybe_null || !args[0]->is_null())
2398  nr++;
2399  int8store(res,nr);
2400 }
2401 
2402 
2404 {
2405  longlong field_count;
2406  uchar *res=result_field->ptr;
2407 
2408  DBUG_ASSERT (aggr->Aggrtype() != Aggregator::DISTINCT_AGGREGATOR);
2409 
2410  if (hybrid_type == DECIMAL_RESULT)
2411  {
2412  my_decimal value, *arg_val= args[0]->val_decimal(&value);
2413  if (!args[0]->null_value)
2414  {
2415  binary2my_decimal(E_DEC_FATAL_ERROR, res,
2416  dec_buffs + 1, f_precision, f_scale);
2417  field_count= sint8korr(res + dec_bin_size);
2418  my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs, arg_val, dec_buffs + 1);
2419  my_decimal2binary(E_DEC_FATAL_ERROR, dec_buffs,
2420  res, f_precision, f_scale);
2421  res+= dec_bin_size;
2422  field_count++;
2423  int8store(res, field_count);
2424  }
2425  }
2426  else
2427  {
2428  double nr;
2429 
2430  nr= args[0]->val_real();
2431  if (!args[0]->null_value)
2432  {
2433  double old_nr;
2434  float8get(old_nr, res);
2435  field_count= sint8korr(res + sizeof(double));
2436  old_nr+= nr;
2437  float8store(res,old_nr);
2438  res+= sizeof(double);
2439  field_count++;
2440  int8store(res, field_count);
2441  }
2442  }
2443 }
2444 
2445 
2446 void Item_sum_hybrid::update_field()
2447 {
2448  switch (hybrid_type) {
2449  case STRING_RESULT:
2450  if (args[0]->is_temporal())
2451  min_max_update_temporal_field();
2452  else
2453  min_max_update_str_field();
2454  break;
2455  case INT_RESULT:
2456  min_max_update_int_field();
2457  break;
2458  case DECIMAL_RESULT:
2460  break;
2461  default:
2462  min_max_update_real_field();
2463  }
2464 }
2465 
2466 
2467 void Item_sum_hybrid::min_max_update_temporal_field()
2468 {
2469  longlong nr, old_nr;
2470  old_nr= result_field->val_temporal_by_field_type();
2471  nr= args[0]->val_temporal_by_field_type();
2472  if (!args[0]->null_value)
2473  {
2474  if (result_field->is_null(0))
2475  old_nr= nr;
2476  else
2477  {
2478  bool res= unsigned_flag ?
2479  (ulonglong) old_nr > (ulonglong) nr : old_nr > nr;
2480  if ((cmp_sign > 0) ^ (!res))
2481  old_nr= nr;
2482  }
2483  result_field->set_notnull();
2484  }
2485  else if (result_field->is_null(0))
2486  result_field->set_null();
2487  result_field->store_packed(old_nr);
2488 }
2489 
2490 
2491 void Item_sum_hybrid::min_max_update_str_field()
2492 {
2493  DBUG_ASSERT(cmp);
2494  String *res_str=args[0]->val_str(&cmp->value1);
2495 
2496  if (!args[0]->null_value)
2497  {
2498  result_field->val_str(&cmp->value2);
2499 
2500  if (result_field->is_null() ||
2501  (cmp_sign * sortcmp(res_str,&cmp->value2,collation.collation)) < 0)
2502  result_field->store(res_str->ptr(),res_str->length(),res_str->charset());
2503  result_field->set_notnull();
2504  }
2505 }
2506 
2507 
2508 void Item_sum_hybrid::min_max_update_real_field()
2509 {
2510  double nr,old_nr;
2511 
2512  old_nr=result_field->val_real();
2513  nr= args[0]->val_real();
2514  if (!args[0]->null_value)
2515  {
2516  if (result_field->is_null(0) ||
2517  (cmp_sign > 0 ? old_nr > nr : old_nr < nr))
2518  old_nr=nr;
2519  result_field->set_notnull();
2520  }
2521  else if (result_field->is_null(0))
2522  result_field->set_null();
2523  result_field->store(old_nr);
2524 }
2525 
2526 
2527 void Item_sum_hybrid::min_max_update_int_field()
2528 {
2529  longlong nr,old_nr;
2530 
2531  old_nr=result_field->val_int();
2532  nr=args[0]->val_int();
2533  if (!args[0]->null_value)
2534  {
2535  if (result_field->is_null(0))
2536  old_nr=nr;
2537  else
2538  {
2539  bool res=(unsigned_flag ?
2540  (ulonglong) old_nr > (ulonglong) nr :
2541  old_nr > nr);
2542  /* (cmp_sign > 0 && res) || (!(cmp_sign > 0) && !res) */
2543  if ((cmp_sign > 0) ^ (!res))
2544  old_nr=nr;
2545  }
2546  result_field->set_notnull();
2547  }
2548  else if (result_field->is_null(0))
2549  result_field->set_null();
2550  result_field->store(old_nr, unsigned_flag);
2551 }
2552 
2553 
2559 {
2560  /* TODO: optimize: do not get result_field in case of args[0] is NULL */
2561  my_decimal old_val, nr_val;
2562  const my_decimal *old_nr= result_field->val_decimal(&old_val);
2563  const my_decimal *nr= args[0]->val_decimal(&nr_val);
2564  if (!args[0]->null_value)
2565  {
2566  if (result_field->is_null(0))
2567  old_nr=nr;
2568  else
2569  {
2570  bool res= my_decimal_cmp(old_nr, nr) > 0;
2571  /* (cmp_sign > 0 && res) || (!(cmp_sign > 0) && !res) */
2572  if ((cmp_sign > 0) ^ (!res))
2573  old_nr=nr;
2574  }
2575  result_field->set_notnull();
2576  }
2577  else if (result_field->is_null(0))
2578  result_field->set_null();
2579  result_field->store_decimal(old_nr);
2580 }
2581 
2582 
2583 Item_avg_field::Item_avg_field(Item_result res_type, Item_sum_avg *item)
2584 {
2585  item_name= item->item_name;
2586  decimals=item->decimals;
2587  max_length= item->max_length;
2588  unsigned_flag= item->unsigned_flag;
2589  field=item->result_field;
2590  maybe_null=1;
2591  hybrid_type= res_type;
2592  prec_increment= item->prec_increment;
2593  if (hybrid_type == DECIMAL_RESULT)
2594  {
2595  f_scale= item->f_scale;
2596  f_precision= item->f_precision;
2597  dec_bin_size= item->dec_bin_size;
2598  }
2599 }
2600 
2601 double Item_avg_field::val_real()
2602 {
2603  // fix_fields() never calls for this Item
2604  double nr;
2605  longlong count;
2606  uchar *res;
2607 
2608  if (hybrid_type == DECIMAL_RESULT)
2609  return val_real_from_decimal();
2610 
2611  float8get(nr,field->ptr);
2612  res= (field->ptr+sizeof(double));
2613  count= sint8korr(res);
2614 
2615  if ((null_value= !count))
2616  return 0.0;
2617  return nr/(double) count;
2618 }
2619 
2620 
2621 my_decimal *Item_avg_field::val_decimal(my_decimal *dec_buf)
2622 {
2623  // fix_fields() never calls for this Item
2624  if (hybrid_type == REAL_RESULT)
2625  return val_decimal_from_real(dec_buf);
2626 
2627  longlong count= sint8korr(field->ptr + dec_bin_size);
2628  if ((null_value= !count))
2629  return 0;
2630 
2631  my_decimal dec_count, dec_field;
2632  binary2my_decimal(E_DEC_FATAL_ERROR,
2633  field->ptr, &dec_field, f_precision, f_scale);
2634  int2my_decimal(E_DEC_FATAL_ERROR, count, 0, &dec_count);
2635  my_decimal_div(E_DEC_FATAL_ERROR, dec_buf,
2636  &dec_field, &dec_count, prec_increment);
2637  return dec_buf;
2638 }
2639 
2640 
2641 String *Item_avg_field::val_str(String *str)
2642 {
2643  // fix_fields() never calls for this Item
2644  if (hybrid_type == DECIMAL_RESULT)
2645  return val_string_from_decimal(str);
2646  return val_string_from_real(str);
2647 }
2648 
2649 
2650 Item_std_field::Item_std_field(Item_sum_std *item)
2651  : Item_variance_field(item)
2652 {
2653 }
2654 
2655 
2656 double Item_std_field::val_real()
2657 {
2658  double nr;
2659  // fix_fields() never calls for this Item
2660  nr= Item_variance_field::val_real();
2661  DBUG_ASSERT(nr >= 0.0);
2662  return sqrt(nr);
2663 }
2664 
2665 
2666 my_decimal *Item_std_field::val_decimal(my_decimal *dec_buf)
2667 {
2668  /*
2669  We can't call val_decimal_from_real() for DECIMAL_RESULT as
2670  Item_variance_field::val_real() would cause an infinite loop
2671  */
2672  my_decimal tmp_dec, *dec;
2673  double nr;
2674  if (hybrid_type == REAL_RESULT)
2675  return val_decimal_from_real(dec_buf);
2676 
2677  dec= Item_variance_field::val_decimal(dec_buf);
2678  if (!dec)
2679  return 0;
2680  my_decimal2double(E_DEC_FATAL_ERROR, dec, &nr);
2681  DBUG_ASSERT(nr >= 0.0);
2682  nr= sqrt(nr);
2683  double2my_decimal(E_DEC_FATAL_ERROR, nr, &tmp_dec);
2684  my_decimal_round(E_DEC_FATAL_ERROR, &tmp_dec, decimals, FALSE, dec_buf);
2685  return dec_buf;
2686 }
2687 
2688 
2689 Item_variance_field::Item_variance_field(Item_sum_variance *item)
2690 {
2691  item_name= item->item_name;
2692  decimals=item->decimals;
2693  max_length=item->max_length;
2694  unsigned_flag= item->unsigned_flag;
2695  field=item->result_field;
2696  maybe_null=1;
2697  sample= item->sample;
2698  prec_increment= item->prec_increment;
2699  if ((hybrid_type= item->hybrid_type) == DECIMAL_RESULT)
2700  {
2701  f_scale0= item->f_scale0;
2702  f_precision0= item->f_precision0;
2703  dec_bin_size0= item->dec_bin_size0;
2704  f_scale1= item->f_scale1;
2705  f_precision1= item->f_precision1;
2706  dec_bin_size1= item->dec_bin_size1;
2707  }
2708 }
2709 
2710 
2711 double Item_variance_field::val_real()
2712 {
2713  // fix_fields() never calls for this Item
2714  if (hybrid_type == DECIMAL_RESULT)
2715  return val_real_from_decimal();
2716 
2717  double recurrence_s;
2718  ulonglong count;
2719  float8get(recurrence_s, (field->ptr + sizeof(double)));
2720  count=sint8korr(field->ptr+sizeof(double)*2);
2721 
2722  if ((null_value= (count <= sample)))
2723  return 0.0;
2724 
2725  return variance_fp_recurrence_result(recurrence_s, count, sample);
2726 }
2727 
2728 
2729 /****************************************************************************
2730 ** Functions to handle dynamic loadable aggregates
2731 ** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
2732 ** Adapted for UDAs by: Andreas F. Bobak <bobak@relog.ch>.
2733 ** Rewritten by: Monty.
2734 ****************************************************************************/
2735 
2736 #ifdef HAVE_DLOPEN
2737 
2738 void Item_udf_sum::clear()
2739 {
2740  DBUG_ENTER("Item_udf_sum::clear");
2741  udf.clear();
2742  DBUG_VOID_RETURN;
2743 }
2744 
2745 bool Item_udf_sum::add()
2746 {
2747  DBUG_ENTER("Item_udf_sum::add");
2748  udf.add(&null_value);
2749  DBUG_RETURN(0);
2750 }
2751 
2752 void Item_udf_sum::cleanup()
2753 {
2754  /*
2755  udf_handler::cleanup() nicely handles case when we have not
2756  original item but one created by copy_or_same() method.
2757  */
2758  udf.cleanup();
2759  Item_sum::cleanup();
2760 }
2761 
2762 
2763 void Item_udf_sum::print(String *str, enum_query_type query_type)
2764 {
2765  str->append(func_name());
2766  str->append('(');
2767  for (uint i=0 ; i < arg_count ; i++)
2768  {
2769  if (i)
2770  str->append(',');
2771  args[i]->print(str, query_type);
2772  }
2773  str->append(')');
2774 }
2775 
2776 
2777 Item *Item_sum_udf_float::copy_or_same(THD* thd)
2778 {
2779  return new (thd->mem_root) Item_sum_udf_float(thd, this);
2780 }
2781 
2782 double Item_sum_udf_float::val_real()
2783 {
2784  DBUG_ASSERT(fixed == 1);
2785  DBUG_ENTER("Item_sum_udf_float::val");
2786  DBUG_PRINT("info",("result_type: %d arg_count: %d",
2787  args[0]->result_type(), arg_count));
2788  DBUG_RETURN(udf.val(&null_value));
2789 }
2790 
2791 
2792 String *Item_sum_udf_float::val_str(String *str)
2793 {
2794  return val_string_from_real(str);
2795 }
2796 
2797 
2798 my_decimal *Item_sum_udf_float::val_decimal(my_decimal *dec)
2799 {
2800  return val_decimal_from_real(dec);
2801 }
2802 
2803 
2804 String *Item_sum_udf_decimal::val_str(String *str)
2805 {
2806  return val_string_from_decimal(str);
2807 }
2808 
2809 
2810 double Item_sum_udf_decimal::val_real()
2811 {
2812  return val_real_from_decimal();
2813 }
2814 
2815 
2816 longlong Item_sum_udf_decimal::val_int()
2817 {
2818  return val_int_from_decimal();
2819 }
2820 
2821 
2822 my_decimal *Item_sum_udf_decimal::val_decimal(my_decimal *dec_buf)
2823 {
2824  DBUG_ASSERT(fixed == 1);
2825  DBUG_ENTER("Item_func_udf_decimal::val_decimal");
2826  DBUG_PRINT("info",("result_type: %d arg_count: %d",
2827  args[0]->result_type(), arg_count));
2828 
2829  DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
2830 }
2831 
2832 
2833 Item *Item_sum_udf_decimal::copy_or_same(THD* thd)
2834 {
2835  return new (thd->mem_root) Item_sum_udf_decimal(thd, this);
2836 }
2837 
2838 
2839 Item *Item_sum_udf_int::copy_or_same(THD* thd)
2840 {
2841  return new (thd->mem_root) Item_sum_udf_int(thd, this);
2842 }
2843 
2844 longlong Item_sum_udf_int::val_int()
2845 {
2846  DBUG_ASSERT(fixed == 1);
2847  DBUG_ENTER("Item_sum_udf_int::val_int");
2848  DBUG_PRINT("info",("result_type: %d arg_count: %d",
2849  args[0]->result_type(), arg_count));
2850  DBUG_RETURN(udf.val_int(&null_value));
2851 }
2852 
2853 
2854 String *Item_sum_udf_int::val_str(String *str)
2855 {
2856  return val_string_from_int(str);
2857 }
2858 
2859 my_decimal *Item_sum_udf_int::val_decimal(my_decimal *dec)
2860 {
2861  return val_decimal_from_int(dec);
2862 }
2863 
2864 
2867 void Item_sum_udf_str::fix_length_and_dec()
2868 {
2869  DBUG_ENTER("Item_sum_udf_str::fix_length_and_dec");
2870  max_length=0;
2871  for (uint i = 0; i < arg_count; i++)
2872  set_if_bigger(max_length,args[i]->max_length);
2873  DBUG_VOID_RETURN;
2874 }
2875 
2876 
2877 Item *Item_sum_udf_str::copy_or_same(THD* thd)
2878 {
2879  return new (thd->mem_root) Item_sum_udf_str(thd, this);
2880 }
2881 
2882 
2883 my_decimal *Item_sum_udf_str::val_decimal(my_decimal *dec)
2884 {
2885  return val_decimal_from_string(dec);
2886 }
2887 
2888 String *Item_sum_udf_str::val_str(String *str)
2889 {
2890  DBUG_ASSERT(fixed == 1);
2891  DBUG_ENTER("Item_sum_udf_str::str");
2892  String *res=udf.val_str(str,&str_value);
2893  null_value = !res;
2894  DBUG_RETURN(res);
2895 }
2896 
2897 #endif /* HAVE_DLOPEN */
2898 
2899 
2900 /*****************************************************************************
2901  GROUP_CONCAT function
2902 
2903  SQL SYNTAX:
2904  GROUP_CONCAT([DISTINCT] expr,... [ORDER BY col [ASC|DESC],...]
2905  [SEPARATOR str_const])
2906 
2907  concat of values from "group by" operation
2908 
2909  BUGS
2910  Blobs doesn't work with DISTINCT or ORDER BY
2911 *****************************************************************************/
2912 
2913 
2914 
2930 extern "C"
2931 int group_concat_key_cmp_with_distinct(const void* arg, const void* key1,
2932  const void* key2)
2933 {
2935  TABLE *table= item_func->table;
2936 
2937  for (uint i= 0; i < item_func->arg_count_field; i++)
2938  {
2939  Item *item= item_func->args[i];
2940  /*
2941  If item is a const item then either get_tmp_table_field returns 0
2942  or it is an item over a const table.
2943  */
2944  if (item->const_item())
2945  continue;
2946  /*
2947  We have to use get_tmp_table_field() instead of
2948  real_item()->get_tmp_table_field() because we want the field in
2949  the temporary table, not the original field
2950  */
2951  Field *field= item->get_tmp_table_field();
2952 
2953  if (!field)
2954  continue;
2955 
2956  uint offset= field->offset(field->table->record[0])-table->s->null_bytes;
2957  int res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset);
2958  if (res)
2959  return res;
2960  }
2961  return 0;
2962 }
2963 
2964 
2969 extern "C"
2970 int group_concat_key_cmp_with_order(const void* arg, const void* key1,
2971  const void* key2)
2972 {
2973  const Item_func_group_concat* grp_item= (Item_func_group_concat*) arg;
2974  ORDER **order_item, **end;
2975  TABLE *table= grp_item->table;
2976 
2977  for (order_item= grp_item->order, end=order_item+ grp_item->arg_count_order;
2978  order_item < end;
2979  order_item++)
2980  {
2981  Item *item= *(*order_item)->item;
2982  /*
2983  If item is a const item then either get_tmp_table_field returns 0
2984  or it is an item over a const table.
2985  */
2986  if (item->const_item())
2987  continue;
2988  /*
2989  We have to use get_tmp_table_field() instead of
2990  real_item()->get_tmp_table_field() because we want the field in
2991  the temporary table, not the original field
2992  */
2993  Field *field= item->get_tmp_table_field();
2994  if (!field)
2995  continue;
2996 
2997  uint offset= (field->offset(field->table->record[0]) -
2998  table->s->null_bytes);
2999  int res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset);
3000  if (res)
3001  return ((*order_item)->direction == ORDER::ORDER_ASC) ? res : -res;
3002  }
3003  /*
3004  We can't return 0 because in that case the tree class would remove this
3005  item as double value. This would cause problems for case-changes and
3006  if the returned values are not the same we do the sort on.
3007  */
3008  return 1;
3009 }
3010 
3011 
3016 extern "C"
3017 int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)),
3018  void* item_arg)
3019 {
3020  Item_func_group_concat *item= (Item_func_group_concat *) item_arg;
3021  TABLE *table= item->table;
3022  String tmp((char *)table->record[1], table->s->reclength,
3023  default_charset_info);
3024  String tmp2;
3025  uchar *key= (uchar *) key_arg;
3026  String *result= &item->result;
3027  Item **arg= item->args, **arg_end= item->args + item->arg_count_field;
3028  uint old_length= result->length();
3029 
3030  if (item->no_appended)
3031  item->no_appended= FALSE;
3032  else
3033  result->append(*item->separator);
3034 
3035  tmp.length(0);
3036 
3037  for (; arg < arg_end; arg++)
3038  {
3039  String *res;
3040  /*
3041  We have to use get_tmp_table_field() instead of
3042  real_item()->get_tmp_table_field() because we want the field in
3043  the temporary table, not the original field
3044  We also can't use table->field array to access the fields
3045  because it contains both order and arg list fields.
3046  */
3047  if ((*arg)->const_item())
3048  res= (*arg)->val_str(&tmp);
3049  else
3050  {
3051  Field *field= (*arg)->get_tmp_table_field();
3052  if (field)
3053  {
3054  uint offset= (field->offset(field->table->record[0]) -
3055  table->s->null_bytes);
3056  DBUG_ASSERT(offset < table->s->reclength);
3057  res= field->val_str(&tmp, key + offset);
3058  }
3059  else
3060  res= (*arg)->val_str(&tmp);
3061  }
3062  if (res)
3063  result->append(*res);
3064  }
3065 
3066  item->row_count++;
3067 
3068  /* stop if length of result more than max_length */
3069  if (result->length() > item->max_length)
3070  {
3071  int well_formed_error;
3072  const CHARSET_INFO *cs= item->collation.collation;
3073  const char *ptr= result->ptr();
3074  uint add_length;
3075  /*
3076  It's ok to use item->result.length() as the fourth argument
3077  as this is never used to limit the length of the data.
3078  Cut is done with the third argument.
3079  */
3080  add_length= cs->cset->well_formed_len(cs,
3081  ptr + old_length,
3082  ptr + item->max_length,
3083  result->length(),
3084  &well_formed_error);
3085  result->length(old_length + add_length);
3086  item->warning_for_row= TRUE;
3087  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3088  ER_CUT_VALUE_GROUP_CONCAT, ER(ER_CUT_VALUE_GROUP_CONCAT),
3089  item->row_count);
3090 
3094  if (table && table->blob_storage)
3095  table->blob_storage->set_truncated_value(false);
3096  return 1;
3097  }
3098  return 0;
3099 }
3100 
3101 
3113  bool distinct_arg, List<Item> *select_list,
3114  const SQL_I_List<ORDER> &order_list,
3115  String *separator_arg)
3116  :tmp_table_param(0), separator(separator_arg), tree(0),
3117  unique_filter(NULL), table(0),
3118  order(0), context(context_arg),
3119  arg_count_order(order_list.elements),
3120  arg_count_field(select_list->elements),
3121  row_count(0),
3122  distinct(distinct_arg),
3123  warning_for_row(FALSE),
3124  force_copy_fields(0), original(0)
3125 {
3126  Item *item_select;
3127  Item **arg_ptr;
3128 
3129  quick_group= FALSE;
3130  arg_count= arg_count_field + arg_count_order;
3131 
3132  /*
3133  We need to allocate:
3134  args - arg_count_field+arg_count_order
3135  (for possible order items in temporare tables)
3136  order - arg_count_order
3137  */
3138  if (!(args= (Item**) sql_alloc(sizeof(Item*) * arg_count +
3139  sizeof(ORDER*)*arg_count_order)))
3140  return;
3141 
3142  if (!(orig_args= (Item **) sql_alloc(sizeof(Item *) * arg_count)))
3143  {
3144  args= NULL;
3145  return;
3146  }
3147 
3148  order= (ORDER**)(args + arg_count);
3149 
3150  /* fill args items of show and sort */
3151  List_iterator_fast<Item> li(*select_list);
3152 
3153  for (arg_ptr=args ; (item_select= li++) ; arg_ptr++)
3154  *arg_ptr= item_select;
3155 
3156  if (arg_count_order)
3157  {
3158  ORDER **order_ptr= order;
3159  for (ORDER *order_item= order_list.first;
3160  order_item != NULL;
3161  order_item= order_item->next)
3162  {
3163  (*order_ptr++)= order_item;
3164  *arg_ptr= *order_item->item;
3165  order_item->item= arg_ptr++;
3166  }
3167  }
3168  memcpy(orig_args, args, sizeof(Item*) * arg_count);
3169 }
3170 
3171 
3173  Item_func_group_concat *item)
3174  :Item_sum(thd, item),
3175  tmp_table_param(item->tmp_table_param),
3176  separator(item->separator),
3177  tree(item->tree),
3178  unique_filter(item->unique_filter),
3179  table(item->table),
3180  context(item->context),
3181  arg_count_order(item->arg_count_order),
3182  arg_count_field(item->arg_count_field),
3183  row_count(item->row_count),
3184  distinct(item->distinct),
3185  warning_for_row(item->warning_for_row),
3186  always_null(item->always_null),
3187  force_copy_fields(item->force_copy_fields),
3188  original(item)
3189 {
3190  quick_group= item->quick_group;
3191  result.set_charset(collation.collation);
3192 
3193  /*
3194  Since the ORDER structures pointed to by the elements of the 'order' array
3195  may be modified in find_order_in_list() called from
3196  Item_func_group_concat::setup(), create a copy of those structures so that
3197  such modifications done in this object would not have any effect on the
3198  object being copied.
3199  */
3200  ORDER *tmp;
3201  if (!(order= (ORDER **) thd->alloc(sizeof(ORDER *) * arg_count_order +
3202  sizeof(ORDER) * arg_count_order)))
3203  return;
3204  tmp= (ORDER *)(order + arg_count_order);
3205  for (uint i= 0; i < arg_count_order; i++, tmp++)
3206  {
3207  /*
3208  Compiler generated copy constructor is used to
3209  to copy all the members of ORDER struct.
3210  It's also necessary to update ORDER::next pointer
3211  so that it points to new ORDER element.
3212  */
3213  new (tmp) st_order(*(item->order[i]));
3214  tmp->next= (i + 1 == arg_count_order) ? NULL : (tmp + 1);
3215  order[i]= tmp;
3216  }
3217 }
3218 
3219 
3220 
3221 void Item_func_group_concat::cleanup()
3222 {
3223  DBUG_ENTER("Item_func_group_concat::cleanup");
3224  Item_sum::cleanup();
3225 
3226  /*
3227  Free table and tree if they belong to this item (if item have not pointer
3228  to original item from which was made copy => it own its objects )
3229  */
3230  if (!original)
3231  {
3232  delete tmp_table_param;
3233  tmp_table_param= 0;
3234  if (table)
3235  {
3236  THD *thd= table->in_use;
3237  if (table->blob_storage)
3238  delete table->blob_storage;
3239  free_tmp_table(thd, table);
3240  table= 0;
3241  if (tree)
3242  {
3243  delete_tree(tree);
3244  tree= 0;
3245  }
3246  if (unique_filter)
3247  {
3248  delete unique_filter;
3249  unique_filter= NULL;
3250  }
3251  }
3252  DBUG_ASSERT(tree == 0);
3253  }
3254  DBUG_VOID_RETURN;
3255 }
3256 
3257 
3259 {
3260  Field *field;
3261  DBUG_ASSERT(collation.collation);
3262  /*
3263  max_characters is maximum number of characters
3264  what can fit into max_length size. It's necessary
3265  to use field size what allows to store group_concat
3266  result without truncation. For this purpose we use
3267  max_characters * CS->mbmaxlen.
3268  */
3269  const uint32 max_characters= max_length / collation.collation->mbminlen;
3270  if (max_characters > CONVERT_IF_BIGGER_TO_BLOB)
3271  field= new Field_blob(max_characters * collation.collation->mbmaxlen,
3272  maybe_null, item_name.ptr(), collation.collation, TRUE);
3273  else
3274  field= new Field_varstring(max_characters * collation.collation->mbmaxlen,
3275  maybe_null, item_name.ptr(), table->s, collation.collation);
3276 
3277  if (field)
3278  field->init(table);
3279  return field;
3280 }
3281 
3282 
3283 Item *Item_func_group_concat::copy_or_same(THD* thd)
3284 {
3285  return new (thd->mem_root) Item_func_group_concat(thd, this);
3286 }
3287 
3288 
3289 void Item_func_group_concat::clear()
3290 {
3291  result.length(0);
3292  result.copy();
3293  null_value= TRUE;
3294  warning_for_row= FALSE;
3295  no_appended= TRUE;
3296  if (tree)
3297  reset_tree(tree);
3298  if (unique_filter)
3299  unique_filter->reset();
3300  if (table && table->blob_storage)
3301  table->blob_storage->reset();
3302  /* No need to reset the table as we never call write_row */
3303 }
3304 
3305 
3306 bool Item_func_group_concat::add()
3307 {
3308  if (always_null)
3309  return 0;
3310  copy_fields(tmp_table_param);
3311  if (copy_funcs(tmp_table_param->items_to_copy, table->in_use))
3312  return TRUE;
3313 
3314  for (uint i= 0; i < arg_count_field; i++)
3315  {
3316  Item *show_item= args[i];
3317  if (show_item->const_item())
3318  continue;
3319 
3320  Field *field= show_item->get_tmp_table_field();
3321  if (field && field->is_null_in_record((const uchar*) table->record[0]))
3322  return 0; // Skip row if it contains null
3323  }
3324 
3325  null_value= FALSE;
3326  bool row_eligible= TRUE;
3327 
3328  if (distinct)
3329  {
3330  /* Filter out duplicate rows. */
3331  uint count= unique_filter->elements_in_tree();
3332  unique_filter->unique_add(table->record[0] + table->s->null_bytes);
3333  if (count == unique_filter->elements_in_tree())
3334  row_eligible= FALSE;
3335  }
3336 
3337  TREE_ELEMENT *el= 0; // Only for safety
3338  if (row_eligible && tree)
3339  {
3340  DBUG_EXECUTE_IF("trigger_OOM_in_gconcat_add",
3341  DBUG_SET("+d,simulate_persistent_out_of_memory"););
3342  el= tree_insert(tree, table->record[0] + table->s->null_bytes, 0,
3343  tree->custom_arg);
3344  DBUG_EXECUTE_IF("trigger_OOM_in_gconcat_add",
3345  DBUG_SET("-d,simulate_persistent_out_of_memory"););
3346  /* check if there was enough memory to insert the row */
3347  if (!el)
3348  return 1;
3349  }
3350  /*
3351  If the row is not a duplicate (el->count == 1)
3352  we can dump the row here in case of GROUP_CONCAT(DISTINCT...)
3353  instead of doing tree traverse later.
3354  */
3355  if (row_eligible && !warning_for_row &&
3356  (!tree || (el->count == 1 && distinct && !arg_count_order)))
3357  dump_leaf_key(table->record[0] + table->s->null_bytes, 1, this);
3358 
3359  return 0;
3360 }
3361 
3362 
3363 bool
3364 Item_func_group_concat::fix_fields(THD *thd, Item **ref)
3365 {
3366  uint i; /* for loop variable */
3367  DBUG_ASSERT(fixed == 0);
3368 
3369  if (init_sum_func_check(thd))
3370  return TRUE;
3371 
3372  maybe_null= 1;
3373 
3374  /*
3375  Fix fields for select list and ORDER clause
3376  */
3377 
3378  for (i=0 ; i < arg_count ; i++)
3379  {
3380  if ((!args[i]->fixed &&
3381  args[i]->fix_fields(thd, args + i)) ||
3382  args[i]->check_cols(1))
3383  return TRUE;
3384  }
3385 
3386  /* skip charset aggregation for order columns */
3387  if (agg_item_charsets_for_string_result(collation, func_name(),
3388  args, arg_count - arg_count_order))
3389  return 1;
3390 
3391  result.set_charset(collation.collation);
3392  result_field= 0;
3393  null_value= 1;
3394  max_length= thd->variables.group_concat_max_len;
3395 
3396  uint32 offset;
3397  if (separator->needs_conversion(separator->length(), separator->charset(),
3398  collation.collation, &offset))
3399  {
3400  uint32 buflen= collation.collation->mbmaxlen * separator->length();
3401  uint errors, conv_length;
3402  char *buf;
3403  String *new_separator;
3404 
3405  if (!(buf= (char*) thd->stmt_arena->alloc(buflen)) ||
3406  !(new_separator= new(thd->stmt_arena->mem_root)
3407  String(buf, buflen, collation.collation)))
3408  return TRUE;
3409 
3410  conv_length= copy_and_convert(buf, buflen, collation.collation,
3411  separator->ptr(), separator->length(),
3412  separator->charset(), &errors);
3413  new_separator->length(conv_length);
3414  separator= new_separator;
3415  }
3416 
3417  if (check_sum_func(thd, ref))
3418  return TRUE;
3419 
3420  fixed= 1;
3421  return FALSE;
3422 }
3423 
3424 
3426 {
3427  List<Item> list;
3428  SELECT_LEX *select_lex= thd->lex->current_select;
3429  const bool order_or_distinct= test(arg_count_order > 0 || distinct);
3430  DBUG_ENTER("Item_func_group_concat::setup");
3431 
3432  /*
3433  Currently setup() can be called twice. Please add
3434  assertion here when this is fixed.
3435  */
3436  if (table || tree)
3437  DBUG_RETURN(FALSE);
3438 
3439  if (!(tmp_table_param= new TMP_TABLE_PARAM))
3440  DBUG_RETURN(TRUE);
3441 
3442  /* Push all not constant fields to the list and create a temp table */
3443  always_null= 0;
3444  for (uint i= 0; i < arg_count_field; i++)
3445  {
3446  Item *item= args[i];
3447  if (list.push_back(item))
3448  DBUG_RETURN(TRUE);
3449  if (item->const_item())
3450  {
3451  if (item->is_null())
3452  {
3453  always_null= 1;
3454  DBUG_RETURN(FALSE);
3455  }
3456  }
3457  }
3458 
3459  List<Item> all_fields(list);
3460  /*
3461  Try to find every ORDER expression in the list of GROUP_CONCAT
3462  arguments. If an expression is not found, prepend it to
3463  "all_fields". The resulting field list is used as input to create
3464  tmp table columns.
3465  */
3466  if (arg_count_order &&
3467  setup_order(thd, Ref_ptr_array(args, arg_count),
3468  context->table_list, list, all_fields, *order))
3469  DBUG_RETURN(TRUE);
3470 
3471  count_field_types(select_lex, tmp_table_param, all_fields, 0);
3472  tmp_table_param->force_copy_fields= force_copy_fields;
3473  DBUG_ASSERT(table == 0);
3474  if (order_or_distinct)
3475  {
3476  /*
3477  Force the create_tmp_table() to convert BIT columns to INT
3478  as we cannot compare two table records containg BIT fields
3479  stored in the the tree used for distinct/order by.
3480  Moreover we don't even save in the tree record null bits
3481  where BIT fields store parts of their data.
3482  */
3483  List_iterator_fast<Item> li(all_fields);
3484  Item *item;
3485  while ((item= li++))
3486  {
3487  if (item->type() == Item::FIELD_ITEM &&
3488  ((Item_field*) item)->field->type() == FIELD_TYPE_BIT)
3489  item->marker= 4;
3490  }
3491  }
3492 
3493  /*
3494  We have to create a temporary table to get descriptions of fields
3495  (types, sizes and so on).
3496 
3497  Note that in the table, we first have the ORDER BY fields, then the
3498  field list.
3499  */
3500  if (!(table= create_tmp_table(thd, tmp_table_param, all_fields,
3501  (ORDER*) 0, 0, TRUE,
3502  (select_lex->options | thd->variables.option_bits),
3503  HA_POS_ERROR, (char*) "")))
3504  DBUG_RETURN(TRUE);
3505  table->file->extra(HA_EXTRA_NO_ROWS);
3506  table->no_rows= 1;
3507 
3512  if (order_or_distinct && table->s->blob_fields)
3513  table->blob_storage= new Blob_mem_storage();
3514 
3515  /*
3516  Need sorting or uniqueness: init tree and choose a function to sort.
3517  Don't reserve space for NULLs: if any of gconcat arguments is NULL,
3518  the row is not added to the result.
3519  */
3520  uint tree_key_length= table->s->reclength - table->s->null_bytes;
3521 
3522  if (arg_count_order)
3523  {
3524  tree= &tree_base;
3525  /*
3526  Create a tree for sorting. The tree is used to sort (according to the
3527  syntax of this function). If there is no ORDER BY clause, we don't
3528  create this tree.
3529  */
3530  init_tree(tree, min<uint>(thd->variables.max_heap_table_size,
3531  thd->variables.sortbuff_size/16), 0,
3532  tree_key_length,
3533  group_concat_key_cmp_with_order , 0, NULL, (void*) this);
3534  }
3535 
3536  if (distinct)
3537  unique_filter= new Unique(group_concat_key_cmp_with_distinct,
3538  (void*)this,
3539  tree_key_length,
3540  ram_limitation(thd));
3541 
3542  DBUG_RETURN(FALSE);
3543 }
3544 
3545 
3546 /* This is used by rollup to create a separate usable copy of the function */
3547 
3548 void Item_func_group_concat::make_unique()
3549 {
3550  tmp_table_param= 0;
3551  table=0;
3552  original= 0;
3553  force_copy_fields= 1;
3554  tree= 0;
3555 }
3556 
3557 
3558 String* Item_func_group_concat::val_str(String* str)
3559 {
3560  DBUG_ASSERT(fixed == 1);
3561  if (null_value)
3562  return 0;
3563  if (no_appended && tree)
3564  /* Tree is used for sorting as in ORDER BY */
3565  tree_walk(tree, &dump_leaf_key, this, left_root_right);
3566 
3567  if (table && table->blob_storage &&
3568  table->blob_storage->is_truncated_value())
3569  {
3570  warning_for_row= true;
3571  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3572  ER_CUT_VALUE_GROUP_CONCAT, ER(ER_CUT_VALUE_GROUP_CONCAT),
3573  row_count);
3574  }
3575 
3576  return &result;
3577 }
3578 
3579 
3580 void Item_func_group_concat::print(String *str, enum_query_type query_type)
3581 {
3582  str->append(STRING_WITH_LEN("group_concat("));
3583  if (distinct)
3584  str->append(STRING_WITH_LEN("distinct "));
3585  for (uint i= 0; i < arg_count_field; i++)
3586  {
3587  if (i)
3588  str->append(',');
3589  orig_args[i]->print(str, query_type);
3590  }
3591  if (arg_count_order)
3592  {
3593  str->append(STRING_WITH_LEN(" order by "));
3594  for (uint i= 0 ; i < arg_count_order ; i++)
3595  {
3596  if (i)
3597  str->append(',');
3598  orig_args[i + arg_count_field]->print(str, query_type);
3599  if (order[i]->direction == ORDER::ORDER_ASC)
3600  str->append(STRING_WITH_LEN(" ASC"));
3601  else
3602  str->append(STRING_WITH_LEN(" DESC"));
3603  }
3604  }
3605  str->append(STRING_WITH_LEN(" separator \'"));
3606  str->append(*separator);
3607  str->append(STRING_WITH_LEN("\')"));
3608 }
3609 
3610 
3611 Item_func_group_concat::~Item_func_group_concat()
3612 {
3613  if (!original && unique_filter)
3614  delete unique_filter;
3615 }