~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to sql/item_func.cc

Merged from trunk.

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