~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to server/item_func.cc

  • Committer: Jim Winstead
  • Date: 2008-07-19 02:56:45 UTC
  • mto: (202.1.8 codestyle)
  • mto: This revision was merged to the branch mainline in revision 207.
  • Revision ID: jimw@mysql.com-20080719025645-w2pwytebgzusjzjb
Various fixes to enable compilation on Mac OS X, and remove the glib dependency.
Temporarily disables tab-completion in the drizzle client until an appropriate
autoconf check can be added/enabled.

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