~linuxjedi/drizzle/trunk-bug-667053

« back to all changes in this revision

Viewing changes to sql/item_func.cc

  • Committer: brian
  • Date: 2008-06-25 05:29:13 UTC
  • Revision ID: brian@localhost.localdomain-20080625052913-6upwo0jsrl4lnapl
clean slate

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* Copyright (C) 2000-2003 MySQL AB
 
2
 
 
3
   This program is free software; you can redistribute it and/or modify
 
4
   it under the terms of the GNU General Public License as published by
 
5
   the Free Software Foundation; version 2 of the License.
 
6
 
 
7
   This program is distributed in the hope that it will be useful,
 
8
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
   GNU General Public License for more details.
 
11
 
 
12
   You should have received a copy of the GNU General Public License
 
13
   along with this program; if not, write to the Free Software
 
14
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
15
 
 
16
 
 
17
/**
 
18
  @file
 
19
 
 
20
  @brief
 
21
  This file defines all numerical functions
 
22
*/
 
23
 
 
24
#ifdef USE_PRAGMA_IMPLEMENTATION
 
25
#pragma implementation                          // gcc: Class implementation
 
26
#endif
 
27
 
 
28
#include "mysql_priv.h"
 
29
#include "slave.h"                              // for wait_for_master_pos
 
30
#include "rpl_mi.h"
 
31
#include <m_ctype.h>
 
32
#include <hash.h>
 
33
#include <time.h>
 
34
#include <ft_global.h>
 
35
#include <my_bit.h>
 
36
 
 
37
bool check_reserved_words(LEX_STRING *name)
 
38
{
 
39
  if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") ||
 
40
      !my_strcasecmp(system_charset_info, name->str, "LOCAL") ||
 
41
      !my_strcasecmp(system_charset_info, name->str, "SESSION"))
 
42
    return TRUE;
 
43
  return FALSE;
 
44
}
 
45
 
 
46
 
 
47
/**
 
48
  @return
 
49
    TRUE if item is a constant
 
50
*/
 
51
 
 
52
bool
 
53
eval_const_cond(COND *cond)
 
54
{
 
55
  return ((Item_func*) cond)->val_int() ? TRUE : FALSE;
 
56
}
 
57
 
 
58
 
 
59
void Item_func::set_arguments(List<Item> &list)
 
60
{
 
61
  allowed_arg_cols= 1;
 
62
  arg_count=list.elements;
 
63
  args= tmp_arg;                                // If 2 arguments
 
64
  if (arg_count <= 2 || (args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
 
65
  {
 
66
    List_iterator_fast<Item> li(list);
 
67
    Item *item;
 
68
    Item **save_args= args;
 
69
 
 
70
    while ((item=li++))
 
71
    {
 
72
      *(save_args++)= item;
 
73
      with_sum_func|=item->with_sum_func;
 
74
    }
 
75
  }
 
76
  list.empty();                                 // Fields are used
 
77
}
 
78
 
 
79
Item_func::Item_func(List<Item> &list)
 
80
  :allowed_arg_cols(1)
 
81
{
 
82
  set_arguments(list);
 
83
}
 
84
 
 
85
Item_func::Item_func(THD *thd, Item_func *item)
 
86
  :Item_result_field(thd, item),
 
87
   allowed_arg_cols(item->allowed_arg_cols),
 
88
   arg_count(item->arg_count),
 
89
   used_tables_cache(item->used_tables_cache),
 
90
   not_null_tables_cache(item->not_null_tables_cache),
 
91
   const_item_cache(item->const_item_cache)
 
92
{
 
93
  if (arg_count)
 
94
  {
 
95
    if (arg_count <=2)
 
96
      args= tmp_arg;
 
97
    else
 
98
    {
 
99
      if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
 
100
        return;
 
101
    }
 
102
    memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count);
 
103
  }
 
104
}
 
105
 
 
106
 
 
107
/*
 
108
  Resolve references to table column for a function and its argument
 
109
 
 
110
  SYNOPSIS:
 
111
  fix_fields()
 
112
  thd           Thread object
 
113
  ref           Pointer to where this object is used.  This reference
 
114
                is used if we want to replace this object with another
 
115
                one (for example in the summary functions).
 
116
 
 
117
  DESCRIPTION
 
118
    Call fix_fields() for all arguments to the function.  The main intention
 
119
    is to allow all Item_field() objects to setup pointers to the table fields.
 
120
 
 
121
    Sets as a side effect the following class variables:
 
122
      maybe_null        Set if any argument may return NULL
 
123
      with_sum_func     Set if any of the arguments contains a sum function
 
124
      used_tables_cache Set to union of the tables used by arguments
 
125
 
 
126
      str_value.charset If this is a string function, set this to the
 
127
                        character set for the first argument.
 
128
                        If any argument is binary, this is set to binary
 
129
 
 
130
   If for any item any of the defaults are wrong, then this can
 
131
   be fixed in the fix_length_and_dec() function that is called
 
132
   after this one or by writing a specialized fix_fields() for the
 
133
   item.
 
134
 
 
135
  RETURN VALUES
 
136
  FALSE ok
 
137
  TRUE  Got error.  Stored with my_error().
 
138
*/
 
139
 
 
140
bool
 
141
Item_func::fix_fields(THD *thd, Item **ref)
 
142
{
 
143
  DBUG_ASSERT(fixed == 0);
 
144
  Item **arg,**arg_end;
 
145
  void *save_thd_marker= thd->thd_marker;
 
146
  uchar buff[STACK_BUFF_ALLOC];                 // Max argument in function
 
147
  thd->thd_marker= 0;
 
148
  used_tables_cache= not_null_tables_cache= 0;
 
149
  const_item_cache=1;
 
150
 
 
151
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
 
152
    return TRUE;                                // Fatal error if flag is set!
 
153
  if (arg_count)
 
154
  {                                             // Print purify happy
 
155
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
 
156
    {
 
157
      Item *item;
 
158
      /*
 
159
        We can't yet set item to *arg as fix_fields may change *arg
 
160
        We shouldn't call fix_fields() twice, so check 'fixed' field first
 
161
      */
 
162
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg)))
 
163
        return TRUE;                            /* purecov: inspected */
 
164
      item= *arg;
 
165
 
 
166
      if (allowed_arg_cols)
 
167
      {
 
168
        if (item->check_cols(allowed_arg_cols))
 
169
          return 1;
 
170
      }
 
171
      else
 
172
      {
 
173
        /*  we have to fetch allowed_arg_cols from first argument */
 
174
        DBUG_ASSERT(arg == args); // it is first argument
 
175
        allowed_arg_cols= item->cols();
 
176
        DBUG_ASSERT(allowed_arg_cols); // Can't be 0 any more
 
177
      }
 
178
 
 
179
      if (item->maybe_null)
 
180
        maybe_null=1;
 
181
 
 
182
      with_sum_func= with_sum_func || item->with_sum_func;
 
183
      used_tables_cache|=     item->used_tables();
 
184
      not_null_tables_cache|= item->not_null_tables();
 
185
      const_item_cache&=      item->const_item();
 
186
      with_subselect|=        item->with_subselect;
 
187
    }
 
188
  }
 
189
  fix_length_and_dec();
 
190
  if (thd->is_error()) // An error inside fix_length_and_dec occured
 
191
    return TRUE;
 
192
  fixed= 1;
 
193
  thd->thd_marker= save_thd_marker;
 
194
  return FALSE;
 
195
}
 
196
 
 
197
 
 
198
void Item_func::fix_after_pullout(st_select_lex *new_parent, Item **ref)
 
199
{
 
200
  Item **arg,**arg_end;
 
201
 
 
202
  used_tables_cache= not_null_tables_cache= 0;
 
203
  const_item_cache=1;
 
204
 
 
205
  if (arg_count)
 
206
  {
 
207
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
 
208
    {
 
209
      (*arg)->fix_after_pullout(new_parent, arg);
 
210
      Item *item= *arg;
 
211
 
 
212
      used_tables_cache|=     item->used_tables();
 
213
      not_null_tables_cache|= item->not_null_tables();
 
214
      const_item_cache&=      item->const_item();
 
215
    }
 
216
  }
 
217
}
 
218
 
 
219
 
 
220
bool Item_func::walk(Item_processor processor, bool walk_subquery,
 
221
                     uchar *argument)
 
222
{
 
223
  if (arg_count)
 
224
  {
 
225
    Item **arg,**arg_end;
 
226
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
 
227
    {
 
228
      if ((*arg)->walk(processor, walk_subquery, argument))
 
229
        return 1;
 
230
    }
 
231
  }
 
232
  return (this->*processor)(argument);
 
233
}
 
234
 
 
235
void Item_func::traverse_cond(Cond_traverser traverser,
 
236
                              void *argument, traverse_order order)
 
237
{
 
238
  if (arg_count)
 
239
  {
 
240
    Item **arg,**arg_end;
 
241
 
 
242
    switch (order) {
 
243
    case(PREFIX):
 
244
      (*traverser)(this, argument);
 
245
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
 
246
      {
 
247
        (*arg)->traverse_cond(traverser, argument, order);
 
248
      }
 
249
      break;
 
250
    case (POSTFIX):
 
251
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
 
252
      {
 
253
        (*arg)->traverse_cond(traverser, argument, order);
 
254
      }
 
255
      (*traverser)(this, argument);
 
256
    }
 
257
  }
 
258
  else
 
259
    (*traverser)(this, argument);
 
260
}
 
261
 
 
262
 
 
263
/**
 
264
  Transform an Item_func object with a transformer callback function.
 
265
 
 
266
    The function recursively applies the transform method to each
 
267
    argument of the Item_func node.
 
268
    If the call of the method for an argument item returns a new item
 
269
    the old item is substituted for a new one.
 
270
    After this the transformer is applied to the root node
 
271
    of the Item_func object. 
 
272
  @param transformer   the transformer callback function to be applied to
 
273
                       the nodes of the tree of the object
 
274
  @param argument      parameter to be passed to the transformer
 
275
 
 
276
  @return
 
277
    Item returned as the result of transformation of the root node
 
278
*/
 
279
 
 
280
Item *Item_func::transform(Item_transformer transformer, uchar *argument)
 
281
{
 
282
  if (arg_count)
 
283
  {
 
284
    Item **arg,**arg_end;
 
285
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
 
286
    {
 
287
      Item *new_item= (*arg)->transform(transformer, argument);
 
288
      if (!new_item)
 
289
        return 0;
 
290
 
 
291
      /*
 
292
        THD::change_item_tree() should be called only if the tree was
 
293
        really transformed, i.e. when a new item has been created.
 
294
        Otherwise we'll be allocating a lot of unnecessary memory for
 
295
        change records at each execution.
 
296
      */
 
297
      if (*arg != new_item)
 
298
        current_thd->change_item_tree(arg, new_item);
 
299
    }
 
300
  }
 
301
  return (this->*transformer)(argument);
 
302
}
 
303
 
 
304
 
 
305
/**
 
306
  Compile Item_func object with a processor and a transformer
 
307
  callback functions.
 
308
 
 
309
    First the function applies the analyzer to the root node of
 
310
    the Item_func object. Then if the analizer succeeeds (returns TRUE)
 
311
    the function recursively applies the compile method to each argument
 
312
    of the Item_func node.
 
313
    If the call of the method for an argument item returns a new item
 
314
    the old item is substituted for a new one.
 
315
    After this the transformer is applied to the root node
 
316
    of the Item_func object. 
 
317
 
 
318
  @param analyzer      the analyzer callback function to be applied to the
 
319
                       nodes of the tree of the object
 
320
  @param[in,out] arg_p parameter to be passed to the processor
 
321
  @param transformer   the transformer callback function to be applied to the
 
322
                       nodes of the tree of the object
 
323
  @param arg_t         parameter to be passed to the transformer
 
324
 
 
325
  @return
 
326
    Item returned as the result of transformation of the root node
 
327
*/
 
328
 
 
329
Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p,
 
330
                         Item_transformer transformer, uchar *arg_t)
 
331
{
 
332
  if (!(this->*analyzer)(arg_p))
 
333
    return 0;
 
334
  if (arg_count)
 
335
  {
 
336
    Item **arg,**arg_end;
 
337
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
 
338
    {
 
339
      /* 
 
340
        The same parameter value of arg_p must be passed
 
341
        to analyze any argument of the condition formula.
 
342
      */   
 
343
      uchar *arg_v= *arg_p;
 
344
      Item *new_item= (*arg)->compile(analyzer, &arg_v, transformer, arg_t);
 
345
      if (new_item && *arg != new_item)
 
346
        current_thd->change_item_tree(arg, new_item);
 
347
    }
 
348
  }
 
349
  return (this->*transformer)(arg_t);
 
350
}
 
351
 
 
352
/**
 
353
  See comments in Item_cmp_func::split_sum_func()
 
354
*/
 
355
 
 
356
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
 
357
                               List<Item> &fields)
 
358
{
 
359
  Item **arg, **arg_end;
 
360
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
 
361
    (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE);
 
362
}
 
363
 
 
364
 
 
365
void Item_func::update_used_tables()
 
366
{
 
367
  used_tables_cache=0;
 
368
  const_item_cache=1;
 
369
  for (uint i=0 ; i < arg_count ; i++)
 
370
  {
 
371
    args[i]->update_used_tables();
 
372
    used_tables_cache|=args[i]->used_tables();
 
373
    const_item_cache&=args[i]->const_item();
 
374
  }
 
375
}
 
376
 
 
377
 
 
378
table_map Item_func::used_tables() const
 
379
{
 
380
  return used_tables_cache;
 
381
}
 
382
 
 
383
 
 
384
table_map Item_func::not_null_tables() const
 
385
{
 
386
  return not_null_tables_cache;
 
387
}
 
388
 
 
389
 
 
390
void Item_func::print(String *str, enum_query_type query_type)
 
391
{
 
392
  str->append(func_name());
 
393
  str->append('(');
 
394
  print_args(str, 0, query_type);
 
395
  str->append(')');
 
396
}
 
397
 
 
398
 
 
399
void Item_func::print_args(String *str, uint from, enum_query_type query_type)
 
400
{
 
401
  for (uint i=from ; i < arg_count ; i++)
 
402
  {
 
403
    if (i != from)
 
404
      str->append(',');
 
405
    args[i]->print(str, query_type);
 
406
  }
 
407
}
 
408
 
 
409
 
 
410
void Item_func::print_op(String *str, enum_query_type query_type)
 
411
{
 
412
  str->append('(');
 
413
  for (uint i=0 ; i < arg_count-1 ; i++)
 
414
  {
 
415
    args[i]->print(str, query_type);
 
416
    str->append(' ');
 
417
    str->append(func_name());
 
418
    str->append(' ');
 
419
  }
 
420
  args[arg_count-1]->print(str, query_type);
 
421
  str->append(')');
 
422
}
 
423
 
 
424
 
 
425
bool Item_func::eq(const Item *item, bool binary_cmp) const
 
426
{
 
427
  /* Assume we don't have rtti */
 
428
  if (this == item)
 
429
    return 1;
 
430
  if (item->type() != FUNC_ITEM)
 
431
    return 0;
 
432
  Item_func *item_func=(Item_func*) item;
 
433
  Item_func::Functype func_type;
 
434
  if ((func_type= functype()) != item_func->functype() ||
 
435
      arg_count != item_func->arg_count ||
 
436
      (func_type != Item_func::FUNC_SP &&
 
437
       func_name() != item_func->func_name()) ||
 
438
      (func_type == Item_func::FUNC_SP &&
 
439
       my_strcasecmp(system_charset_info, func_name(), item_func->func_name())))
 
440
    return 0;
 
441
  for (uint i=0; i < arg_count ; i++)
 
442
    if (!args[i]->eq(item_func->args[i], binary_cmp))
 
443
      return 0;
 
444
  return 1;
 
445
}
 
446
 
 
447
 
 
448
Field *Item_func::tmp_table_field(TABLE *table)
 
449
{
 
450
  Field *field;
 
451
 
 
452
  switch (result_type()) {
 
453
  case INT_RESULT:
 
454
    if (max_length > MY_INT32_NUM_DECIMAL_DIGITS)
 
455
      field= new Field_longlong(max_length, maybe_null, name, unsigned_flag);
 
456
    else
 
457
      field= new Field_long(max_length, maybe_null, name, unsigned_flag);
 
458
    break;
 
459
  case REAL_RESULT:
 
460
    field= new Field_double(max_length, maybe_null, name, decimals);
 
461
    break;
 
462
  case STRING_RESULT:
 
463
    return make_string_field(table);
 
464
    break;
 
465
  case DECIMAL_RESULT:
 
466
    field= new Field_new_decimal(my_decimal_precision_to_length(decimal_precision(),
 
467
                                                                decimals,
 
468
                                                                unsigned_flag),
 
469
                                 maybe_null, name, decimals, unsigned_flag);
 
470
    break;
 
471
  case ROW_RESULT:
 
472
  default:
 
473
    // This case should never be chosen
 
474
    DBUG_ASSERT(0);
 
475
    field= 0;
 
476
    break;
 
477
  }
 
478
  if (field)
 
479
    field->init(table);
 
480
  return field;
 
481
}
 
482
 
 
483
 
 
484
my_decimal *Item_func::val_decimal(my_decimal *decimal_value)
 
485
{
 
486
  DBUG_ASSERT(fixed);
 
487
  int2my_decimal(E_DEC_FATAL_ERROR, val_int(), unsigned_flag, decimal_value);
 
488
  return decimal_value;
 
489
}
 
490
 
 
491
 
 
492
String *Item_real_func::val_str(String *str)
 
493
{
 
494
  DBUG_ASSERT(fixed == 1);
 
495
  double nr= val_real();
 
496
  if (null_value)
 
497
    return 0; /* purecov: inspected */
 
498
  str->set_real(nr,decimals, &my_charset_bin);
 
499
  return str;
 
500
}
 
501
 
 
502
 
 
503
my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value)
 
504
{
 
505
  DBUG_ASSERT(fixed);
 
506
  double nr= val_real();
 
507
  if (null_value)
 
508
    return 0; /* purecov: inspected */
 
509
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
 
510
  return decimal_value;
 
511
}
 
512
 
 
513
 
 
514
void Item_func::fix_num_length_and_dec()
 
515
{
 
516
  uint fl_length= 0;
 
517
  decimals=0;
 
518
  for (uint i=0 ; i < arg_count ; i++)
 
519
  {
 
520
    set_if_bigger(decimals,args[i]->decimals);
 
521
    set_if_bigger(fl_length, args[i]->max_length);
 
522
  }
 
523
  max_length=float_length(decimals);
 
524
  if (fl_length > max_length)
 
525
  {
 
526
    decimals= NOT_FIXED_DEC;
 
527
    max_length= float_length(NOT_FIXED_DEC);
 
528
  }
 
529
}
 
530
 
 
531
 
 
532
void Item_func_numhybrid::fix_num_length_and_dec()
 
533
{}
 
534
 
 
535
 
 
536
/**
 
537
  Set max_length/decimals of function if function is fixed point and
 
538
  result length/precision depends on argument ones.
 
539
*/
 
540
 
 
541
void Item_func::count_decimal_length()
 
542
{
 
543
  int max_int_part= 0;
 
544
  decimals= 0;
 
545
  unsigned_flag= 1;
 
546
  for (uint i=0 ; i < arg_count ; i++)
 
547
  {
 
548
    set_if_bigger(decimals, args[i]->decimals);
 
549
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
 
550
    set_if_smaller(unsigned_flag, args[i]->unsigned_flag);
 
551
  }
 
552
  int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
 
553
  max_length= my_decimal_precision_to_length(precision, decimals,
 
554
                                             unsigned_flag);
 
555
}
 
556
 
 
557
 
 
558
/**
 
559
  Set max_length of if it is maximum length of its arguments.
 
560
*/
 
561
 
 
562
void Item_func::count_only_length()
 
563
{
 
564
  max_length= 0;
 
565
  unsigned_flag= 0;
 
566
  for (uint i=0 ; i < arg_count ; i++)
 
567
  {
 
568
    set_if_bigger(max_length, args[i]->max_length);
 
569
    set_if_bigger(unsigned_flag, args[i]->unsigned_flag);
 
570
  }
 
571
}
 
572
 
 
573
 
 
574
/**
 
575
  Set max_length/decimals of function if function is floating point and
 
576
  result length/precision depends on argument ones.
 
577
*/
 
578
 
 
579
void Item_func::count_real_length()
 
580
{
 
581
  uint32 length= 0;
 
582
  decimals= 0;
 
583
  max_length= 0;
 
584
  for (uint i=0 ; i < arg_count ; i++)
 
585
  {
 
586
    if (decimals != NOT_FIXED_DEC)
 
587
    {
 
588
      set_if_bigger(decimals, args[i]->decimals);
 
589
      set_if_bigger(length, (args[i]->max_length - args[i]->decimals));
 
590
    }
 
591
    set_if_bigger(max_length, args[i]->max_length);
 
592
  }
 
593
  if (decimals != NOT_FIXED_DEC)
 
594
  {
 
595
    max_length= length;
 
596
    length+= decimals;
 
597
    if (length < max_length)  // If previous operation gave overflow
 
598
      max_length= UINT_MAX32;
 
599
    else
 
600
      max_length= length;
 
601
  }
 
602
}
 
603
 
 
604
 
 
605
 
 
606
void Item_func::signal_divide_by_null()
 
