~ubuntu-branches/ubuntu/precise/mysql-5.1/precise

« back to all changes in this revision

Viewing changes to sql/item_sum.cc

  • Committer: Bazaar Package Importer
  • Author(s): Norbert Tretkowski
  • Date: 2010-03-17 14:56:02 UTC
  • Revision ID: james.westby@ubuntu.com-20100317145602-x7e30l1b2sb5s6w6
Tags: upstream-5.1.45
ImportĀ upstreamĀ versionĀ 5.1.45

Show diffs side-by-side

added added

removed removed

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