~drizzle-trunk/drizzle/development

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