607
{
 
608
  THD *thd= current_thd;
 
609
  if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
 
610
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DIVISION_BY_ZERO,
 
611
                 ER(ER_DIVISION_BY_ZERO));
 
612
  null_value= 1;
 
613
}
 
614
 
 
615
 
 
616
Item *Item_func::get_tmp_table_item(THD *thd)
 
617
{
 
618
  if (!with_sum_func && !const_item() && functype() != SUSERVAR_FUNC)
 
619
    return new Item_field(result_field);
 
620
  return copy_or_same(thd);
 
621
}
 
622
 
 
623
double Item_int_func::val_real()
 
624
{
 
625
  DBUG_ASSERT(fixed == 1);
 
626
 
 
627
  return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int();
 
628
}
 
629
 
 
630
 
 
631
String *Item_int_func::val_str(String *str)
 
632
{
 
633
  DBUG_ASSERT(fixed == 1);
 
634
  longlong nr=val_int();
 
635
  if (null_value)
 
636
    return 0;
 
637
  str->set_int(nr, unsigned_flag, &my_charset_bin);
 
638
  return str;
 
639
}
 
640
 
 
641
 
 
642
void Item_func_connection_id::fix_length_and_dec()
 
643
{
 
644
  Item_int_func::fix_length_and_dec();
 
645
  max_length= 10;
 
646
}
 
647
 
 
648
 
 
649
bool Item_func_connection_id::fix_fields(THD *thd, Item **ref)
 
650
{
 
651
  if (Item_int_func::fix_fields(thd, ref))
 
652
    return TRUE;
 
653
  thd->thread_specific_used= TRUE;
 
654
  value= thd->variables.pseudo_thread_id;
 
655
  return FALSE;
 
656
}
 
657
 
 
658
 
 
659
/**
 
660
  Check arguments here to determine result's type for a numeric
 
661
  function of two arguments.
 
662
*/
 
663
 
 
664
void Item_num_op::find_num_type(void)
 
665
{
 
666
  DBUG_ENTER("Item_num_op::find_num_type");
 
667
  DBUG_PRINT("info", ("name %s", func_name()));
 
668
  DBUG_ASSERT(arg_count == 2);
 
669
  Item_result r0= args[0]->result_type();
 
670
  Item_result r1= args[1]->result_type();
 
671
 
 
672
  if (r0 == REAL_RESULT || r1 == REAL_RESULT ||
 
673
      r0 == STRING_RESULT || r1 ==STRING_RESULT)
 
674
  {
 
675
    count_real_length();
 
676
    max_length= float_length(decimals);
 
677
    hybrid_type= REAL_RESULT;
 
678
  }
 
679
  else if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT)
 
680
  {
 
681
    hybrid_type= DECIMAL_RESULT;
 
682
    result_precision();
 
683
  }
 
684
  else
 
685
  {
 
686
    DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT);
 
687
    decimals= 0;
 
688
    hybrid_type=INT_RESULT;
 
689
    result_precision();
 
690
  }
 
691
  DBUG_PRINT("info", ("Type: %s",
 
692
             (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
 
693
              hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
 
694
              hybrid_type == INT_RESULT ? "INT_RESULT" :
 
695
              "--ILLEGAL!!!--")));
 
696
  DBUG_VOID_RETURN;
 
697
}
 
698
 
 
699
 
 
700
/**
 
701
  Set result type for a numeric function of one argument
 
702
  (can be also used by a numeric function of many arguments, if the result
 
703
  type depends only on the first argument)
 
704
*/
 
705
 
 
706
void Item_func_num1::find_num_type()
 
707
{
 
708
  DBUG_ENTER("Item_func_num1::find_num_type");
 
709
  DBUG_PRINT("info", ("name %s", func_name()));
 
710
  switch (hybrid_type= args[0]->result_type()) {
 
711
  case INT_RESULT:
 
712
    unsigned_flag= args[0]->unsigned_flag;
 
713
    break;
 
714
  case STRING_RESULT:
 
715
  case REAL_RESULT:
 
716
    hybrid_type= REAL_RESULT;
 
717
    max_length= float_length(decimals);
 
718
    break;
 
719
  case DECIMAL_RESULT:
 
720
    break;
 
721
  default:
 
722
    DBUG_ASSERT(0);
 
723
  }
 
724
  DBUG_PRINT("info", ("Type: %s",
 
725
                      (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
 
726
                       hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
 
727
                       hybrid_type == INT_RESULT ? "INT_RESULT" :
 
728
                       "--ILLEGAL!!!--")));
 
729
  DBUG_VOID_RETURN;
 
730
}
 
731
 
 
732
 
 
733
void Item_func_num1::fix_num_length_and_dec()
 
734
{
 
735
  decimals= args[0]->decimals;
 
736
  max_length= args[0]->max_length;
 
737
}
 
738
 
 
739
 
 
740
void Item_func_numhybrid::fix_length_and_dec()
 
741
{
 
742
  fix_num_length_and_dec();
 
743
  find_num_type();
 
744
}
 
745
 
 
746
 
 
747
String *Item_func_numhybrid::val_str(String *str)
 
748
{
 
749
  DBUG_ASSERT(fixed == 1);
 
750
  switch (hybrid_type) {
 
751
  case DECIMAL_RESULT:
 
752
  {
 
753
    my_decimal decimal_value, *val;
 
754
    if (!(val= decimal_op(&decimal_value)))
 
755
      return 0;                                 // null is set
 
756
    my_decimal_round(E_DEC_FATAL_ERROR, val, decimals, FALSE, val);
 
757
    my_decimal2string(E_DEC_FATAL_ERROR, val, 0, 0, 0, str);
 
758
    break;
 
759
  }
 
760
  case INT_RESULT:
 
761
  {
 
762
    longlong nr= int_op();
 
763
    if (null_value)
 
764
      return 0; /* purecov: inspected */
 
765
    str->set_int(nr, unsigned_flag, &my_charset_bin);
 
766
    break;
 
767
  }
 
768
  case REAL_RESULT:
 
769
  {
 
770
    double nr= real_op();
 
771
    if (null_value)
 
772
      return 0; /* purecov: inspected */
 
773
    str->set_real(nr,decimals,&my_charset_bin);
 
774
    break;
 
775
  }
 
776
  case STRING_RESULT:
 
777
    return str_op(&str_value);
 
778
  default:
 
779
    DBUG_ASSERT(0);
 
780
  }
 
781
  return str;
 
782
}
 
783
 
 
784
 
 
785
double Item_func_numhybrid::val_real()
 
786
{
 
787
  DBUG_ASSERT(fixed == 1);
 
788
  switch (hybrid_type) {
 
789
  case DECIMAL_RESULT:
 
790
  {
 
791
    my_decimal decimal_value, *val;
 
792
    double result;
 
793
    if (!(val= decimal_op(&decimal_value)))
 
794
      return 0.0;                               // null is set
 
795
    my_decimal2double(E_DEC_FATAL_ERROR, val, &result);
 
796
    return result;
 
797
  }
 
798
  case INT_RESULT:
 
799
  {
 
800
    longlong result= int_op();
 
801
    return unsigned_flag ? (double) ((ulonglong) result) : (double) result;
 
802
  }
 
803
  case REAL_RESULT:
 
804
    return real_op();
 
805
  case STRING_RESULT:
 
806
  {
 
807
    char *end_not_used;
 
808
    int err_not_used;
 
809
    String *res= str_op(&str_value);
 
810
    return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
 
811
                             &end_not_used, &err_not_used) : 0.0);
 
812
  }
 
813
  default:
 
814
    DBUG_ASSERT(0);
 
815
  }
 
816
  return 0.0;
 
817
}
 
818
 
 
819
 
 
820
longlong Item_func_numhybrid::val_int()
 
821
{
 
822
  DBUG_ASSERT(fixed == 1);
 
823
  switch (hybrid_type) {
 
824
  case DECIMAL_RESULT:
 
825
  {
 
826
    my_decimal decimal_value, *val;
 
827
    if (!(val= decimal_op(&decimal_value)))
 
828
      return 0;                                 // null is set
 
829
    longlong result;
 
830
    my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result);
 
831
    return result;
 
832
  }
 
833
  case INT_RESULT:
 
834
    return int_op();
 
835
  case REAL_RESULT:
 
836
    return (longlong) rint(real_op());
 
837
  case STRING_RESULT:
 
838
  {
 
839
    int err_not_used;
 
840
    String *res;
 
841
    if (!(res= str_op(&str_value)))
 
842
      return 0;
 
843
 
 
844
    char *end= (char*) res->ptr() + res->length();
 
845
    CHARSET_INFO *cs= str_value.charset();
 
846
    return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used);
 
847
  }
 
848
  default:
 
849
    DBUG_ASSERT(0);
 
850
  }
 
851
  return 0;
 
852
}
 
853
 
 
854
 
 
855
my_decimal *Item_func_numhybrid::val_decimal(my_decimal *decimal_value)
 
856
{
 
857
  my_decimal *val= decimal_value;
 
858
  DBUG_ASSERT(fixed == 1);
 
859
  switch (hybrid_type) {
 
860
  case DECIMAL_RESULT:
 
861
    val= decimal_op(decimal_value);
 
862
    break;
 
863
  case INT_RESULT:
 
864
  {
 
865
    longlong result= int_op();
 
866
    int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, decimal_value);
 
867
    break;
 
868
  }
 
869
  case REAL_RESULT:
 
870
  {
 
871
    double result= (double)real_op();
 
872
    double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value);
 
873
    break;
 
874
  }
 
875
  case STRING_RESULT:
 
876
  {
 
877
    String *res;
 
878
    if (!(res= str_op(&str_value)))
 
879
      return NULL;
 
880
 
 
881
    str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
 
882
                   res->length(), res->charset(), decimal_value);
 
883
    break;
 
884
  }  
 
885
  case ROW_RESULT:
 
886
  default:
 
887
    DBUG_ASSERT(0);
 
888
  }
 
889
  return val;
 
890
}
 
891
 
 
892
 
 
893
void Item_func_signed::print(String *str, enum_query_type query_type)
 
894
{
 
895
  str->append(STRING_WITH_LEN("cast("));
 
896
  args[0]->print(str, query_type);
 
897
  str->append(STRING_WITH_LEN(" as signed)"));
 
898
 
 
899
}
 
900
 
 
901
 
 
902
longlong Item_func_signed::val_int_from_str(int *error)
 
903
{
 
904
  char buff[MAX_FIELD_WIDTH], *end, *start;
 
905
  uint32 length;
 
906
  String tmp(buff,sizeof(buff), &my_charset_bin), *res;
 
907
  longlong value;
 
908
 
 
909
  /*
 
910
    For a string result, we must first get the string and then convert it
 
911
    to a longlong
 
912
  */
 
913
 
 
914
  if (!(res= args[0]->val_str(&tmp)))
 
915
  {
 
916
    null_value= 1;
 
917
    *error= 0;
 
918
    return 0;
 
919
  }
 
920
  null_value= 0;
 
921
  start= (char *)res->ptr();
 
922
  length= res->length();
 
923
 
 
924
  end= start + length;
 
925
  value= my_strtoll10(start, &end, error);
 
926
  if (*error > 0 || end != start+ length)
 
927
  {
 
928
    char err_buff[128];
 
929
    String err_tmp(err_buff,(uint32) sizeof(err_buff), system_charset_info);
 
930
    err_tmp.copy(start, length, system_charset_info);
 
931
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
 
932
                        ER_TRUNCATED_WRONG_VALUE,
 
933
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
 
934
                        err_tmp.c_ptr());
 
935
  }
 
936
  return value;
 
937
}
 
938
 
 
939
 
 
940
longlong Item_func_signed::val_int()
 
941
{
 
942
  longlong value;
 
943
  int error;
 
944
 
 
945
  if (args[0]->cast_to_int_type() != STRING_RESULT ||
 
946
      args[0]->result_as_longlong())
 
947
  {
 
948
    value= args[0]->val_int();
 
949
    null_value= args[0]->null_value; 
 
950
    return value;
 
951
  }
 
952
 
 
953
  value= val_int_from_str(&error);
 
954
  if (value < 0 && error == 0)
 
955
  {
 
956
    push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
957
                 "Cast to signed converted positive out-of-range integer to "
 
958
                 "it's negative complement");
 
959
  }
 
960
  return value;
 
961
}
 
962
 
 
963
 
 
964
void Item_func_unsigned::print(String *str, enum_query_type query_type)
 
965
{
 
966
  str->append(STRING_WITH_LEN("cast("));
 
967
  args[0]->print(str, query_type);
 
968
  str->append(STRING_WITH_LEN(" as unsigned)"));
 
969
 
 
970
}
 
971
 
 
972
 
 
973
longlong Item_func_unsigned::val_int()
 
974
{
 
975
  longlong value;
 
976
  int error;
 
977
 
 
978
  if (args[0]->cast_to_int_type() == DECIMAL_RESULT)
 
979
  {
 
980
    my_decimal tmp, *dec= args[0]->val_decimal(&tmp);
 
981
    if (!(null_value= args[0]->null_value))
 
982
      my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &value);
 
983
    else
 
984
      value= 0;
 
985
    return value;
 
986
  }
 
987
  else if (args[0]->cast_to_int_type() != STRING_RESULT ||
 
988
           args[0]->result_as_longlong())
 
989
  {
 
990
    value= args[0]->val_int();
 
991
    null_value= args[0]->null_value; 
 
992
    return value;
 
993
  }
 
994
 
 
995
  value= val_int_from_str(&error);
 
996
  if (error < 0)
 
997
    push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
 
998
                 "Cast to unsigned converted negative integer to it's "
 
999
                 "positive complement");
 
1000
  return value;
 
1001
}
 
1002
 
 
1003
 
 
1004
String *Item_decimal_typecast::val_str(String *str)
 
1005
{
 
1006
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
 
1007
  if (null_value)
 
1008
    return NULL;
 
1009
  my_decimal2string(E_DEC_FATAL_ERROR, tmp, 0, 0, 0, str);
 
1010
  return str;
 
1011
}
 
1012
 
 
1013
 
 
1014
double Item_decimal_typecast::val_real()
 
1015
{
 
1016
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
 
1017
  double res;
 
1018
  if (null_value)
 
1019
    return 0.0;
 
1020
  my_decimal2double(E_DEC_FATAL_ERROR, tmp, &res);
 
1021
  return res;
 
1022
}
 
1023
 
 
1024
 
 
1025
longlong Item_decimal_typecast::val_int()
 
1026
{
 
1027
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
 
1028
  longlong res;
 
1029
  if (null_value)
 
1030
    return 0;
 
1031
  my_decimal2int(E_DEC_FATAL_ERROR, tmp, unsigned_flag, &res);
 
1032
  return res;
 
1033
}
 
1034
 
 
1035
 
 
1036
my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec)
 
1037
{
 
1038
  my_decimal tmp_buf, *tmp= args[0]->val_decimal(&tmp_buf);
 
1039
  bool sign;
 
1040
  uint precision;
 
1041
 
 
1042
  if ((null_value= args[0]->null_value))
 
1043
    return NULL;
 
1044
  my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec);
 
1045
  sign= dec->sign();
 
1046
  if (unsigned_flag)
 
1047
  {
 
1048
    if (sign)
 
1049
    {
 
1050
      my_decimal_set_zero(dec);
 
1051
      goto err;
 
1052
    }
 
1053
  }
 
1054
  precision= my_decimal_length_to_precision(max_length,
 
1055
                                            decimals, unsigned_flag);
 
1056
  if (precision - decimals < (uint) my_decimal_intg(dec))
 
1057
  {
 
1058
    max_my_decimal(dec, precision, decimals);
 
1059
    dec->sign(sign);
 
1060
    goto err;
 
1061
  }
 
1062
  return dec;
 
1063
 
 
1064
err:
 
1065
  push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
1066
                      ER_WARN_DATA_OUT_OF_RANGE,
 
1067
                      ER(ER_WARN_DATA_OUT_OF_RANGE),
 
1068
                      name, 1);
 
1069
  return dec;
 
1070
}
 
1071
 
 
1072
 
 
1073
void Item_decimal_typecast::print(String *str, enum_query_type query_type)
 
1074
{
 
1075
  char len_buf[20*3 + 1];
 
1076
  char *end;
 
1077
 
 
1078
  uint precision= my_decimal_length_to_precision(max_length, decimals,
 
1079
                                                 unsigned_flag);
 
1080
  str->append(STRING_WITH_LEN("cast("));
 
1081
  args[0]->print(str, query_type);
 
1082
  str->append(STRING_WITH_LEN(" as decimal("));
 
1083
 
 
1084
  end=int10_to_str(precision, len_buf,10);
 
1085
  str->append(len_buf, (uint32) (end - len_buf));
 
1086
 
 
1087
  str->append(',');
 
1088
 
 
1089
  end=int10_to_str(decimals, len_buf,10);
 
1090
  str->append(len_buf, (uint32) (end - len_buf));
 
1091
 
 
1092
  str->append(')');
 
1093
  str->append(')');
 
1094
}
 
1095
 
 
1096
 
 
1097
double Item_func_plus::real_op()
 
1098
{
 
1099
  double value= args[0]->val_real() + args[1]->val_real();
 
1100
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1101
    return 0.0;
 
1102
  return fix_result(value);
 
1103
}
 
1104
 
 
1105
 
 
1106
longlong Item_func_plus::int_op()
 
1107
{
 
1108
  longlong value=args[0]->val_int()+args[1]->val_int();
 
1109
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1110
    return 0;
 
1111
  return value;
 
1112
}
 
1113
 
 
1114
 
 
1115
/**
 
1116
  Calculate plus of two decimals.
 
1117
 
 
1118
  @param decimal_value  Buffer that can be used to store result
 
1119
 
 
1120
  @retval
 
1121
    0  Value was NULL;  In this case null_value is set
 
1122
  @retval
 
1123
    \# Value of operation as a decimal
 
1124
*/
 
1125
 
 
1126
my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
 
1127
{
 
1128
  my_decimal value1, *val1;
 
1129
  my_decimal value2, *val2;
 
1130
  val1= args[0]->val_decimal(&value1);
 
1131
  if ((null_value= args[0]->null_value))
 
1132
    return 0;
 
1133
  val2= args[1]->val_decimal(&value2);
 
1134
  if (!(null_value= (args[1]->null_value ||
 
1135
                     (my_decimal_add(E_DEC_FATAL_ERROR, decimal_value, val1,
 
1136
                                     val2) > 3))))
 
1137
    return decimal_value;
 
1138
  return 0;
 
1139
}
 
1140
 
 
1141
/**
 
1142
  Set precision of results for additive operations (+ and -)
 
1143
*/
 
1144
void Item_func_additive_op::result_precision()
 
1145
{
 
1146
  decimals= max(args[0]->decimals, args[1]->decimals);
 
1147
  int max_int_part= max(args[0]->decimal_precision() - args[0]->decimals,
 
1148
                        args[1]->decimal_precision() - args[1]->decimals);
 
1149
  int precision= min(max_int_part + 1 + decimals, DECIMAL_MAX_PRECISION);
 
1150
 
 
1151
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
 
1152
  if (result_type() == INT_RESULT)
 
1153
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
 
1154
  else
 
1155
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
 
1156
  max_length= my_decimal_precision_to_length(precision, decimals,
 
1157
                                             unsigned_flag);
 
1158
}
 
1159
 
 
1160
 
 
1161
/**
 
1162
  The following function is here to allow the user to force
 
1163
  subtraction of UNSIGNED BIGINT to return negative values.
 
1164
*/
 
1165
 
 
1166
void Item_func_minus::fix_length_and_dec()
 
1167
{
 
1168
  Item_num_op::fix_length_and_dec();
 
1169
  if (unsigned_flag &&
 
1170
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
 
1171
    unsigned_flag=0;
 
1172
}
 
1173
 
 
1174
 
 
1175
double Item_func_minus::real_op()
 
1176
{
 
1177
  double value= args[0]->val_real() - args[1]->val_real();
 
1178
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1179
    return 0.0;
 
1180
  return fix_result(value);
 
1181
}
 
1182
 
 
1183
 
 
1184
longlong Item_func_minus::int_op()
 
1185
{
 
1186
  longlong value=args[0]->val_int() - args[1]->val_int();
 
1187
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1188
    return 0;
 
1189
  return value;
 
1190
}
 
1191
 
 
1192
 
 
1193
/**
 
1194
  See Item_func_plus::decimal_op for comments.
 
1195
*/
 
1196
 
 
1197
my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
 
1198
{
 
1199
  my_decimal value1, *val1;
 
1200
  my_decimal value2, *val2= 
 
1201
 
 
1202
  val1= args[0]->val_decimal(&value1);
 
1203
  if ((null_value= args[0]->null_value))
 
1204
    return 0;
 
1205
  val2= args[1]->val_decimal(&value2);
 
1206
  if (!(null_value= (args[1]->null_value ||
 
1207
                     (my_decimal_sub(E_DEC_FATAL_ERROR, decimal_value, val1,
 
1208
                                     val2) > 3))))
 
1209
    return decimal_value;
 
1210
  return 0;
 
1211
}
 
1212
 
 
1213
 
 
1214
double Item_func_mul::real_op()
 
1215
{
 
1216
  DBUG_ASSERT(fixed == 1);
 
1217
  double value= args[0]->val_real() * args[1]->val_real();
 
1218
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1219
    return 0.0;
 
1220
  return fix_result(value);
 
1221
}
 
1222
 
 
1223
 
 
1224
longlong Item_func_mul::int_op()
 
1225
{
 
1226
  DBUG_ASSERT(fixed == 1);
 
1227
  longlong value=args[0]->val_int()*args[1]->val_int();
 
1228
  if ((null_value=args[0]->null_value || args[1]->null_value))
 
1229
    return 0;
 
1230
  return value;
 
1231
}
 
1232
 
 
1233
 
 
1234
/** See Item_func_plus::decimal_op for comments. */
 
1235
 
 
1236
my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
 
1237
{
 
1238
  my_decimal value1, *val1;
 
1239
  my_decimal value2, *val2;
 
1240
  val1= args[0]->val_decimal(&value1);
 
1241
  if ((null_value= args[0]->null_value))
 
1242
    return 0;
 
1243
  val2= args[1]->val_decimal(&value2);
 
1244
  if (!(null_value= (args[1]->null_value ||
 
1245
                     (my_decimal_mul(E_DEC_FATAL_ERROR, decimal_value, val1,
 
1246
                                    val2) > 3))))
 
1247
    return decimal_value;
 
1248
  return 0;
 
1249
}
 
1250
 
 
1251
 
 
1252
void Item_func_mul::result_precision()
 
1253
{
 
1254
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
 
1255
  if (result_type() == INT_RESULT)
 
1256
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
 
1257
  else
 
1258
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
 
1259
  decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE);
 
1260
  int precision= min(args[0]->decimal_precision() + args[1]->decimal_precision(),
 
1261
                     DECIMAL_MAX_PRECISION);
 
1262
  max_length= my_decimal_precision_to_length(precision, decimals,unsigned_flag);
 
1263
}
 
