~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/item_sum.cc

Renamed more stuff to drizzle.

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
  @brief
21
21
  Sum functions (COUNT, MIN...)
22
22
*/
23
 
#include "config.h"
24
 
#include <cstdio>
25
 
#include <math.h>
26
 
#include <drizzled/sql_select.h>
27
 
#include <drizzled/error.h>
28
 
#include <drizzled/hybrid_type_traits.h>
29
 
#include <drizzled/hybrid_type_traits_integer.h>
30
 
#include <drizzled/hybrid_type_traits_decimal.h>
31
 
#include <drizzled/sql_base.h>
32
 
 
33
 
#include <drizzled/item/sum.h>
34
 
#include <drizzled/field/decimal.h>
35
 
#include <drizzled/field/double.h>
36
 
#include <drizzled/field/int64_t.h>
37
 
#include <drizzled/field/date.h>
38
 
#include <drizzled/field/datetime.h>
39
 
 
40
 
#include "drizzled/internal/m_string.h"
41
 
 
42
 
#include <algorithm>
43
 
 
44
 
using namespace std;
45
 
 
46
 
namespace drizzled
47
 
{
48
 
 
49
 
extern my_decimal decimal_zero;
50
 
extern plugin::StorageEngine *heap_engine;
 
23
 
 
24
#ifdef USE_PRAGMA_IMPLEMENTATION
 
25
#pragma implementation                          // gcc: Class implementation
 
26
#endif
 
27
 
 
28
#include "mysql_priv.h"
 
29
#include "sql_select.h"
51
30
 
52
31
/**
53
32
  Prepare an aggregate function item for checking context conditions.
58
37
    If the set function is not allowed in any subquery where it occurs
59
38
    an error is reported immediately.
60
39
 
61
 
  @param session      reference to the thread context info
 
40
  @param thd      reference to the thread context info
62
41
 
63
42
  @note
64
43
    This function is to be called for any item created for a set function
70
49
  @retval
71
50
    FALSE  otherwise
72
51
*/
73
 
 
74
 
bool Item_sum::init_sum_func_check(Session *session)
 
52
 
 
53
bool Item_sum::init_sum_func_check(THD *thd)
75
54
{
76
 
  if (!session->lex->allow_sum_func)
 
55
  if (!thd->lex->allow_sum_func)
77
56
  {
78
57
    my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE),
79
58
               MYF(0));
80
 
    return true;
 
59
    return TRUE;
81
60
  }
82
61
  /* Set a reference to the nesting set function if there is  any */
83
 
  in_sum_func= session->lex->in_sum_func;
 
62
  in_sum_func= thd->lex->in_sum_func;
84
63
  /* Save a pointer to object to be used in items for nested set functions */
85
 
  session->lex->in_sum_func= this;
86
 
  nest_level= session->lex->current_select->nest_level;
 
64
  thd->lex->in_sum_func= this;
 
65
  nest_level= thd->lex->current_select->nest_level;
87
66
  ref_by= 0;
88
67
  aggr_level= -1;
89
68
  aggr_sel= NULL;
90
69
  max_arg_level= -1;
91
70
  max_sum_func_level= -1;
92
71
  outer_fields.empty();
93
 
  return false;
 
72
  return FALSE;
94
73
}
95
74
 
96
75
/**
105
84
    If the context conditions are not met the method reports an error.
106
85
    If the set function is aggregated in some outer subquery the method
107
86
    adds it to the chain of items for such set functions that is attached
108
 
    to the the Select_Lex structure for this subquery.
 
87
    to the the st_select_lex structure for this subquery.
109
88
 
110
89
    A number of designated members of the object are used to check the
111
90
    conditions. They are specified in the comment before the Item_sum
112
91
    class declaration.
113
92
    Additionally a bitmap variable called allow_sum_func is employed.
114
 
    It is included into the session->lex structure.
 
93
    It is included into the thd->lex structure.
115
94
    The bitmap contains 1 at n-th position if the set function happens
116
95
    to occur under a construct of the n-th level subquery where usage
117
96
    of set functions are allowed (i.e either in the SELECT list or
122
101
         HAVING t1.a IN (SELECT t2.c FROM t2 WHERE AVG(t1.b) > 20) AND
123
102
                t1.a > (SELECT MIN(t2.d) FROM t2);
124
103
    @endcode
125
 
    allow_sum_func will contain:
126
 
    - for SUM(t1.b) - 1 at the first position
 
104
    allow_sum_func will contain: 
 
105
    - for SUM(t1.b) - 1 at the first position 
127
106
    - for AVG(t1.b) - 1 at the first position, 0 at the second position
128
107
    - for MIN(t2.d) - 1 at the first position, 1 at the second position.
129
108
 
130
 
  @param session  reference to the thread context info
 
109
  @param thd  reference to the thread context info
131
110
  @param ref  location of the pointer to this item in the embedding expression
132
111
 
133
112
  @note
141
120
  @retval
142
121
    FALSE  otherwise
143
122
*/
144
 
 
145
 
bool Item_sum::check_sum_func(Session *session, Item **ref)
 
123
 
 
124
bool Item_sum::check_sum_func(THD *thd, Item **ref)
146
125
{
147
 
  bool invalid= false;
148
 
  nesting_map allow_sum_func= session->lex->allow_sum_func;
149
 
  /*
 
126
  bool invalid= FALSE;
 
127
  nesting_map allow_sum_func= thd->lex->allow_sum_func;
 
128
  /*  
150
129
    The value of max_arg_level is updated if an argument of the set function
151
130
    contains a column reference resolved  against a subquery whose level is
152
131
    greater than the current value of max_arg_level.
153
132
    max_arg_level cannot be greater than nest level.
154
 
    nest level is always >= 0
155
 
  */
 
133
    nest level is always >= 0  
 
134
  */ 
156
135
  if (nest_level == max_arg_level)
157
136
  {
158
137
    /*
159
 
      The function must be aggregated in the current subquery,
160
 
      If it is there under a construct where it is not allowed
161
 
      we report an error.
162
 
    */
 
138
      The function must be aggregated in the current subquery, 
 
139
      If it is there under a construct where it is not allowed 
 
140
      we report an error. 
 
141
    */ 
163
142
    invalid= !(allow_sum_func & (1 << max_arg_level));
164
143
  }
165
144
  else if (max_arg_level >= 0 || !(allow_sum_func & (1 << nest_level)))
169
148
      Try to find a subquery where it can be aggregated;
170
149
      If we fail to find such a subquery report an error.
171
150
    */
172
 
    if (register_sum_func(session, ref))
173
 
      return true;
 
151
    if (register_sum_func(thd, ref))
 
152
      return TRUE;
174
153
    invalid= aggr_level < 0 && !(allow_sum_func & (1 << nest_level));
175
 
    if (!invalid && false)
 
154
    if (!invalid && thd->variables.sql_mode & MODE_ANSI)
176
155
      invalid= aggr_level < 0 && max_arg_level < nest_level;
177
156
  }
178
157
  if (!invalid && aggr_level < 0)
179
158
  {
180
159
    aggr_level= nest_level;
181
 
    aggr_sel= session->lex->current_select;
 
160
    aggr_sel= thd->lex->current_select;
182
161
  }
183
162
  /*
184
163
    By this moment we either found a subquery where the set function is
185
164
    to be aggregated  and assigned a value that is  >= 0 to aggr_level,
186
 
    or set the value of 'invalid' to TRUE to report later an error.
 
165
    or set the value of 'invalid' to TRUE to report later an error. 
187
166
  */
188
 
  /*
 
167
  /* 
189
168
    Additionally we have to check whether possible nested set functions
190
169
    are acceptable here: they are not, if the level of aggregation of
191
170
    some of them is less than aggr_level.
192
171
  */
193
 
  if (!invalid)
 
172
  if (!invalid) 
194
173
    invalid= aggr_level <= max_sum_func_level;
195
 
  if (invalid)
 
174
  if (invalid)  
196
175
  {
197
176
    my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE),
198
177
               MYF(0));
199
 
    return true;
 
178
    return TRUE;
200
179
  }
201
180
 
202
181
  if (in_sum_func)
204
183
    /*
205
184
      If the set function is nested adjust the value of
206
185
      max_sum_func_level for the nesting set function.
207
 
      We take into account only enclosed set functions that are to be
208
 
      aggregated on the same level or above of the nest level of
 
186
      We take into account only enclosed set functions that are to be 
 
187
      aggregated on the same level or above of the nest level of 
209
188
      the enclosing set function.
210
189
      But we must always pass up the max_sum_func_level because it is
211
190
      the maximum nested level of all directly and indirectly enclosed
256
235
    List_iterator<Item_field> of(outer_fields);
257
236
    while ((field= of++))
258
237
    {
259
 
      Select_Lex *sel= field->cached_table->select_lex;
 
238
      SELECT_LEX *sel= field->cached_table->select_lex;
260
239
      if (sel->nest_level < aggr_level)
261
240
      {
262
241
        if (in_sum_func)
268
247
          in_sum_func->outer_fields.push_back(field);
269
248
        }
270
249
        else
271
 
        {
272
 
          sel->full_group_by_flag.set(NON_AGG_FIELD_USED);
273
 
        }
 
250
          sel->full_group_by_flag|= NON_AGG_FIELD_USED;
274
251
      }
275
252
      if (sel->nest_level > aggr_level &&
276
 
          (sel->full_group_by_flag.test(SUM_FUNC_USED)) &&
277
 
          ! sel->group_list.elements)
 
253
          (sel->full_group_by_flag & SUM_FUNC_USED) &&
 
254
          !sel->group_list.elements)
278
255
      {
279
256
        my_message(ER_MIX_OF_GROUP_FUNC_AND_FIELDS,
280
257
                   ER(ER_MIX_OF_GROUP_FUNC_AND_FIELDS), MYF(0));
281
 
        return true;
 
258
        return TRUE;
282
259
      }
283
260
    }
284
261
  }
285
 
  aggr_sel->full_group_by_flag.set(SUM_FUNC_USED);
 
262
  aggr_sel->full_group_by_flag|= SUM_FUNC_USED;
286
263
  update_used_tables();
287
 
  session->lex->in_sum_func= in_sum_func;
288
 
  return false;
 
264
  thd->lex->in_sum_func= in_sum_func;
 
265
  return FALSE;
289
266
}
290
267
 
291
268
/**
295
272
    aggregated. If it finds such a subquery then aggr_level is set to
296
273
    the nest level of this subquery and the item for the set function
297
274
    is added to the list of set functions used in nested subqueries
298
 
    inner_sum_func_list defined for each subquery. When the item is placed
 
275
    inner_sum_func_list defined for each subquery. When the item is placed 
299
276
    there the field 'ref_by' is set to ref.
300
277
 
301
278
  @note
304
281
    a subquery in one chain. It would simplify the process of 'splitting'
305
282
    for set functions.
306
283
 
307
 
  @param session  reference to the thread context info
 
284
  @param thd  reference to the thread context info
308
285
  @param ref  location of the pointer to this item in the embedding expression
309
286
 
310
287
  @retval
311
288
    FALSE  if the executes without failures (currently always)
312
289
  @retval
313
290
    TRUE   otherwise
314
 
*/
 
291
*/  
315
292
 
316
 
bool Item_sum::register_sum_func(Session *session, Item **ref)
 
