~drizzle-trunk/drizzle/development

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