1264
 
 
1265
 
 
1266
double Item_func_div::real_op()
 
1267
{
 
1268
  DBUG_ASSERT(fixed == 1);
 
1269
  double value= args[0]->val_real();
 
1270
  double val2= args[1]->val_real();
 
1271
  if ((null_value= args[0]->null_value || args[1]->null_value))
 
1272
    return 0.0;
 
1273
  if (val2 == 0.0)
 
1274
  {
 
1275
    signal_divide_by_null();
 
1276
    return 0.0;
 
1277
  }
 
1278
  return fix_result(value/val2);
 
1279
}
 
1280
 
 
1281
 
 
1282
my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
 
1283
{
 
1284
  my_decimal value1, *val1;
 
1285
  my_decimal value2, *val2;
 
1286
  int err;
 
1287
 
 
1288
  val1= args[0]->val_decimal(&value1);
 
1289
  if ((null_value= args[0]->null_value))
 
1290
    return 0;
 
1291
  val2= args[1]->val_decimal(&value2);
 
1292
  if ((null_value= args[1]->null_value))
 
1293
    return 0;
 
1294
  if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
 
1295
                           val1, val2, prec_increment)) > 3)
 
1296
  {
 
1297
    if (err == E_DEC_DIV_ZERO)
 
1298
      signal_divide_by_null();
 
1299
    null_value= 1;
 
1300
    return 0;
 
1301
  }
 
1302
  return decimal_value;
 
1303
}
 
1304
 
 
1305
 
 
1306
void Item_func_div::result_precision()
 
1307
{
 
1308
  uint precision=min(args[0]->decimal_precision() + prec_increment,
 
1309
                     DECIMAL_MAX_PRECISION);
 
1310
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
 
1311
  if (result_type() == INT_RESULT)
 
1312
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
 
1313
  else
 
1314
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
 
1315
  decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
 
1316
  max_length= my_decimal_precision_to_length(precision, decimals,
 
1317
                                             unsigned_flag);
 
1318
}
 
1319
 
 
1320
 
 
1321
void Item_func_div::fix_length_and_dec()
 
1322
{
 
1323
  DBUG_ENTER("Item_func_div::fix_length_and_dec");
 
1324
  prec_increment= current_thd->variables.div_precincrement;
 
1325
  Item_num_op::fix_length_and_dec();
 
1326
  switch(hybrid_type) {
 
1327
  case REAL_RESULT:
 
1328
  {
 
1329
    decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment;
 
1330
    set_if_smaller(decimals, NOT_FIXED_DEC);
 
1331
    max_length=args[0]->max_length - args[0]->decimals + decimals;
 
1332
    uint tmp=float_length(decimals);
 
1333
    set_if_smaller(max_length,tmp);
 
1334
    break;
 
1335
  }
 
1336
  case INT_RESULT:
 
1337
    hybrid_type= DECIMAL_RESULT;
 
1338
    DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
 
1339
    result_precision();
 
1340
    break;
 
1341
  case DECIMAL_RESULT:
 
1342
    result_precision();
 
1343
    break;
 
1344
  default:
 
1345
    DBUG_ASSERT(0);
 
1346
  }
 
1347
  maybe_null= 1; // devision by zero
 
1348
  DBUG_VOID_RETURN;
 
1349
}
 
1350
 
 
1351
 
 
1352
/* Integer division */
 
1353
longlong Item_func_int_div::val_int()
 
1354
{
 
1355
  DBUG_ASSERT(fixed == 1);
 
1356
  longlong value=args[0]->val_int();
 
1357
  longlong val2=args[1]->val_int();
 
1358
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
 
1359
    return 0;
 
1360
  if (val2 == 0)
 
1361
  {
 
1362
    signal_divide_by_null();
 
1363
    return 0;
 
1364
  }
 
1365
  return (unsigned_flag ?
 
1366
          (ulonglong) value / (ulonglong) val2 :
 
1367
          value / val2);
 
1368
}
 
1369
 
 
1370
 
 
1371
void Item_func_int_div::fix_length_and_dec()
 
1372
{
 
1373
  Item_result argtype= args[0]->result_type();
 
1374
  /* use precision ony for the data type it is applicable for and valid */
 
1375
  max_length=args[0]->max_length -
 
1376
    (argtype == DECIMAL_RESULT || argtype == INT_RESULT ?
 
1377
     args[0]->decimals : 0);
 
1378
  maybe_null=1;
 
1379
  unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
 
1380
}
 
1381
 
 
1382
 
 
1383
longlong Item_func_mod::int_op()
 
1384
{
 
1385
  DBUG_ASSERT(fixed == 1);
 
1386
  longlong value=  args[0]->val_int();
 
1387
  longlong val2= args[1]->val_int();
 
1388
  longlong result;
 
1389
 
 
1390
  if ((null_value= args[0]->null_value || args[1]->null_value))
 
1391
    return 0; /* purecov: inspected */
 
1392
  if (val2 == 0)
 
1393
  {
 
1394
    signal_divide_by_null();
 
1395
    return 0;
 
1396
  }
 
1397
 
 
1398
  if (args[0]->unsigned_flag)
 
1399
    result= args[1]->unsigned_flag ? 
 
1400
      ((ulonglong) value) % ((ulonglong) val2) : ((ulonglong) value) % val2;
 
1401
  else
 
1402
    result= args[1]->unsigned_flag ?
 
1403
      value % ((ulonglong) val2) : value % val2;
 
1404
 
 
1405
  return result;
 
1406
}
 
1407
 
 
1408
double Item_func_mod::real_op()
 
1409
{
 
1410
  DBUG_ASSERT(fixed == 1);
 
1411
  double value= args[0]->val_real();
 
1412
  double val2=  args[1]->val_real();
 
1413
  if ((null_value= args[0]->null_value || args[1]->null_value))
 
1414
    return 0.0; /* purecov: inspected */
 
1415
  if (val2 == 0.0)
 
1416
  {
 
1417
    signal_divide_by_null();
 
1418
    return 0.0;
 
1419
  }
 
1420
  return fmod(value,val2);
 
1421
}
 
1422
 
 
1423
 
 
1424
my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
 
1425
{
 
1426
  my_decimal value1, *val1;
 
1427
  my_decimal value2, *val2;
 
1428
 
 
1429
  val1= args[0]->val_decimal(&value1);
 
1430
  if ((null_value= args[0]->null_value))
 
1431
    return 0;
 
1432
  val2= args[1]->val_decimal(&value2);
 
1433
  if ((null_value= args[1]->null_value))
 
1434
    return 0;
 
1435
  switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
 
1436
                         val1, val2)) {
 
1437
  case E_DEC_TRUNCATED:
 
1438
  case E_DEC_OK:
 
1439
    return decimal_value;
 
1440
  case E_DEC_DIV_ZERO:
 
1441
    signal_divide_by_null();
 
1442
  default:
 
1443
    null_value= 1;
 
1444
    return 0;
 
1445
  }
 
1446
}
 
1447
 
 
1448
 
 
1449
void Item_func_mod::result_precision()
 
1450
{
 
1451
  decimals= max(args[0]->decimals, args[1]->decimals);
 
1452
  max_length= max(args[0]->max_length, args[1]->max_length);
 
1453
}
 
1454
 
 
1455
 
 
1456
void Item_func_mod::fix_length_and_dec()
 
1457
{
 
1458
  Item_num_op::fix_length_and_dec();
 
1459
  maybe_null= 1;
 
1460
  unsigned_flag= args[0]->unsigned_flag;
 
1461
}
 
1462
 
 
1463
 
 
1464
double Item_func_neg::real_op()
 
1465
{
 
1466
  double value= args[0]->val_real();
 
1467
  null_value= args[0]->null_value;
 
1468
  return -value;
 
1469
}
 
1470
 
 
1471
 
 
1472
longlong Item_func_neg::int_op()
 
1473
{
 
1474
  longlong value= args[0]->val_int();
 
1475
  null_value= args[0]->null_value;
 
1476
  return -value;
 
1477
}
 
1478
 
 
1479
 
 
1480
my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
 
1481
{
 
1482
  my_decimal val, *value= args[0]->val_decimal(&val);
 
1483
  if (!(null_value= args[0]->null_value))
 
1484
  {
 
1485
    my_decimal2decimal(value, decimal_value);
 
1486
    my_decimal_neg(decimal_value);
 
1487
    return decimal_value;
 
1488
  }
 
1489
  return 0;
 
1490
}
 
1491
 
 
1492
 
 
1493
void Item_func_neg::fix_num_length_and_dec()
 
1494
{
 
1495
  decimals= args[0]->decimals;
 
1496
  /* 1 add because sign can appear */
 
1497
  max_length= args[0]->max_length + 1;
 
1498
}
 
1499
 
 
1500
 
 
1501
void Item_func_neg::fix_length_and_dec()
 
1502
{
 
1503
  DBUG_ENTER("Item_func_neg::fix_length_and_dec");
 
1504
  Item_func_num1::fix_length_and_dec();
 
1505
 
 
1506
  /*
 
1507
    If this is in integer context keep the context as integer if possible
 
1508
    (This is how multiplication and other integer functions works)
 
1509
    Use val() to get value as arg_type doesn't mean that item is
 
1510
    Item_int or Item_real due to existence of Item_param.
 
1511
  */
 
1512
  if (hybrid_type == INT_RESULT && args[0]->const_item())
 
1513
  {
 
1514
    longlong val= args[0]->val_int();
 
1515
    if ((ulonglong) val >= (ulonglong) LONGLONG_MIN &&
 
1516
        ((ulonglong) val != (ulonglong) LONGLONG_MIN ||
 
1517
          args[0]->type() != INT_ITEM))        
 
1518
    {
 
1519
      /*
 
1520
        Ensure that result is converted to DECIMAL, as longlong can't hold
 
1521
        the negated number
 
1522
      */
 
1523
      hybrid_type= DECIMAL_RESULT;
 
1524
      DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
 
1525
    }
 
1526
  }
 
1527
  unsigned_flag= 0;
 
1528
  DBUG_VOID_RETURN;
 
1529
}
 
1530
 
 
1531
 
 
1532
double Item_func_abs::real_op()
 
1533
{
 
1534
  double value= args[0]->val_real();
 
1535
  null_value= args[0]->null_value;
 
1536
  return fabs(value);
 
1537
}
 
1538
 
 
1539
 
 
1540
longlong Item_func_abs::int_op()
 
1541
{
 
1542
  longlong value= args[0]->val_int();
 
1543
  if ((null_value= args[0]->null_value))
 
1544
    return 0;
 
1545
  return (value >= 0) || unsigned_flag ? value : -value;
 
1546
}
 
1547
 
 
1548
 
 
1549
my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
 
1550
{
 
1551
  my_decimal val, *value= args[0]->val_decimal(&val);
 
1552
  if (!(null_value= args[0]->null_value))
 
1553
  {
 
1554
    my_decimal2decimal(value, decimal_value);
 
1555
    if (decimal_value->sign())
 
1556
      my_decimal_neg(decimal_value);
 
1557
    return decimal_value;
 
1558
  }
 
1559
  return 0;
 
1560
}
 
1561
 
 
1562
 
 
1563
void Item_func_abs::fix_length_and_dec()
 
1564
{
 
1565
  Item_func_num1::fix_length_and_dec();
 
1566
  unsigned_flag= args[0]->unsigned_flag;
 
1567
}
 
1568
 
 
1569
 
 
1570
/** Gateway to natural LOG function. */
 
1571
double Item_func_ln::val_real()
 
1572
{
 
1573
  DBUG_ASSERT(fixed == 1);
 
1574
  double value= args[0]->val_real();
 
1575
  if ((null_value= args[0]->null_value))
 
1576
    return 0.0;
 
1577
  if (value <= 0.0)
 
1578
  {
 
1579
    signal_divide_by_null();
 
1580
    return 0.0;
 
1581
  }
 
1582
  return log(value);
 
1583
}
 
1584
 
 
1585
/** 
 
1586
  Extended but so slower LOG function.
 
1587
 
 
1588
  We have to check if all values are > zero and first one is not one
 
1589
  as these are the cases then result is not a number.
 
1590
*/ 
 
1591
double Item_func_log::val_real()
 
1592
{
 
1593
  DBUG_ASSERT(fixed == 1);
 
1594
  double value= args[0]->val_real();
 
1595
  if ((null_value= args[0]->null_value))
 
1596
    return 0.0;
 
1597
  if (value <= 0.0)
 
1598
  {
 
1599
    signal_divide_by_null();
 
1600
    return 0.0;
 
1601
  }
 
1602
  if (arg_count == 2)
 
1603
  {
 
1604
    double value2= args[1]->val_real();
 
1605
    if ((null_value= args[1]->null_value))
 
1606
      return 0.0;
 
1607
    if (value2 <= 0.0 || value == 1.0)
 
1608
    {
 
1609
      signal_divide_by_null();
 
1610
      return 0.0;
 
1611
    }
 
1612
    return log(value2) / log(value);
 
1613
  }
 
1614
  return log(value);
 
1615
}
 
1616
 
 
1617
double Item_func_log2::val_real()
 
1618
{
 
1619
  DBUG_ASSERT(fixed == 1);
 
1620
  double value= args[0]->val_real();
 
1621
 
 
1622
  if ((null_value=args[0]->null_value))
 
1623
    return 0.0;
 
1624
  if (value <= 0.0)
 
1625
  {
 
1626
    signal_divide_by_null();
 
1627
    return 0.0;
 
1628
  }
 
1629
  return log(value) / M_LN2;
 
1630
}
 
1631
 
 
1632
double Item_func_log10::val_real()
 
1633
{
 
1634
  DBUG_ASSERT(fixed == 1);
 
1635
  double value= args[0]->val_real();
 
1636
  if ((null_value= args[0]->null_value))
 
1637
    return 0.0;
 
1638
  if (value <= 0.0)
 
1639
  {
 
1640
    signal_divide_by_null();
 
1641
    return 0.0;
 
1642
  }
 
1643
  return log10(value);
 
1644
}
 
1645
 
 
1646
double Item_func_exp::val_real()
 
1647
{
 
1648
  DBUG_ASSERT(fixed == 1);
 
1649
  double value= args[0]->val_real();
 
1650
  if ((null_value=args[0]->null_value))
 
1651
    return 0.0; /* purecov: inspected */
 
1652
  return fix_result(exp(value));
 
1653
}
 
1654
 
 
1655
double Item_func_sqrt::val_real()
 
1656
{
 
1657
  DBUG_ASSERT(fixed == 1);
 
1658
  double value= args[0]->val_real();
 
1659
  if ((null_value=(args[0]->null_value || value < 0)))
 
1660
    return 0.0; /* purecov: inspected */
 
1661
  return sqrt(value);
 
1662
}
 
1663
 
 
1664
double Item_func_pow::val_real()
 
1665
{
 
1666
  DBUG_ASSERT(fixed == 1);
 
1667
  double value= args[0]->val_real();
 
1668
  double val2= args[1]->val_real();
 
1669
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
 
1670
    return 0.0; /* purecov: inspected */
 
1671
  return fix_result(pow(value,val2));
 
1672
}
 
1673
 
 
1674
// Trigonometric functions
 
1675
 
 
1676
double Item_func_acos::val_real()
 
1677
{
 
1678
  DBUG_ASSERT(fixed == 1);
 
1679
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
 
1680
  volatile double value= args[0]->val_real();
 
1681
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
 
1682
    return 0.0;
 
1683
  return acos(value);
 
1684
}
 
1685
 
 
1686
double Item_func_asin::val_real()
 
1687
{
 
1688
  DBUG_ASSERT(fixed == 1);
 
1689
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
 
1690
  volatile double value= args[0]->val_real();
 
1691
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
 
1692
    return 0.0;
 
1693
  return asin(value);
 
1694
}
 
1695
 
 
1696
double Item_func_atan::val_real()
 
1697
{
 
1698
  DBUG_ASSERT(fixed == 1);
 
1699
  double value= args[0]->val_real();
 
1700
  if ((null_value=args[0]->null_value))
 
1701
    return 0.0;
 
1702
  if (arg_count == 2)
 
1703
  {
 
1704
    double val2= args[1]->val_real();
 
1705
    if ((null_value=args[1]->null_value))
 
1706
      return 0.0;
 
1707
    return fix_result(atan2(value,val2));
 
1708
  }
 
1709
  return atan(value);
 
1710
}
 
1711
 
 
1712
double Item_func_cos::val_real()
 
1713
{
 
1714
  DBUG_ASSERT(fixed == 1);
 
1715
  double value= args[0]->val_real();
 
1716
  if ((null_value=args[0]->null_value))
 
1717
    return 0.0;
 
1718
  return cos(value);
 
1719
}
 
1720
 
 
1721
double Item_func_sin::val_real()
 
1722
{
 
1723
  DBUG_ASSERT(fixed == 1);
 
1724
  double value= args[0]->val_real();
 
1725
  if ((null_value=args[0]->null_value))
 
1726
    return 0.0;
 
1727
  return sin(value);
 
1728
}
 
1729
 
 
1730
double Item_func_tan::val_real()
 
1731
{
 
1732
  DBUG_ASSERT(fixed == 1);
 
1733
  double value= args[0]->val_real();
 
1734
  if ((null_value=args[0]->null_value))
 
1735
    return 0.0;
 
1736
  return fix_result(tan(value));
 
1737
}
 
1738
 
 
1739
 
 
1740
// Shift-functions, same as << and >> in C/C++
 
1741
 
 
1742
 
 
1743
longlong Item_func_shift_left::val_int()
 
1744
{
 
1745
  DBUG_ASSERT(fixed == 1);
 
1746
  uint shift;
 
1747
  ulonglong res= ((ulonglong) args[0]->val_int() <<
 
1748
                  (shift=(uint) args[1]->val_int()));
 
1749
  if (args[0]->null_value || args[1]->null_value)
 
1750
  {
 
1751
    null_value=1;
 
1752
    return 0;
 
1753
  }
 
1754
  null_value=0;
 
1755
  return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0));
 
1756
}
 
1757
 
 
1758
longlong Item_func_shift_right::val_int()
 
1759
{
 
1760
  DBUG_ASSERT(fixed == 1);
 
1761
  uint shift;
 
1762
  ulonglong res= (ulonglong) args[0]->val_int() >>
 
1763
    (shift=(uint) args[1]->val_int());
 
1764
  if (args[0]->null_value || args[1]->null_value)
 
1765
  {
 
1766
    null_value=1;
 
1767
    return 0;
 
1768
  }
 
1769
  null_value=0;
 
1770
  return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0));
 
1771
}
 
1772
 
 
1773
 
 
1774
longlong Item_func_bit_neg::val_int()
 
1775
{
 
1776
  DBUG_ASSERT(fixed == 1);
 
1777
  ulonglong res= (ulonglong) args[0]->val_int();
 
1778
  if ((null_value=args[0]->null_value))
 
1779
    return 0;
 
1780
  return ~res;
 
1781
}
 
1782
 
 
1783
 
 
1784
// Conversion functions
 
1785
 
 
1786
void Item_func_integer::fix_length_and_dec()
 
1787
{
 
1788
  max_length=args[0]->max_length - args[0]->decimals+1;
 
1789
  uint tmp=float_length(decimals);
 
1790
  set_if_smaller(max_length,tmp);
 
1791
  decimals=0;
 
1792
}
 
1793
 
 
1794
void Item_func_int_val::fix_num_length_and_dec()
 
1795
{
 
1796
  max_length= args[0]->max_length - (args[0]->decimals ?
 
1797
                                     args[0]->decimals + 1 :
 
1798
                                     0) + 2;
 
1799
  uint tmp= float_length(decimals);
 
1800
  set_if_smaller(max_length,tmp);
 
1801
  decimals= 0;
 
1802
}
 
1803
 
 
1804
 
 
1805
void Item_func_int_val::find_num_type()
 