293
bool Item_sum::register_sum_func(THD *thd, Item **ref)
317
294
{
318
 
  Select_Lex *sl;
319
 
  nesting_map allow_sum_func= session->lex->allow_sum_func;
320
 
  for (sl= session->lex->current_select->master_unit()->outer_select() ;
 
295
  SELECT_LEX *sl;
 
296
  nesting_map allow_sum_func= thd->lex->allow_sum_func;
 
297
  for (sl= thd->lex->current_select->master_unit()->outer_select() ;
321
298
       sl && sl->nest_level > max_arg_level;
322
299
       sl= sl->master_unit()->outer_select() )
323
300
  {
330
307
  }
331
308
  if (sl && (allow_sum_func & (1 << sl->nest_level)))
332
309
  {
333
 
    /*
 
310
    /* 
334
311
      We reached the subquery of level max_arg_level and checked
335
 
      that the function can be aggregated here.
 
312
      that the function can be aggregated here. 
336
313
      The set function will be aggregated in this subquery.
337
 
    */
 
314
    */   
338
315
    aggr_level= sl->nest_level;
339
316
    aggr_sel= sl;
340
317
 
353
330
    aggr_sel->inner_sum_func_list= this;
354
331
    aggr_sel->with_sum_func= 1;
355
332
 
356
 
    /*
 
333
    /* 
357
334
      Mark Item_subselect(s) as containing aggregate function all the way up
358
335
      to aggregate function's calculation context.
359
336
      Note that we must not mark the Item of calculation context itself
360
 
      because with_sum_func on the calculation context Select_Lex is
 
337
      because with_sum_func on the calculation context st_select_lex is
361
338
      already set above.
362
339
 
363
 
      with_sum_func being set for an Item means that this Item refers
 
340
      with_sum_func being set for an Item means that this Item refers 
364
341
      (somewhere in it, e.g. one of its arguments if it's a function) directly
365
342
      or through intermediate items to an aggregate function that is calculated
366
343
      in a context "outside" of the Item (e.g. in the current or outer select).
367
344
 
368
 
      with_sum_func being set for an Select_Lex means that this Select_Lex
 
345
      with_sum_func being set for an st_select_lex means that this st_select_lex
369
346
      has aggregate functions directly referenced (i.e. not through a sub-select).
370
347
    */
371
 
    for (sl= session->lex->current_select;
 
348
    for (sl= thd->lex->current_select; 
372
349
         sl && sl != aggr_sel && sl->master_unit()->item;
373
350
         sl= sl->master_unit()->outer_select() )
374
351
      sl->master_unit()->item->with_sum_func= 1;
375
352
  }
376
 
  session->lex->current_select->mark_as_dependent(aggr_sel);
377
 
  return false;
 
353
  thd->lex->current_select->mark_as_dependent(aggr_sel);
 
354
  return FALSE;
378
355
}
379
356
 
380
357
 
381
 
Item_sum::Item_sum(List<Item> &list) :arg_count(list.elements),
382
 
  forced_const(false)
 
358
Item_sum::Item_sum(List<Item> &list) :arg_count(list.elements), 
 
359
  forced_const(FALSE)
383
360
{
384
 
  if ((args=(Item**) memory::sql_alloc(sizeof(Item*)*arg_count)))
 
361
  if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
385
362
  {
386
 
    uint32_t i=0;
 
363
    uint i=0;
387
364
    List_iterator_fast<Item> li(list);
388
365
    Item *item;
389
366
 
401
378
  Constructor used in processing select with temporary tebles.
402
379
*/
403
380
 
404
 
Item_sum::Item_sum(Session *session, Item_sum *item):
405
 
  Item_result_field(session, item), arg_count(item->arg_count),
 
381
Item_sum::Item_sum(THD *thd, Item_sum *item):
 
382
  Item_result_field(thd, item), arg_count(item->arg_count),
406
383
  aggr_sel(item->aggr_sel),
407
384
  nest_level(item->nest_level), aggr_level(item->aggr_level),
408
385
  quick_group(item->quick_group), used_tables_cache(item->used_tables_cache),
409
 
  forced_const(item->forced_const)
 
386
  forced_const(item->forced_const) 
410
387
{
411
388
  if (arg_count <= 2)
412
389
    args=tmp_args;
413
390
  else
414
 
    if (!(args= (Item**) session->alloc(sizeof(Item*)*arg_count)))
 
391
    if (!(args= (Item**) thd->alloc(sizeof(Item*)*arg_count)))
415
392
      return;
416
393
  memcpy(args, item->args, sizeof(Item*)*arg_count);
417
394
}
419
396
 
420
397
void Item_sum::mark_as_sum_func()
421
398
{
422
 
  Select_Lex *cur_select= current_session->lex->current_select;
 
399
  SELECT_LEX *cur_select= current_thd->lex->current_select;
423
400
  cur_select->n_sum_items++;
424
401
  cur_select->with_sum_func= 1;
425
402
  with_sum_func= 1;
426
403
}
427
404
 
428
405
 
429
 
void Item_sum::make_field(SendField *tmp_field)
 
406
void Item_sum::make_field(Send_field *tmp_field)
430
407
{
431
408
  if (args[0]->type() == Item::FIELD_ITEM && keep_field_type())
432
409
  {
449
426
void Item_sum::print(String *str, enum_query_type query_type)
450
427
{
451
428
  str->append(func_name());
452
 
  for (uint32_t i=0 ; i < arg_count ; i++)
 
429
  for (uint i=0 ; i < arg_count ; i++)
453
430
  {
454
431
    if (i)
455
432
      str->append(',');
461
438
void Item_sum::fix_num_length_and_dec()
462
439
{
463
440
  decimals=0;
464
 
  for (uint32_t i=0 ; i < arg_count ; i++)
 
441
  for (uint i=0 ; i < arg_count ; i++)
465
442
    set_if_bigger(decimals,args[i]->decimals);
466
443
  max_length=float_length(decimals);
467
444
}
468
445
 
469
 
Item *Item_sum::get_tmp_table_item(Session *session)
 
446
Item *Item_sum::get_tmp_table_item(THD *thd)
470
447
{
471
 
  Item_sum* sum_item= (Item_sum *) copy_or_same(session);
 
448
  Item_sum* sum_item= (Item_sum *) copy_or_same(thd);
472
449
  if (sum_item && sum_item->result_field)          // If not a const sum func
473
450
  {
474
451
    Field *result_field_tmp= sum_item->result_field;
475
 
    for (uint32_t i=0 ; i < sum_item->arg_count ; i++)
 
452
    for (uint i=0 ; i < sum_item->arg_count ; i++)
476
453
    {
477
454
      Item *arg= sum_item->args[i];
478
455
      if (!arg->const_item())
489
466
 
490
467
 
491
468
bool Item_sum::walk (Item_processor processor, bool walk_subquery,
492
 
                     unsigned char *argument)
 
469
                     uchar *argument)
493
470
{
494
471
  if (arg_count)
495
472
  {
504
481
}
505
482
 
506
483
 
507
 
Field *Item_sum::create_tmp_field(bool ,
508
 
                                  Table *table,
509
 
                                  uint32_t convert_blob_length)
 
484
Field *Item_sum::create_tmp_field(bool group __attribute__((__unused__)),
 
485
                                  TABLE *table,
 
486
                                  uint convert_blob_length)
510
487
{
511
488
  Field *field;
512
489
  switch (result_type()) {
513
490
  case REAL_RESULT:
514
 
    field= new Field_double(max_length, maybe_null, name, decimals, true);
 
491
    field= new Field_double(max_length, maybe_null, name, decimals, TRUE);
515
492
    break;
516
493
  case INT_RESULT:
517
 
    field= new Field_int64_t(max_length, maybe_null, name, unsigned_flag);
 
494
    field= new Field_longlong(max_length, maybe_null, name, unsigned_flag);
518
495
    break;
519
496
  case STRING_RESULT:
520
497
    if (max_length/collation.collation->mbmaxlen <= 255 ||
522
499
        !convert_blob_length)
523
500
      return make_string_field(table);
524
501
    field= new Field_varstring(convert_blob_length, maybe_null,
525
 
                               name, table->getMutableShare(), collation.collation);
 
502
                               name, table->s, collation.collation);
526
503
    break;
527
504
  case DECIMAL_RESULT:
528
 
    field= new Field_decimal(max_length, maybe_null, name,
 
505
    field= new Field_new_decimal(max_length, maybe_null, name,
529
506
                                 decimals, unsigned_flag);
530
507
    break;
531
508
  case ROW_RESULT:
532
509
  default:
533
510
    // This case should never be choosen
534
 
    assert(0);
 
511
    DBUG_ASSERT(0);
535
512
    return 0;
536
513
  }
537
514
  if (field)
545
522
  if (!forced_const)
546
523
  {
547
524
    used_tables_cache= 0;
548
 
    for (uint32_t i=0 ; i < arg_count ; i++)
 
525
    for (uint i=0 ; i < arg_count ; i++)
549
526
    {
550
527
      args[i]->update_used_tables();
551
528
      used_tables_cache|= args[i]->used_tables();
566
543
}
567
544
 
568
545
 
569
 
int64_t Item_sum_num::val_int()
570
 
{
571
 
  assert(fixed == 1);
572
 
  return (int64_t) rint(val_real());             /* Real as default */
573
 
}
574
 
 
575
 
 
576
546
my_decimal *Item_sum_num::val_decimal(my_decimal *decimal_value)
577
547
{
578
548
  return val_decimal_from_real(decimal_value);
593
563
 
594
564
 
595
565
bool
596
 
Item_sum_num::fix_fields(Session *session, Item **ref)
 
566
Item_sum_num::fix_fields(THD *thd, Item **ref)
597
567
{
598
 
  assert(fixed == 0);
 
568
  DBUG_ASSERT(fixed == 0);
599
569
 
600
 
  if (init_sum_func_check(session))
601
 
    return true;
 
570
  if (init_sum_func_check(thd))
 
571
    return TRUE;
602
572
 
603
573
  decimals=0;
604
574
  maybe_null=0;
605
 
  for (uint32_t i=0 ; i < arg_count ; i++)
 
575
  for (uint i=0 ; i < arg_count ; i++)
606
576
  {
607
 
    if (args[i]->fix_fields(session, args + i) || args[i]->check_cols(1))
608
 
      return true;
 
577
    if (args[i]->fix_fields(thd, args + i) || args[i]->check_cols(1))
 
578
      return TRUE;
609
579
    set_if_bigger(decimals, args[i]->decimals);
610
580
    maybe_null |= args[i]->maybe_null;
611
581
  }
614
584
  null_value=1;
615
585
  fix_length_and_dec();
616
586
 
617
 
  if (check_sum_func(session, ref))
618
 
    return true;
 
587
  if (check_sum_func(thd, ref))
 
588
    return TRUE;
619
589
 
620
590
  fixed= 1;
621
 
  return false;
 
591
  return FALSE;
622
592
}
623
593
 
624
594
 
625
 
Item_sum_hybrid::Item_sum_hybrid(Session *session, Item_sum_hybrid *item)
626
 
  :Item_sum(session, item), value(item->value), hybrid_type(item->hybrid_type),
 
595
Item_sum_hybrid::Item_sum_hybrid(THD *thd, Item_sum_hybrid *item)
 
596
  :Item_sum(thd, item), value(item->value), hybrid_type(item->hybrid_type),
627
597
  hybrid_field_type(item->hybrid_field_type), cmp_sign(item->cmp_sign),
628
598
  was_values(item->was_values)
629
599
{
646
616
    break;
647
617
  case ROW_RESULT:
648
618
  default:
649
 
    assert(0);
 
619
    DBUG_ASSERT(0);
650
620
  }
651
621
  collation.set(item->collation);
652
622
}
653
623
 
654
624
bool
655
 
Item_sum_hybrid::fix_fields(Session *session, Item **ref)
 
625
Item_sum_hybrid::fix_fields(THD *thd, Item **ref)
656
626
{
657
 
  assert(fixed == 0);
 
627
  DBUG_ASSERT(fixed == 0);
658
628
 
659
629
  Item *item= args[0];
660
630
 
661
 
  if (init_sum_func_check(session))
662
 
    return true;
 
631
  if (init_sum_func_check(thd))
 
632
    return TRUE;
663
633
 
664
634
  // 'item' can be changed during fix_fields
665
 
  if ((!item->fixed && item->fix_fields(session, args)) ||
 
635
  if ((!item->fixed && item->fix_fields(thd, args)) ||
666
636
      (item= args[0])->check_cols(1))
667
 
    return true;
 
637
    return TRUE;
668
638
  decimals=item->decimals;
669
639
 
670
640
  switch (hybrid_type= item->result_type()) {
685
655
    break;
686
656
  case ROW_RESULT:
687
657
  default:
688
 
    assert(0);
 
658
    DBUG_ASSERT(0);
689
659
  };
690
660
  /* MIN/MAX can return NULL for empty set indepedent of the used column */
691
661
  maybe_null= 1;
700
670
  else
701
671
    hybrid_field_type= Item::field_type();
702
672
 
703
 
  if (check_sum_func(session, ref))
704
 
    return true;
 
673
  if (check_sum_func(thd, ref))
 
674
    return TRUE;
705
675
 
706
676
  fixed= 1;
707
 
  return false;
 
677
  return FALSE;
708
678
}
709
679
 
710
 
Field *Item_sum_hybrid::create_tmp_field(bool group, Table *table,
711
 
                                         uint32_t convert_blob_length)
 
680
Field *Item_sum_hybrid::create_tmp_field(bool group, TABLE *table,
 
681
                                         uint convert_blob_length)
712
682
{
713
683
  Field *field;
714
684
  if (args[0]->type() == Item::FIELD_ITEM)
715
685
  {
716
686
    field= ((Item_field*) args[0])->field;
717
 
 
718
 
    if ((field= create_tmp_field_from_field(current_session, field, name, table,
 
687
    
 
688
    if ((field= create_tmp_field_from_field(current_thd, field, name, table,
719
689
                                            NULL, convert_blob_length)))
720
690
      field->flags&= ~NOT_NULL_FLAG;
721
691
    return field;
726
696
    fields creations separately.
727
697
  */
728
698
  switch (args[0]->field_type()) {
729
 
  case DRIZZLE_TYPE_DATE:
730
 
    field= new Field_date(maybe_null, name, collation.collation);
731
 
    break;
732
 
  case DRIZZLE_TYPE_TIMESTAMP:
733
 
  case DRIZZLE_TYPE_DATETIME:
 
699
  case MYSQL_TYPE_NEWDATE:
 
700
    field= new Field_newdate(maybe_null, name, collation.collation);
 
701
    break;
 
702
  case MYSQL_TYPE_TIME:
 
703
    field= new Field_time(maybe_null, name, collation.collation);
 
704
    break;
 
705
  case MYSQL_TYPE_TIMESTAMP:
 
706
  case MYSQL_TYPE_DATETIME:
734
707
    field= new Field_datetime(maybe_null, name, collation.collation);
735
708
    break;
736
709
  default:
750
723
  @todo
751
724
  check if the following assignments are really needed
752
725
*/
753
 
Item_sum_sum::Item_sum_sum(Session *session, Item_sum_sum *item)
754
 
  :Item_sum_num(session, item), hybrid_type(item->hybrid_type),
 
726
Item_sum_sum::Item_sum_sum(THD *thd, Item_sum_sum *item) 
 
727
  :Item_sum_num(thd, item), hybrid_type(item->hybrid_type),
755
728
   curr_dec_buff(item->curr_dec_buff)
756
729
{
757
730
  /* TODO: check if the following assignments are really needed */
764
737
    sum= item->sum;
765
738
}
766
739
 
767
 
Item *Item_sum_sum::copy_or_same(Session* session)
 
740
Item *Item_sum_sum::copy_or_same(THD* thd)
768
741
{
769
 
  return new (session->mem_root) Item_sum_sum(session, this);
 
742
  return new (thd->mem_root) Item_sum_sum(thd, this);
770
743
}
771
744
 
772
745
 
773
746
void Item_sum_sum::clear()
774
747
{
 
748
  DBUG_ENTER("Item_sum_sum::clear");
775
749
  null_value=1;
776
750
  if (hybrid_type == DECIMAL_RESULT)
777
751
  {
780
754
  }
781
755
  else
782
756
    sum= 0.0;
783
 
  return;
 
757
  DBUG_VOID_RETURN;
784
758
}
785
759
 
786
760
 
787
761
void Item_sum_sum::fix_length_and_dec()
788
762
{
 
763
  DBUG_ENTER("Item_sum_sum::fix_length_and_dec");
789
764
  maybe_null=null_value=1;
790
765
  decimals= args[0]->decimals;
791
766
  switch (args[0]->result_type()) {
808
783
  }
809
784
  case ROW_RESULT:
810
785
  default:
811
 
    assert(0);
 
786
    DBUG_ASSERT(0);
812
787
  }
813
 
  return;
 
788
  DBUG_PRINT("info", ("Type: %s (%d, %d)",
 
789
                      (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
 
790
                       hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
 
791
                       hybrid_type == INT_RESULT ? "INT_RESULT" :
 
792
                       "--ILLEGAL!!!--"),
 
793
                      max_length,
 
794
                      (int)decimals));
 
795
  DBUG_VOID_RETURN;
814
796
}
815
797
 
816
798
 
817
799
bool Item_sum_sum::add()
818
800
{
 
801
  DBUG_ENTER("Item_sum_sum::add");
819
802
  if (hybrid_type == DECIMAL_RESULT)
820
803
  {
821
804
    my_decimal value, *val= args[0]->val_decimal(&value);
833
816
    if (!args[0]->null_value)
834
817
      null_value= 0;
835
818
  }
836
 
  return(0);
 
819
  DBUG_RETURN(0);
837
820
}
838
821
 
839
822
 
840
 
int64_t Item_sum_sum::val_int()
 
823
longlong Item_sum_sum::val_int()
841
824
{
842
 
  assert(fixed == 1);
 
825
  DBUG_ASSERT(fixed == 1);
843
826
  if (hybrid_type == DECIMAL_RESULT)
844
827
  {
845
 
    int64_t result;
 
828
    longlong result;
846
829
    my_decimal2int(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, unsigned_flag,
847
830
                   &result);
848
831
    return result;
849
832
  }
850
 
  return (int64_t) rint(val_real());
 
833
  return (longlong) rint(val_real());
851
834
}
852
835
 
853
836
 
854
837
double Item_sum_sum::val_real()
855
838
{
856
 
  assert(fixed == 1);
 
839
  DBUG_ASSERT(fixed == 1);
857
840
  if (hybrid_type == DECIMAL_RESULT)
858
841
    my_decimal2double(E_DEC_FATAL_ERROR, dec_buffs + curr_dec_buff, &sum);
859
842
  return sum;
877
860
 
878
861
/***************************************************************************/
879
862
 
 
863
C_MODE_START
 
864
 
880
865
/* Declarations for auxilary C-callbacks */
881
866
 
882
867
static int simple_raw_key_cmp(void* arg, const void* key1, const void* key2)
883
868
{
884
 
    return memcmp(key1, key2, *(uint32_t *) arg);
 
869
    return memcmp(key1, key2, *(uint *) arg);
885
870
}
886
871
 
887
872
 
888
873
static int item_sum_distinct_walk(void *element,
889
 
                                  uint32_t ,
 
874
                                  element_count num_of_dups __attribute__((__unused__)),
890
875
                                  void *item)
891
876
{
892
877
  return ((Item_sum_distinct*) (item))->unique_walk_function(element);
893
878
}
894
879
 
 
880
C_MODE_END
 
881
 
895
882
/* Item_sum_distinct */
896
883
 
897
884
Item_sum_distinct::Item_sum_distinct(Item *item_arg)
907
894
}
908
895
 
909
896
 
910
 
Item_sum_distinct::Item_sum_distinct(Session *session, Item_sum_distinct *original)
911
 
  :Item_sum_num(session, original), val(original->val), tree(0),
 
897
Item_sum_distinct::Item_sum_distinct(THD *thd, Item_sum_distinct *original)
 
898
  :Item_sum_num(thd, original), val(original->val), tree(0),
912
899
  table_field_type(original->table_field_type)
913
900
{
914
901
  quick_group= 0;
929
916
  virtual void fix_length_and_dec(Item *item, Item *arg) const
930
917
  { Hybrid_type_traits_decimal::instance()->fix_length_and_dec(item, arg); }
931
918
 
932
 
  virtual void div(Hybrid_type *val, uint64_t u) const
 
919
  virtual void div(Hybrid_type *val, ulonglong u) const
933
920
  {
934
921
    int2my_decimal(E_DEC_FATAL_ERROR, val->integer, 0, val->dec_buf);
935
922
    val->used_dec_buf_no= 0;
948
935
  return &fast_decimal_traits_instance;
949
936
}
950
937
 
951
 
 
952
938
void Item_sum_distinct::fix_length_and_dec()
953
939
{
954
 
  assert(args[0]->fixed);
 
940
  DBUG_ASSERT(args[0]->fixed);
955
941
 
956
 
  null_value= maybe_null= true;
957
942
  table_field_type= args[0]->field_type();
958
943
 
959
944
  /* Adjust tmp table type according to the chosen aggregation type */
961
946
  case STRING_RESULT:
962
947
  case REAL_RESULT:
963
948
    val.traits= Hybrid_type_traits::instance();
964
 
    table_field_type= DRIZZLE_TYPE_DOUBLE;
 
949
    if (table_field_type != MYSQL_TYPE_FLOAT)
 
950
      table_field_type= MYSQL_TYPE_DOUBLE;
965
951
    break;
966
952
  case INT_RESULT:
967
953
  /*
968
954
    Preserving int8, int16, int32 field types gives ~10% performance boost
969
955
    as the size of result tree becomes significantly smaller.
970
 
    Another speed up we gain by using int64_t for intermediate
 
956
    Another speed up we gain by using longlong for intermediate
971
957
    calculations. The range of int64 is enough to hold sum 2^32 distinct
972
958
    integers each <= 2^32.
973
959
  */
974
 
  if (table_field_type == DRIZZLE_TYPE_LONG)
 
960
  if (table_field_type >= MYSQL_TYPE_TINY && table_field_type <= MYSQL_TYPE_LONG)
975
961
  {
976
962
    val.traits= Hybrid_type_traits_fast_decimal::instance();
977
963
    break;
978
964
  }
979
 
  table_field_type= DRIZZLE_TYPE_LONGLONG;
 
965
  table_field_type= MYSQL_TYPE_LONGLONG;
980
966
  /* fallthrough */
981
967
  case DECIMAL_RESULT:
982
968
    val.traits= Hybrid_type_traits_decimal::instance();
983
 
    if (table_field_type != DRIZZLE_TYPE_LONGLONG)
984
 
      table_field_type= DRIZZLE_TYPE_DECIMAL;
 
969
    if (table_field_type != MYSQL_TYPE_LONGLONG)
 
970
      table_field_type= MYSQL_TYPE_NEWDECIMAL;
985
971
    break;
986
972
  case ROW_RESULT:
987
973
  default:
988
 
    assert(0);
 
974
    DBUG_ASSERT(0);
989
975
  }
990
976
  val.traits->fix_length_and_dec(this, args[0]);
991
977
}
992
978
 
993
979
 
994
 
enum Item_result Item_sum_distinct::result_type () const
995
 
{
996
 
  return val.traits->type();
997
 
}
998
 
 
999
 
 
1000
980
/**
1001
981
  @todo
1002
982
  check that the case of CHAR(0) works OK
1003
983
*/
1004
 
bool Item_sum_distinct::setup(Session *session)
 
984
bool Item_sum_distinct::setup(THD *thd)
1005
985
{
1006
 
  List<CreateField> field_list;
1007
 
  CreateField field_def;                              /* field definition */
 
986
  List<Create_field> field_list;
 
987
  Create_field field_def;                              /* field definition */
 
988
  DBUG_ENTER("Item_sum_distinct::setup");
1008
989
  /* It's legal to call setup() more than once when in a subquery */
1009
990
  if (tree)
1010
 
    return(false);
 
991
    DBUG_RETURN(FALSE);
1011
992
 
1012
993
  /*
1013
994
    Virtual table and the tree are created anew on each re-execution of
1015
996
    mem_root.
1016
997
  */
1017
998
  if (field_list.push_back(&field_def))
1018
 
    return(true);
 
999
    DBUG_RETURN(TRUE);
1019
1000
 
1020
1001
  null_value= maybe_null= 1;
1021
1002
  quick_group= 0;
1022
1003
 
1023
 
  assert(args[0]->fixed);
 
1004
  DBUG_ASSERT(args[0]->fixed);
1024
1005
 
1025
1006
  field_def.init_for_tmp_table(table_field_type, args[0]->max_length,
1026
 
                               args[0]->decimals, args[0]->maybe_null);
 
1007
                               args[0]->decimals, args[0]->maybe_null,
 
1008
                               args[0]->unsigned_flag);
1027
1009
 
1028
 
  if (! (table= session->create_virtual_tmp_table(field_list)))
1029
 
    return(true);
 
1010
  if (! (table= create_virtual_tmp_table(thd, field_list)))
 
1011
    DBUG_RETURN(TRUE);
1030
1012
 
1031
1013
  /* XXX: check that the case of CHAR(0) works OK */
1032
 
  tree_key_length= table->getShare()->getRecordLength() - table->getShare()->null_bytes;
 
1014
  tree_key_length= table->s->reclength - table->s->null_bytes;
1033
1015
 
1034
1016
  /*
1035
1017
    Unique handles all unique elements in a tree until they can't fit
1037
1019
    simple_raw_key_cmp because the table contains numbers only; decimals
1038
1020
    are converted to binary representation as well.
1039
1021
  */
1040
 
  tree= new Unique(simple_raw_key_cmp, &tree_key_length,
1041
 
                   tree_key_length,
1042
 
                   (size_t)session->variables.max_heap_table_size);
 
1022
  tree= new Unique(simple_raw_key_cmp, &tree_key_length, tree_key_length,
 
1023
                   thd->variables.max_heap_table_size);
1043
1024
 
1044
 
  is_evaluated= false;
1045
 
  return(tree == 0);
 
1025
  is_evaluated= FALSE;
 
1026
  DBUG_RETURN(tree == 0);
1046
1027
}
1047
1028
 
1048
1029
 
1049
1030
bool Item_sum_distinct::add()
1050
1031
{
1051
 
  args[0]->save_in_field(table->getField(0), false);
1052
 
  is_evaluated= false;
1053
 
  if (!table->getField(0)->is_null())
 
1032
  args[0]->save_in_field(table->field[0], FALSE);
 
1033
  is_evaluated= FALSE;
 
1034
  if (!table->field[0]->is_null())
1054
1035
  {
1055
 
    assert(tree);
 
1036
    DBUG_ASSERT(tree);
1056
1037
    null_value= 0;
1057
1038
    /*
1058
1039
      '0' values are also stored in the tree. This doesn't matter
1059
1040
      for SUM(DISTINCT), but is important for AVG(DISTINCT)
1060
1041
    */
1061
 
    return tree->unique_add(table->getField(0)->ptr);
 
1042
    return tree->unique_add(table->field[0]->ptr);
1062
1043
  }
1063
1044
  return 0;
1064
1045
}
1066
1047
 
1067
1048
bool Item_sum_distinct::unique_walk_function(void *element)
1068
1049
{
1069
 
  memcpy(table->getField(0)->ptr, element, tree_key_length);
 
1050
  memcpy(table->field[0]->ptr, element, tree_key_length);
1070
1051
  ++count;
1071
 
  val.traits->add(&val, table->getField(0));
 
1052
  val.traits->add(&val, table->field[0]);
1072
1053
  return 0;
1073
1054
}
1074
1055
 
1075
1056
 
1076
1057
void Item_sum_distinct::clear()
1077
1058
{
1078
 
  assert(tree != 0);                        /* we always have a tree */
 
1059
  DBUG_ENTER("Item_sum_distinct::clear");
 
1060
  DBUG_ASSERT(tree != 0);                        /* we always have a tree */
1079
1061
  null_value= 1;
1080
1062
  tree->reset();
1081
 
  is_evaluated= false;
1082
 
  return;
 
1063
  is_evaluated= FALSE;
 
1064
  DBUG_VOID_RETURN;
1083
1065
}
1084
1066
 
1085
1067
void Item_sum_distinct::cleanup()
1088
1070
  delete tree;
1089
1071
  tree= 0;
1090
1072
  table= 0;
1091
 
  is_evaluated= false;
 
1073
  is_evaluated= FALSE;
1092
1074
}
1093
1075
 
1094
1076
Item_sum_distinct::~Item_sum_distinct()
1110
1092
     */
1111
1093
    if (tree)
1112
1094
    {
1113
 
      table->getField(0)->set_notnull();
 
1095
      table->field[0]->set_notnull();
1114
1096
      tree->walk(item_sum_distinct_walk, (void*) this);
1115
1097
    }
1116
 
    is_evaluated= true;
 
1098
    is_evaluated= TRUE;
1117
1099
  }
1118
1100
}
1119
1101
 
1134
1116
}
1135
1117
 
1136
1118
 
1137
 
int64_t Item_sum_distinct::val_int()
 
1119
longlong Item_sum_distinct::val_int()
1138
1120
{
1139
1121
  calculate_val_and_count();
1140
1122
  return val.traits->val_int(&val, unsigned_flag);
1157
1139
Item_sum_avg_distinct::fix_length_and_dec()
1158
1140
{
1159
1141
  Item_sum_distinct::fix_length_and_dec();
1160
 
  prec_increment= current_session->variables.div_precincrement;
 
1142
  prec_increment= current_thd->variables.div_precincrement;
1161
1143
  /*
1162
1144
    AVG() will divide val by count. We need to reserve digits
1163
1145
    after decimal point as the result can be fractional.
1164
1146
  */
1165
 
  decimals= min(decimals + prec_increment, (unsigned int)NOT_FIXED_DEC);
 
1147
  decimals= min(decimals + prec_increment, NOT_FIXED_DEC);
1166
1148
}
1167
1149
 
1168
1150
 
1174
1156
    Item_sum_distinct::calculate_val_and_count();
1175
1157
    if (count)
1176
1158
      val.traits->div(&val, count);
1177
 
    is_evaluated= true;
 
1159
    is_evaluated= TRUE;
1178
1160
  }
1179
1161
}
1180
1162
 
1181
1163
 
1182
 
Item *Item_sum_count::copy_or_same(Session* session)
 
1164
Item *Item_sum_count::copy_or_same(THD* thd)
1183
1165
{
1184
 
  return new (session->mem_root) Item_sum_count(session, this);
 
1166
  return new (thd->mem_root) Item_sum_count(thd, this);
1185
1167
}
1186
1168
 
1187
1169
 
1198
1180
  return 0;
1199
1181
}
1200
1182
 
1201
 
int64_t Item_sum_count::val_int()
 
1183
longlong Item_sum_count::val_int()
1202
1184
{
1203
 
  assert(fixed == 1);
1204
 
  return (int64_t) count;
 
1185
  DBUG_ASSERT(fixed == 1);
 
1186
  return (longlong) count;
1205
1187
}
1206
1188
 
1207
1189
 
1208
1190
void Item_sum_count::cleanup()
1209
1191
{
 
1192
  DBUG_ENTER("Item_sum_count::cleanup");
1210
1193
  count= 0;
1211
1194
  Item_sum_int::cleanup();
1212
 
  return;
 
1195
  DBUG_VOID_RETURN;
1213
1196
}
1214
1197
 
1215
1198
 
1220
1203
{
1221
1204
  Item_sum_sum::fix_length_and_dec();
1222
1205
  maybe_null=null_value=1;
1223
 
  prec_increment= current_session->variables.div_precincrement;
 
1206
  prec_increment= current_thd->variables.div_precincrement;
1224
1207
  if (hybrid_type == DECIMAL_RESULT)
1225
1208
  {
1226
1209
    int precision= args[0]->decimal_precision() + prec_increment;
1227
 
    decimals= min(args[0]->decimals + prec_increment, (unsigned int) DECIMAL_MAX_SCALE);
 
1210
    decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
1228
1211
    max_length= my_decimal_precision_to_length(precision, decimals,
1229
1212
                                               unsigned_flag);
1230
1213
    f_precision= min(precision+DECIMAL_LONGLONG_DIGITS, DECIMAL_MAX_PRECISION);
1232
1215
    dec_bin_size= my_decimal_get_binary_size(f_precision, f_scale);
1233
1216
  }
1234
1217
  else {
1235
 
    decimals= min(args[0]->decimals + prec_increment, (unsigned int) NOT_FIXED_DEC);
 
1218
    decimals= min(args[0]->decimals + prec_increment, NOT_FIXED_DEC);
1236
1219
    max_length= args[0]->max_length + prec_increment;
1237
1220
  }
1238
1221
}
1239
1222
 
1240
1223
 
1241
 
Item *Item_sum_avg::copy_or_same(Session* session)
 
1224
Item *Item_sum_avg::copy_or_same(THD* thd)
1242
1225
{
1243
 
  return new (session->mem_root) Item_sum_avg(session, this);
 
1226
  return new (thd->mem_root) Item_sum_avg(thd, this);
1244
1227
}
1245
1228
 
1246
1229
 
1247
 
Field *Item_sum_avg::create_tmp_field(bool group, Table *table,
1248
 
                                      uint32_t )
 
1230
Field *Item_sum_avg::create_tmp_field(bool group, TABLE *table,
 
1231
                                      uint convert_blob_len __attribute__((__unused__)))
1249
1232
{
1250
1233
  Field *field;
1251
1234
  if (group)
1255
1238
      The easiest way is to do this is to store both value in a string
1256
1239
      and unpack on access.
1257
1240
    */
1258
 
    field= new Field_varstring(((hybrid_type == DECIMAL_RESULT) ?
1259
 
                                dec_bin_size : sizeof(double)) + sizeof(int64_t),
1260
 
                               0, name, table->getMutableShare(), &my_charset_bin);
 
1241
    field= new Field_string(((hybrid_type == DECIMAL_RESULT) ?
 
1242
                             dec_bin_size : sizeof(double)) + sizeof(longlong),
 
1243
                            0, name, &my_charset_bin);
1261
1244
  }
1262
1245
  else if (hybrid_type == DECIMAL_RESULT)
1263
 
    field= new Field_decimal(max_length, maybe_null, name,
1264
 
                             decimals, unsigned_flag);
 
1246
    field= new Field_new_decimal(max_length, maybe_null, name,
 
1247
                                 decimals, unsigned_flag);
1265
1248
  else
1266
 
    field= new Field_double(max_length, maybe_null, name, decimals, true);
 
1249
    field= new Field_double(max_length, maybe_null, name, decimals, TRUE);
1267
1250
  if (field)
1268
1251
    field->init(table);
1269
1252
  return field;
1280
1263
bool Item_sum_avg::add()
1281
1264
{
1282
1265
  if (Item_sum_sum::add())
1283
 
    return true;
 
1266
    return TRUE;
1284
1267
  if (!args[0]->null_value)
1285
1268
    count++;
1286
 
  return false;
 
1269
  return FALSE;
1287
1270
}
1288
1271
 
1289
1272
double Item_sum_avg::val_real()
1290
1273
{
1291
 
  assert(fixed == 1);
 
1274
  DBUG_ASSERT(fixed == 1);
1292
1275
  if (!count)
1293
1276
  {
1294
1277
    null_value=1;
1295
1278
    return 0.0;
1296
1279
  }
1297
 
  return Item_sum_sum::val_real() / uint64_t2double(count);
1298
 
}
1299
 
 
1300
 
 
1301
 
int64_t Item_sum_avg::val_int()
1302
 
{
1303
 
  return (int64_t) rint(val_real());
 
1280
  return Item_sum_sum::val_real() / ulonglong2double(count);
1304
1281
}
1305
1282
 
1306
1283
 
1308
1285
{
1309
1286
  my_decimal sum_buff, cnt;
1310
1287
  const my_decimal *sum_dec;
1311
 
  assert(fixed == 1);
 
1288
  DBUG_ASSERT(fixed == 1);
1312
1289
  if (!count)
1313
1290
  {
1314
1291
    null_value=1;
1343
1320
 
1344
1321
double Item_sum_std::val_real()
1345
1322
{
1346
 
  assert(fixed == 1);
 
1323
  DBUG_ASSERT(fixed == 1);
1347
1324
  double nr= Item_sum_variance::val_real();
1348
 
  assert(nr >= 0.0);
 
1325
  DBUG_ASSERT(nr >= 0.0);
1349
1326
  return sqrt(nr);
1350
1327
}
1351
1328
 
1352
 
Item *Item_sum_std::copy_or_same(Session* session)
 
1329
Item *Item_sum_std::copy_or_same(THD* thd)
1353
1330
{
1354
 
  return new (session->mem_root) Item_sum_std(session, this);
 
1331
  return new (thd->mem_root) Item_sum_std(thd, this);
1355
1332
}
1356
1333
 
1357
1334
 
1372
1349
  variance.  The difference between the two classes is that the first is used
1373
1350
  for a mundane SELECT, while the latter is used in a GROUPing SELECT.
1374
1351
*/
1375
 
static void variance_fp_recurrence_next(double *m, double *s, uint64_t *count, double nr)
 
1352
static void variance_fp_recurrence_next(double *m, double *s, ulonglong *count, double nr)
1376
1353
{
1377
1354
  *count += 1;
1378
1355
 
1379
 
  if (*count == 1)
 
1356
  if (*count == 1) 
1380
1357
  {
1381
1358
    *m= nr;
1382
1359
    *s= 0;
1390
1367
}
1391
1368
 
1392
1369
 
1393
 
static double variance_fp_recurrence_result(double s, uint64_t count, bool is_sample_variance)
 
1370
static double variance_fp_recurrence_result(double s, ulonglong count, bool is_sample_variance)
1394
1371
{
1395
1372
  if (count == 1)
1396
1373
    return 0.0;
1403
1380
}
1404
1381
 
1405
1382
 
1406
 
Item_sum_variance::Item_sum_variance(Session *session, Item_sum_variance *item):
1407
 
  Item_sum_num(session, item), hybrid_type(item->hybrid_type),
 
1383
Item_sum_variance::Item_sum_variance(THD *thd, Item_sum_variance *item):
 
1384
  Item_sum_num(thd, item), hybrid_type(item->hybrid_type),
1408
1385
    count(item->count), sample(item->sample),
1409
1386
    prec_increment(item->prec_increment)
1410
1387
{
1415
1392
 
1416
1393
void Item_sum_variance::fix_length_and_dec()
1417
1394
{
 
1395
  DBUG_ENTER("Item_sum_variance::fix_length_and_dec");
1418
1396
  maybe_null= null_value= 1;
1419
 
  prec_increment= current_session->variables.div_precincrement;
 
1397
  prec_increment= current_thd->variables.div_precincrement;
1420
1398
 
1421
1399
  /*
1422
1400
    According to the SQL2003 standard (Part 2, Foundations; sec 10.9,
1423
 
    aggregate function; paragraph 7h of Syntax Rules), "the declared
 
1401
    aggregate function; paragraph 7h of Syntax Rules), "the declared 
1424
1402
    type of the result is an implementation-defined aproximate numeric
1425
1403
    type.
1426
1404
  */
1429
1407
  switch (args[0]->result_type()) {
1430
1408
  case REAL_RESULT:
1431
1409
  case STRING_RESULT:
1432
 
    decimals= min(args[0]->decimals + 4, (int)NOT_FIXED_DEC);
 
1410
    decimals= min(args[0]->decimals + 4, NOT_FIXED_DEC);
1433
1411
    break;
1434
1412
  case INT_RESULT:
1435
1413
  case DECIMAL_RESULT:
1436
1414
  {
1437
1415
    int precision= args[0]->decimal_precision()*2 + prec_increment;
1438
 
    decimals= min(args[0]->decimals + prec_increment, (unsigned int) DECIMAL_MAX_SCALE);
 
1416
    decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
1439
1417
    max_length= my_decimal_precision_to_length(precision, decimals,
1440
1418
                                               unsigned_flag);
1441
1419
 
1443
1421
  }
1444
1422
  case ROW_RESULT:
1445
1423
  default:
1446
 
    assert(0);
 
1424
    DBUG_ASSERT(0);
1447
1425
  }
1448
 
  return;
 
1426
  DBUG_PRINT("info", ("Type: REAL_RESULT (%d, %d)", max_length, (int)decimals));
 
1427
  DBUG_VOID_RETURN;
1449
1428
}
1450
1429
 
1451
1430
 
1452
 
Item *Item_sum_variance::copy_or_same(Session* session)
 
1431
Item *Item_sum_variance::copy_or_same(THD* thd)
1453
1432
{
1454
 
  return new (session->mem_root) Item_sum_variance(session, this);
 
1433
  return new (thd->mem_root) Item_sum_variance(thd, this);
1455
1434
}
1456
1435
 
1457
1436
 
1460
1439
  If we're grouping, then we need some space to serialize variables into, to
1461
1440
  pass around.
1462
1441
*/
1463
 
Field *Item_sum_variance::create_tmp_field(bool group, Table *table,
1464
 
                                           uint32_t )
 
1442
Field *Item_sum_variance::create_tmp_field(bool group, TABLE *table,
 
1443
                                           uint convert_blob_len __attribute__((__unused__)))
1465
1444
{
1466
1445
  Field *field;
1467
1446
  if (group)
1471
1450
      The easiest way is to do this is to store both value in a string
1472
1451
      and unpack on access.
1473
1452
    */
1474
 
    field= new Field_varstring(sizeof(double)*2 + sizeof(int64_t), 0, name, table->getMutableShare(), &my_charset_bin);
 
1453
    field= new Field_string(sizeof(double)*2 + sizeof(longlong), 0, name, &my_charset_bin);
1475
1454
  }
1476
1455
  else
1477
 
    field= new Field_double(max_length, maybe_null, name, decimals, true);
 
1456
    field= new Field_double(max_length, maybe_null, name, decimals, TRUE);
1478
1457
 
1479
1458
  if (field != NULL)
1480
1459
    field->init(table);
1485
1464
 
1486
1465
void Item_sum_variance::clear()
1487
1466
{
1488
 
  count= 0;
 
1467
  count= 0; 
1489
1468
}
1490
1469
 
1491
1470
bool Item_sum_variance::add()
1492
1471
{
1493
 
  /*
 
1472
  /* 
1494
1473
    Why use a temporary variable?  We don't know if it is null until we
1495
1474
    evaluate it, which has the side-effect of setting null_value .
1496
1475
  */
1497
1476
  double nr= args[0]->val_real();
1498
 
 
 
1477
  
1499
1478
  if (!args[0]->null_value)
1500
1479
    variance_fp_recurrence_next(&recurrence_m, &recurrence_s, &count, nr);
1501
1480
  return 0;
1503
1482
 
1504
1483
double Item_sum_variance::val_real()
1505
1484
{
1506
 
  assert(fixed == 1);
 
1485
  DBUG_ASSERT(fixed == 1);
1507
1486
 
1508
1487
  /*
1509
1488
    'sample' is a 1/0 boolean value.  If it is 1/true, id est this is a sample
1514
1493
    Another way to read it is that 'sample' is the numerical threshhold, at and
1515
1494
    below which a 'count' number of items is called NULL.
1516
1495
  */
1517
 
  assert((sample == 0) || (sample == 1));
 
1496
  DBUG_ASSERT((sample == 0) || (sample == 1));
1518
1497
  if (count <= sample)
1519
1498
  {
1520
1499
    null_value=1;
1526
1505
}
1527
1506
 
1528
1507
 
1529
 
int64_t Item_sum_variance::val_int()
1530
 
{
1531
 
  /* can't be fix_fields()ed */
1532
 
  return (int64_t) rint(val_real());
1533
 
}
1534
 
 
1535
 
 
1536
1508
my_decimal *Item_sum_variance::val_decimal(my_decimal *dec_buf)
1537
1509
{
1538
 
  assert(fixed == 1);
 
1510
  DBUG_ASSERT(fixed == 1);
1539
1511
  return val_decimal_from_real(dec_buf);
1540
1512
}
1541
1513
 
1543
1515
void Item_sum_variance::reset_field()
1544
1516
{
1545
1517
  double nr;
1546
 
  unsigned char *res= result_field->ptr;
 
1518
  uchar *res= result_field->ptr;
1547
1519
 
1548
1520
  nr= args[0]->val_real();              /* sets null_value as side-effect */
1549
1521
 
1550
1522
  if (args[0]->null_value)
1551
 
    memset(res, 0, sizeof(double)*2+sizeof(int64_t));
 
1523
    bzero(res,sizeof(double)*2+sizeof(longlong));
1552
1524
  else
1553
1525
  {
1554
 
    /* Serialize format is (double)m, (double)s, (int64_t)count */
1555
 
    uint64_t tmp_count;
 
1526
    /* Serialize format is (double)m, (double)s, (longlong)count */
 
1527
    ulonglong tmp_count;
1556
1528
    double tmp_s;
1557
1529
    float8store(res, nr);               /* recurrence variable m */
1558
1530
    tmp_s= 0.0;
1565
1537
 
1566
1538
void Item_sum_variance::update_field()
1567
1539
{
1568
 
  uint64_t field_count;
1569
 
  unsigned char *res=result_field->ptr;
 
1540
  ulonglong field_count;
 
1541
  uchar *res=result_field->ptr;
1570
1542
 
1571
1543
  double nr= args[0]->val_real();       /* sets null_value as side-effect */
1572
1544
 
1573
1545
  if (args[0]->null_value)
1574
1546
    return;
1575
1547
 
1576
 
  /* Serialize format is (double)m, (double)s, (int64_t)count */
 
1548
  /* Serialize format is (double)m, (double)s, (longlong)count */
1577
1549
  double field_recurrence_m, field_recurrence_s;
1578
1550
  float8get(field_recurrence_m, res);
1579
1551
  float8get(field_recurrence_s, res + sizeof(double));
1610
1582
 
1611
1583
double Item_sum_hybrid::val_real()
1612
1584
{
1613
 
  assert(fixed == 1);
 
1585
  DBUG_ASSERT(fixed == 1);
1614
1586
  if (null_value)
1615
1587
    return 0.0;
1616
1588
  switch (hybrid_type) {
1623
1595
                             &end_not_used, &err_not_used) : 0.0);
1624
1596
  }
1625
1597
  case INT_RESULT:
 
1598
    if (unsigned_flag)
 
1599
      return ulonglong2double(sum_int);
1626
1600
    return (double) sum_int;
1627
1601
  case DECIMAL_RESULT:
1628
1602
    my_decimal2double(E_DEC_FATAL_ERROR, &sum_dec, &sum);
1632
1606
  case ROW_RESULT:
1633
1607
  default:
1634
1608
    // This case should never be choosen
1635
 
    assert(0);
 
1609
    DBUG_ASSERT(0);
1636
1610
    return 0;
1637
1611
  }
1638
1612
}
1639
1613
 
1640
 
int64_t Item_sum_hybrid::val_int()
 
1614
longlong Item_sum_hybrid::val_int()
1641
1615
{
1642
 
  assert(fixed == 1);
 
1616
  DBUG_ASSERT(fixed == 1);
1643
1617
  if (null_value)
1644
1618
    return 0;
1645
1619
  switch (hybrid_type) {
1647
1621
    return sum_int;
1648
1622
  case DECIMAL_RESULT:
1649
1623
  {
1650
 
    int64_t result;
 
1624
    longlong result;
1651
1625
    my_decimal2int(E_DEC_FATAL_ERROR, &sum_dec, unsigned_flag, &result);
1652
1626
    return sum_int;
1653
1627
  }
1654
1628
  default:
1655
 
    return (int64_t) rint(Item_sum_hybrid::val_real());
 
1629
    return (longlong) rint(Item_sum_hybrid::val_real());
1656
1630
  }
1657
1631
}
1658
1632
 
1659
1633
 
1660
1634
my_decimal *Item_sum_hybrid::val_decimal(my_decimal *val)
1661
1635
{
1662
 
  assert(fixed == 1);
 
1636
  DBUG_ASSERT(fixed == 1);
1663
1637
  if (null_value)
1664
1638
    return 0;
1665
1639
  switch (hybrid_type) {
1678
1652
  case ROW_RESULT:
1679
1653
  default:
1680
1654
    // This case should never be choosen
1681
 
    assert(0);
 
1655
    DBUG_ASSERT(0);
1682
1656
    break;
1683
1657
  }
1684
1658
  return val;                                   // Keep compiler happy
1688
1662
String *
1689
1663
Item_sum_hybrid::val_str(String *str)
1690
1664
{
1691
 
  assert(fixed == 1);
 
1665
  DBUG_ASSERT(fixed == 1);
1692
1666
  if (null_value)
1693
1667
    return 0;
1694
1668
  switch (hybrid_type) {
1706
1680
  case ROW_RESULT:
1707
1681
  default:
1708
1682
    // This case should never be choosen
1709
 
    assert(0);
 
1683
    DBUG_ASSERT(0);
1710
1684
    break;
1711
1685
  }
1712
1686
  return str;                                   // Keep compiler happy
1715
1689
 
1716
1690
void Item_sum_hybrid::cleanup()
1717
1691
{
 
1692
  DBUG_ENTER("Item_sum_hybrid::cleanup");
1718
1693
  Item_sum::cleanup();
1719
 
  forced_const= false;
 
1694
  forced_const= FALSE;
1720
1695
 
1721
1696
  /*
1722
1697
    by default it is TRUE to avoid TRUE reporting by
1725
1700
    no_rows_in_result() set it to FALSE if was not results found.
1726
1701
    If some results found it will be left unchanged.
1727
1702
  */
1728
 
  was_values= true;
1729
 
  return;
 
1703
  was_values= TRUE;
 
1704
  DBUG_VOID_RETURN;
1730
1705
}
1731
1706
 
1732
1707
void Item_sum_hybrid::no_rows_in_result()
1733
1708
{
1734
 
  was_values= false;
 
1709
  was_values= FALSE;
1735
1710
  clear();
1736
1711
}
1737
1712
 
1738
1713
 
1739
 
Item *Item_sum_min::copy_or_same(Session* session)
 
1714
Item *Item_sum_min::copy_or_same(THD* thd)
1740
1715
{
1741
 
  return new (session->mem_root) Item_sum_min(session, this);
 
1716
  return new (thd->mem_root) Item_sum_min(thd, this);
1742
1717
}
1743
1718
 
1744
1719
 
1758
1733
  break;
1759
1734
  case INT_RESULT:
1760
1735
  {
1761
 
    int64_t nr=args[0]->val_int();
 
1736
    longlong nr=args[0]->val_int();
1762
1737
    if (!args[0]->null_value && (null_value ||
1763
 
                                 (unsigned_flag &&
1764
 
                                  (uint64_t) nr < (uint64_t) sum_int) ||
 
1738
                                 (unsigned_flag && 
 
1739
                                  (ulonglong) nr < (ulonglong) sum_int) ||
1765
1740
                                 (!unsigned_flag && nr < sum_int)))
1766
1741
    {
1767
1742
      sum_int=nr;
1793
1768
  case ROW_RESULT:
1794
1769
  default:
1795
1770
    // This case should never be choosen
1796
 
    assert(0);
 
1771
    DBUG_ASSERT(0);
1797
1772
    break;
1798
1773
  }
1799
1774
  return 0;
1800
1775
}
1801
1776
 
1802
1777
 
1803
 
Item *Item_sum_max::copy_or_same(Session* session)
 
1778
Item *Item_sum_max::copy_or_same(THD* thd)
1804
1779
{
1805
 
  return new (session->mem_root) Item_sum_max(session, this);
 
1780
  return new (thd->mem_root) Item_sum_max(thd, this);
1806
1781
}
1807
1782
 
1808
1783
 
1822
1797
  break;
1823
1798
  case INT_RESULT:
1824
1799
  {
1825
 
    int64_t nr=args[0]->val_int();
 
1800
    longlong nr=args[0]->val_int();
1826
1801
    if (!args[0]->null_value && (null_value ||
1827
 
                                 (unsigned_flag &&
1828
 
                                  (uint64_t) nr > (uint64_t) sum_int) ||
 
1802
                                 (unsigned_flag && 
 
1803
                                  (ulonglong) nr > (ulonglong) sum_int) ||
1829
1804
                                 (!unsigned_flag && nr > sum_int)))
1830
1805
    {
1831
1806
      sum_int=nr;
1857
1832
  case ROW_RESULT:
1858
1833
  default:
1859
1834
    // This case should never be choosen
1860
 
    assert(0);
 
1835
    DBUG_ASSERT(0);
1861
1836
    break;
1862
1837
  }
1863
1838
  return 0;
1866
1841
 
1867
1842
/* bit_or and bit_and */
1868
1843
 
1869
 
int64_t Item_sum_bit::val_int()
 
1844
longlong Item_sum_bit::val_int()
1870
1845
{
1871
 
  assert(fixed == 1);
1872
 
  return (int64_t) bits;
 
1846
  DBUG_ASSERT(fixed == 1);
 
1847
  return (longlong) bits;
1873
1848
}
1874
1849
 
1875
1850
 
1878
1853
  bits= reset_bits;
1879
1854
}
1880
1855
 
1881
 
Item *Item_sum_or::copy_or_same(Session* session)
 
1856
Item *Item_sum_or::copy_or_same(THD* thd)
1882
1857
{
1883
 
  return new (session->mem_root) Item_sum_or(session, this);
 
1858
  return new (thd->mem_root) Item_sum_or(thd, this);
1884
1859
}
1885
1860
 
1886
1861
 
1887
1862
bool Item_sum_or::add()
1888
1863
{
1889
 
  uint64_t value= (uint64_t) args[0]->val_int();
 
1864
  ulonglong value= (ulonglong) args[0]->val_int();
1890
1865
  if (!args[0]->null_value)
1891
1866
    bits|=value;
1892
1867
  return 0;
1893
1868
}
1894
1869
 
1895
 
Item *Item_sum_xor::copy_or_same(Session* session)
 
1870
Item *Item_sum_xor::copy_or_same(THD* thd)
1896
1871
{
1897
 
  return new (session->mem_root) Item_sum_xor(session, this);
 
1872
  return new (thd->mem_root) Item_sum_xor(thd, this);
1898
1873
}
1899
1874
 
1900
1875
 
1901
1876
bool Item_sum_xor::add()
1902
1877
{
1903
 
  uint64_t value= (uint64_t) args[0]->val_int();
 
1878
  ulonglong value= (ulonglong) args[0]->val_int();
1904
1879
  if (!args[0]->null_value)
1905
1880
    bits^=value;
1906
1881
  return 0;
1907
1882
}
1908
1883
 
1909
 
Item *Item_sum_and::copy_or_same(Session* session)
 
1884
Item *Item_sum_and::copy_or_same(THD* thd)
1910
1885
{
1911
 
  return new (session->mem_root) Item_sum_and(session, this);
 
1886
  return new (thd->mem_root) Item_sum_and(thd, this);
1912
1887
}
1913
1888
 
1914
1889
 
1915
1890
bool Item_sum_and::add()
1916
1891
{
1917
 
  uint64_t value= (uint64_t) args[0]->val_int();
 
1892
  ulonglong value= (ulonglong) args[0]->val_int();
1918
1893
  if (!args[0]->null_value)
1919
1894
    bits&=value;
1920
1895
  return 0;
1927
1902
void Item_sum_num::reset_field()
1928
1903
{
1929
1904
  double nr= args[0]->val_real();
1930
 
  unsigned char *res=result_field->ptr;
 
1905
  uchar *res=result_field->ptr;
1931
1906
 
1932
1907
  if (maybe_null)
1933
1908
  {
1966
1941
  }
1967
1942
  case INT_RESULT:
1968
1943
  {
1969
 
    int64_t nr=args[0]->val_int();
 
1944
    longlong nr=args[0]->val_int();
1970
1945
 
1971
1946
    if (maybe_null)
1972
1947
    {
2020
1995
  }
2021
1996
  case ROW_RESULT:
2022
1997
  default:
2023
 
    assert(0);
 
1998
    DBUG_ASSERT(0);
2024
1999
  }
2025
2000
}
2026
2001
 
2036
2011
  }
2037
2012
  else
2038
2013
  {
2039
 
    assert(hybrid_type == REAL_RESULT);
 
2014
    DBUG_ASSERT(hybrid_type == REAL_RESULT);
2040
2015
    double nr= args[0]->val_real();                     // Nulls also return 0
2041
2016
    float8store(result_field->ptr, nr);
2042
2017
  }
2049
2024
 
2050
2025
void Item_sum_count::reset_field()
2051
2026
{
2052
 
  unsigned char *res=result_field->ptr;
2053
 
  int64_t nr=0;
 
2027
  uchar *res=result_field->ptr;
 
2028
  longlong nr=0;
2054
2029
 
2055
2030
  if (!args[0]->maybe_null || !args[0]->is_null())
2056
2031
    nr=1;
2060
2035
 
2061
2036
void Item_sum_avg::reset_field()
2062
2037
{
2063
 
  unsigned char *res=result_field->ptr;
 
2038
  uchar *res=result_field->ptr;
2064
2039
  if (hybrid_type == DECIMAL_RESULT)
2065
2040
  {
2066
 
    int64_t tmp;
 
2041
    longlong tmp;
2067
2042
    my_decimal value, *arg_dec= args[0]->val_decimal(&value);
2068
2043
    if (args[0]->null_value)
2069
2044
    {
2081
2056
    double nr= args[0]->val_real();
2082
2057
 
2083
2058
    if (args[0]->null_value)
2084
 
      memset(res, 0, sizeof(double)+sizeof(int64_t));
 
2059
      bzero(res,sizeof(double)+sizeof(longlong));
2085
2060
    else
2086
2061
    {
2087
 
      int64_t tmp= 1;
 
2062
      longlong tmp= 1;
2088
2063
      float8store(res,nr);
2089
2064
      res+=sizeof(double);
2090
2065
      int8store(res,tmp);
2101
2076
 
2102
2077
void Item_sum_bit::update_field()
2103
2078
{
2104
 
  unsigned char *res=result_field->ptr;
 
2079
  uchar *res=result_field->ptr;
2105
2080
  bits= uint8korr(res);
2106
2081
  add();
2107
2082
  int8store(res, bits);
2136
2111
  else
2137
2112
  {
2138
2113
    double old_nr,nr;
2139
 
    unsigned char *res=result_field->ptr;
 
2114
    uchar *res=result_field->ptr;
2140
2115
 
2141
2116
    float8get(old_nr,res);
2142
2117
    nr= args[0]->val_real();
2152
2127
 
2153
2128
void Item_sum_count::update_field()
2154
2129
{
2155
 
  int64_t nr;
2156
 
  unsigned char *res=result_field->ptr;
 
2130
  longlong nr;
 
2131
  uchar *res=result_field->ptr;
2157
2132
 
2158
2133
  nr=sint8korr(res);
2159
2134
  if (!args[0]->maybe_null || !args[0]->is_null())
2164
2139
 
2165
2140
void Item_sum_avg::update_field()
2166
2141
{
2167
 
  int64_t field_count;
2168
 
  unsigned char *res=result_field->ptr;
 
2142
  longlong field_count;
 
2143
  uchar *res=result_field->ptr;
2169
2144
  if (hybrid_type == DECIMAL_RESULT)
2170
2145
  {
2171
2146
    my_decimal value, *arg_val= args[0]->val_decimal(&value);
2260
2235
void
2261
2236
Item_sum_hybrid::min_max_update_int_field()
2262
2237
{
2263
 
  int64_t nr,old_nr;
 
2238
  longlong nr,old_nr;
2264
2239
 
2265
2240
  old_nr=result_field->val_int();
2266
2241
  nr=args[0]->val_int();
2271
2246
    else
2272
2247
    {
2273
2248
      bool res=(unsigned_flag ?
2274
 
                (uint64_t) old_nr > (uint64_t) nr :
 
2249
                (ulonglong) old_nr > (ulonglong) nr :
2275
2250
                old_nr > nr);
2276
2251
      /* (cmp_sign > 0 && res) || (!(cmp_sign > 0) && !res) */
2277
2252
      if ((cmp_sign > 0) ^ (!res))
2337
2312
{
2338
2313
  // fix_fields() never calls for this Item
2339
2314
  double nr;
2340
 
  int64_t count;
2341
 
  unsigned char *res;
 
2315
  longlong count;
 
2316
  uchar *res;
2342
2317
 
2343
2318
  if (hybrid_type == DECIMAL_RESULT)
2344
2319
    return val_real_from_decimal();
2353
2328
}
2354
2329
 
2355
2330
 
2356
 
int64_t Item_avg_field::val_int()
 
2331
longlong Item_avg_field::val_int()
2357
2332
{
2358
 
  return (int64_t) rint(val_real());
 
2333
  return (longlong) rint(val_real());
2359
2334
}
2360
2335
 
2361
2336
 
2365
2340
  if (hybrid_type == REAL_RESULT)
2366
2341
    return val_decimal_from_real(dec_buf);
2367
2342
 
2368
 
  int64_t count= sint8korr(field->ptr + dec_bin_size);
 
2343
  longlong count= sint8korr(field->ptr + dec_bin_size);
2369
2344
  if ((null_value= !count))
2370
2345
    return 0;
2371
2346
 
2399
2374
  double nr;
2400
2375
  // fix_fields() never calls for this Item
2401
2376
  nr= Item_variance_field::val_real();
2402
 
  assert(nr >= 0.0);
 
2377
  DBUG_ASSERT(nr >= 0.0);
2403
2378
  return sqrt(nr);
2404
2379
}
2405
2380
 
2419
2394
  if (!dec)
2420
2395
    return 0;
2421
2396
  my_decimal2double(E_DEC_FATAL_ERROR, dec, &nr);
2422
 
  assert(nr >= 0.0);
 
2397
  DBUG_ASSERT(nr >= 0.0);
2423
2398
  nr= sqrt(nr);
2424
2399
  double2my_decimal(E_DEC_FATAL_ERROR, nr, &tmp_dec);
2425
 
  my_decimal_round(E_DEC_FATAL_ERROR, &tmp_dec, decimals, false, dec_buf);
 
2400
  my_decimal_round(E_DEC_FATAL_ERROR, &tmp_dec, decimals, FALSE, dec_buf);
2426
2401
  return dec_buf;
2427
2402
}
2428
2403
 
2449
2424
}
2450
2425
 
2451
2426
 
2452
 
int64_t Item_variance_field::val_int()
2453
 
{
2454
 
  /* can't be fix_fields()ed */
2455
 
  return (int64_t) rint(val_real());
2456
 
}
2457
 
 
2458
 
 
2459
2427
double Item_variance_field::val_real()
2460
2428
{
2461
2429
  // fix_fields() never calls for this Item
2463
2431
    return val_real_from_decimal();
2464
2432
 
2465
2433
  double recurrence_s;
2466
 
  uint64_t count;
 
2434
  ulonglong count;
2467
2435
  float8get(recurrence_s, (field->ptr + sizeof(double)));
2468
2436
  count=sint8korr(field->ptr+sizeof(double)*2);
2469
2437
 
2478
2446
** COUNT(DISTINCT ...)
2479
2447
****************************************************************************/
2480
2448
 
2481
 
int simple_str_key_cmp(void* arg, unsigned char* key1, unsigned char* key2)
 
2449
int simple_str_key_cmp(void* arg, uchar* key1, uchar* key2)
2482
2450
{
2483
2451
  Field *f= (Field*) arg;
2484
2452
  return f->cmp(key1, key2);
2491
2459
  static
2492
2460
*/
2493
2461
 
2494
 
int composite_key_cmp(void* arg, unsigned char* key1, unsigned char* key2)
 
2462
int composite_key_cmp(void* arg, uchar* key1, uchar* key2)
2495
2463
{
2496
2464
  Item_sum_count_distinct* item = (Item_sum_count_distinct*)arg;
2497
 
  Field **field    = item->table->getFields();
2498
 
  Field **field_end= field + item->table->getShare()->sizeFields();
2499
 
  uint32_t *lengths=item->field_lengths;
 
2465
  Field **field    = item->table->field;
 
2466
  Field **field_end= field + item->table->s->fields;
 
2467
  uint32 *lengths=item->field_lengths;
2500
2468
  for (; field < field_end; ++field)
2501
2469
  {
2502
2470
    Field* f = *field;
2510
2478
  return 0;
2511
2479
}
2512
2480
 
2513
 
static int count_distinct_walk(void *,
2514
 
                               uint32_t ,
 
2481
 
 
2482
C_MODE_START
 
2483
 
 
2484
static int count_distinct_walk(void *elem __attribute__((__unused__)),
 
2485
                               element_count count __attribute__((__unused__)),
2515
2486
                               void *arg)
2516
2487
{
2517
 
  (*((uint64_t*)arg))++;
 
2488
  (*((ulonglong*)arg))++;
2518
2489
  return 0;
2519
2490
}
2520
2491
 
 
2492
C_MODE_END
 
2493
 
 
2494
 
2521
2495
void Item_sum_count_distinct::cleanup()
2522
2496
{
 
2497
  DBUG_ENTER("Item_sum_count_distinct::cleanup");
2523
2498
  Item_sum_int::cleanup();
2524
2499
 
2525
2500
  /* Free objects only if we own them. */
2532
2507
    */
2533
2508
    delete tree;
2534
2509
    tree= 0;
2535
 
    is_evaluated= false;
 
2510
    is_evaluated= FALSE;
2536
2511
    if (table)
2537
2512
    {
 
2513
      free_tmp_table(table->in_use, table);
2538
2514
      table= 0;
2539
2515
    }
2540
2516
    delete tmp_table_param;
2541
2517
    tmp_table_param= 0;
2542
2518
  }
2543
 
  always_null= false;
2544
 
  return;
 
2519
  always_null= FALSE;
 
2520
  DBUG_VOID_RETURN;
2545
2521
}
2546
2522
 
2547
2523
 
2556
2532
  original= 0;
2557
2533
  force_copy_fields= 1;
2558
2534
  tree= 0;
2559
 
  is_evaluated= false;
 
2535
  is_evaluated= FALSE;
2560
2536
  tmp_table_param= 0;
2561
 
  always_null= false;
 
2537
  always_null= FALSE;
2562
2538
}
2563
2539
 
2564
2540
 
2568
2544
}
2569
2545
 
2570
2546
 
2571
 
bool Item_sum_count_distinct::setup(Session *session)
 
2547
bool Item_sum_count_distinct::setup(THD *thd)
2572
2548
{
2573
2549
  List<Item> list;
2574
 
  Select_Lex *select_lex= session->lex->current_select;
 
2550
  SELECT_LEX *select_lex= thd->lex->current_select;
2575
2551
 
2576
2552
  /*
2577
2553
    Setup can be called twice for ROLLUP items. This is a bug.
2578
 
    Please add assert(tree == 0) here when it's fixed.
 
2554
    Please add DBUG_ASSERT(tree == 0) here when it's fixed.
2579
2555
    It's legal to call setup() more than once when in a subquery
2580
2556
  */
2581
2557
  if (tree || table || tmp_table_param)
2582
 
    return false;
 
2558
    return FALSE;
2583
2559
 
2584
 
  if (!(tmp_table_param= new Tmp_Table_Param))
2585
 
    return true;
 
2560
  if (!(tmp_table_param= new TMP_TABLE_PARAM))
 
2561
    return TRUE;
2586
2562
 
2587
2563
  /* Create a table with an unique key over all parameters */
2588
 
  for (uint32_t i=0; i < arg_count ; i++)
 
2564
  for (uint i=0; i < arg_count ; i++)
2589
2565
  {
2590
2566
    Item *item=args[i];
2591
2567
    if (list.push_back(item))
2592
 
      return true;                              // End of memory
 
2568
      return TRUE;                              // End of memory
2593
2569
    if (item->const_item() && item->is_null())
2594
2570
      always_null= 1;
2595
2571
  }
2596
2572
  if (always_null)
2597
 
    return false;
 
2573
    return FALSE;
2598
2574
  count_field_types(select_lex, tmp_table_param, list, 0);
2599
2575
  tmp_table_param->force_copy_fields= force_copy_fields;
2600
 
  assert(table == 0);
 
2576
  DBUG_ASSERT(table == 0);
2601
2577
 
2602
 
  if (!(table= create_tmp_table(session, tmp_table_param, list, (order_st*) 0, 1,
 
2578
  if (!(table= create_tmp_table(thd, tmp_table_param, list, (ORDER*) 0, 1,
2603
2579
                                0,
2604
 
                                (select_lex->options | session->options),
 
2580
                                (select_lex->options | thd->options),
2605
2581
                                HA_POS_ERROR, (char*)"")))
2606
 
  {
2607
 
    return true;
2608
 
  }
2609
 
  table->cursor->extra(HA_EXTRA_NO_ROWS);               // Don't update rows
 
2582
    return TRUE;
 
2583
  table->file->extra(HA_EXTRA_NO_ROWS);         // Don't update rows
2610
2584
  table->no_rows=1;
2611
2585
 
2612
 
  if (table->getShare()->db_type() == heap_engine)
 
2586
  if (table->s->db_type() == heap_hton)
2613
2587
  {
2614
2588
    /*
2615
2589
      No blobs, otherwise it would have been MyISAM: set up a compare
2617
2591
    */
2618
2592
    qsort_cmp2 compare_key;
2619
2593
    void* cmp_arg;
2620
 
    Field **field= table->getFields();
2621
 
    Field **field_end= field + table->getShare()->sizeFields();
2622
 
    bool all_binary= true;
 
2594
    Field **field= table->field;
 
2595
    Field **field_end= field + table->s->fields;
 
2596
    bool all_binary= TRUE;
2623
2597
 
2624
2598
    for (tree_key_length= 0; field < field_end; ++field)
2625
2599
    {
2626
2600
      Field *f= *field;
2627
2601
      enum enum_field_types f_type= f->type();
2628
2602
      tree_key_length+= f->pack_length();
2629
 
      if (f_type == DRIZZLE_TYPE_VARCHAR)
 
2603
      if ((f_type == MYSQL_TYPE_VARCHAR) || (!f->binary() && (f_type == MYSQL_TYPE_STRING)))
2630
2604
      {
2631
 
        all_binary= false;
 
2605
        all_binary= FALSE;
2632
2606
        break;
2633
2607
      }
2634
2608
    }
2639
2613
    }
2640
2614
    else
2641
2615
    {
2642
 
      if (table->getShare()->sizeFields() == 1)
 
2616
      if (table->s->fields == 1)
2643
2617
      {
2644
2618
        /*
2645
2619
          If we have only one field, which is the most common use of
2648
2622
          about other fields.
2649
2623
        */
2650
2624
        compare_key= (qsort_cmp2) simple_str_key_cmp;
2651
 
        cmp_arg= (void*) table->getField(0);
 
2625
        cmp_arg= (void*) table->field[0];
2652
2626
        /* tree_key_length has been set already */
2653
2627
      }
2654
2628
      else
2655
2629
      {
2656
 
        uint32_t *length;
 
2630
        uint32 *length;
2657
2631
        compare_key= (qsort_cmp2) composite_key_cmp;
2658
2632
        cmp_arg= (void*) this;
2659
 
        field_lengths= (uint32_t*) session->alloc(table->getShare()->sizeFields() * sizeof(uint32_t));
2660
 
        for (tree_key_length= 0, length= field_lengths, field= table->getFields();
 
2633
        field_lengths= (uint32*) thd->alloc(table->s->fields * sizeof(uint32));
 
2634
        for (tree_key_length= 0, length= field_lengths, field= table->field;
2661
2635
             field < field_end; ++field, ++length)
2662
2636
        {
2663
2637
          *length= (*field)->pack_length();
2665
2639
        }
2666
2640
      }
2667
2641
    }
2668
 
    assert(tree == 0);
 
2642
    DBUG_ASSERT(tree == 0);
2669
2643
    tree= new Unique(compare_key, cmp_arg, tree_key_length,
2670
 
                     (size_t)session->variables.max_heap_table_size);
 
2644
                     thd->variables.max_heap_table_size);
2671
2645
    /*
2672
2646
      The only time tree_key_length could be 0 is if someone does
2673
2647
      count(distinct) on a char(0) field - stupid thing to do,
2674
2648
      but this has to be handled - otherwise someone can crash
2675
2649
      the server with a DoS attack
2676
2650
    */
2677
 
    is_evaluated= false;
 
2651
    is_evaluated= FALSE;
2678
2652
    if (! tree)
2679
 
      return true;
 
2653
      return TRUE;
2680
2654
  }
2681
 
  return false;
 
2655
  return FALSE;
2682
2656
}
2683
2657
 
2684
2658
 
2685
 
Item *Item_sum_count_distinct::copy_or_same(Session* session)
 
2659
Item *Item_sum_count_distinct::copy_or_same(THD* thd) 
2686
2660
{
2687
 
  return new (session->mem_root) Item_sum_count_distinct(session, this);
 
2661
  return new (thd->mem_root) Item_sum_count_distinct(thd, this);
2688
2662
}
2689
2663
 
2690
2664
 
2691
2665
void Item_sum_count_distinct::clear()
2692
2666
{
2693
2667
  /* tree and table can be both null only if always_null */
2694
 
  is_evaluated= false;
 
2668
  is_evaluated= FALSE;
2695
2669
  if (tree)
2696
2670
  {
2697
2671
    tree->reset();
2698
2672
  }
2699
2673
  else if (table)
2700
2674
  {
2701
 
    table->cursor->extra(HA_EXTRA_NO_CACHE);
2702
 
    table->cursor->ha_delete_all_rows();
2703
 
    table->cursor->extra(HA_EXTRA_WRITE_CACHE);
 
2675
    table->file->extra(HA_EXTRA_NO_CACHE);
 
2676
    table->file->ha_delete_all_rows();
 
2677
    table->file->extra(HA_EXTRA_WRITE_CACHE);
2704
2678
  }
2705
2679
}
2706
2680
 
2712
2686
  copy_fields(tmp_table_param);
2713
2687
  copy_funcs(tmp_table_param->items_to_copy);
2714
2688
 
2715
 
  for (Field **field= table->getFields() ; *field ; field++)
2716
 
  {
 
2689
  for (Field **field=table->field ; *field ; field++)
2717
2690
    if ((*field)->is_real_null(0))
2718
 
    {
2719
2691
      return 0;                                 // Don't count NULL
2720
 
    }
2721
 
  }
2722
2692
 
2723
 
  is_evaluated= false;
 
2693
  is_evaluated= FALSE;
2724
2694
  if (tree)
2725
2695
  {
2726
2696
    /*
2729
2699
      bloat the tree without providing any valuable info. Besides,
2730
2700
      key_length used to initialize the tree didn't include space for them.
2731
2701
    */
2732
 
    return tree->unique_add(table->record[0] + table->getShare()->null_bytes);
 
2702
    return tree->unique_add(table->record[0] + table->s->null_bytes);
2733
2703
  }
2734
 
  if ((error= table->cursor->insertRecord(table->record[0])) &&
2735
 
      table->cursor->is_fatal_error(error, HA_CHECK_DUP))
2736
 
    return true;
2737
 
  return false;
 
2704
  if ((error= table->file->ha_write_row(table->record[0])) &&
 
2705
      table->file->is_fatal_error(error, HA_CHECK_DUP))
 
2706
    return TRUE;
 
2707
  return FALSE;
2738
2708
}
2739
2709
 
2740
2710
 
2741
 
int64_t Item_sum_count_distinct::val_int()
 
2711
longlong Item_sum_count_distinct::val_int()
2742
2712
{
2743
2713
  int error;
2744
 
  assert(fixed == 1);
 
2714
  DBUG_ASSERT(fixed == 1);
2745
2715
  if (!table)                                   // Empty query
2746
 
    return 0L;
 
2716
    return 0LL;
2747
2717
  if (tree)
2748
2718
  {
2749
2719
    if (is_evaluated)
2750
2720
      return count;
2751
2721
 
2752
2722
    if (tree->elements == 0)
2753
 
      return (int64_t) tree->elements_in_tree(); // everything fits in memory
 
2723
      return (longlong) tree->elements_in_tree(); // everything fits in memory
2754
2724
    count= 0;
2755
2725
    tree->walk(count_distinct_walk, (void*) &count);
2756
 
    is_evaluated= true;
2757
 
    return (int64_t) count;
 
2726
    is_evaluated= TRUE;
 
2727
    return (longlong) count;
2758
2728
  }
2759
2729
 
2760
 
  error= table->cursor->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
 
2730
  error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
2761
2731
 
2762
2732
  if(error)
2763
2733
  {
2764
 
    table->print_error(error, MYF(0));
2765
 
  }
2766
 
 
2767
 
  return table->cursor->stats.records;
2768
 
}
 
2734
    table->file->print_error(error, MYF(0));
 
2735
  }
 
2736
 
 
2737
  return table->file->stats.records;
 
2738
}
 
2739
 
 
2740
 
 
2741
/****************************************************************************
 
2742
** Functions to handle dynamic loadable aggregates
 
2743
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
 
2744
** Adapted for UDAs by: Andreas F. Bobak <bobak@relog.ch>.
 
2745
** Rewritten by: Monty.
 
2746
****************************************************************************/
 
2747
 
 
2748
#ifdef HAVE_DLOPEN
 
2749
 
 
2750
void Item_udf_sum::clear()
 
2751
{
 
2752
  DBUG_ENTER("Item_udf_sum::clear");
 
2753
  udf.clear();
 
2754
  DBUG_VOID_RETURN;
 
2755
}
 
2756
 
 
2757
bool Item_udf_sum::add()
 
2758
{
 
2759
  DBUG_ENTER("Item_udf_sum::add");
 
2760
  udf.add(&null_value);
 
2761
  DBUG_RETURN(0);
 
2762
}
 
2763
 
 
2764
void Item_udf_sum::cleanup()
 
2765
{
 
2766
  /*
 
2767
    udf_handler::cleanup() nicely handles case when we have not
 
2768
    original item but one created by copy_or_same() method.
 
2769
  */
 
2770
  udf.cleanup();
 
2771
  Item_sum::cleanup();
 
2772
}
 
2773
 
 
2774
 
 
2775
void Item_udf_sum::print(String *str, enum_query_type query_type)
 
2776
{
 
2777
  str->append(func_name());
 
2778
  str->append('(');
 
2779
  for (uint i=0 ; i < arg_count ; i++)
 
2780
  {
 
2781
    if (i)
 
2782
      str->append(',');
 
2783
    args[i]->print(str, query_type);
 
2784
  }
 
2785
  str->append(')');
 
2786
}
 
2787
 
 
2788
 
 
2789
Item *Item_sum_udf_float::copy_or_same(THD* thd)
 
2790
{
 
2791
  return new (thd->mem_root) Item_sum_udf_float(thd, this);
 
2792
}
 
2793
 
 
2794
double Item_sum_udf_float::val_real()
 
2795
{
 
2796
  DBUG_ASSERT(fixed == 1);
 
2797
  DBUG_ENTER("Item_sum_udf_float::val");
 
2798
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
 
2799
                     args[0]->result_type(), arg_count));
 
2800
  DBUG_RETURN(udf.val(&null_value));
 
2801
}
 
2802
 
 
2803
 
 
2804
String *Item_sum_udf_float::val_str(String *str)
 
2805
{
 
2806
  return val_string_from_real(str);
 
2807
}
 
2808
 
 
2809
 
 
2810
my_decimal *Item_sum_udf_float::val_decimal(my_decimal *dec)
 
2811
{
 
2812
  return val_decimal_from_real(dec);
 
2813
}
 
2814
 
 
2815
 
 
2816
String *Item_sum_udf_decimal::val_str(String *str)
 
2817
{
 
2818
  return val_string_from_decimal(str);
 
2819
}
 
2820
 
 
2821
 
 
2822
double Item_sum_udf_decimal::val_real()
 
2823
{
 
2824
  return val_real_from_decimal();
 
2825
}
 
2826
 
 
2827
 
 
2828
longlong Item_sum_udf_decimal::val_int()
 
2829
{
 
2830
  return val_int_from_decimal();
 
2831
}
 
2832
 
 
2833
 
 
2834
my_decimal *Item_sum_udf_decimal::val_decimal(my_decimal *dec_buf)
 
2835
{
 
2836
  DBUG_ASSERT(fixed == 1);
 
2837
  DBUG_ENTER("Item_func_udf_decimal::val_decimal");
 
2838
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
 
2839
                     args[0]->result_type(), arg_count));
 
2840
 
 
2841
  DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
 
2842
}
 
2843
 
 
2844
 
 
2845
Item *Item_sum_udf_decimal::copy_or_same(THD* thd)
 
2846
{
 
2847
  return new (thd->mem_root) Item_sum_udf_decimal(thd, this);
 
2848
}
 
2849
 
 
2850
 
 
2851
Item *Item_sum_udf_int::copy_or_same(THD* thd)
 
2852
{
 
2853
  return new (thd->mem_root) Item_sum_udf_int(thd, this);
 
2854
}
 
2855
 
 
2856
longlong Item_sum_udf_int::val_int()
 
2857
{
 
2858
  DBUG_ASSERT(fixed == 1);
 
2859
  DBUG_ENTER("Item_sum_udf_int::val_int");
 
2860
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
 
2861
                     args[0]->result_type(), arg_count));
 
2862
  DBUG_RETURN(udf.val_int(&null_value));
 
2863
}
 
2864
 
 
2865
 
 
2866
String *Item_sum_udf_int::val_str(String *str)
 
2867
{
 
2868
  return val_string_from_int(str);
 
2869
}
 
2870
 
 
2871
my_decimal *Item_sum_udf_int::val_decimal(my_decimal *dec)
 
2872
{
 
2873
  return val_decimal_from_int(dec);
 
2874
}
 
2875
 
 
2876
 
 
2877
/** Default max_length is max argument length. */
 
2878
 
 
2879
void Item_sum_udf_str::fix_length_and_dec()
 
2880
{
 
2881
  DBUG_ENTER("Item_sum_udf_str::fix_length_and_dec");
 
2882
  max_length=0;
 
2883
  for (uint i = 0; i < arg_count; i++)
 
2884
    set_if_bigger(max_length,args[i]->max_length);
 
2885
  DBUG_VOID_RETURN;
 
2886
}
 
2887
 
 
2888
 
 
2889
Item *Item_sum_udf_str::copy_or_same(THD* thd)
 
2890
{
 
2891
  return new (thd->mem_root) Item_sum_udf_str(thd, this);
 
2892
}
 
2893
 
 
2894
 
 
2895
my_decimal *Item_sum_udf_str::val_decimal(my_decimal *dec)
 
2896
{
 
2897
  return val_decimal_from_string(dec);
 
2898
}
 
2899
 
 
2900
String *Item_sum_udf_str::val_str(String *str)
 
2901
{
 
2902
  DBUG_ASSERT(fixed == 1);
 
2903
  DBUG_ENTER("Item_sum_udf_str::str");
 
2904
  String *res=udf.val_str(str,&str_value);
 
2905
  null_value = !res;
 
2906
  DBUG_RETURN(res);
 
2907
}
 
2908
 
 
2909
#endif /* HAVE_DLOPEN */
 
2910
 
2769
2911
 
2770
2912
/*****************************************************************************
2771
2913
 GROUP_CONCAT function
2772
2914
 
2773
2915
 SQL SYNTAX:
2774
 
  GROUP_CONCAT([DISTINCT] expr,... [order_st BY col [ASC|DESC],...]
 
2916
  GROUP_CONCAT([DISTINCT] expr,... [ORDER BY col [ASC|DESC],...]
2775
2917
    [SEPARATOR str_const])
2776
2918
 
2777
2919
 concat of values from "group by" operation
2778
2920
 
2779
2921
 BUGS
2780
 
   Blobs doesn't work with DISTINCT or order_st BY
 
2922
   Blobs doesn't work with DISTINCT or ORDER BY
2781
2923
*****************************************************************************/
2782
2924
 
2783
2925
 
2784
 
/**
 
2926
/** 
2785
2927
  Compares the values for fields in expr list of GROUP_CONCAT.
2786
2928
  @note
2787
 
 
 
2929
       
2788
2930
     GROUP_CONCAT([DISTINCT] expr [,expr ...]
2789
 
              [order_st BY {unsigned_integer | col_name | expr}
 
2931
              [ORDER BY {unsigned_integer | col_name | expr}
2790
2932
                  [ASC | DESC] [,col_name ...]]
2791
2933
              [SEPARATOR str_val])
2792
 
 
 
2934
 
2793
2935
  @return
2794
 
  @retval -1 : key1 < key2
 
2936
  @retval -1 : key1 < key2 
2795
2937
  @retval  0 : key1 = key2
2796
 
  @retval  1 : key1 > key2
 
2938
  @retval  1 : key1 > key2 
2797
2939
*/
2798
2940
 
2799
 
int group_concat_key_cmp_with_distinct(void* arg, const void* key1,
 
2941
int group_concat_key_cmp_with_distinct(void* arg, const void* key1, 
2800
2942
                                       const void* key2)
2801
2943
{
2802
2944
  Item_func_group_concat *item_func= (Item_func_group_concat*)arg;
2803
 
  Table *table= item_func->table;
 
2945
  TABLE *table= item_func->table;
2804
2946
 
2805
 
  for (uint32_t i= 0; i < item_func->arg_count_field; i++)
 
2947
  for (uint i= 0; i < item_func->arg_count_field; i++)
2806
2948
  {
2807
2949
    Item *item= item_func->args[i];
2808
 
    /*
 
2950
    /* 
2809
2951
      If field_item is a const item then either get_tp_table_field returns 0
2810
 
      or it is an item over a const table.
 
2952
      or it is an item over a const table. 
2811
2953
    */
2812
2954
    if (item->const_item())
2813
2955
      continue;
2818
2960
    */
2819
2961
    Field *field= item->get_tmp_table_field();
2820
2962
    int res;
2821
 
    uint32_t offset= field->offset(field->getTable()->record[0])-table->getShare()->null_bytes;
2822
 
    if((res= field->cmp((unsigned char*)key1 + offset, (unsigned char*)key2 + offset)))
 
2963
    uint offset= field->offset(field->table->record[0])-table->s->null_bytes;
 
2964
    if((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset)))
2823
2965
      return res;
2824
2966
  }
2825
2967
  return 0;
2830
2972
  function of sort for syntax: GROUP_CONCAT(expr,... ORDER BY col,... )
2831
2973
*/
2832
2974
 
2833
 
int group_concat_key_cmp_with_order(void* arg, const void* key1,
 
2975
int group_concat_key_cmp_with_order(void* arg, const void* key1, 
2834
2976
                                    const void* key2)
2835
2977
{
2836
2978
  Item_func_group_concat* grp_item= (Item_func_group_concat*) arg;
2837
 
  order_st **order_item, **end;
2838
 
  Table *table= grp_item->table;
 
2979
  ORDER **order_item, **end;
 
2980
  TABLE *table= grp_item->table;
2839
2981
 
2840
2982
  for (order_item= grp_item->order, end=order_item+ grp_item->arg_count_order;
2841
2983
       order_item < end;
2848
2990
      the temporary table, not the original field
2849
2991
    */
2850
2992
    Field *field= item->get_tmp_table_field();
2851
 
    /*
 
2993
    /* 
2852
2994
      If item is a const item then either get_tp_table_field returns 0
2853
 
      or it is an item over a const table.
 
2995
      or it is an item over a const table. 
2854
2996
    */
2855
2997
    if (field && !item->const_item())
2856
2998
    {
2857
2999
      int res;
2858
 
      uint32_t offset= (field->offset(field->getTable()->record[0]) -
2859
 
                    table->getShare()->null_bytes);
2860
 
      if ((res= field->cmp((unsigned char*)key1 + offset, (unsigned char*)key2 + offset)))
 
3000
      uint offset= (field->offset(field->table->record[0]) -
 
3001
                    table->s->null_bytes);
 
3002
      if ((res= field->cmp((uchar*)key1 + offset, (uchar*)key2 + offset)))
2861
3003
        return (*order_item)->asc ? res : -res;
2862
3004
    }
2863
3005
  }
2874
3016
  Append data from current leaf to item->result.
2875
3017
*/
2876
3018
 
2877
 
int dump_leaf_key(unsigned char* key, uint32_t ,
 
3019
int dump_leaf_key(uchar* key, element_count count __attribute__((unused)),
2878
3020
                  Item_func_group_concat *item)
2879
3021
{
2880
 
  Table *table= item->table;
2881
 
  String tmp((char *)table->getUpdateRecord(), table->getShare()->getRecordLength(),
 
3022
  TABLE *table= item->table;
 
3023
  String tmp((char *)table->record[1], table->s->reclength,
2882
3024
             default_charset_info);
2883
3025
  String tmp2;
2884
3026
  String *result= &item->result;
2885
3027
  Item **arg= item->args, **arg_end= item->args + item->arg_count_field;
2886
 
  uint32_t old_length= result->length();
 
3028
  uint old_length= result->length();
2887
3029
 
2888
3030
  if (item->no_appended)
2889
 
    item->no_appended= false;
 
3031
    item->no_appended= FALSE;
2890
3032
  else
2891
3033
    result->append(*item->separator);
2892
3034
 
2905
3047
        because it contains both order and arg list fields.
2906
3048
      */
2907
3049
      Field *field= (*arg)->get_tmp_table_field();
2908
 
      uint32_t offset= (field->offset(field->getTable()->record[0]) -
2909
 
                    table->getShare()->null_bytes);
2910
 
      assert(offset < table->getShare()->getRecordLength());
 
3050
      uint offset= (field->offset(field->table->record[0]) -
 
3051
                    table->s->null_bytes);
 
3052
      DBUG_ASSERT(offset < table->s->reclength);
2911
3053
      res= field->val_str(&tmp, key + offset);
2912
3054
    }
2913
3055
    else
2920
3062
  if (result->length() > item->max_length)
2921
3063
  {
2922
3064
    int well_formed_error;
2923
 
    const CHARSET_INFO * const cs= item->collation.collation;
 
3065
    CHARSET_INFO *cs= item->collation.collation;
2924
3066
    const char *ptr= result->ptr();
2925
 
    uint32_t add_length;
 
3067
    uint add_length;
2926
3068
    /*
2927
3069
      It's ok to use item->result.length() as the fourth argument
2928
3070
      as this is never used to limit the length of the data.
2935
3077
                                          &well_formed_error);
2936
3078
    result->length(old_length + add_length);
2937
3079
    item->count_cut_values++;
2938
 
    item->warning_for_row= true;
 
3080
    item->warning_for_row= TRUE;
2939
3081
    return 1;
2940
3082
  }
2941
3083
  return 0;
2956
3098
                       bool distinct_arg, List<Item> *select_list,
2957
3099
                       SQL_LIST *order_list, String *separator_arg)
2958
3100
  :tmp_table_param(0), warning(0),
2959
 
   separator(separator_arg), tree(NULL), unique_filter(NULL), table(0),
 
3101
   separator(separator_arg), tree(0), unique_filter(NULL), table(0),
2960
3102
   order(0), context(context_arg),
2961
3103
   arg_count_order(order_list ? order_list->elements : 0),
2962
3104
   arg_count_field(select_list->elements),
2963
3105
   count_cut_values(0),
2964
3106
   distinct(distinct_arg),
2965
 
   warning_for_row(false),
 
3107
   warning_for_row(FALSE),
2966
3108
   force_copy_fields(0), original(0)
2967
3109
{
2968
3110
  Item *item_select;
2969
3111
  Item **arg_ptr;
2970
3112
 
2971
 
  quick_group= false;
 
3113
  quick_group= FALSE;
2972
3114
  arg_count= arg_count_field + arg_count_order;
2973
3115
 
2974
3116
  /*
2977
3119
           (for possible order items in temporare tables)
2978
3120
    order - arg_count_order
2979
3121
  */
2980
 
  if (!(args= (Item**) memory::sql_alloc(sizeof(Item*) * arg_count +
2981
 
                                 sizeof(order_st*)*arg_count_order)))
 
3122
  if (!(args= (Item**) sql_alloc(sizeof(Item*) * arg_count +
 
3123
                                 sizeof(ORDER*)*arg_count_order)))
2982
3124
    return;
2983
3125
 
2984
 
  order= (order_st**)(args + arg_count);
 
3126
  order= (ORDER**)(args + arg_count);
2985
3127
 
2986
3128
  /* fill args items of show and sort */
2987
3129
  List_iterator_fast<Item> li(*select_list);
2991
3133
 
2992
3134
  if (arg_count_order)
2993
3135
  {
2994
 
    order_st **order_ptr= order;
2995
 
    for (order_st *order_item= (order_st*) order_list->first;
 
3136
    ORDER **order_ptr= order;
 
3137
    for (ORDER *order_item= (ORDER*) order_list->first;
2996
3138
         order_item != NULL;
2997
3139
         order_item= order_item->next)
2998
3140
    {
3004
3146
}
3005
3147
 
3006
3148
 
3007
 
Item_func_group_concat::Item_func_group_concat(Session *session,
 
3149
Item_func_group_concat::Item_func_group_concat(THD *thd,
3008
3150
                                               Item_func_group_concat *item)
3009
 
  :Item_sum(session, item),
 
3151
  :Item_sum(thd, item),
3010
3152
  tmp_table_param(item->tmp_table_param),
3011
3153
  warning(item->warning),
3012
3154
  separator(item->separator),
3032
3174
 
3033
3175
void Item_func_group_concat::cleanup()
3034
3176
{
 
3177
  DBUG_ENTER("Item_func_group_concat::cleanup");
3035
3178
  Item_sum::cleanup();
3036
3179
 
3037
3180
  /* Adjust warning message to include total number of cut values */
3038
3181
  if (warning)
3039
3182
  {
3040
 
    char warn_buff[DRIZZLE_ERRMSG_SIZE];
3041
 
    snprintf(warn_buff, sizeof(warn_buff), ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values);
3042
 
    warning->set_msg(current_session, warn_buff);
 
3183
    char warn_buff[MYSQL_ERRMSG_SIZE];
 
3184
    sprintf(warn_buff, ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values);
 
3185
    warning->set_msg(current_thd, warn_buff);
3043
3186
    warning= 0;
3044
3187
  }
3045
3188
 
3053
3196
    tmp_table_param= 0;
3054
3197
    if (table)
3055
3198
    {
3056
 
      Session *session= table->in_use;
 
3199
      THD *thd= table->in_use;
 
3200
      free_tmp_table(thd, table);
3057
3201
      table= 0;
3058
3202
      if (tree)
3059
3203
      {
3067
3211
      }
3068
3212
      if (warning)
3069
3213
      {
3070
 
        char warn_buff[DRIZZLE_ERRMSG_SIZE];
3071
 
        snprintf(warn_buff, sizeof(warn_buff), ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values);
3072
 
        warning->set_msg(session, warn_buff);
 
3214
        char warn_buff[MYSQL_ERRMSG_SIZE];
 
3215
        sprintf(warn_buff, ER(ER_CUT_VALUE_GROUP_CONCAT), count_cut_values);
 
3216
        warning->set_msg(thd, warn_buff);
3073
3217
        warning= 0;
3074
3218
      }
3075
3219
    }
3076
 
    assert(tree == 0 && warning == 0);
 
3220
    DBUG_ASSERT(tree == 0 && warning == 0);
3077
3221
  }
3078
 
  return;
 
3222
  DBUG_VOID_RETURN;
3079
3223
}
3080
3224
 
3081
3225
 
3082
 
Item *Item_func_group_concat::copy_or_same(Session* session)
 
3226
Item *Item_func_group_concat::copy_or_same(THD* thd)
3083
3227
{
3084
 
  return new (session->mem_root) Item_func_group_concat(session, this);
 
3228
  return new (thd->mem_root) Item_func_group_concat(thd, this);
3085
3229
}
3086
3230
 
3087
3231
 
3089
3233
{
3090
3234
  result.length(0);
3091
3235
  result.copy();
3092
 
  null_value= true;
3093
 
  warning_for_row= false;
3094
 
  no_appended= true;
 
3236
  null_value= TRUE;
 
3237
  warning_for_row= FALSE;
 
3238
  no_appended= TRUE;
3095
3239
  if (tree)
3096
3240
    reset_tree(tree);
3097
3241
  if (distinct)
3107
3251
  copy_fields(tmp_table_param);
3108
3252
  copy_funcs(tmp_table_param->items_to_copy);
3109
3253
 
3110
 
  for (uint32_t i= 0; i < arg_count_field; i++)
 
3254
  for (uint i= 0; i < arg_count_field; i++)
3111
3255
  {
3112
3256
    Item *show_item= args[i];
3113
3257
    if (!show_item->const_item())
3114
3258
    {
3115
3259
      Field *f= show_item->get_tmp_table_field();
3116
 
      if (f->is_null_in_record((const unsigned char*) table->record[0]))
 
3260
      if (f->is_null_in_record((const uchar*) table->record[0]))
3117
3261
        return 0;                               // Skip row if it contains null
3118
3262
    }
3119
3263
  }
3120
3264
 
3121
 
  null_value= false;
3122
 
  bool row_eligible= true;
 
3265
  null_value= FALSE;
 
3266
  bool row_eligible= TRUE;
3123
3267
 
3124
 
  if (distinct)
 
3268
  if (distinct) 
3125
3269
  {
3126
3270
    /* Filter out duplicate rows. */
3127
 
    uint32_t count= unique_filter->elements_in_tree();
3128
 
    unique_filter->unique_add(table->record[0] + table->getShare()->null_bytes);
 
3271
    uint count= unique_filter->elements_in_tree();
 
3272
    unique_filter->unique_add(table->record[0] + table->s->null_bytes);
3129
3273
    if (count == unique_filter->elements_in_tree())
3130
 
      row_eligible= false;
 
3274
      row_eligible= FALSE;
3131
3275
  }
3132
3276
 
3133
3277
  TREE_ELEMENT *el= 0;                          // Only for safety
3134
3278
  if (row_eligible && tree)
3135
 
    el= tree_insert(tree, table->record[0] + table->getShare()->null_bytes, 0,
 
3279
    el= tree_insert(tree, table->record[0] + table->s->null_bytes, 0,
3136
3280
                    tree->custom_arg);
3137
3281
  /*
3138
3282
    If the row is not a duplicate (el->count == 1)
3141
3285
  */
3142
3286
  if (row_eligible && !warning_for_row &&
3143
3287
      (!tree || (el->count == 1 && distinct && !arg_count_order)))
3144
 
    dump_leaf_key(table->record[0] + table->getShare()->null_bytes, 1, this);
 
3288
    dump_leaf_key(table->record[0] + table->s->null_bytes, 1, this);
3145
3289
 
3146
3290
  return 0;
3147
3291
}
3148
3292
 
3149
3293
 
3150
3294
bool
3151
 
Item_func_group_concat::fix_fields(Session *session, Item **ref)
 
3295
Item_func_group_concat::fix_fields(THD *thd, Item **ref)
3152
3296
{
3153
 
  uint32_t i;                       /* for loop variable */
3154
 
  assert(fixed == 0);
 
3297
  uint i;                       /* for loop variable */
 
3298
  DBUG_ASSERT(fixed == 0);
3155
3299
 
3156
 
  if (init_sum_func_check(session))
3157
 
    return true;
 
3300
  if (init_sum_func_check(thd))
 
3301
    return TRUE;
3158
3302
 
3159
3303
  maybe_null= 1;
3160
3304
 
3161
3305
  /*
3162
 
    Fix fields for select list and order_st clause
 
3306
    Fix fields for select list and ORDER clause
3163
3307
  */
3164
3308
 
3165
3309
  for (i=0 ; i < arg_count ; i++)
3166
3310
  {
3167
3311
    if ((!args[i]->fixed &&
3168
 
         args[i]->fix_fields(session, args + i)) ||
 
3312
         args[i]->fix_fields(thd, args + i)) ||
3169
3313
        args[i]->check_cols(1))
3170
 
      return true;
 
3314
      return TRUE;
3171
3315
  }
3172
3316
 
3173
3317
  if (agg_item_charsets(collation, func_name(),
3180
3324
  result.set_charset(collation.collation);
3181
3325
  result_field= 0;
3182
3326
  null_value= 1;
3183
 
  max_length= (size_t)session->variables.group_concat_max_len;
3184
 
 
3185
 
  if (check_sum_func(session, ref))
3186
 
    return true;
 
3327
  max_length= thd->variables.group_concat_max_len;
 
3328
 
 
3329
  uint32 offset;
 
3330
  if (separator->needs_conversion(separator->length(), separator->charset(),
 
3331
                                  collation.collation, &offset))
 
3332
  {
 
3333
    uint32 buflen= collation.collation->mbmaxlen * separator->length();
 
3334
    uint errors, conv_length;
 
3335
    char *buf;
 
3336
    String *new_separator;
 
3337
 
 
3338
    if (!(buf= (char*) thd->stmt_arena->alloc(buflen)) ||
 
3339
        !(new_separator= new(thd->stmt_arena->mem_root)
 
3340
                           String(buf, buflen, collation.collation)))
 
3341
      return TRUE;
 
3342
    
 
3343
    conv_length= copy_and_convert(buf, buflen, collation.collation,
 
3344
                                  separator->ptr(), separator->length(),
 
3345
                                  separator->charset(), &errors);
 
3346
    new_separator->length(conv_length);
 
3347
    separator= new_separator;
 
3348
  }
 
3349
 
 
3350
  if (check_sum_func(thd, ref))
 
3351
    return TRUE;
3187
3352
 
3188
3353
  fixed= 1;
3189
 
  return false;
 
3354
  return FALSE;
3190
3355
}
3191
3356
 
3192
3357
 
3193
 
bool Item_func_group_concat::setup(Session *session)
 
3358
bool Item_func_group_concat::setup(THD *thd)
3194
3359
{
3195
3360
  List<Item> list;
3196
 
  Select_Lex *select_lex= session->lex->current_select;
 
3361
  SELECT_LEX *select_lex= thd->lex->current_select;
 
3362
  DBUG_ENTER("Item_func_group_concat::setup");
3197
3363
 
3198
3364
  /*
3199
3365
    Currently setup() can be called twice. Please add
3200
3366
    assertion here when this is fixed.
3201
3367
  */
3202
3368
  if (table || tree)
3203
 
    return(false);
 
3369
    DBUG_RETURN(FALSE);
3204
3370
 
3205
 
  if (!(tmp_table_param= new Tmp_Table_Param))
3206
 
    return(true);
 
3371
  if (!(tmp_table_param= new TMP_TABLE_PARAM))
 
3372
    DBUG_RETURN(TRUE);
3207
3373
 
3208
3374
  /* We'll convert all blobs to varchar fields in the temporary table */
3209
3375
  tmp_table_param->convert_blob_length= max_length *
3210
3376
                                        collation.collation->mbmaxlen;
3211
3377
  /* Push all not constant fields to the list and create a temp table */
3212
3378
  always_null= 0;
3213
 
  for (uint32_t i= 0; i < arg_count_field; i++)
 
3379
  for (uint i= 0; i < arg_count_field; i++)
3214
3380
  {
3215
3381
    Item *item= args[i];
3216
3382
    if (list.push_back(item))
3217
 
      return(true);
 
3383
      DBUG_RETURN(TRUE);
3218
3384
    if (item->const_item())
3219
3385
    {
3220
3386
      if (item->is_null())
3221
3387
      {
3222
3388
        always_null= 1;
3223
 
        return(false);
 
3389
        DBUG_RETURN(FALSE);
3224
3390
      }
3225
3391
    }
3226
3392
  }
3227
3393
 
3228
3394
  List<Item> all_fields(list);
3229
3395
  /*
3230
 
    Try to find every order_st expression in the list of GROUP_CONCAT
 
3396
    Try to find every ORDER expression in the list of GROUP_CONCAT
3231
3397
    arguments. If an expression is not found, prepend it to
3232
3398
    "all_fields". The resulting field list is used as input to create
3233
3399
    tmp table columns.
3234
3400
  */
3235
3401
  if (arg_count_order &&
3236
 
      setup_order(session, args, context->table_list, list, all_fields, *order))
3237
 
    return(true);
 
3402
      setup_order(thd, args, context->table_list, list, all_fields, *order))
 
3403
    DBUG_RETURN(TRUE);
3238
3404
 
3239
3405
  count_field_types(select_lex, tmp_table_param, all_fields, 0);
3240
3406
  tmp_table_param->force_copy_fields= force_copy_fields;
3241
 
  assert(table == 0);
 
3407
  DBUG_ASSERT(table == 0);
3242
3408
  if (arg_count_order > 0 || distinct)
3243
3409
  {
3244
3410
    /*
3247
3413
      DISTINCT. This leads to truncation if the BLOB's size exceeds
3248
3414
      Field_varstring::MAX_SIZE.
3249
3415
    */
3250
 
    set_if_smaller(tmp_table_param->convert_blob_length,
 
3416
    set_if_smaller(tmp_table_param->convert_blob_length, 
3251
3417
                   Field_varstring::MAX_SIZE);
3252
3418
  }
3253
3419
 
3258
3424
    Note that in the table, we first have the ORDER BY fields, then the
3259
3425
    field list.
3260
3426
  */
3261
 
  if (!(table= create_tmp_table(session, tmp_table_param, all_fields,
3262
 
                                (order_st*) 0, 0, true,
3263
 
                                (select_lex->options | session->options),
 
3427
  if (!(table= create_tmp_table(thd, tmp_table_param, all_fields,
 
3428
                                (ORDER*) 0, 0, TRUE,
 
3429
                                (select_lex->options | thd->options),
3264
3430
                                HA_POS_ERROR, (char*) "")))
3265
 
  {
3266
 
    return(true);
3267
 
  }
3268
 
 
3269
 
  table->cursor->extra(HA_EXTRA_NO_ROWS);
 
3431
    DBUG_RETURN(TRUE);
 
3432
  table->file->extra(HA_EXTRA_NO_ROWS);
3270
3433
  table->no_rows= 1;
3271
3434
 
3272
3435
  /*
3274
3437
     Don't reserve space for NULLs: if any of gconcat arguments is NULL,
3275
3438
     the row is not added to the result.
3276
3439
  */
3277
 
  uint32_t tree_key_length= table->getShare()->getRecordLength() - table->getShare()->null_bytes;
 
3440
  uint tree_key_length= table->s->reclength - table->s->null_bytes;
3278
3441
 
3279
3442
  if (arg_count_order)
3280
3443
  {
3284
3447
      syntax of this function). If there is no ORDER BY clause, we don't
3285
3448
      create this tree.
3286
3449
    */
3287
 
    init_tree(tree, (uint32_t) min(session->variables.max_heap_table_size,
3288
 
                                   (uint64_t)(session->variables.sortbuff_size/16)), 
3289
 
              0,
3290
 
              tree_key_length,
3291
 
              group_concat_key_cmp_with_order , false, NULL, (void*) this);
 
3450
    init_tree(tree, (uint) min(thd->variables.max_heap_table_size,
 
3451
                               thd->variables.sortbuff_size/16), 0,
 
3452
              tree_key_length, 
 
3453
              group_concat_key_cmp_with_order , 0, NULL, (void*) this);
3292
3454
  }
3293
3455
 
3294
3456
  if (distinct)
3295
3457
    unique_filter= new Unique(group_concat_key_cmp_with_distinct,
3296
3458
                              (void*)this,
3297
3459
                              tree_key_length,
3298
 
                              (size_t)session->variables.max_heap_table_size);
3299
 
 
3300
 
  return(false);
 
3460
                              thd->variables.max_heap_table_size);
 
3461
  
 
3462
  DBUG_RETURN(FALSE);
3301
3463
}
3302
3464
 
3303
3465
 
3312
3474
  tree= 0;
3313
3475
}
3314
3476
 
3315
 
double Item_func_group_concat::val_real()
3316
 
{
3317
 
  String *res;  res=val_str(&str_value);
3318
 
  return res ? internal::my_atof(res->c_ptr()) : 0.0;
3319
 
}
3320
 
 
3321
 
int64_t Item_func_group_concat::val_int()
3322
 
{
3323
 
  String *res;
3324
 
  char *end_ptr;
3325
 
  int error;
3326
 
  if (!(res= val_str(&str_value)))
3327
 
    return (int64_t) 0;
3328
 
  end_ptr= (char*) res->ptr()+ res->length();
3329
 
  return internal::my_strtoll10(res->ptr(), &end_ptr, &error);
3330
 
}
3331
 
 
3332
 
String* Item_func_group_concat::val_str(String* )
3333
 
{
3334
 
  assert(fixed == 1);
 
3477
 
 
3478
String* Item_func_group_concat::val_str(String* str __attribute__((__unused__)))
 
3479
{
 
3480
  DBUG_ASSERT(fixed == 1);
3335
3481
  if (null_value)
3336
3482
    return 0;
3337
3483
  if (no_appended && tree)
3344
3490
      ER_CUT_VALUE_GROUP_CONCAT needs an argument, but this gets set in
3345
3491
      Item_func_group_concat::cleanup().
3346
3492
    */
3347
 
    assert(table);
3348
 
    warning= push_warning(table->in_use, DRIZZLE_ERROR::WARN_LEVEL_WARN,
 
3493
    DBUG_ASSERT(table);
 
3494
    warning= push_warning(table->in_use, MYSQL_ERROR::WARN_LEVEL_WARN,
3349
3495
                          ER_CUT_VALUE_GROUP_CONCAT,
3350
3496
                          ER(ER_CUT_VALUE_GROUP_CONCAT));
3351
3497
  }
3358
3504
  str->append(STRING_WITH_LEN("group_concat("));
3359
3505
  if (distinct)
3360
3506
    str->append(STRING_WITH_LEN("distinct "));
3361
 
  for (uint32_t i= 0; i < arg_count_field; i++)
 
3507
  for (uint i= 0; i < arg_count_field; i++)
3362
3508
  {
3363
3509
    if (i)
3364
3510
      str->append(',');
3367
3513
  if (arg_count_order)
3368
3514
  {
3369
3515
    str->append(STRING_WITH_LEN(" order by "));
3370
 
    for (uint32_t i= 0 ; i < arg_count_order ; i++)
 
3516
    for (uint i= 0 ; i < arg_count_order ; i++)
3371
3517
    {
3372
3518
      if (i)
3373
3519
        str->append(',');
3387
3533
Item_func_group_concat::~Item_func_group_concat()
3388
3534
{
3389
3535
  if (!original && unique_filter)
3390
 
    delete unique_filter;
 
3536
    delete unique_filter;    
3391
3537
}
3392
 
 
3393
 
} /* namespace drizzled */