~drizzle-trunk/drizzle/development

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