1806
{
 
1807
  DBUG_ENTER("Item_func_int_val::find_num_type");
 
1808
  DBUG_PRINT("info", ("name %s", func_name()));
 
1809
  switch(hybrid_type= args[0]->result_type())
 
1810
  {
 
1811
  case STRING_RESULT:
 
1812
  case REAL_RESULT:
 
1813
    hybrid_type= REAL_RESULT;
 
1814
    max_length= float_length(decimals);
 
1815
    break;
 
1816
  case INT_RESULT:
 
1817
  case DECIMAL_RESULT:
 
1818
    /*
 
1819
      -2 because in most high position can't be used any digit for longlong
 
1820
      and one position for increasing value during operation
 
1821
    */
 
1822
    if ((args[0]->max_length - args[0]->decimals) >=
 
1823
        (DECIMAL_LONGLONG_DIGITS - 2))
 
1824
    {
 
1825
      hybrid_type= DECIMAL_RESULT;
 
1826
    }
 
1827
    else
 
1828
    {
 
1829
      unsigned_flag= args[0]->unsigned_flag;
 
1830
      hybrid_type= INT_RESULT;
 
1831
    }
 
1832
    break;
 
1833
  default:
 
1834
    DBUG_ASSERT(0);
 
1835
  }
 
1836
  DBUG_PRINT("info", ("Type: %s",
 
1837
                      (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
 
1838
                       hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
 
1839
                       hybrid_type == INT_RESULT ? "INT_RESULT" :
 
1840
                       "--ILLEGAL!!!--")));
 
1841
 
 
1842
  DBUG_VOID_RETURN;
 
1843
}
 
1844
 
 
1845
 
 
1846
longlong Item_func_ceiling::int_op()
 
1847
{
 
1848
  longlong result;
 
1849
  switch (args[0]->result_type()) {
 
1850
  case INT_RESULT:
 
1851
    result= args[0]->val_int();
 
1852
    null_value= args[0]->null_value;
 
1853
    break;
 
1854
  case DECIMAL_RESULT:
 
1855
  {
 
1856
    my_decimal dec_buf, *dec;
 
1857
    if ((dec= Item_func_ceiling::decimal_op(&dec_buf)))
 
1858
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
 
1859
    else
 
1860
      result= 0;
 
1861
    break;
 
1862
  }
 
1863
  default:
 
1864
    result= (longlong)Item_func_ceiling::real_op();
 
1865
  };
 
1866
  return result;
 
1867
}
 
1868
 
 
1869
 
 
1870
double Item_func_ceiling::real_op()
 
1871
{
 
1872
  /*
 
1873
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
 
1874
    bug)
 
1875
  */
 
1876
  volatile double value= args[0]->val_real();
 
1877
  null_value= args[0]->null_value;
 
1878
  return ceil(value);
 
1879
}
 
1880
 
 
1881
 
 
1882
my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
 
1883
{
 
1884
  my_decimal val, *value= args[0]->val_decimal(&val);
 
1885
  if (!(null_value= (args[0]->null_value ||
 
1886
                     my_decimal_ceiling(E_DEC_FATAL_ERROR, value,
 
1887
                                        decimal_value) > 1)))
 
1888
    return decimal_value;
 
1889
  return 0;
 
1890
}
 
1891
 
 
1892
 
 
1893
longlong Item_func_floor::int_op()
 
1894
{
 
1895
  longlong result;
 
1896
  switch (args[0]->result_type()) {
 
1897
  case INT_RESULT:
 
1898
    result= args[0]->val_int();
 
1899
    null_value= args[0]->null_value;
 
1900
    break;
 
1901
  case DECIMAL_RESULT:
 
1902
  {
 
1903
    my_decimal dec_buf, *dec;
 
1904
    if ((dec= Item_func_floor::decimal_op(&dec_buf)))
 
1905
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
 
1906
    else
 
1907
      result= 0;
 
1908
    break;
 
1909
  }
 
1910
  default:
 
1911
    result= (longlong)Item_func_floor::real_op();
 
1912
  };
 
1913
  return result;
 
1914
}
 
1915
 
 
1916
 
 
1917
double Item_func_floor::real_op()
 
1918
{
 
1919
  /*
 
1920
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
 
1921
    bug)
 
1922
  */
 
1923
  volatile double value= args[0]->val_real();
 
1924
  null_value= args[0]->null_value;
 
1925
  return floor(value);
 
1926
}
 
1927
 
 
1928
 
 
1929
my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value)
 
1930
{
 
1931
  my_decimal val, *value= args[0]->val_decimal(&val);
 
1932
  if (!(null_value= (args[0]->null_value ||
 
1933
                     my_decimal_floor(E_DEC_FATAL_ERROR, value,
 
1934
                                      decimal_value) > 1)))
 
1935
    return decimal_value;
 
1936
  return 0;
 
1937
}
 
1938
 
 
1939
 
 
1940
void Item_func_round::fix_length_and_dec()
 
1941
{
 
1942
  int      decimals_to_set;
 
1943
  longlong val1;
 
1944
  bool     val1_unsigned;
 
1945
  
 
1946
  unsigned_flag= args[0]->unsigned_flag;
 
1947
  if (!args[1]->const_item())
 
1948
  {
 
1949
    max_length= args[0]->max_length;
 
1950
    decimals= args[0]->decimals;
 
1951
    if (args[0]->result_type() == DECIMAL_RESULT)
 
1952
    {
 
1953
      max_length++;
 
1954
      hybrid_type= DECIMAL_RESULT;
 
1955
    }
 
1956
    else
 
1957
      hybrid_type= REAL_RESULT;
 
1958
    return;
 
1959
  }
 
1960
 
 
1961
  val1= args[1]->val_int();
 
1962
  val1_unsigned= args[1]->unsigned_flag;
 
1963
  if (val1 < 0)
 
1964
    decimals_to_set= val1_unsigned ? INT_MAX : 0;
 
1965
  else
 
1966
    decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1;
 
1967
 
 
1968
  if (args[0]->decimals == NOT_FIXED_DEC)
 
1969
  {
 
1970
    max_length= args[0]->max_length;
 
1971
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
 
1972
    hybrid_type= REAL_RESULT;
 
1973
    return;
 
1974
  }
 
1975
  
 
1976
  switch (args[0]->result_type()) {
 
1977
  case REAL_RESULT:
 
1978
  case STRING_RESULT:
 
1979
    hybrid_type= REAL_RESULT;
 
1980
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
 
1981
    max_length= float_length(decimals);
 
1982
    break;
 
1983
  case INT_RESULT:
 
1984
    if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS))
 
1985
    {
 
1986
      int length_can_increase= test(!truncate && (val1 < 0) && !val1_unsigned);
 
1987
      max_length= args[0]->max_length + length_can_increase;
 
1988
      /* Here we can keep INT_RESULT */
 
1989
      hybrid_type= INT_RESULT;
 
1990
      decimals= 0;
 
1991
      break;
 
1992
    }
 
1993
    /* fall through */
 
1994
  case DECIMAL_RESULT:
 
1995
  {
 
1996
    hybrid_type= DECIMAL_RESULT;
 
1997
    decimals_to_set= min(DECIMAL_MAX_SCALE, decimals_to_set);
 
1998
    int decimals_delta= args[0]->decimals - decimals_to_set;
 
1999
    int precision= args[0]->decimal_precision();
 
2000
    int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1;
 
2001
 
 
2002
    precision-= decimals_delta - length_increase;
 
2003
    decimals= min(decimals_to_set, DECIMAL_MAX_SCALE);
 
2004
    max_length= my_decimal_precision_to_length(precision, decimals,
 
2005
                                               unsigned_flag);
 
2006
    break;
 
2007
  }
 
2008
  default:
 
2009
    DBUG_ASSERT(0); /* This result type isn't handled */
 
2010
  }
 
2011
}
 
2012
 
 
2013
double my_double_round(double value, longlong dec, bool dec_unsigned,
 
2014
                       bool truncate)
 
2015
{
 
2016
  double tmp;
 
2017
  bool dec_negative= (dec < 0) && !dec_unsigned;
 
2018
  ulonglong abs_dec= dec_negative ? -dec : dec;
 
2019
  /*
 
2020
    tmp2 is here to avoid return the value with 80 bit precision
 
2021
    This will fix that the test round(0.1,1) = round(0.1,1) is true
 
2022
  */
 
2023
  volatile double tmp2;
 
2024
 
 
2025
  tmp=(abs_dec < array_elements(log_10) ?
 
2026
       log_10[abs_dec] : pow(10.0,(double) abs_dec));
 
2027
 
 
2028
  if (dec_negative && my_isinf(tmp))
 
2029
    tmp2= 0;
 
2030
  else if (!dec_negative && my_isinf(value * tmp))
 
2031
    tmp2= value;
 
2032
  else if (truncate)
 
2033
  {
 
2034
    if (value >= 0)
 
2035
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
 
2036
    else
 
2037
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
 
2038
  }
 
2039
  else
 
2040
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
 
2041
  return tmp2;
 
2042
}
 
2043
 
 
2044
 
 
2045
double Item_func_round::real_op()
 
2046
{
 
2047
  double value= args[0]->val_real();
 
2048
 
 
2049
  if (!(null_value= args[0]->null_value || args[1]->null_value))
 
2050
    return my_double_round(value, args[1]->val_int(), args[1]->unsigned_flag,
 
2051
                           truncate);
 
2052
 
 
2053
  return 0.0;
 
2054
}
 
2055
 
 
2056
/*
 
2057
  Rounds a given value to a power of 10 specified as the 'to' argument,
 
2058
  avoiding overflows when the value is close to the ulonglong range boundary.
 
2059
*/
 
2060
 
 
2061
static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to)
 
2062
{
 
2063
  ulonglong tmp= value / to * to;
 
2064
  return (value - tmp < (to >> 1)) ? tmp : tmp + to;
 
2065
}
 
2066
 
 
2067
 
 
2068
longlong Item_func_round::int_op()
 
2069
{
 
2070
  longlong value= args[0]->val_int();
 
2071
  longlong dec= args[1]->val_int();
 
2072
  decimals= 0;
 
2073
  ulonglong abs_dec;
 
2074
  if ((null_value= args[0]->null_value || args[1]->null_value))
 
2075
    return 0;
 
2076
  if ((dec >= 0) || args[1]->unsigned_flag)
 
2077
    return value; // integer have not digits after point
 
2078
 
 
2079
  abs_dec= -dec;
 
2080
  longlong tmp;
 
2081
  
 
2082
  if(abs_dec >= array_elements(log_10_int))
 
2083
    return 0;
 
2084
  
 
2085
  tmp= log_10_int[abs_dec];
 
2086
  
 
2087
  if (truncate)
 
2088
    value= (unsigned_flag) ?
 
2089
      ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp;
 
2090
  else
 
2091
    value= (unsigned_flag || value >= 0) ?
 
2092
      my_unsigned_round((ulonglong) value, tmp) :
 
2093
      -(longlong) my_unsigned_round((ulonglong) -value, tmp);
 
2094
  return value;
 
2095
}
 
2096
 
 
2097
 
 
2098
my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
 
2099
{
 
2100
  my_decimal val, *value= args[0]->val_decimal(&val);
 
2101
  longlong dec= args[1]->val_int();
 
2102
  if (dec >= 0 || args[1]->unsigned_flag)
 
2103
    dec= min((ulonglong) dec, decimals);
 
2104
  else if (dec < INT_MIN)
 
2105
    dec= INT_MIN;
 
2106
    
 
2107
  if (!(null_value= (args[0]->null_value || args[1]->null_value ||
 
2108
                     my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec,
 
2109
                                      truncate, decimal_value) > 1))) 
 
2110
  {
 
2111
    decimal_value->frac= decimals;
 
2112
    return decimal_value;
 
2113
  }
 
2114
  return 0;
 
2115
}
 
2116
 
 
2117
 
 
2118
void Item_func_rand::seed_random(Item *arg)
 
2119
{
 
2120
  /*
 
2121
    TODO: do not do reinit 'rand' for every execute of PS/SP if
 
2122
    args[0] is a constant.
 
2123
  */
 
2124
  uint32 tmp= (uint32) arg->val_int();
 
2125
  randominit(rand, (uint32) (tmp*0x10001L+55555555L),
 
2126
             (uint32) (tmp*0x10000001L));
 
2127
}
 
2128
 
 
2129
 
 
2130
bool Item_func_rand::fix_fields(THD *thd,Item **ref)
 
2131
{
 
2132
  if (Item_real_func::fix_fields(thd, ref))
 
2133
    return TRUE;
 
2134
  used_tables_cache|= RAND_TABLE_BIT;
 
2135
  if (arg_count)
 
2136
  {                                     // Only use argument once in query
 
2137
    /*
 
2138
      Allocate rand structure once: we must use thd->stmt_arena
 
2139
      to create rand in proper mem_root if it's a prepared statement or
 
2140
      stored procedure.
 
2141
 
 
2142
      No need to send a Rand log event if seed was given eg: RAND(seed),
 
2143
      as it will be replicated in the query as such.
 
2144
    */
 
2145
    if (!rand && !(rand= (struct rand_struct*)
 
2146
                   thd->stmt_arena->alloc(sizeof(*rand))))
 
2147
      return TRUE;
 
2148
 
 
2149
    if (args[0]->const_item())
 
2150
      seed_random (args[0]);
 
2151
  }
 
2152
  else
 
2153
  {
 
2154
    /*
 
2155
      Save the seed only the first time RAND() is used in the query
 
2156
      Once events are forwarded rather than recreated,
 
2157
      the following can be skipped if inside the slave thread
 
2158
    */
 
2159
    if (!thd->rand_used)
 
2160
    {
 
2161
      thd->rand_used= 1;
 
2162
      thd->rand_saved_seed1= thd->rand.seed1;
 
2163
      thd->rand_saved_seed2= thd->rand.seed2;
 
2164
    }
 
2165
    rand= &thd->rand;
 
2166
  }
 
2167
  return FALSE;
 
2168
}
 
2169
 
 
2170
void Item_func_rand::update_used_tables()
 
2171
{
 
2172
  Item_real_func::update_used_tables();
 
2173
  used_tables_cache|= RAND_TABLE_BIT;
 
2174
}
 
2175
 
 
2176
 
 
2177
double Item_func_rand::val_real()
 
2178
{
 
2179
  DBUG_ASSERT(fixed == 1);
 
2180
  if (arg_count && !args[0]->const_item())
 
2181
    seed_random (args[0]);
 
2182
  return my_rnd(rand);
 
2183
}
 
2184
 
 
2185
longlong Item_func_sign::val_int()
 
2186
{
 
2187
  DBUG_ASSERT(fixed == 1);
 
2188
  double value= args[0]->val_real();
 
2189
  null_value=args[0]->null_value;
 
2190
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
 
2191
}
 
2192
 
 
2193
 
 
2194
double Item_func_units::val_real()
 
2195
{
 
2196
  DBUG_ASSERT(fixed == 1);
 
2197
  double value= args[0]->val_real();
 
2198
  if ((null_value=args[0]->null_value))
 
2199
    return 0;
 
2200
  return value*mul+add;
 
2201
}
 
2202
 
 
2203
 
 
2204
void Item_func_min_max::fix_length_and_dec()
 
2205
{
 
2206
  int max_int_part=0;
 
2207
  bool datetime_found= FALSE;
 
2208
  decimals=0;
 
2209
  max_length=0;
 
2210
  maybe_null=0;
 
2211
  cmp_type=args[0]->result_type();
 
2212
 
 
2213
  for (uint i=0 ; i < arg_count ; i++)
 
2214
  {
 
2215
    set_if_bigger(max_length, args[i]->max_length);
 
2216
    set_if_bigger(decimals, args[i]->decimals);
 
2217
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
 
2218
    if (args[i]->maybe_null)
 
2219
      maybe_null=1;
 
2220
    cmp_type=item_cmp_type(cmp_type,args[i]->result_type());
 
2221
    if (args[i]->result_type() != ROW_RESULT && args[i]->is_datetime())
 
2222
    {
 
2223
      datetime_found= TRUE;
 
2224
      if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME)
 
2225
        datetime_item= args[i];
 
2226
    }
 
2227
  }
 
2228
  if (cmp_type == STRING_RESULT)
 
2229
  {
 
2230
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
 
2231
    if (datetime_found)
 
2232
    {
 
2233
      thd= current_thd;
 
2234
      compare_as_dates= TRUE;
 
2235
    }
 
2236
  }
 
2237
  else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT))
 
2238
    max_length= my_decimal_precision_to_length(max_int_part+decimals, decimals,
 
2239
                                            unsigned_flag);
 
2240
  cached_field_type= agg_field_type(args, arg_count);
 
2241
}
 
2242
 
 
2243
 
 
2244
/*
 
2245
  Compare item arguments in the DATETIME context.
 
2246
 
 
2247
  SYNOPSIS
 
2248
    cmp_datetimes()
 
2249
    value [out]   found least/greatest DATE/DATETIME value
 
2250
 
 
2251
  DESCRIPTION
 
2252
    Compare item arguments as DATETIME values and return the index of the
 
2253
    least/greatest argument in the arguments array.
 
2254
    The correct integer DATE/DATETIME value of the found argument is
 
2255
    stored to the value pointer, if latter is provided.
 
2256
 
 
2257
  RETURN
 
2258
   0    If one of arguments is NULL
 
2259
   #    index of the least/greatest argument
 
2260
*/
 
2261
 
 
2262
uint Item_func_min_max::cmp_datetimes(ulonglong *value)
 
2263
{
 
2264
  ulonglong min_max= 0;
 
2265
  uint min_max_idx= 0;
 
2266
 
 
2267
  for (uint i=0; i < arg_count ; i++)
 
2268
  {
 
2269
    Item **arg= args + i;
 
2270
    bool is_null;
 
2271
    ulonglong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null);
 
2272
    if ((null_value= args[i]->null_value))
 
2273
      return 0;
 
2274
    if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
 
2275
    {
 
2276
      min_max= res;
 
2277
      min_max_idx= i;
 
2278
    }
 
2279
  }
 
2280
  if (value)
 
2281
  {
 
2282
    *value= min_max;
 
2283
    if (datetime_item->field_type() == MYSQL_TYPE_DATE)
 
2284
      *value/= 1000000L;
 
2285
  }
 
2286
  return min_max_idx;
 
2287
}
 
2288
 
 
2289
 
 
2290
String *Item_func_min_max::val_str(String *str)
 
2291
{
 
2292
  DBUG_ASSERT(fixed == 1);
 
2293
  if (compare_as_dates)
 
2294
  {
 
2295
    String *str_res;
 
2296
    uint min_max_idx= cmp_datetimes(NULL);
 
2297
    if (null_value)
 
2298
      return 0;
 
2299
    str_res= args[min_max_idx]->val_str(str);
 
2300
    str_res->set_charset(collation.collation);
 
2301
    return str_res;
 
2302
  }
 
2303
  switch (cmp_type) {
 
2304
  case INT_RESULT:
 
2305
  {
 
2306
    longlong nr=val_int();
 
2307
    if (null_value)
 
2308
      return 0;
 
2309
    str->set_int(nr, unsigned_flag, &my_charset_bin);
 
2310
    return str;
 
2311
  }
 
2312
  case DECIMAL_RESULT:
 
2313
  {
 
2314
    my_decimal dec_buf, *dec_val= val_decimal(&dec_buf);
 
2315
    if (null_value)
 
2316
      return 0;
 
2317
    my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str);
 
2318
    return str;
 
2319
  }
 
2320
  case REAL_RESULT:
 
2321
  {
 
2322
    double nr= val_real();
 
2323
    if (null_value)
 
2324
      return 0; /* purecov: inspected */
 
2325
    str->set_real(nr,decimals,&my_charset_bin);
 
2326
    return str;
 
2327
  }
 
2328
  case STRING_RESULT:
 
2329
  {
 
2330
    String *res= NULL;
 
2331
 
 
2332
    for (uint i=0; i < arg_count ; i++)
 
2333
    {
 
2334
      if (i == 0)
 
2335
        res=args[i]->val_str(str);
 
2336
      else
 
2337
      {
 
2338
        String *res2;
 
2339
        res2= args[i]->val_str(res == str ? &tmp_value : str);
 
2340
        if (res2)
 
2341
        {
 
2342
          int cmp= sortcmp(res,res2,collation.collation);
 
2343
          if ((cmp_sign < 0 ? cmp : -cmp) < 0)
 
2344
            res=res2;
 
2345
        }
 
2346
      }
 
2347
      if ((null_value= args[i]->null_value))
 
2348
        return 0;
 
2349
    }
 
2350
    res->set_charset(collation.collation);
 
2351
    return res;
 
2352
  }
 
2353
  case ROW_RESULT:
 
2354
  default:
 
2355
    // This case should never be chosen
 
2356
    DBUG_ASSERT(0);
 
2357
    return 0;
 
2358
  }
 
2359
  return 0;                                     // Keep compiler happy
 
2360
}
 
2361
 
 
2362
 
 
2363
double Item_func_min_max::val_real()
 
