~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/item_func.cc

  • Committer: Monty Taylor
  • Date: 2008-09-15 17:24:04 UTC
  • Revision ID: monty@inaugust.com-20080915172404-ygh6hiyu0q7qpa9x
Removed strndup calls.

Show diffs side-by-side

added added

removed removed

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