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