2364
{
 
2365
  DBUG_ASSERT(fixed == 1);
 
2366
  double value=0.0;
 
2367
  if (compare_as_dates)
 
2368
  {
 
2369
    ulonglong result= 0;
 
2370
    (void)cmp_datetimes(&result);
 
2371
    return (double)result;
 
2372
  }
 
2373
  for (uint i=0; i < arg_count ; i++)
 
2374
  {
 
2375
    if (i == 0)
 
2376
      value= args[i]->val_real();
 
2377
    else
 
2378
    {
 
2379
      double tmp= args[i]->val_real();
 
2380
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
 
2381
        value=tmp;
 
2382
    }
 
2383
    if ((null_value= args[i]->null_value))
 
2384
      break;
 
2385
  }
 
2386
  return value;
 
2387
}
 
2388
 
 
2389
 
 
2390
longlong Item_func_min_max::val_int()
 
2391
{
 
2392
  DBUG_ASSERT(fixed == 1);
 
2393
  longlong value=0;
 
2394
  if (compare_as_dates)
 
2395
  {
 
2396
    ulonglong result= 0;
 
2397
    (void)cmp_datetimes(&result);
 
2398
    return (longlong)result;
 
2399
  }
 
2400
  for (uint i=0; i < arg_count ; i++)
 
2401
  {
 
2402
    if (i == 0)
 
2403
      value=args[i]->val_int();
 
2404
    else
 
2405
    {
 
2406
      longlong tmp=args[i]->val_int();
 
2407
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
 
2408
        value=tmp;
 
2409
    }
 
2410
    if ((null_value= args[i]->null_value))
 
2411
      break;
 
2412
  }
 
2413
  return value;
 
2414
}
 
2415
 
 
2416
 
 
2417
my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
 
2418
{
 
2419
  DBUG_ASSERT(fixed == 1);
 
2420
  my_decimal tmp_buf, *tmp, *res= NULL;
 
2421
 
 
2422
  if (compare_as_dates)
 
2423
  {
 
2424
    ulonglong value= 0;
 
2425
    (void)cmp_datetimes(&value);
 
2426
    ulonglong2decimal(value, dec);
 
2427
    return dec;
 
2428
  }
 
2429
  for (uint i=0; i < arg_count ; i++)
 
2430
  {
 
2431
    if (i == 0)
 
2432
      res= args[i]->val_decimal(dec);
 
2433
    else
 
2434
    {
 
2435
      tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
 
2436
      if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
 
2437
      {
 
2438
        if (tmp == &tmp_buf)
 
2439
        {
 
2440
          /* Move value out of tmp_buf as this will be reused on next loop */
 
2441
          my_decimal2decimal(tmp, dec);
 
2442
          res= dec;
 
2443
        }
 
2444
        else
 
2445
          res= tmp;
 
2446
      }
 
2447
    }
 
2448
    if ((null_value= args[i]->null_value))
 
2449
    {
 
2450
      res= 0;
 
2451
      break;
 
2452
    }
 
2453
  }
 
2454
  return res;
 
2455
}
 
2456
 
 
2457
 
 
2458
longlong Item_func_length::val_int()
 
2459
{
 
2460
  DBUG_ASSERT(fixed == 1);
 
2461
  String *res=args[0]->val_str(&value);
 
2462
  if (!res)
 
2463
  {
 
2464
    null_value=1;
 
2465
    return 0; /* purecov: inspected */
 
2466
  }
 
2467
  null_value=0;
 
2468
  return (longlong) res->length();
 
2469
}
 
2470
 
 
2471
 
 
2472
longlong Item_func_char_length::val_int()
 
2473
{
 
2474
  DBUG_ASSERT(fixed == 1);
 
2475
  String *res=args[0]->val_str(&value);
 
2476
  if (!res)
 
2477
  {
 
2478
    null_value=1;
 
2479
    return 0; /* purecov: inspected */
 
2480
  }
 
2481
  null_value=0;
 
2482
  return (longlong) res->numchars();
 
2483
}
 
2484
 
 
2485
 
 
2486
longlong Item_func_coercibility::val_int()
 
2487
{
 
2488
  DBUG_ASSERT(fixed == 1);
 
2489
  null_value= 0;
 
2490
  return (longlong) args[0]->collation.derivation;
 
2491
}
 
2492
 
 
2493
 
 
2494
void Item_func_locate::fix_length_and_dec()
 
2495
{
 
2496
  max_length= MY_INT32_NUM_DECIMAL_DIGITS;
 
2497
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1);
 
2498
}
 
2499
 
 
2500
 
 
2501
longlong Item_func_locate::val_int()
 
2502
{
 
2503
  DBUG_ASSERT(fixed == 1);
 
2504
  String *a=args[0]->val_str(&value1);
 
2505
  String *b=args[1]->val_str(&value2);
 
2506
  if (!a || !b)
 
2507
  {
 
2508
    null_value=1;
 
2509
    return 0; /* purecov: inspected */
 
2510
  }
 
2511
  null_value=0;
 
2512
  /* must be longlong to avoid truncation */
 
2513
  longlong start=  0; 
 
2514
  longlong start0= 0;
 
2515
  my_match_t match;
 
2516
 
 
2517
  if (arg_count == 3)
 
2518
  {
 
2519
    start0= start= args[2]->val_int() - 1;
 
2520
 
 
2521
    if ((start < 0) || (start > a->length()))
 
2522
      return 0;
 
2523
 
 
2524
    /* start is now sufficiently valid to pass to charpos function */
 
2525
    start= a->charpos((int) start);
 
2526
 
 
2527
    if (start + b->length() > a->length())
 
2528
      return 0;
 
2529
  }
 
2530
 
 
2531
  if (!b->length())                             // Found empty string at start
 
2532
    return start + 1;
 
2533
  
 
2534
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
 
2535
                                            a->ptr()+start,
 
2536
                                            (uint) (a->length()-start),
 
2537
                                            b->ptr(), b->length(),
 
2538
                                            &match, 1))
 
2539
    return 0;
 
2540
  return (longlong) match.mb_len + start0 + 1;
 
2541
}
 
2542
 
 
2543
 
 
2544
void Item_func_locate::print(String *str, enum_query_type query_type)
 
2545
{
 
2546
  str->append(STRING_WITH_LEN("locate("));
 
2547
  args[1]->print(str, query_type);
 
2548
  str->append(',');
 
2549
  args[0]->print(str, query_type);
 
2550
  if (arg_count == 3)
 
2551
  {
 
2552
    str->append(',');
 
2553
    args[2]->print(str, query_type);
 
2554
  }
 
2555
  str->append(')');
 
2556
}
 
2557
 
 
2558
 
 
2559
longlong Item_func_field::val_int()
 
2560
{
 
2561
  DBUG_ASSERT(fixed == 1);
 
2562
 
 
2563
  if (cmp_type == STRING_RESULT)
 
2564
  {
 
2565
    String *field;
 
2566
    if (!(field= args[0]->val_str(&value)))
 
2567
      return 0;
 
2568
    for (uint i=1 ; i < arg_count ; i++)
 
2569
    {
 
2570
      String *tmp_value=args[i]->val_str(&tmp);
 
2571
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
 
2572
        return (longlong) (i);
 
2573
    }
 
2574
  }
 
2575
  else if (cmp_type == INT_RESULT)
 
2576
  {
 
2577
    longlong val= args[0]->val_int();
 
2578
    if (args[0]->null_value)
 
2579
      return 0;
 
2580
    for (uint i=1; i < arg_count ; i++)
 
2581
    {
 
2582
      if (val == args[i]->val_int() && !args[i]->null_value)
 
2583
        return (longlong) (i);
 
2584
    }
 
2585
  }
 
2586
  else if (cmp_type == DECIMAL_RESULT)
 
2587
  {
 
2588
    my_decimal dec_arg_buf, *dec_arg,
 
2589
               dec_buf, *dec= args[0]->val_decimal(&dec_buf);
 
2590
    if (args[0]->null_value)
 
2591
      return 0;
 
2592
    for (uint i=1; i < arg_count; i++)
 
2593
    {
 
2594
      dec_arg= args[i]->val_decimal(&dec_arg_buf);
 
2595
      if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec))
 
2596
        return (longlong) (i);
 
2597
    }
 
2598
  }
 
2599
  else
 
2600
  {
 
2601
    double val= args[0]->val_real();
 
2602
    if (args[0]->null_value)
 
2603
      return 0;
 
2604
    for (uint i=1; i < arg_count ; i++)
 
2605
    {
 
2606
      if (val == args[i]->val_real() && !args[i]->null_value)
 
2607
        return (longlong) (i);
 
2608
    }
 
2609
  }
 
2610
  return 0;
 
2611
}
 
2612
 
 
2613
 
 
2614
void Item_func_field::fix_length_and_dec()
 
2615
{
 
2616
  maybe_null=0; max_length=3;
 
2617
  cmp_type= args[0]->result_type();
 
2618
  for (uint i=1; i < arg_count ; i++)
 
2619
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
 
2620
  if (cmp_type == STRING_RESULT)
 
2621
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1);
 
2622
}
 
2623
 
 
2624
 
 
2625
longlong Item_func_ascii::val_int()
 
2626
{
 
2627
  DBUG_ASSERT(fixed == 1);
 
2628
  String *res=args[0]->val_str(&value);
 
2629
  if (!res)
 
2630
  {
 
2631
    null_value=1;
 
2632
    return 0;
 
2633
  }
 
2634
  null_value=0;
 
2635
  return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0);
 
2636
}
 
2637
 
 
2638
longlong Item_func_ord::val_int()
 
2639
{
 
2640
  DBUG_ASSERT(fixed == 1);
 
2641
  String *res=args[0]->val_str(&value);
 
2642
  if (!res)
 
2643
  {
 
2644
    null_value=1;
 
2645
    return 0;
 
2646
  }
 
2647
  null_value=0;
 
2648
  if (!res->length()) return 0;
 
2649
#ifdef USE_MB
 
2650
  if (use_mb(res->charset()))
 
2651
  {
 
2652
    register const char *str=res->ptr();
 
2653
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
 
2654
    if (!l)
 
2655
      return (longlong)((uchar) *str);
 
2656
    while (l--)
 
2657
      n=(n<<8)|(uint32)((uchar) *str++);
 
2658
    return (longlong) n;
 
2659
  }
 
2660
#endif
 
2661
  return (longlong) ((uchar) (*res)[0]);
 
2662
}
 
2663
 
 
2664
        /* Search after a string in a string of strings separated by ',' */
 
2665
        /* Returns number of found type >= 1 or 0 if not found */
 
2666
        /* This optimizes searching in enums to bit testing! */
 
2667
 
 
2668
void Item_func_find_in_set::fix_length_and_dec()
 
2669
{
 
2670
  decimals=0;
 
2671
  max_length=3;                                 // 1-999
 
2672
  if (args[0]->const_item() && args[1]->type() == FIELD_ITEM)
 
2673
  {
 
2674
    Field *field= ((Item_field*) args[1])->field;
 
2675
    if (field->real_type() == MYSQL_TYPE_SET)
 
2676
    {
 
2677
      String *find=args[0]->val_str(&value);
 
2678
      if (find)
 
2679
      {
 
2680
        enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
 
2681
                              find->length(), 0);
 
2682
        enum_bit=0;
 
2683
        if (enum_value)
 
2684
          enum_bit=LL(1) << (enum_value-1);
 
2685
      }
 
2686
    }
 
2687
  }
 
2688
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1);
 
2689
}
 
2690
 
 
2691
static const char separator=',';
 
2692
 
 
2693
longlong Item_func_find_in_set::val_int()
 
2694
{
 
2695
  DBUG_ASSERT(fixed == 1);
 
2696
  if (enum_value)
 
2697
  {
 
2698
    ulonglong tmp=(ulonglong) args[1]->val_int();
 
2699
    if (!(null_value=args[1]->null_value || args[0]->null_value))
 
2700
    {
 
2701
      if (tmp & enum_bit)
 
2702
        return enum_value;
 
2703
    }
 
2704
    return 0L;
 
2705
  }
 
2706
 
 
2707
  String *find=args[0]->val_str(&value);
 
2708
  String *buffer=args[1]->val_str(&value2);
 
2709
  if (!find || !buffer)
 
2710
  {
 
2711
    null_value=1;
 
2712
    return 0; /* purecov: inspected */
 
2713
  }
 
2714
  null_value=0;
 
2715
 
 
2716
  int diff;
 
2717
  if ((diff=buffer->length() - find->length()) >= 0)
 
2718
  {
 
2719
    my_wc_t wc;
 
2720
    CHARSET_INFO *cs= cmp_collation.collation;
 
2721
    const char *str_begin= buffer->ptr();
 
2722
    const char *str_end= buffer->ptr();
 
2723
    const char *real_end= str_end+buffer->length();
 
2724
    const uchar *find_str= (const uchar *) find->ptr();
 
2725
    uint find_str_len= find->length();
 
2726
    int position= 0;
 
2727
    while (1)
 
2728
    {
 
2729
      int symbol_len;
 
2730
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
 
2731
                                       (uchar*) real_end)) > 0)
 
2732
      {
 
2733
        const char *substr_end= str_end + symbol_len;
 
2734
        bool is_last_item= (substr_end == real_end);
 
2735
        bool is_separator= (wc == (my_wc_t) separator);
 
2736
        if (is_separator || is_last_item)
 
2737
        {
 
2738
          position++;
 
2739
          if (is_last_item && !is_separator)
 
2740
            str_end= substr_end;
 
2741
          if (!my_strnncoll(cs, (const uchar *) str_begin,
 
2742
                            str_end - str_begin,
 
2743
                            find_str, find_str_len))
 
2744
            return (longlong) position;
 
2745
          else
 
2746
            str_begin= substr_end;
 
2747
        }
 
2748
        str_end= substr_end;
 
2749
      }
 
2750
      else if (str_end - str_begin == 0 &&
 
2751
               find_str_len == 0 &&
 
2752
               wc == (my_wc_t) separator)
 
2753
        return (longlong) ++position;
 
2754
      else
 
2755
        return LL(0);
 
2756
    }
 
2757
  }
 
2758
  return 0;
 
2759
}
 
2760
 
 
2761
longlong Item_func_bit_count::val_int()
 
2762
{
 
2763
  DBUG_ASSERT(fixed == 1);
 
2764
  ulonglong value= (ulonglong) args[0]->val_int();
 
2765
  if ((null_value= args[0]->null_value))
 
2766
    return 0; /* purecov: inspected */
 
2767
  return (longlong) my_count_bits(value);
 
2768
}
 
2769
 
 
2770
 
 
2771
/****************************************************************************
 
2772
** Functions to handle dynamic loadable functions
 
2773
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
 
2774
** Rewritten by monty.
 
2775
****************************************************************************/
 
2776
 
 
2777
#ifdef HAVE_DLOPEN
 
2778
 
 
2779
void udf_handler::cleanup()
 
2780
{
 
2781
  if (!not_original)
 
2782
  {
 
2783
    if (initialized)
 
2784
    {
 
2785
      if (u_d->func_deinit != NULL)
 
2786
      {
 
2787
        Udf_func_deinit deinit= u_d->func_deinit;
 
2788
        (*deinit)(&initid);
 
2789
      }
 
2790
      free_udf(u_d);
 
2791
      initialized= FALSE;
 
2792
    }
 
2793
    if (buffers)                                // Because of bug in ecc
 
2794
      delete [] buffers;
 
2795
    buffers= 0;
 
2796
  }
 
2797
}
 
2798
 
 
2799
 
 
2800
bool
 
2801
udf_handler::fix_fields(THD *thd, Item_result_field *func,
 
2802
                        uint arg_count, Item **arguments)
 
2803
{
 
2804
  uchar buff[STACK_BUFF_ALLOC];                 // Max argument in function
 
2805
  DBUG_ENTER("Item_udf_func::fix_fields");
 
2806
 
 
2807
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
 
2808
    DBUG_RETURN(TRUE);                          // Fatal error flag is set!
 
2809
 
 
2810
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
 
2811
 
 
2812
  if (!tmp_udf)
 
2813
  {
 
2814
    my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
 
2815
    DBUG_RETURN(TRUE);
 
2816
  }
 
2817
  u_d=tmp_udf;
 
2818
  args=arguments;
 
2819
 
 
2820
  /* Fix all arguments */
 
2821
  func->maybe_null=0;
 
2822
  used_tables_cache=0;
 
2823
  const_item_cache=1;
 
2824
 
 
2825
  if ((f_args.arg_count=arg_count))
 
2826
  {
 
2827
    if (!(f_args.arg_type= (Item_result*)
 
2828
          sql_alloc(f_args.arg_count*sizeof(Item_result))))
 
2829
 
 
2830
    {
 
2831
      free_udf(u_d);
 
2832
      DBUG_RETURN(TRUE);
 
2833
    }
 
2834
    uint i;
 
2835
    Item **arg,**arg_end;
 
2836
    for (i=0, arg=arguments, arg_end=arguments+arg_count;
 
2837
         arg != arg_end ;
 
2838
         arg++,i++)
 
2839
    {
 
2840
      if (!(*arg)->fixed &&
 
2841
          (*arg)->fix_fields(thd, arg))
 
2842
        DBUG_RETURN(1);
 
2843
      // we can't assign 'item' before, because fix_fields() can change arg
 
2844
      Item *item= *arg;
 
2845
      if (item->check_cols(1))
 
2846
        DBUG_RETURN(TRUE);
 
2847
      /*
 
2848
        TODO: We should think about this. It is not always
 
2849
        right way just to set an UDF result to return my_charset_bin
 
2850
        if one argument has binary sorting order.
 
2851
        The result collation should be calculated according to arguments
 
2852
        derivations in some cases and should not in other cases.
 
2853
        Moreover, some arguments can represent a numeric input
 
2854
        which doesn't effect the result character set and collation.
 
2855
        There is no a general rule for UDF. Everything depends on
 
2856
        the particular user defined function.
 
2857
      */
 
2858
      if (item->collation.collation->state & MY_CS_BINSORT)
 
2859
        func->collation.set(&my_charset_bin);
 
2860
      if (item->maybe_null)
 
2861
        func->maybe_null=1;
 
2862
      func->with_sum_func= func->with_sum_func || item->with_sum_func;
 
2863
      used_tables_cache|=item->used_tables();
 
2864
      const_item_cache&=item->const_item();
 
2865
      f_args.arg_type[i]=item->result_type();
 
2866
    }
 
2867
    //TODO: why all following memory is not allocated with 1 call of sql_alloc?
 
2868
    if (!(buffers=new String[arg_count]) ||
 
2869
        !(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
 
2870
        !(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) ||
 
2871
        !(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) ||
 
2872
        !(num_buffer= (char*) sql_alloc(arg_count *
 
2873
                                        ALIGN_SIZE(sizeof(double)))) ||
 
2874
        !(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) ||
 
2875
        !(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count *
 
2876
                                                       sizeof(long))))
 
2877
    {
 
2878
      free_udf(u_d);
 
2879
      DBUG_RETURN(TRUE);
 
2880
    }
 
2881
  }
 
2882
  func->fix_length_and_dec();
 
2883
  initid.max_length=func->max_length;
 
2884
  initid.maybe_null=func->maybe_null;
 
2885
  initid.const_item=const_item_cache;
 
2886
  initid.decimals=func->decimals;
 
2887
  initid.ptr=0;
 
2888
 
 
2889
  if (u_d->func_init)
 
2890
  {
 
2891
    char init_msg_buff[MYSQL_ERRMSG_SIZE];
 
2892
    char *to=num_buffer;
 
2893
    for (uint i=0; i < arg_count; i++)
 
2894
    {
 
2895
      /*
 
2896
       For a constant argument i, args->args[i] points to the argument value. 
 
2897
       For non-constant, args->args[i] is NULL.
 
2898
      */
 
2899
      f_args.args[i]= NULL;         /* Non-const unless updated below. */
 
2900
 
 
2901
      f_args.lengths[i]= arguments[i]->max_length;
 
2902
      f_args.maybe_null[i]= (char) arguments[i]->maybe_null;
 
2903
      f_args.attributes[i]= arguments[i]->name;
 
2904
      f_args.attribute_lengths[i]= arguments[i]->name_length;
 
2905
 
 
2906
      if (arguments[i]->const_item())
 
2907
      {
 
2908
        switch (arguments[i]->result_type()) 
 
2909
        {
 
2910
        case STRING_RESULT:
 
2911
        case DECIMAL_RESULT:
 
2912
        {
 
2913
          String *res= arguments[i]->val_str(&buffers[i]);
 
2914
          if (arguments[i]->null_value)
 
2915
            continue;
 
2916
          f_args.args[i]= (char*) res->c_ptr();
 
2917
          f_args.lengths[i]= res->length();
 
2918
          break;
 
2919
        }
 
2920
        case INT_RESULT:
 
2921
          *((longlong*) to)= arguments[i]->val_int();
 
2922
          if (arguments[i]->null_value)
 
2923
            continue;
 
2924
          f_args.args[i]= to;
 
2925
          to+= ALIGN_SIZE(sizeof(longlong));
 
2926
          break;
 
2927
        case REAL_RESULT:
 
2928
          *((double*) to)= arguments[i]->val_real();
 
2929
          if (arguments[i]->null_value)
 
2930
            continue;
 
2931
          f_args.args[i]= to;
 
2932
          to+= ALIGN_SIZE(sizeof(double));
 
2933
          break;
 
2934
        case ROW_RESULT:
 
2935
        default:
 
2936
          // This case should never be chosen
 
2937
          DBUG_ASSERT(0);
 
2938
          break;
 
2939
        }
 
2940
      }
 
2941
    }
 
2942
    Udf_func_init init= u_d->func_init;
 
2943
    if ((error=(uchar) init(&initid, &f_args, init_msg_buff)))
 
2944
    {
 
2945
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
 
2946
               u_d->name.str, init_msg_buff);
 
2947
      free_udf(u_d);
 
2948
      DBUG_RETURN(TRUE);
 
2949
    }
 
2950
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
 
2951
    func->maybe_null=initid.maybe_null;
 
2952
    const_item_cache=initid.const_item;
 
2953
    /* 
 
2954
      Keep used_tables_cache in sync with const_item_cache.
 
2955
      See the comment in Item_udf_func::update_used tables.
 
2956
    */  
 
2957
    if (!const_item_cache && !used_tables_cache)
 
2958
      used_tables_cache= RAND_TABLE_BIT;
 
2959
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
 
2960
  }
 
2961
  initialized=1;
 
2962
  if (error)
 
2963
  {
 
2964
    my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
 
2965
             u_d->name.str, ER(ER_UNKNOWN_ERROR));
 
2966
    DBUG_RETURN(TRUE);
 
2967
  }
 
2968
  DBUG_RETURN(FALSE);
 
2969
}
 
2970
 
 
2971
 
 
2972
bool udf_handler::get_arguments()
 
2973
{
 
2974
  if (error)
 
2975
    return 1;                                   // Got an error earlier
 
2976
  char *to= num_buffer;
 
2977
  uint str_count=0;
 
2978
  for (uint i=0; i < f_args.arg_count; i++)
 
2979
  {
 
2980
    f_args.args[i]=0;
 
2981
    switch (f_args.arg_type[i]) {
 
2982
    case STRING_RESULT:
 
2983
    case DECIMAL_RESULT:
 
2984
      {
 
2985
        String *res=args[i]->val_str(&buffers[str_count++]);
 
2986
        if (!(args[i]->null_value))
 
2987
        {
 
2988
          f_args.args[i]=    (char*) res->ptr();
 
2989
          f_args.lengths[i]= res->length();
 
2990
          break;
 
2991
        }
 
2992
      }
 
2993
    case INT_RESULT:
 
2994
      *((longlong*) to) = args[i]->val_int();
 
2995
      if (!args[i]->null_value)
 
2996
      {
 
2997
        f_args.args[i]=to;
 
2998
        to+= ALIGN_SIZE(sizeof(longlong));
 
2999
      }
 
3000
      break;
 
3001
    case REAL_RESULT:
 
3002
      *((double*) to)= args[i]->val_real();
 
3003
      if (!args[i]->null_value)
 
3004
      {
 
3005
        f_args.args[i]=to;
 
3006
        to+= ALIGN_SIZE(sizeof(double));
 
3007
      }
 
3008
      break;
 
3009
    case ROW_RESULT:
 
3010
    default:
 
3011
      // This case should never be chosen
 
3012
      DBUG_ASSERT(0);
 
3013
      break;
 
3014
    }
 
3015
  }
 
3016
  return 0;
 
3017
}
 
3018
 
 
3019
/**
 
3020
  @return
 
3021
    (String*)NULL in case of NULL values
 
3022
*/
 
3023
String *udf_handler::val_str(String *str,String *save_str)
 
3024
{
 
3025
  uchar is_null_tmp=0;
 
3026
  ulong res_length;
 
3027
  DBUG_ENTER("udf_handler::val_str");
 
3028
 
 
3029
  if (get_arguments())
 
3030
    DBUG_RETURN(0);
 
3031
  char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
 
3032
    (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
 
3033
    u_d->func;
 
3034
 
 
3035
  if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH)
 
3036
  {                                             // This happens VERY seldom
 
3037
    if (str->alloc(MAX_FIELD_WIDTH))
 
3038
    {
 
3039
      error=1;
 
3040
      DBUG_RETURN(0);
 
3041
    }
 
3042
  }
 
3043
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
 
3044
                 &is_null_tmp, &error);
 
3045
  DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length));
 
3046
  if (is_null_tmp || !res || error)             // The !res is for safety
 
3047
  {
 
3048
    DBUG_PRINT("info", ("Null or error"));
 
3049
    DBUG_RETURN(0);
 
3050
  }
 
3051
  if (res == str->ptr())
 
3052
  {
 
3053
    str->length(res_length);
 
3054
    DBUG_PRINT("exit", ("str: %s", str->ptr()));
 
3055
    DBUG_RETURN(str);
 
3056
  }
 
3057
  save_str->set(res, res_length, str->charset());
 
3058
  DBUG_PRINT("exit", ("save_str: %s", save_str->ptr()));
 
3059
  DBUG_RETURN(save_str);
 
3060
}
 
3061
 
 
3062
 
 
3063
/*
 
3064
  For the moment, UDF functions are returning DECIMAL values as strings
 
3065
*/
 
3066
 
 
3067
my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf)
 
3068
{
 
3069
  char buf[DECIMAL_MAX_STR_LENGTH+1], *end;
 
3070
  ulong res_length= DECIMAL_MAX_STR_LENGTH;
 
3071
 
 
3072
  if (get_arguments())
 
3073
  {
 
3074
    *null_value=1;
 
3075
    return 0;
 
3076
  }
 
3077
  char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
 
3078
    (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
 
3079
    u_d->func;
 
3080
 
 
3081
  char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error);
 
3082
  if (is_null || error)
 
3083
  {
 
3084
    *null_value= 1;
 
3085
    return 0;
 
3086
  }
 
3087
  end= res+ res_length;
 
3088
  str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
 
3089
  return dec_buf;
 
3090
}
 
3091
 
 
3092
 
 
3093
void Item_udf_func::cleanup()
 
3094
{
 
3095
  udf.cleanup();
 
3096
  Item_func::cleanup();
 
3097
}
 
3098
 
 
3099
 
 
3100
void Item_udf_func::print(String *str, enum_query_type query_type)
 
3101
{
 
3102
  str->append(func_name());
 
3103
  str->append('(');
 
3104
  for (uint i=0 ; i < arg_count ; i++)
 
3105
  {
 
3106
    if (i != 0)
 
3107
      str->append(',');
 
3108
    args[i]->print_item_w_name(str, query_type);
 
3109
  }
 
3110
  str->append(')');
 
3111
}
 
3112
 
 
3113
 
 
3114
double Item_func_udf_float::val_real()
 
3115
{
 
3116
  DBUG_ASSERT(fixed == 1);
 
3117
  DBUG_ENTER("Item_func_udf_float::val");
 
3118
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
 
3119
                     args[0]->result_type(), arg_count));
 
3120
  DBUG_RETURN(udf.val(&null_value));
 
3121
}
 
3122
 
 
3123
 
 
3124
String *Item_func_udf_float::val_str(String *str)
 
3125
{
 
3126
  DBUG_ASSERT(fixed == 1);
 
3127
  double nr= val_real();
 
3128
  if (null_value)
 
3129
    return 0;                                   /* purecov: inspected */
 
3130
  str->set_real(nr,decimals,&my_charset_bin);
 
3131
  return str;
 
3132
}
 
3133
 
 
3134
 
 
3135
longlong Item_func_udf_int::val_int()
 
3136
{
 
3137
  DBUG_ASSERT(fixed == 1);
 
3138
  DBUG_ENTER("Item_func_udf_int::val_int");
 
3139
  DBUG_RETURN(udf.val_int(&null_value));
 
3140
}
 
3141
 
 
3142
 
 
3143
String *Item_func_udf_int::val_str(String *str)
 
3144
{
 
3145
  DBUG_ASSERT(fixed == 1);
 
3146
  longlong nr=val_int();
 
3147
  if (null_value)
 
3148
    return 0;
 
3149
  str->set_int(nr, unsigned_flag, &my_charset_bin);
 
3150
  return str;
 
3151
}
 
3152
 
 
3153
 
 
3154
longlong Item_func_udf_decimal::val_int()
 
3155
{
 
3156
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
 
3157
  longlong result;
 
3158
  if (null_value)
 
3159
    return 0;
 
3160
  my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
 
3161
  return result;
 
3162
}
 
3163
 
 
3164
 
 
3165
double Item_func_udf_decimal::val_real()
 
3166
{
 
3167
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
 
3168
  double result;
 
3169
  if (null_value)
 
3170
    return 0.0;
 
3171
  my_decimal2double(E_DEC_FATAL_ERROR, dec, &result);
 
3172
  return result;
 
3173
}
 
3174
 
 
3175
 
 
3176
my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf)
 
3177
{
 
3178
  DBUG_ASSERT(fixed == 1);
 
3179
  DBUG_ENTER("Item_func_udf_decimal::val_decimal");
 
3180
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
 
3181
                     args[0]->result_type(), arg_count));
 
3182
 
 
3183
  DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
 
3184
}
 
3185
 
 
3186
 
 
3187
String *Item_func_udf_decimal::val_str(String *str)
 
3188
{
 
3189
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
 
3190
  if (null_value)
 
3191
    return 0;
 
3192
  if (str->length() < DECIMAL_MAX_STR_LENGTH)
 
3193
    str->length(DECIMAL_MAX_STR_LENGTH);
 
3194
  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
 
3195
  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str);
 
3196
  return str;
 
3197
}
 
3198
 
 
3199
 
 
3200
void Item_func_udf_decimal::fix_length_and_dec()
 
3201
{
 
3202
  fix_num_length_and_dec();
 
3203
}
 
3204
 
 
3205
 
 
3206
/* Default max_length is max argument length */
 
3207
 
 
3208
void Item_func_udf_str::fix_length_and_dec()
 
3209
{
 
3210
  DBUG_ENTER("Item_func_udf_str::fix_length_and_dec");
 
3211
  max_length=0;
 
3212
  for (uint i = 0; i < arg_count; i++)
 
3213
    set_if_bigger(max_length,args[i]->max_length);
 
3214
  DBUG_VOID_RETURN;
 
3215
}
 
3216
 
 
3217
String *Item_func_udf_str::val_str(String *str)
 
3218
{
 
3219
  DBUG_ASSERT(fixed == 1);
 
3220
  String *res=udf.val_str(str,&str_value);
 
3221
  null_value = !res;
 
3222
  return res;
 
3223
}
 
3224
 
 
3225
 
 
3226
/**
 
3227
  @note
 
3228
  This has to come last in the udf_handler methods, or C for AIX
 
3229
  version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.)
 
3230
*/
 
3231
 
 
3232
udf_handler::~udf_handler()
 
3233
{
 
3234
  /* Everything should be properly cleaned up by this moment. */
 
3235
  DBUG_ASSERT(not_original || !(initialized || buffers));
 
3236
}
 
3237
 
 
3238
#else
 
3239
bool udf_handler::get_arguments() { return 0; }
 
3240
#endif /* HAVE_DLOPEN */
 
3241
 
 
3242
/*
 
3243
** User level locks
 
3244
*/
 
3245
 
 
3246
pthread_mutex_t LOCK_user_locks;
 
3247
static HASH hash_user_locks;
 
3248
 
 
3249
class User_level_lock
 
3250
{
 
3251
  uchar *key;
 
3252
  size_t key_length;
 
3253
 
 
3254
public:
 
3255
  int count;
 
3256
  bool locked;
 
3257
  pthread_cond_t cond;
 
3258
  my_thread_id thread_id;
 
3259
  void set_thread(THD *thd) { thread_id= thd->thread_id; }
 
3260
 
 
3261
  User_level_lock(const uchar *key_arg,uint length, ulong id) 
 
3262
    :key_length(length),count(1),locked(1), thread_id(id)
 
3263
  {
 
3264
    key= (uchar*) my_memdup(key_arg,length,MYF(0));
 
3265
    pthread_cond_init(&cond,NULL);
 
3266
    if (key)
 
3267
    {
 
3268
      if (my_hash_insert(&hash_user_locks,(uchar*) this))
 
3269
      {
 
3270
        my_free(key,MYF(0));
 
3271
        key=0;
 
3272
      }
 
3273
    }
 
3274
  }
 
3275
  ~User_level_lock()
 
3276
  {
 
3277
    if (key)
 
3278
    {
 
3279
      hash_delete(&hash_user_locks,(uchar*) this);
 
3280
      my_free(key, MYF(0));
 
3281
    }
 
3282
    pthread_cond_destroy(&cond);
 
3283
  }
 
3284
  inline bool initialized() { return key != 0; }
 
3285
  friend void item_user_lock_release(User_level_lock *ull);
 
3286
  friend uchar *ull_get_key(const User_level_lock *ull, size_t *length,
 
3287
                            my_bool not_used);
 
3288
};
 
3289
 
 
3290
uchar *ull_get_key(const User_level_lock *ull, size_t *length,
 
3291
                   my_bool not_used __attribute__((unused)))
 
3292
{
 
3293
  *length= ull->key_length;
 
3294
  return ull->key;
 
3295
}
 
3296
 
 
3297
 
 
3298
static bool item_user_lock_inited= 0;
 
3299
 
 
3300
void item_user_lock_init(void)
 
3301
{
 
3302
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
 
3303
  hash_init(&hash_user_locks,system_charset_info,
 
3304
            16,0,0,(hash_get_key) ull_get_key,NULL,0);
 
3305
  item_user_lock_inited= 1;
 
3306
}
 
3307
 
 
3308
void item_user_lock_free(void)
 
3309
{
 
3310
  if (item_user_lock_inited)
 
3311
  {
 
3312
    item_user_lock_inited= 0;
 
3313
    hash_free(&hash_user_locks);
 
3314
    pthread_mutex_destroy(&LOCK_user_locks);
 
3315
  }
 
3316
}
 
3317
 
 
3318
void item_user_lock_release(User_level_lock *ull)
 
3319
{
 
3320
  ull->locked=0;
 
3321
  ull->thread_id= 0;
 
3322
  if (--ull->count)
 
3323
    pthread_cond_signal(&ull->cond);
 
3324
  else
 
3325
    delete ull;
 
3326
}
 
3327
 
 
3328
/**
 
3329
  Wait until we are at or past the given position in the master binlog
 
3330
  on the slave.
 
3331
*/
 
3332
 
 
3333
longlong Item_master_pos_wait::val_int()
 
3334
{
 
3335
  DBUG_ASSERT(fixed == 1);
 
3336
  THD* thd = current_thd;
 
3337
  String *log_name = args[0]->val_str(&value);
 
3338
  int event_count= 0;
 
3339
 
 
3340
  null_value=0;
 
3341
  if (thd->slave_thread || !log_name || !log_name->length())
 
3342
  {
 
3343
    null_value = 1;
 
3344
    return 0;
 
3345
  }
 
3346
#ifdef HAVE_REPLICATION
 
3347
  longlong pos = (ulong)args[1]->val_int();
 
3348
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
 
3349
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
 
3350
  {
 
3351
    null_value = 1;
 
3352
    event_count=0;
 
3353
  }
 
3354
#endif
 
3355
  return event_count;
 
3356
}
 
3357
 
 
3358
#ifdef EXTRA_DEBUG
 
3359
void debug_sync_point(const char* lock_name, uint lock_timeout)
 
3360
{
 
3361
}
 
3362
 
 
3363
#endif
 
3364
 
 
3365
 
 
3366
longlong Item_func_last_insert_id::val_int()
 
3367
{
 
3368
  THD *thd= current_thd;
 
3369
  DBUG_ASSERT(fixed == 1);
 
3370
  if (arg_count)
 
3371
  {
 
3372
    longlong value= args[0]->val_int();
 
3373
    null_value= args[0]->null_value;
 
3374
    /*
 
3375
      LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as
 
3376
      documented in the manual. We don't want to touch
 
3377
      first_successful_insert_id_in_cur_stmt because it would make
 
3378
      LAST_INSERT_ID(X) take precedence over an generated auto_increment
 
3379
      value for this row.
 
3380
    */
 
3381
    thd->arg_of_last_insert_id_function= TRUE;
 
3382
    thd->first_successful_insert_id_in_prev_stmt= value;
 
3383
    return value;
 
3384
  }
 
3385
  return thd->read_first_successful_insert_id_in_prev_stmt();
 
3386
}
 
3387
 
 
3388
 
 
3389
bool Item_func_last_insert_id::fix_fields(THD *thd, Item **ref)
 
3390
{
 
3391
  return Item_int_func::fix_fields(thd, ref);
 
3392
}
 
3393
 
 
3394
 
 
3395
/* This function is just used to test speed of different functions */
 
3396
 
 
3397
longlong Item_func_benchmark::val_int()
 
3398
{
 
3399
  DBUG_ASSERT(fixed == 1);
 
3400
  char buff[MAX_FIELD_WIDTH];
 
3401
  String tmp(buff,sizeof(buff), &my_charset_bin);
 
3402
  my_decimal tmp_decimal;
 
3403
  THD *thd=current_thd;
 
3404
  ulonglong loop_count;
 
3405
 
 
3406
  loop_count= (ulonglong) args[0]->val_int();
 
3407
 
 
3408
  if (args[0]->null_value ||
 
3409
      (!args[0]->unsigned_flag && (((longlong) loop_count) < 0)))
 
3410
  {
 
3411
    if (!args[0]->null_value)
 
3412
    {
 
3413
      char buff[22];
 
3414
      llstr(((longlong) loop_count), buff);
 
3415
      push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
 
3416
                          ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
 
3417
                          "count", buff, "benchmark");
 
3418
    }
 
3419
 
 
3420
    null_value= 1;
 
3421
    return 0;
 
3422
  }
 
3423
 
 
3424
  null_value=0;
 
3425
  for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++)
 
3426
  {
 
3427
    switch (args[1]->result_type()) {
 
3428
    case REAL_RESULT:
 
3429
      (void) args[1]->val_real();
 
3430
      break;
 
3431
    case INT_RESULT:
 
3432
      (void) args[1]->val_int();
 
3433
      break;
 
3434
    case STRING_RESULT:
 
3435
      (void) args[1]->val_str(&tmp);
 
3436
      break;
 
3437
    case DECIMAL_RESULT:
 
3438
      (void) args[1]->val_decimal(&tmp_decimal);
 
3439
      break;
 
3440
    case ROW_RESULT:
 
3441
    default:
 
3442
      // This case should never be chosen
 
3443
      DBUG_ASSERT(0);
 
3444
      return 0;
 
3445
    }
 
3446
  }
 
3447
  return 0;
 
3448
}
 
3449
 
 
3450
 
 
3451
void Item_func_benchmark::print(String *str, enum_query_type query_type)
 
3452
{
 
3453
  str->append(STRING_WITH_LEN("benchmark("));
 
3454
  args[0]->print(str, query_type);
 
3455
  str->append(',');
 
3456
  args[1]->print(str, query_type);
 
3457
  str->append(')');
 
3458
}
 
3459
 
 
3460
#define extra_size sizeof(double)
 
3461
 
 
3462
static user_var_entry *get_variable(HASH *hash, LEX_STRING &name,
 
3463
                                    bool create_if_not_exists)
 
3464
{
 
3465
  user_var_entry *entry;
 
3466
 
 
3467
  if (!(entry = (user_var_entry*) hash_search(hash, (uchar*) name.str,
 
3468
                                              name.length)) &&
 
3469
      create_if_not_exists)
 
3470
  {
 
3471
    uint size=ALIGN_SIZE(sizeof(user_var_entry))+name.length+1+extra_size;
 
3472
    if (!hash_inited(hash))
 
3473
      return 0;
 
3474
    if (!(entry = (user_var_entry*) my_malloc(size,MYF(MY_WME | ME_FATALERROR))))
 
3475
      return 0;
 
3476
    entry->name.str=(char*) entry+ ALIGN_SIZE(sizeof(user_var_entry))+
 
3477
      extra_size;
 
3478
    entry->name.length=name.length;
 
3479
    entry->value=0;
 
3480
    entry->length=0;
 
3481
    entry->update_query_id=0;
 
3482
    entry->collation.set(NULL, DERIVATION_IMPLICIT, 0);
 
3483
    entry->unsigned_flag= 0;
 
3484
    /*
 
3485
      If we are here, we were called from a SET or a query which sets a
 
3486
      variable. Imagine it is this:
 
3487
      INSERT INTO t SELECT @a:=10, @a:=@a+1.
 
3488
      Then when we have a Item_func_get_user_var (because of the @a+1) so we
 
3489
      think we have to write the value of @a to the binlog. But before that,
 
3490
      we have a Item_func_set_user_var to create @a (@a:=10), in this we mark
 
3491
      the variable as "already logged" (line below) so that it won't be logged
 
3492
      by Item_func_get_user_var (because that's not necessary).
 
3493
    */
 
3494
    entry->used_query_id=current_thd->query_id;
 
3495
    entry->type=STRING_RESULT;
 
3496
    memcpy(entry->name.str, name.str, name.length+1);
 
3497
    if (my_hash_insert(hash,(uchar*) entry))
 
3498
    {
 
3499
      my_free((char*) entry,MYF(0));
 
3500
      return 0;
 
3501
    }
 
3502
  }
 
3503
  return entry;
 
3504
}
 
3505
 
 
3506
/*
 
3507
  When a user variable is updated (in a SET command or a query like
 
3508
  SELECT @a:= ).
 
3509
*/
 
3510
 
 
3511
bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
 
3512
{
 
3513
  DBUG_ASSERT(fixed == 0);
 
3514
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
 
3515
  if (Item_func::fix_fields(thd, ref) ||
 
3516
      !(entry= get_variable(&thd->user_vars, name, 1)))
 
3517
    return TRUE;
 
3518
  /* 
 
3519
     Remember the last query which updated it, this way a query can later know
 
3520
     if this variable is a constant item in the query (it is if update_query_id
 
3521
     is different from query_id).
 
3522
  */
 
3523
  entry->update_query_id= thd->query_id;
 
3524
  /*
 
3525
    As it is wrong and confusing to associate any 
 
3526
    character set with NULL, @a should be latin2
 
3527
    after this query sequence:
 
3528
 
 
3529
      SET @a=_latin2'string';
 
3530
      SET @a=NULL;
 
3531
 
 
3532
    I.e. the second query should not change the charset
 
3533
    to the current default value, but should keep the 
 
3534
    original value assigned during the first query.
 
3535
    In order to do it, we don't copy charset
 
3536
    from the argument if the argument is NULL
 
3537
    and the variable has previously been initialized.
 
3538
  */
 
3539
  null_item= (args[0]->type() == NULL_ITEM);
 
3540
  if (!entry->collation.collation || !null_item)
 
3541
    entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
 
3542
  collation.set(entry->collation.collation, DERIVATION_IMPLICIT);
 
3543
  cached_result_type= args[0]->result_type();
 
3544
  return FALSE;
 
3545
}
 
3546
 
 
3547
 
 
3548
void
 
3549
Item_func_set_user_var::fix_length_and_dec()
 
3550
{
 
3551
  maybe_null=args[0]->maybe_null;
 
3552
  max_length=args[0]->max_length;
 
3553
  decimals=args[0]->decimals;
 
3554
  collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
 
3555
}
 
3556
 
 
3557
 
 
3558
/*
 
3559
  Mark field in read_map
 
3560
 
 
3561
  NOTES
 
3562
    This is used by filesort to register used fields in a a temporary
 
3563
    column read set or to register used fields in a view
 
3564
*/
 
3565
 
 
3566
bool Item_func_set_user_var::register_field_in_read_map(uchar *arg)
 
3567
{
 
3568
  if (result_field)
 
3569
  {
 
3570
    TABLE *table= (TABLE *) arg;
 
3571
    if (result_field->table == table || !table)
 
3572
      bitmap_set_bit(result_field->table->read_set, result_field->field_index);
 
3573
  }
 
3574
  return 0;
 
3575
}
 
3576
 
 
3577
 
 
3578
/**
 
3579
  Set value to user variable.
 
3580
 
 
3581
  @param entry          pointer to structure representing variable
 
3582
  @param set_null       should we set NULL value ?
 
3583
  @param ptr            pointer to buffer with new value
 
3584
  @param length         length of new value
 
3585
  @param type           type of new value
 
3586
  @param cs             charset info for new value
 
3587
  @param dv             derivation for new value
 
3588
  @param unsigned_arg   indiates if a value of type INT_RESULT is unsigned
 
3589
 
 
3590
  @note Sets error and fatal error if allocation fails.
 
3591
 
 
3592
  @retval
 
3593
    false   success
 
3594
  @retval
 
3595
    true    failure
 
3596
*/
 
3597
 
 
3598
static bool
 
3599
update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length,
 
3600
            Item_result type, CHARSET_INFO *cs, Derivation dv,
 
3601
            bool unsigned_arg)
 
3602
{
 
3603
  if (set_null)
 
3604
  {
 
3605
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
 
3606
    if (entry->value && entry->value != pos)
 
3607
      my_free(entry->value,MYF(0));
 
3608
    entry->value= 0;
 
3609
    entry->length= 0;
 
3610
  }
 
3611
  else
 
3612
  {
 
3613
    if (type == STRING_RESULT)
 
3614
      length++;                                 // Store strings with end \0
 
3615
    if (length <= extra_size)
 
3616
    {
 
3617
      /* Save value in value struct */
 
3618
      char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
 
3619
      if (entry->value != pos)
 
3620
      {
 
3621
        if (entry->value)
 
3622
          my_free(entry->value,MYF(0));
 
3623
        entry->value=pos;
 
3624
      }
 
3625
    }
 
3626
    else
 
3627
    {
 
3628
      /* Allocate variable */
 
3629
      if (entry->length != length)
 
3630
      {
 
3631
        char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
 
3632
        if (entry->value == pos)
 
3633
          entry->value=0;
 
3634
        entry->value= (char*) my_realloc(entry->value, length,
 
3635
                                         MYF(MY_ALLOW_ZERO_PTR | MY_WME |
 
3636
                                             ME_FATALERROR));
 
3637
        if (!entry->value)
 
3638
          return 1;
 
3639
      }
 
3640
    }
 
3641
    if (type == STRING_RESULT)
 
3642
    {
 
3643
      length--;                                 // Fix length change above
 
3644
      entry->value[length]= 0;                  // Store end \0
 
3645
    }
 
3646
    memcpy(entry->value,ptr,length);
 
3647
    if (type == DECIMAL_RESULT)
 
3648
      ((my_decimal*)entry->value)->fix_buffer_pointer();
 
3649
    entry->length= length;
 
3650
    entry->collation.set(cs, dv);
 
3651
    entry->unsigned_flag= unsigned_arg;
 
3652
  }
 
3653
  entry->type=type;
 
3654
  return 0;
 
3655
}
 
3656
 
 
3657
 
 
3658
bool
 
3659
Item_func_set_user_var::update_hash(void *ptr, uint length,
 
3660
                                    Item_result res_type,
 
3661
                                    CHARSET_INFO *cs, Derivation dv,
 
3662
                                    bool unsigned_arg)
 
3663
{
 
3664
  /*
 
3665
    If we set a variable explicitely to NULL then keep the old
 
3666
    result type of the variable
 
3667
  */
 
3668
  if ((null_value= args[0]->null_value) && null_item)
 
3669
    res_type= entry->type;                      // Don't change type of item
 
3670
  if (::update_hash(entry, (null_value= args[0]->null_value),
 
3671
                    ptr, length, res_type, cs, dv, unsigned_arg))
 
3672
  {
 
3673
    null_value= 1;
 
3674
    return 1;
 
3675
  }
 
3676
  return 0;
 
3677
}
 
3678
 
 
3679
 
 
3680
/** Get the value of a variable as a double. */
 
3681
 
 
3682
double user_var_entry::val_real(my_bool *null_value)
 
3683
{
 
3684
  if ((*null_value= (value == 0)))
 
3685
    return 0.0;
 
3686
 
 
3687
  switch (type) {
 
3688
  case REAL_RESULT:
 
3689
    return *(double*) value;
 
3690
  case INT_RESULT:
 
3691
    return (double) *(longlong*) value;
 
3692
  case DECIMAL_RESULT:
 
3693
  {
 
3694
    double result;
 
3695
    my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *)value, &result);
 
3696
    return result;
 
3697
  }
 
3698
  case STRING_RESULT:
 
3699
    return my_atof(value);                      // This is null terminated
 
3700
  case ROW_RESULT:
 
3701
    DBUG_ASSERT(1);                             // Impossible
 
3702
    break;
 
3703
  }
 
3704
  return 0.0;                                   // Impossible
 
3705
}
 
3706
 
 
3707
 
 
3708
/** Get the value of a variable as an integer. */
 
3709
 
 
3710
longlong user_var_entry::val_int(my_bool *null_value) const
 
3711
{
 
3712
  if ((*null_value= (value == 0)))
 
3713
    return LL(0);
 
3714
 
 
3715
  switch (type) {
 
3716
  case REAL_RESULT:
 
3717
    return (longlong) *(double*) value;
 
3718
  case INT_RESULT:
 
3719
    return *(longlong*) value;
 
3720
  case DECIMAL_RESULT:
 
3721
  {
 
3722
    longlong result;
 
3723
    my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, &result);
 
3724
    return result;
 
3725
  }
 
3726
  case STRING_RESULT:
 
3727
  {
 
3728
    int error;
 
3729
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
 
3730
  }
 
3731
  case ROW_RESULT:
 
3732
    DBUG_ASSERT(1);                             // Impossible
 
3733
    break;
 
3734
  }
 
3735
  return LL(0);                                 // Impossible
 
3736
}
 
3737
 
 
3738
 
 
3739
/** Get the value of a variable as a string. */
 
3740
 
 
3741
String *user_var_entry::val_str(my_bool *null_value, String *str,
 
3742
                                uint decimals)
 
3743
{
 
3744
  if ((*null_value= (value == 0)))
 
3745
    return (String*) 0;
 
3746
 
 
3747
  switch (type) {
 
3748
  case REAL_RESULT:
 
3749
    str->set_real(*(double*) value, decimals, &my_charset_bin);
 
3750
    break;
 
3751
  case INT_RESULT:
 
3752
    if (!unsigned_flag)
 
3753
      str->set(*(longlong*) value, &my_charset_bin);
 
3754
    else
 
3755
      str->set(*(ulonglong*) value, &my_charset_bin);
 
3756
    break;
 
3757
  case DECIMAL_RESULT:
 
3758
    my_decimal2string(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, 0, 0, str);
 
3759
    break;
 
3760
  case STRING_RESULT:
 
3761
    if (str->copy(value, length, collation.collation))
 
3762
      str= 0;                                   // EOM error
 
3763
  case ROW_RESULT:
 
3764
    DBUG_ASSERT(1);                             // Impossible
 
3765
    break;
 
3766
  }
 
3767
  return(str);
 
3768
}
 
3769
 
 
3770
/** Get the value of a variable as a decimal. */
 
3771
 
 
3772
my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val)
 
3773
{
 
3774
  if ((*null_value= (value == 0)))
 
3775
    return 0;
 
3776
 
 
3777
  switch (type) {
 
3778
  case REAL_RESULT:
 
3779
    double2my_decimal(E_DEC_FATAL_ERROR, *(double*) value, val);
 
3780
    break;
 
3781
  case INT_RESULT:
 
3782
    int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) value, 0, val);
 
3783
    break;
 
3784
  case DECIMAL_RESULT:
 
3785
    val= (my_decimal *)value;
 
3786
    break;
 
3787
  case STRING_RESULT:
 
3788
    str2my_decimal(E_DEC_FATAL_ERROR, value, length, collation.collation, val);
 
3789
    break;
 
3790
  case ROW_RESULT:
 
3791
    DBUG_ASSERT(1);                             // Impossible
 
3792
    break;
 
3793
  }
 
3794
  return(val);
 
3795
}
 
3796
 
 
3797
/**
 
3798
  This functions is invoked on SET \@variable or
 
3799
  \@variable:= expression.
 
3800
 
 
3801
  Evaluate (and check expression), store results.
 
3802
 
 
3803
  @note
 
3804
    For now it always return OK. All problem with value evaluating
 
3805
    will be caught by thd->is_error() check in sql_set_variables().
 
3806
 
 
3807
  @retval
 
3808
    FALSE OK.
 
3809
*/
 
3810
 
 
3811
bool
 
3812
Item_func_set_user_var::check(bool use_result_field)
 
3813
{
 
3814
  DBUG_ENTER("Item_func_set_user_var::check");
 
3815
  if (use_result_field && !result_field)
 
3816
    use_result_field= FALSE;
 
3817
 
 
3818
  switch (cached_result_type) {
 
3819
  case REAL_RESULT:
 
3820
  {
 
3821
    save_result.vreal= use_result_field ? result_field->val_real() :
 
3822
                        args[0]->val_real();
 
3823
    break;
 
3824
  }
 
3825
  case INT_RESULT:
 
3826
  {
 
3827
    save_result.vint= use_result_field ? result_field->val_int() :
 
3828
                       args[0]->val_int();
 
3829
    unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag:
 
3830
                    args[0]->unsigned_flag;
 
3831
    break;
 
3832
  }
 
3833
  case STRING_RESULT:
 
3834
  {
 
3835
    save_result.vstr= use_result_field ? result_field->val_str(&value) :
 
3836
                       args[0]->val_str(&value);
 
3837
    break;
 
3838
  }
 
3839
  case DECIMAL_RESULT:
 
3840
  {
 
3841
    save_result.vdec= use_result_field ?
 
3842
                       result_field->val_decimal(&decimal_buff) :
 
3843
                       args[0]->val_decimal(&decimal_buff);
 
3844
    break;
 
3845
  }
 
3846
  case ROW_RESULT:
 
3847
  default:
 
3848
    // This case should never be chosen
 
3849
    DBUG_ASSERT(0);
 
3850
    break;
 
3851
  }
 
3852
  DBUG_RETURN(FALSE);
 
3853
}
 
3854
 
 
3855
 
 
3856
/**
 
3857
  This functions is invoked on
 
3858
  SET \@variable or \@variable:= expression.
 
3859
 
 
3860
  @note
 
3861
    We have to store the expression as such in the variable, independent of
 
3862
    the value method used by the user
 
3863
 
 
3864
  @retval
 
3865
    0   OK
 
3866
  @retval
 
3867
    1   EOM Error
 
3868
 
 
3869
*/
 
3870
 
 
3871
bool
 
3872
Item_func_set_user_var::update()
 
3873
{
 
3874
  bool res= false;
 
3875
  DBUG_ENTER("Item_func_set_user_var::update");
 
3876
 
 
3877
  switch (cached_result_type) {
 
3878
  case REAL_RESULT:
 
3879
  {
 
3880
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
 
3881
                     REAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, 0);
 
3882
    break;
 
3883
  }
 
3884
  case INT_RESULT:
 
3885
  {
 
3886
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
 
3887
                     INT_RESULT, &my_charset_bin, DERIVATION_IMPLICIT,
 
3888
                     unsigned_flag);
 
3889
    break;
 
3890
  }
 
3891
  case STRING_RESULT:
 
3892
  {
 
3893
    if (!save_result.vstr)                                      // Null value
 
3894
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
 
3895
                       DERIVATION_IMPLICIT, 0);
 
3896
    else
 
3897
      res= update_hash((void*) save_result.vstr->ptr(),
 
3898
                       save_result.vstr->length(), STRING_RESULT,
 
3899
                       save_result.vstr->charset(),
 
3900
                       DERIVATION_IMPLICIT, 0);
 
3901
    break;
 
3902
  }
 
3903
  case DECIMAL_RESULT:
 
3904
  {
 
3905
    if (!save_result.vdec)                                      // Null value
 
3906
      res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin,
 
3907
                       DERIVATION_IMPLICIT, 0);
 
3908
    else
 
3909
      res= update_hash((void*) save_result.vdec,
 
3910
                       sizeof(my_decimal), DECIMAL_RESULT,
 
3911
                       &my_charset_bin, DERIVATION_IMPLICIT, 0);
 
3912
    break;
 
3913
  }
 
3914
  case ROW_RESULT:
 
3915
  default:
 
3916
    // This case should never be chosen
 
3917
    DBUG_ASSERT(0);
 
3918
    break;
 
3919
  }
 
3920
  DBUG_RETURN(res);
 
3921
}
 
3922
 
 
3923
 
 
3924
double Item_func_set_user_var::val_real()
 
3925
{
 
3926
  DBUG_ASSERT(fixed == 1);
 
3927
  check(0);
 
3928
  update();                                     // Store expression
 
3929
  return entry->val_real(&null_value);
 
3930
}
 
3931
 
 
3932
longlong Item_func_set_user_var::val_int()
 
3933
{
 
3934
  DBUG_ASSERT(fixed == 1);
 
3935
  check(0);
 
3936
  update();                                     // Store expression
 
3937
  return entry->val_int(&null_value);
 
3938
}
 
3939
 
 
3940
String *Item_func_set_user_var::val_str(String *str)
 
3941
{
 
3942
  DBUG_ASSERT(fixed == 1);
 
3943
  check(0);
 
3944
  update();                                     // Store expression
 
3945
  return entry->val_str(&null_value, str, decimals);
 
3946
}
 
3947
 
 
3948
 
 
3949
my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
 
3950
{
 
3951
  DBUG_ASSERT(fixed == 1);
 
3952
  check(0);
 
3953
  update();                                     // Store expression
 
3954
  return entry->val_decimal(&null_value, val);
 
3955
}
 
3956
 
 
3957
 
 
3958
double Item_func_set_user_var::val_result()
 
3959
{
 
3960
  DBUG_ASSERT(fixed == 1);
 
3961
  check(TRUE);
 
3962
  update();                                     // Store expression
 
3963
  return entry->val_real(&null_value);
 
3964
}
 
3965
 
 
3966
longlong Item_func_set_user_var::val_int_result()
 
3967
{
 
3968
  DBUG_ASSERT(fixed == 1);
 
3969
  check(TRUE);
 
3970
  update();                                     // Store expression
 
3971
  return entry->val_int(&null_value);
 
3972
}
 
3973
 
 
3974
String *Item_func_set_user_var::str_result(String *str)
 
3975
{
 
3976
  DBUG_ASSERT(fixed == 1);
 
3977
  check(TRUE);
 
3978
  update();                                     // Store expression
 
3979
  return entry->val_str(&null_value, str, decimals);
 
3980
}
 
3981
 
 
3982
 
 
3983
my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
 
3984
{
 
3985
  DBUG_ASSERT(fixed == 1);
 
3986
  check(TRUE);
 
3987
  update();                                     // Store expression
 
3988
  return entry->val_decimal(&null_value, val);
 
3989
}
 
3990
 
 
3991
 
 
3992
void Item_func_set_user_var::print(String *str, enum_query_type query_type)
 
3993
{
 
3994
  str->append(STRING_WITH_LEN("(@"));
 
3995
  str->append(name.str, name.length);
 
3996
  str->append(STRING_WITH_LEN(":="));
 
3997
  args[0]->print(str, query_type);
 
3998
  str->append(')');
 
3999
}
 
4000
 
 
4001
 
 
4002
void Item_func_set_user_var::print_as_stmt(String *str,
 
4003
                                           enum_query_type query_type)
 
4004
{
 
4005
  str->append(STRING_WITH_LEN("set @"));
 
4006
  str->append(name.str, name.length);
 
4007
  str->append(STRING_WITH_LEN(":="));
 
4008
  args[0]->print(str, query_type);
 
4009
  str->append(')');
 
4010
}
 
4011
 
 
4012
bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg)
 
4013
{
 
4014
  if (result_field)
 
4015
  {
 
4016
    check(1);
 
4017
    update();
 
4018
    return protocol->store(result_field);
 
4019
  }
 
4020
  return Item::send(protocol, str_arg);
 
4021
}
 
4022
 
 
4023
void Item_func_set_user_var::make_field(Send_field *tmp_field)
 
4024
{
 
4025
  if (result_field)
 
4026
  {
 
4027
    result_field->make_field(tmp_field);
 
4028
    DBUG_ASSERT(tmp_field->table_name != 0);
 
4029
    if (Item::name)
 
4030
      tmp_field->col_name=Item::name;               // Use user supplied name
 
4031
  }
 
4032
  else
 
4033
    Item::make_field(tmp_field);
 
4034
}
 
4035
 
 
4036
 
 
4037
/*
 
4038
  Save the value of a user variable into a field
 
4039
 
 
4040
  SYNOPSIS
 
4041
    save_in_field()
 
4042
      field           target field to save the value to
 
4043
      no_conversion   flag indicating whether conversions are allowed
 
4044
 
 
4045
  DESCRIPTION
 
4046
    Save the function value into a field and update the user variable
 
4047
    accordingly. If a result field is defined and the target field doesn't
 
4048
    coincide with it then the value from the result field will be used as
 
4049
    the new value of the user variable.
 
4050
 
 
4051
    The reason to have this method rather than simply using the result
 
4052
    field in the val_xxx() methods is that the value from the result field
 
4053
    not always can be used when the result field is defined.
 
4054
    Let's consider the following cases:
 
4055
    1) when filling a tmp table the result field is defined but the value of it
 
4056
    is undefined because it has to be produced yet. Thus we can't use it.
 
4057
    2) on execution of an INSERT ... SELECT statement the save_in_field()
 
4058
    function will be called to fill the data in the new record. If the SELECT
 
4059
    part uses a tmp table then the result field is defined and should be
 
4060
    used in order to get the correct result.
 
4061
 
 
4062
    The difference between the SET_USER_VAR function and regular functions
 
4063
    like CONCAT is that the Item_func objects for the regular functions are
 
4064
    replaced by Item_field objects after the values of these functions have
 
4065
    been stored in a tmp table. Yet an object of the Item_field class cannot
 
4066
    be used to update a user variable.
 
4067
    Due to this we have to handle the result field in a special way here and
 
4068
    in the Item_func_set_user_var::send() function.
 
4069
 
 
4070
  RETURN VALUES
 
4071
    FALSE       Ok
 
4072
    TRUE        Error
 
4073
*/
 
4074
 
 
4075
int Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
 
4076
                                          bool can_use_result_field)
 
4077
{
 
4078
  bool use_result_field= (!can_use_result_field ? 0 :
 
4079
                          (result_field && result_field != field));
 
4080
  int error;
 
4081
 
 
4082
  /* Update the value of the user variable */
 
4083
  check(use_result_field);
 
4084
  update();
 
4085
 
 
4086
  if (result_type() == STRING_RESULT ||
 
4087
      (result_type() == REAL_RESULT && field->result_type() == STRING_RESULT))
 
4088
  {
 
4089
    String *result;
 
4090
    CHARSET_INFO *cs= collation.collation;
 
4091
    char buff[MAX_FIELD_WIDTH];         // Alloc buffer for small columns
 
4092
    str_value.set_quick(buff, sizeof(buff), cs);
 
4093
    result= entry->val_str(&null_value, &str_value, decimals);
 
4094
 
 
4095
    if (null_value)
 
4096
    {
 
4097
      str_value.set_quick(0, 0, cs);
 
4098
      return set_field_to_null_with_conversions(field, no_conversions);
 
4099
    }
 
4100
 
 
4101
    /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
 
4102
 
 
4103
    field->set_notnull();
 
4104
    error=field->store(result->ptr(),result->length(),cs);
 
4105
    str_value.set_quick(0, 0, cs);
 
4106
  }
 
4107
  else if (result_type() == REAL_RESULT)
 
4108
  {
 
4109
    double nr= entry->val_real(&null_value);
 
4110
    if (null_value)
 
4111
      return set_field_to_null(field);
 
4112
    field->set_notnull();
 
4113
    error=field->store(nr);
 
4114
  }
 
4115
  else if (result_type() == DECIMAL_RESULT)
 
4116
  {
 
4117
    my_decimal decimal_value;
 
4118
    my_decimal *val= entry->val_decimal(&null_value, &decimal_value);
 
4119
    if (null_value)
 
4120
      return set_field_to_null(field);
 
4121
    field->set_notnull();
 
4122
    error=field->store_decimal(val);
 
4123
  }
 
4124
  else
 
4125
  {
 
4126
    longlong nr= entry->val_int(&null_value);
 
4127
    if (null_value)
 
4128
      return set_field_to_null_with_conversions(field, no_conversions);
 
4129
    field->set_notnull();
 
4130
    error=field->store(nr, unsigned_flag);
 
4131
  }
 
4132
  return error;
 
4133
}
 
4134
 
 
4135
 
 
4136
String *
 
4137
Item_func_get_user_var::val_str(String *str)
 
4138
{
 
4139
  DBUG_ASSERT(fixed == 1);
 
4140
  DBUG_ENTER("Item_func_get_user_var::val_str");
 
4141
  if (!var_entry)
 
4142
    DBUG_RETURN((String*) 0);                   // No such variable
 
4143
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
 
4144
}
 
4145
 
 
4146
 
 
4147
double Item_func_get_user_var::val_real()
 
4148
{
 
4149
  DBUG_ASSERT(fixed == 1);
 
4150
  if (!var_entry)
 
4151
    return 0.0;                                 // No such variable
 
4152
  return (var_entry->val_real(&null_value));
 
4153
}
 
4154
 
 
4155
 
 
4156
my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
 
4157
{
 
4158
  DBUG_ASSERT(fixed == 1);
 
4159
  if (!var_entry)
 
4160
    return 0;
 
4161
  return var_entry->val_decimal(&null_value, dec);
 
4162
}
 
4163
 
 
4164
 
 
4165
longlong Item_func_get_user_var::val_int()
 
4166
{
 
4167
  DBUG_ASSERT(fixed == 1);
 
4168
  if (!var_entry)
 
4169
    return LL(0);                               // No such variable
 
4170
  return (var_entry->val_int(&null_value));
 
4171
}
 
4172
 
 
4173
 
 
4174
/**
 
4175
  Get variable by name and, if necessary, put the record of variable 
 
4176
  use into the binary log.
 
4177
 
 
4178
  When a user variable is invoked from an update query (INSERT, UPDATE etc),
 
4179
  stores this variable and its value in thd->user_var_events, so that it can be
 
4180
  written to the binlog (will be written just before the query is written, see
 
4181
  log.cc).
 
4182
 
 
4183
  @param      thd        Current thread
 
4184
  @param      name       Variable name
 
4185
  @param[out] out_entry  variable structure or NULL. The pointer is set
 
4186
                         regardless of whether function succeeded or not.
 
4187
 
 
4188
  @retval
 
4189
    0  OK
 
4190
  @retval
 
4191
    1  Failed to put appropriate record into binary log
 
4192
 
 
4193
*/
 
4194
 
 
4195
int get_var_with_binlog(THD *thd, enum_sql_command sql_command,
 
4196
                        LEX_STRING &name, user_var_entry **out_entry)
 
4197
{
 
4198
  BINLOG_USER_VAR_EVENT *user_var_event;
 
4199
  user_var_entry *var_entry;
 
4200
  var_entry= get_variable(&thd->user_vars, name, 0);
 
4201
 
 
4202
  /*
 
4203
    Any reference to user-defined variable which is done from stored
 
4204
    function or trigger affects their execution and the execution of the
 
4205
    calling statement. We must log all such variables even if they are 
 
4206
    not involved in table-updating statements.
 
4207
  */
 
4208
  if (!(opt_bin_log && 
 
4209
       (is_update_query(sql_command) || thd->in_sub_stmt)))
 
4210
  {
 
4211
    *out_entry= var_entry;
 
4212
    return 0;
 
4213
  }
 
4214
 
 
4215
  if (!var_entry)
 
4216
  {
 
4217
    /*
 
4218
      If the variable does not exist, it's NULL, but we want to create it so
 
4219
      that it gets into the binlog (if it didn't, the slave could be
 
4220
      influenced by a variable of the same name previously set by another
 
4221
      thread).
 
4222
      We create it like if it had been explicitly set with SET before.
 
4223
      The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
 
4224
      sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
 
4225
      in dispatch_command()). Instead of building a one-element list to pass to
 
4226
      sql_set_variables(), we could instead manually call check() and update();
 
4227
      this would save memory and time; but calling sql_set_variables() makes
 
4228
      one unique place to maintain (sql_set_variables()). 
 
4229
 
 
4230
      Manipulation with lex is necessary since free_underlaid_joins
 
4231
      is going to release memory belonging to the main query.
 
4232
    */
 
4233
 
 
4234
    List<set_var_base> tmp_var_list;
 
4235
    LEX *sav_lex= thd->lex, lex_tmp;
 
4236
    thd->lex= &lex_tmp;
 
4237
    lex_start(thd);
 
4238
    tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
 
4239
                                                                       new Item_null())));
 
4240
    /* Create the variable */
 
4241
    if (sql_set_variables(thd, &tmp_var_list))
 
4242
    {
 
4243
      thd->lex= sav_lex;
 
4244
      goto err;
 
4245
    }
 
4246
    thd->lex= sav_lex;
 
4247
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
 
4248
      goto err;
 
4249
  }
 
4250
  else if (var_entry->used_query_id == thd->query_id ||
 
4251
           mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
 
4252
  {
 
4253
    /* 
 
4254
       If this variable was already stored in user_var_events by this query
 
4255
       (because it's used in more than one place in the query), don't store
 
4256
       it.
 
4257
    */
 
4258
    *out_entry= var_entry;
 
4259
    return 0;
 
4260
  }
 
4261
 
 
4262
  uint size;
 
4263
  /*
 
4264
    First we need to store value of var_entry, when the next situation
 
4265
    appears:
 
4266
    > set @a:=1;
 
4267
    > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
 
4268
    We have to write to binlog value @a= 1.
 
4269
 
 
4270
    We allocate the user_var_event on user_var_events_alloc pool, not on
 
4271
    the this-statement-execution pool because in SPs user_var_event objects 
 
4272
    may need to be valid after current [SP] statement execution pool is
 
4273
    destroyed.
 
4274
  */
 
4275
  size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;
 
4276
  if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
 
4277
        alloc_root(thd->user_var_events_alloc, size)))
 
4278
    goto err;
 
4279
 
 
4280
  user_var_event->value= (char*) user_var_event +
 
4281
    ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
 
4282
  user_var_event->user_var_event= var_entry;
 
4283
  user_var_event->type= var_entry->type;
 
4284
  user_var_event->charset_number= var_entry->collation.collation->number;
 
4285
  if (!var_entry->value)
 
4286
  {
 
4287
    /* NULL value*/
 
4288
    user_var_event->length= 0;
 
4289
    user_var_event->value= 0;
 
4290
  }
 
4291
  else
 
4292
  {
 
4293
    user_var_event->length= var_entry->length;
 
4294
    memcpy(user_var_event->value, var_entry->value,
 
4295
           var_entry->length);
 
4296
  }
 
4297
  /* Mark that this variable has been used by this query */
 
4298
  var_entry->used_query_id= thd->query_id;
 
4299
  if (insert_dynamic(&thd->user_var_events, (uchar*) &user_var_event))
 
4300
    goto err;
 
4301
 
 
4302
  *out_entry= var_entry;
 
4303
  return 0;
 
4304
 
 
4305
err:
 
4306
  *out_entry= var_entry;
 
4307
  return 1;
 
4308
}
 
4309
 
 
4310
void Item_func_get_user_var::fix_length_and_dec()
 
4311
{
 
4312
  THD *thd=current_thd;
 
4313
  int error;
 
4314
  maybe_null=1;
 
4315
  decimals=NOT_FIXED_DEC;
 
4316
  max_length=MAX_BLOB_WIDTH;
 
4317
 
 
4318
  error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
 
4319
 
 
4320
  /*
 
4321
    If the variable didn't exist it has been created as a STRING-type.
 
4322
    'var_entry' is NULL only if there occured an error during the call to
 
4323
    get_var_with_binlog.
 
4324
  */
 
4325
  if (var_entry)
 
4326
  {
 
4327
    m_cached_result_type= var_entry->type;
 
4328
    unsigned_flag= var_entry->unsigned_flag;
 
4329
    max_length= var_entry->length;
 
4330
 
 
4331
    collation.set(var_entry->collation);
 
4332
    switch(m_cached_result_type) {
 
4333
    case REAL_RESULT:
 
4334
      max_length= DBL_DIG + 8;
 
4335
      break;
 
4336
    case INT_RESULT:
 
4337
      max_length= MAX_BIGINT_WIDTH;
 
4338
      decimals=0;
 
4339
      break;
 
4340
    case STRING_RESULT:
 
4341
      max_length= MAX_BLOB_WIDTH;
 
4342
      break;
 
4343
    case DECIMAL_RESULT:
 
4344
      max_length= DECIMAL_MAX_STR_LENGTH;
 
4345
      decimals= DECIMAL_MAX_SCALE;
 
4346
      break;
 
4347
    case ROW_RESULT:                            // Keep compiler happy
 
4348
    default:
 
4349
      DBUG_ASSERT(0);
 
4350
      break;
 
4351
    }
 
4352
  }
 
4353
  else
 
4354
  {
 
4355
    collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
 
4356
    null_value= 1;
 
4357
    m_cached_result_type= STRING_RESULT;
 
4358
    max_length= MAX_BLOB_WIDTH;
 
4359
  }
 
4360
}
 
4361
 
 
4362
 
 
4363
bool Item_func_get_user_var::const_item() const
 
4364
{
 
4365
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
 
4366
}
 
4367
 
 
4368
 
 
4369
enum Item_result Item_func_get_user_var::result_type() const
 
4370
{
 
4371
  return m_cached_result_type;
 
4372
}
 
4373
 
 
4374
 
 
4375
void Item_func_get_user_var::print(String *str, enum_query_type query_type)
 
4376
{
 
4377
  str->append(STRING_WITH_LEN("(@"));
 
4378
  str->append(name.str,name.length);
 
4379
  str->append(')');
 
4380
}
 
4381
 
 
4382
 
 
4383
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
 
4384
{
 
4385
  /* Assume we don't have rtti */
 
4386
  if (this == item)
 
4387
    return 1;                                   // Same item is same.
 
4388
  /* Check if other type is also a get_user_var() object */
 
4389
  if (item->type() != FUNC_ITEM ||
 
4390
      ((Item_func*) item)->functype() != functype())
 
4391
    return 0;
 
4392
  Item_func_get_user_var *other=(Item_func_get_user_var*) item;
 
4393
  return (name.length == other->name.length &&
 
4394
          !memcmp(name.str, other->name.str, name.length));
 
4395
}
 
4396
 
 
4397
 
 
4398
bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
 
4399
{
 
4400
  DBUG_ASSERT(fixed == 0);
 
4401
  if (Item::fix_fields(thd, ref) ||
 
4402
      !(entry= get_variable(&thd->user_vars, name, 1)))
 
4403
    return TRUE;
 
4404
  entry->type= STRING_RESULT;
 
4405
  /*
 
4406
    Let us set the same collation which is used for loading
 
4407
    of fields in LOAD DATA INFILE.
 
4408
    (Since Item_user_var_as_out_param is used only there).
 
4409
  */
 
4410
  entry->collation.set(thd->variables.collation_database);
 
4411
  entry->update_query_id= thd->query_id;
 
4412
  return FALSE;
 
4413
}
 
4414
 
 
4415
 
 
4416
void Item_user_var_as_out_param::set_null_value(CHARSET_INFO* cs)
 
4417
{
 
4418
  ::update_hash(entry, TRUE, 0, 0, STRING_RESULT, cs,
 
4419
                DERIVATION_IMPLICIT, 0 /* unsigned_arg */);
 
4420
}
 
4421
 
 
4422
 
 
4423
void Item_user_var_as_out_param::set_value(const char *str, uint length,
 
4424
                                           CHARSET_INFO* cs)
 
4425
{
 
4426
  ::update_hash(entry, FALSE, (void*)str, length, STRING_RESULT, cs,
 
4427
                DERIVATION_IMPLICIT, 0 /* unsigned_arg */);
 
4428
}
 
4429
 
 
4430
 
 
4431
double Item_user_var_as_out_param::val_real()
 
4432
{
 
4433
  DBUG_ASSERT(0);
 
4434
  return 0.0;
 
4435
}
 
4436
 
 
4437
 
 
4438
longlong Item_user_var_as_out_param::val_int()
 
4439
{
 
4440
  DBUG_ASSERT(0);
 
4441
  return 0;
 
4442
}
 
4443
 
 
4444
 
 
4445
String* Item_user_var_as_out_param::val_str(String *str)
 
4446
{
 
4447
  DBUG_ASSERT(0);
 
4448
  return 0;
 
4449
}
 
4450
 
 
4451
 
 
4452
my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
 
4453
{
 
4454
  DBUG_ASSERT(0);
 
4455
  return 0;
 
4456
}
 
4457
 
 
4458
 
 
4459
void Item_user_var_as_out_param::print(String *str, enum_query_type query_type)
 
4460
{
 
4461
  str->append('@');
 
4462
  str->append(name.str,name.length);
 
4463
}
 
4464
 
 
4465
 
 
4466
Item_func_get_system_var::
 
4467
Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
 
4468
                       LEX_STRING *component_arg, const char *name_arg,
 
4469
                       size_t name_len_arg)
 
4470
  :var(var_arg), var_type(var_type_arg), component(*component_arg)
 
4471
{
 
4472
  /* set_name() will allocate the name */
 
4473
  set_name(name_arg, name_len_arg, system_charset_info);
 
4474
}
 
4475
 
 
4476
 
 
4477
bool
 
4478
Item_func_get_system_var::fix_fields(THD *thd, Item **ref)
 
4479
{
 
4480
  Item *item;
 
4481
  DBUG_ENTER("Item_func_get_system_var::fix_fields");
 
4482
 
 
4483
  /*
 
4484
    Evaluate the system variable and substitute the result (a basic constant)
 
4485
    instead of this item. If the variable can not be evaluated,
 
4486
    the error is reported in sys_var::item().
 
4487
  */
 
4488
  if (!(item= var->item(thd, var_type, &component)))
 
4489
    DBUG_RETURN(1);                             // Impossible
 
4490
  item->set_name(name, 0, system_charset_info); // don't allocate a new name
 
4491
  thd->change_item_tree(ref, item);
 
4492
 
 
4493
  DBUG_RETURN(0);
 
4494
}
 
4495
 
 
4496
 
 
4497
bool Item_func_get_system_var::is_written_to_binlog()
 
4498
{
 
4499
  return var->is_written_to_binlog(var_type);
 
4500
}
 
4501
 
 
4502
longlong Item_func_bit_xor::val_int()
 
4503
{
 
4504
  DBUG_ASSERT(fixed == 1);
 
4505
  ulonglong arg1= (ulonglong) args[0]->val_int();
 
4506
  ulonglong arg2= (ulonglong) args[1]->val_int();
 
4507
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
 
4508
    return 0;
 
4509
  return (longlong) (arg1 ^ arg2);
 
4510
}
 
4511
 
 
4512
 
 
4513
/***************************************************************************
 
4514
  System variables
 
4515
****************************************************************************/
 
4516
 
 
4517
/**
 
4518
  Return value of an system variable base[.name] as a constant item.
 
4519
 
 
4520
  @param thd                    Thread handler
 
4521
  @param var_type               global / session
 
4522
  @param name                   Name of base or system variable
 
4523
  @param component              Component.
 
4524
 
 
4525
  @note
 
4526
    If component.str = 0 then the variable name is in 'name'
 
4527
 
 
4528
  @return
 
4529
    - 0  : error
 
4530
    - #  : constant item
 
4531
*/
 
4532
 
 
4533
 
 
4534
Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
 
4535
                     LEX_STRING component)
 
4536
{
 
4537
  sys_var *var;
 
4538
  LEX_STRING *base_name, *component_name;
 
4539
 
 
4540
  if (component.str)
 
4541
  {
 
4542
    base_name= &component;
 
4543
    component_name= &name;
 
4544
  }
 
4545
  else
 
4546
  {
 
4547
    base_name= &name;
 
4548
    component_name= &component;                 // Empty string
 
4549
  }
 
4550
 
 
4551
  if (!(var= find_sys_var(thd, base_name->str, base_name->length)))
 
4552
    return 0;
 
4553
  if (component.str)
 
4554
  {
 
4555
    if (!var->is_struct())
 
4556
    {
 
4557
      my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
 
4558
      return 0;
 
4559
    }
 
4560
  }
 
4561
 
 
4562
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
 
4563
 
 
4564
  return new Item_func_get_system_var(var, var_type, component_name,
 
4565
                                      NULL, 0);
 
4566
}
 
4567
 
 
4568
 
 
4569
/**
 
4570
  Check a user level lock.
 
4571
 
 
4572
  Sets null_value=TRUE on error.
 
4573
 
 
4574
  @retval
 
4575
    1           Available
 
4576
  @retval
 
4577
    0           Already taken, or error
 
4578
*/
 
4579
 
 
4580
longlong Item_func_is_free_lock::val_int()
 
4581
{
 
4582
  DBUG_ASSERT(fixed == 1);
 
4583
  String *res=args[0]->val_str(&value);
 
4584
  User_level_lock *ull;
 
4585
 
 
4586
  null_value=0;
 
4587
  if (!res || !res->length())
 
4588
  {
 
4589
    null_value=1;
 
4590
    return 0;
 
4591
  }
 
4592
  
 
4593
  pthread_mutex_lock(&LOCK_user_locks);
 
4594
  ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(),
 
4595
                                       (size_t) res->length());
 
4596
  pthread_mutex_unlock(&LOCK_user_locks);
 
4597
  if (!ull || !ull->locked)
 
4598
    return 1;
 
4599
  return 0;
 
4600
}
 
4601
 
 
4602
longlong Item_func_is_used_lock::val_int()
 
4603
{
 
4604
  DBUG_ASSERT(fixed == 1);
 
4605
  String *res=args[0]->val_str(&value);
 
4606
  User_level_lock *ull;
 
4607
 
 
4608
  null_value=1;
 
4609
  if (!res || !res->length())
 
4610
    return 0;
 
4611
  
 
4612
  pthread_mutex_lock(&LOCK_user_locks);
 
4613
  ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(),
 
4614
                                       (size_t) res->length());
 
4615
  pthread_mutex_unlock(&LOCK_user_locks);
 
4616
  if (!ull || !ull->locked)
 
4617
    return 0;
 
4618
 
 
4619
  null_value=0;
 
4620
  return ull->thread_id;
 
4621
}
 
4622
 
 
4623
 
 
4624
longlong Item_func_row_count::val_int()
 
4625
{
 
4626
  DBUG_ASSERT(fixed == 1);
 
4627
  THD *thd= current_thd;
 
4628
 
 
4629
  return thd->row_count_func;
 
4630
}
 
4631
 
 
4632
longlong Item_func_found_rows::val_int()
 
4633
{
 
4634
  DBUG_ASSERT(fixed == 1);
 
4635
  THD *thd= current_thd;
 
4636
 
 
4637
  return thd->found_rows();
 
4638
}
 
4639
 
 
4640
 
 
4641
 
 
4642
/*
 
4643
  uuid_short handling.
 
4644
 
 
4645
  The short uuid is defined as a longlong that contains the following bytes:
 
4646
 
 
4647
  Bytes  Comment
 
4648
  1      Server_id & 255
 
4649
  4      Startup time of server in seconds
 
4650
  3      Incrementor
 
4651
 
 
4652
  This means that an uuid is guaranteed to be unique
 
4653
  even in a replication environment if the following holds:
 
4654
 
 
4655
  - The last byte of the server id is unique
 
4656
  - If you between two shutdown of the server don't get more than
 
4657
    an average of 2^24 = 16M calls to uuid_short() per second.
 
4658
*/
 
4659
 
 
4660
ulonglong uuid_value;
 
4661
 
 
4662
void uuid_short_init()
 
4663
{
 
4664
  uuid_value= ((((ulonglong) server_id) << 56) + 
 
4665
               (((ulonglong) server_start_time) << 24));
 
4666
}
 
4667
 
 
4668
 
 
4669
longlong Item_func_uuid_short::val_int()
 
4670
{
 
4671
  ulonglong val;
 
4672
  pthread_mutex_lock(&LOCK_uuid_generator);
 
4673
  val= uuid_value++;
 
4674
  pthread_mutex_unlock(&LOCK_uuid_generator);
 
4675
  return (longlong) val;
 
4676
}