item_func.cc 139 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2003 MySQL AB
unknown's avatar
unknown committed
2 3 4

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6 7 8 9 10 11 12 13 14 15 16 17 18

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* This file defines all numerical functions */

19
#ifdef USE_PRAGMA_IMPLEMENTATION
unknown's avatar
unknown committed
20 21 22 23
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
unknown's avatar
unknown committed
24
#include "slave.h"				// for wait_for_master_pos
25
#include "rpl_mi.h"
unknown's avatar
unknown committed
26 27 28 29 30
#include <m_ctype.h>
#include <hash.h>
#include <time.h>
#include <ft_global.h>

31 32 33
#include "sp_head.h"
#include "sp_rcontext.h"
#include "sp.h"
unknown's avatar
unknown committed
34

unknown's avatar
unknown committed
35 36 37 38
#ifdef NO_EMBEDDED_ACCESS_CHECKS
#define sp_restore_security_context(A,B) while (0) {}
#endif

39 40 41 42 43 44 45 46 47 48
bool check_reserved_words(LEX_STRING *name)
{
  if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") ||
      !my_strcasecmp(system_charset_info, name->str, "LOCAL") ||
      !my_strcasecmp(system_charset_info, name->str, "SESSION"))
    return TRUE;
  return FALSE;
}


unknown's avatar
unknown committed
49 50 51 52 53 54 55 56
/* return TRUE if item is a constant */

bool
eval_const_cond(COND *cond)
{
  return ((Item_func*) cond)->val_int() ? TRUE : FALSE;
}

unknown's avatar
unknown committed
57

58
void Item_func::set_arguments(List<Item> &list)
unknown's avatar
unknown committed
59
{
60
  allowed_arg_cols= 1;
unknown's avatar
unknown committed
61
  arg_count=list.elements;
unknown's avatar
unknown committed
62 63
  args= tmp_arg;                                // If 2 arguments
  if (arg_count <= 2 || (args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
unknown's avatar
unknown committed
64
  {
unknown's avatar
unknown committed
65
    List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
66
    Item *item;
unknown's avatar
unknown committed
67
    Item **save_args= args;
unknown's avatar
unknown committed
68 69 70

    while ((item=li++))
    {
unknown's avatar
unknown committed
71
      *(save_args++)= item;
unknown's avatar
unknown committed
72 73 74 75 76 77
      with_sum_func|=item->with_sum_func;
    }
  }
  list.empty();					// Fields are used
}

78 79 80 81 82 83
Item_func::Item_func(List<Item> &list)
  :allowed_arg_cols(1)
{
  set_arguments(list);
}

84
Item_func::Item_func(THD *thd, Item_func *item)
85
  :Item_result_field(thd, item),
86 87 88 89 90
   allowed_arg_cols(item->allowed_arg_cols),
   arg_count(item->arg_count),
   used_tables_cache(item->used_tables_cache),
   not_null_tables_cache(item->not_null_tables_cache),
   const_item_cache(item->const_item_cache)
91 92 93 94 95 96 97 98 99 100
{
  if (arg_count)
  {
    if (arg_count <=2)
      args= tmp_arg;
    else
    {
      if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
	return;
    }
101
    memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count);
102 103 104
  }
}

unknown's avatar
unknown committed
105 106

/*
107
  Resolve references to table column for a function and its argument
unknown's avatar
unknown committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

  SYNOPSIS:
  fix_fields()
  thd		Thread object
  ref		Pointer to where this object is used.  This reference
		is used if we want to replace this object with another
		one (for example in the summary functions).

  DESCRIPTION
    Call fix_fields() for all arguments to the function.  The main intention
    is to allow all Item_field() objects to setup pointers to the table fields.

    Sets as a side effect the following class variables:
      maybe_null	Set if any argument may return NULL
      with_sum_func	Set if any of the arguments contains a sum function
unknown's avatar
unknown committed
123
      used_tables_cache Set to union of the tables used by arguments
unknown's avatar
unknown committed
124 125 126

      str_value.charset If this is a string function, set this to the
			character set for the first argument.
127
			If any argument is binary, this is set to binary
unknown's avatar
unknown committed
128 129 130 131 132 133 134

   If for any item any of the defaults are wrong, then this can
   be fixed in the fix_length_and_dec() function that is called
   after this one or by writing a specialized fix_fields() for the
   item.

  RETURN VALUES
unknown's avatar
unknown committed
135 136
  FALSE	ok
  TRUE	Got error.  Stored with my_error().
unknown's avatar
unknown committed
137 138
*/

unknown's avatar
unknown committed
139
bool
140
Item_func::fix_fields(THD *thd, Item **ref)
unknown's avatar
unknown committed
141
{
142
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
143
  Item **arg,**arg_end;
144
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
145
  uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
146
#endif
147

148
  used_tables_cache= not_null_tables_cache= 0;
unknown's avatar
unknown committed
149 150
  const_item_cache=1;

151
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
unknown's avatar
unknown committed
152
    return TRUE;				// Fatal error if flag is set!
unknown's avatar
unknown committed
153 154 155 156
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
unknown's avatar
unknown committed
157
      Item *item;
unknown's avatar
merge  
unknown committed
158 159 160 161
      /*
	We can't yet set item to *arg as fix_fields may change *arg
	We shouldn't call fix_fields() twice, so check 'fixed' field first
      */
162
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg)))
unknown's avatar
unknown committed
163
	return TRUE;				/* purecov: inspected */
unknown's avatar
unknown committed
164
      item= *arg;
165 166 167 168 169 170 171 172 173 174 175 176 177 178

      if (allowed_arg_cols)
      {
        if (item->check_cols(allowed_arg_cols))
          return 1;
      }
      else
      {
        /*  we have to fetch allowed_arg_cols from first argument */
        DBUG_ASSERT(arg == args); // it is first argument
        allowed_arg_cols= item->cols();
        DBUG_ASSERT(allowed_arg_cols); // Can't be 0 any more
      }

unknown's avatar
unknown committed
179
      if (item->maybe_null)
unknown's avatar
unknown committed
180
	maybe_null=1;
181

unknown's avatar
unknown committed
182
      with_sum_func= with_sum_func || item->with_sum_func;
183 184 185
      used_tables_cache|=     item->used_tables();
      not_null_tables_cache|= item->not_null_tables();
      const_item_cache&=      item->const_item();
186
      with_subselect|=        item->with_subselect;
unknown's avatar
unknown committed
187 188 189
    }
  }
  fix_length_and_dec();
unknown's avatar
unknown committed
190 191
  if (thd->net.report_error) // An error inside fix_length_and_dec occured
    return TRUE;
192
  fixed= 1;
unknown's avatar
unknown committed
193
  return FALSE;
unknown's avatar
unknown committed
194 195
}

196 197

bool Item_func::walk(Item_processor processor, bool walk_subquery,
198
                     uchar *argument)
unknown's avatar
unknown committed
199 200 201 202 203 204
{
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
205
      if ((*arg)->walk(processor, walk_subquery, argument))
unknown's avatar
unknown committed
206 207 208 209 210
	return 1;
    }
  }
  return (this->*processor)(argument);
}
211

212 213
void Item_func::traverse_cond(Cond_traverser traverser,
                              void *argument, traverse_order order)
214 215 216 217
{
  if (arg_count)
  {
    Item **arg,**arg_end;
218 219 220

    switch (order) {
    case(PREFIX):
unknown's avatar
unknown committed
221
      (*traverser)(this, argument);
222 223 224 225 226 227 228 229 230 231
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
      {
	(*arg)->traverse_cond(traverser, argument, order);
      }
      break;
    case (POSTFIX):
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
      {
	(*arg)->traverse_cond(traverser, argument, order);
      }
unknown's avatar
unknown committed
232
      (*traverser)(this, argument);
233 234
    }
  }
235 236
  else
    (*traverser)(this, argument);
237 238
}

unknown's avatar
unknown committed
239 240 241 242 243 244

/*
  Transform an Item_func object with a transformer callback function
   
  SYNOPSIS
    transform()
245 246 247
      transformer   the transformer callback function to be applied to the nodes
                    of the tree of the object
      argument      parameter to be passed to the transformer
unknown's avatar
unknown committed
248 249
  
  DESCRIPTION
250 251 252
    The function recursively applies the transform method to each
    argument of the Item_func node.
    If the call of the method for an argument item returns a new item
unknown's avatar
unknown committed
253
    the old item is substituted for a new one.
254
    After this the transformer is applied to the root node
unknown's avatar
unknown committed
255 256 257 258 259 260
    of the Item_func object. 
     
  RETURN VALUES
    Item returned as the result of transformation of the root node 
*/

261
Item *Item_func::transform(Item_transformer transformer, uchar *argument)
262
{
263 264
  DBUG_ASSERT(!current_thd->is_stmt_prepare());

265 266 267 268 269
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
unknown's avatar
unknown committed
270
      Item *new_item= (*arg)->transform(transformer, argument);
271 272
      if (!new_item)
	return 0;
273 274 275 276 277 278 279

      /*
        THD::change_item_tree() should be called only if the tree was
        really transformed, i.e. when a new item has been created.
        Otherwise we'll be allocating a lot of unnecessary memory for
        change records at each execution.
      */
unknown's avatar
unknown committed
280 281
      if (*arg != new_item)
        current_thd->change_item_tree(arg, new_item);
282 283
    }
  }
unknown's avatar
unknown committed
284
  return (this->*transformer)(argument);
285 286 287
}


288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
/*
  Compile Item_func object with a processor and a transformer callback functions
   
  SYNOPSIS
    compile()
      analyzer      the analyzer callback function to be applied to the nodes
                    of the tree of the object
      arg_p         in/out parameter to be passed to the processor
      transformer   the transformer callback function to be applied to the nodes
                    of the tree of the object
      arg_t         parameter to be passed to the transformer
  
  DESCRIPTION
    First the function applies the analyzer to the root node of
    the Item_func object. Then if the analizer succeeeds (returns TRUE)
    the function recursively applies the compile method to each argument
    of the Item_func node.
    If the call of the method for an argument item returns a new item
    the old item is substituted for a new one.
    After this the transformer is applied to the root node
    of the Item_func object. 
     
  RETURN VALUES
    Item returned as the result of transformation of the root node 
*/

314 315
Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p,
                         Item_transformer transformer, uchar *arg_t)
316 317 318 319 320 321 322 323 324 325 326 327
{
  if (!(this->*analyzer)(arg_p))
    return 0;
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
      /* 
        The same parameter value of arg_p must be passed
        to analyze any argument of the condition formula.
      */   
328
      uchar *arg_v= *arg_p;
329 330 331 332 333 334 335 336
      Item *new_item= (*arg)->compile(analyzer, &arg_v, transformer, arg_t);
      if (new_item && *arg != new_item)
        current_thd->change_item_tree(arg, new_item);
    }
  }
  return (this->*transformer)(arg_t);
}

337 338
/* See comments in Item_cmp_func::split_sum_func() */

339 340
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
                               List<Item> &fields)
unknown's avatar
unknown committed
341
{
342 343
  Item **arg, **arg_end;
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
unknown's avatar
unknown committed
344
    (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE);
unknown's avatar
unknown committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
}


void Item_func::update_used_tables()
{
  used_tables_cache=0;
  const_item_cache=1;
  for (uint i=0 ; i < arg_count ; i++)
  {
    args[i]->update_used_tables();
    used_tables_cache|=args[i]->used_tables();
    const_item_cache&=args[i]->const_item();
  }
}


table_map Item_func::used_tables() const
{
  return used_tables_cache;
}

366 367 368 369 370 371 372

table_map Item_func::not_null_tables() const
{
  return not_null_tables_cache;
}


unknown's avatar
unknown committed
373 374 375 376
void Item_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
unknown's avatar
unknown committed
377
  print_args(str, 0);
378 379 380 381
  str->append(')');
}


unknown's avatar
unknown committed
382
void Item_func::print_args(String *str, uint from)
383
{
unknown's avatar
unknown committed
384
  for (uint i=from ; i < arg_count ; i++)
unknown's avatar
unknown committed
385
  {
unknown's avatar
unknown committed
386
    if (i != from)
unknown's avatar
unknown committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
      str->append(',');
    args[i]->print(str);
  }
}


void Item_func::print_op(String *str)
{
  str->append('(');
  for (uint i=0 ; i < arg_count-1 ; i++)
  {
    args[i]->print(str);
    str->append(' ');
    str->append(func_name());
    str->append(' ');
  }
  args[arg_count-1]->print(str);
  str->append(')');
}

unknown's avatar
unknown committed
407

408
bool Item_func::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
409 410 411 412 413 414 415
{
  /* Assume we don't have rtti */
  if (this == item)
    return 1;
  if (item->type() != FUNC_ITEM)
    return 0;
  Item_func *item_func=(Item_func*) item;
416 417 418 419 420 421 422
  Item_func::Functype func_type;
  if ((func_type= functype()) != item_func->functype() ||
      arg_count != item_func->arg_count ||
      (func_type != Item_func::FUNC_SP &&
       func_name() != item_func->func_name()) ||
      (func_type == Item_func::FUNC_SP &&
       my_strcasecmp(system_charset_info, func_name(), item_func->func_name())))
unknown's avatar
unknown committed
423 424
    return 0;
  for (uint i=0; i < arg_count ; i++)
425
    if (!args[i]->eq(item_func->args[i], binary_cmp))
unknown's avatar
unknown committed
426 427 428 429
      return 0;
  return 1;
}

430

unknown's avatar
unknown committed
431
Field *Item_func::tmp_table_field(TABLE *table)
432
{
unknown's avatar
unknown committed
433 434
  Field *field;
  LINT_INIT(field);
435

unknown's avatar
unknown committed
436
  switch (result_type()) {
437
  case INT_RESULT:
438
    if (max_length > MY_INT32_NUM_DECIMAL_DIGITS)
unknown's avatar
unknown committed
439
      field= new Field_longlong(max_length, maybe_null, name, unsigned_flag);
440
    else
unknown's avatar
unknown committed
441
      field= new Field_long(max_length, maybe_null, name, unsigned_flag);
442 443
    break;
  case REAL_RESULT:
unknown's avatar
unknown committed
444
    field= new Field_double(max_length, maybe_null, name, decimals);
445 446
    break;
  case STRING_RESULT:
unknown's avatar
unknown committed
447
    return make_string_field(table);
448
    break;
unknown's avatar
unknown committed
449
  case DECIMAL_RESULT:
unknown's avatar
unknown committed
450 451 452 453
    field= new Field_new_decimal(my_decimal_precision_to_length(decimal_precision(),
                                                                decimals,
                                                                unsigned_flag),
                                 maybe_null, name, decimals, unsigned_flag);
unknown's avatar
unknown committed
454
    break;
455
  case ROW_RESULT:
unknown's avatar
unknown committed
456
  default:
unknown's avatar
unknown committed
457
    // This case should never be chosen
unknown's avatar
unknown committed
458
    DBUG_ASSERT(0);
unknown's avatar
unknown committed
459
    field= 0;
unknown's avatar
unknown committed
460
    break;
461
  }
unknown's avatar
unknown committed
462 463 464
  if (field)
    field->init(table);
  return field;
465 466
}

unknown's avatar
unknown committed
467

468
bool Item_func::is_expensive_processor(uchar *arg)
469
{
470
  return is_expensive();
471 472 473
}


unknown's avatar
unknown committed
474 475 476 477 478 479 480
my_decimal *Item_func::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(fixed);
  int2my_decimal(E_DEC_FATAL_ERROR, val_int(), unsigned_flag, decimal_value);
  return decimal_value;
}

481

unknown's avatar
unknown committed
482 483
String *Item_real_func::val_str(String *str)
{
484
  DBUG_ASSERT(fixed == 1);
485
  double nr= val_real();
unknown's avatar
unknown committed
486 487
  if (null_value)
    return 0; /* purecov: inspected */
488
  str->set_real(nr,decimals, &my_charset_bin);
unknown's avatar
unknown committed
489 490 491 492
  return str;
}


493 494 495 496 497 498 499 500 501 502 503
my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(fixed);
  double nr= val_real();
  if (null_value)
    return 0; /* purecov: inspected */
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
  return decimal_value;
}


unknown's avatar
unknown committed
504
void Item_func::fix_num_length_and_dec()
unknown's avatar
unknown committed
505
{
506
  uint fl_length= 0;
unknown's avatar
unknown committed
507
  decimals=0;
unknown's avatar
unknown committed
508
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
509 510
  {
    set_if_bigger(decimals,args[i]->decimals);
511 512
    set_if_bigger(fl_length, args[i]->max_length);
  }
unknown's avatar
unknown committed
513
  max_length=float_length(decimals);
514 515 516 517
  if (fl_length > max_length)
  {
    decimals= NOT_FIXED_DEC;
    max_length= float_length(NOT_FIXED_DEC);
unknown's avatar
unknown committed
518
  }
unknown's avatar
unknown committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
}


void Item_func_numhybrid::fix_num_length_and_dec()
{}


/*
  Set max_length/decimals of function if function is fixed point and
  result length/precision depends on argument ones

  SYNOPSIS
    Item_func::count_decimal_length()
*/

void Item_func::count_decimal_length()
{
unknown's avatar
unknown committed
536
  int max_int_part= 0;
unknown's avatar
unknown committed
537
  decimals= 0;
unknown's avatar
unknown committed
538
  unsigned_flag= 1;
unknown's avatar
unknown committed
539
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
540
  {
unknown's avatar
unknown committed
541
    set_if_bigger(decimals, args[i]->decimals);
unknown's avatar
unknown committed
542 543
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
    set_if_smaller(unsigned_flag, args[i]->unsigned_flag);
unknown's avatar
unknown committed
544
  }
unknown's avatar
unknown committed
545 546 547
  int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
unknown's avatar
unknown committed
548 549 550
}


unknown's avatar
unknown committed
551 552 553 554 555 556 557 558
/*
  Set max_length of if it is maximum length of its arguments

  SYNOPSIS
    Item_func::count_only_length()
*/

void Item_func::count_only_length()
unknown's avatar
unknown committed
559
{
unknown's avatar
unknown committed
560
  max_length= 0;
unknown's avatar
unknown committed
561
  unsigned_flag= 0;
unknown's avatar
unknown committed
562
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
563
  {
unknown's avatar
unknown committed
564
    set_if_bigger(max_length, args[i]->max_length);
unknown's avatar
unknown committed
565 566
    set_if_bigger(unsigned_flag, args[i]->unsigned_flag);
  }
unknown's avatar
unknown committed
567 568
}

unknown's avatar
unknown committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604

/*
  Set max_length/decimals of function if function is floating point and
  result length/precision depends on argument ones

  SYNOPSIS
    Item_func::count_real_length()
*/

void Item_func::count_real_length()
{
  uint32 length= 0;
  decimals= 0;
  max_length= 0;
  for (uint i=0 ; i < arg_count ; i++)
  {
    if (decimals != NOT_FIXED_DEC)
    {
      set_if_bigger(decimals, args[i]->decimals);
      set_if_bigger(length, (args[i]->max_length - args[i]->decimals));
    }
    set_if_bigger(max_length, args[i]->max_length);
  }
  if (decimals != NOT_FIXED_DEC)
  {
    max_length= length;
    length+= decimals;
    if (length < max_length)  // If previous operation gave overflow
      max_length= UINT_MAX32;
    else
      max_length= length;
  }
}



unknown's avatar
unknown committed
605 606 607 608 609 610 611 612 613 614
void Item_func::signal_divide_by_null()
{
  THD *thd= current_thd;
  if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DIVISION_BY_ZERO,
                 ER(ER_DIVISION_BY_ZERO));
  null_value= 1;
}


615
Item *Item_func::get_tmp_table_item(THD *thd)
616
{
617
  if (!with_sum_func && !const_item() && functype() != SUSERVAR_FUNC)
618
    return new Item_field(result_field);
619
  return copy_or_same(thd);
620 621
}

622 623 624 625 626 627 628 629
double Item_int_func::val_real()
{
  DBUG_ASSERT(fixed == 1);

  return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int();
}


unknown's avatar
unknown committed
630 631
String *Item_int_func::val_str(String *str)
{
632
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
633 634 635
  longlong nr=val_int();
  if (null_value)
    return 0;
636
  str->set_int(nr, unsigned_flag, &my_charset_bin);
unknown's avatar
unknown committed
637 638 639
  return str;
}

unknown's avatar
unknown committed
640

641 642 643 644 645 646 647 648 649 650 651
void Item_func_connection_id::fix_length_and_dec()
{
  Item_int_func::fix_length_and_dec();
  max_length= 10;
}


bool Item_func_connection_id::fix_fields(THD *thd, Item **ref)
{
  if (Item_int_func::fix_fields(thd, ref))
    return TRUE;
652
  thd->thread_specific_used= TRUE;
653
  value= thd->variables.pseudo_thread_id;
654 655 656 657
  return FALSE;
}


658
/*
659 660
  Check arguments here to determine result's type for a numeric
  function of two arguments.
unknown's avatar
unknown committed
661 662 663

  SYNOPSIS
    Item_num_op::find_num_type()
664
*/
unknown's avatar
unknown committed
665 666 667

void Item_num_op::find_num_type(void)
{
unknown's avatar
unknown committed
668 669 670 671 672 673 674 675
  DBUG_ENTER("Item_num_op::find_num_type");
  DBUG_PRINT("info", ("name %s", func_name()));
  DBUG_ASSERT(arg_count == 2);
  Item_result r0= args[0]->result_type();
  Item_result r1= args[1]->result_type();

  if (r0 == REAL_RESULT || r1 == REAL_RESULT ||
      r0 == STRING_RESULT || r1 ==STRING_RESULT)
676
  {
unknown's avatar
unknown committed
677 678 679 680 681 682 683 684 685
    count_real_length();
    max_length= float_length(decimals);
    hybrid_type= REAL_RESULT;
  }
  else if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT)
  {
    hybrid_type= DECIMAL_RESULT;
    result_precision();
  }
686
  else
687
  {
688
    DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT);
unknown's avatar
unknown committed
689
    decimals= 0;
unknown's avatar
unknown committed
690
    hybrid_type=INT_RESULT;
unknown's avatar
unknown committed
691
    result_precision();
692
  }
unknown's avatar
unknown committed
693 694 695 696 697 698
  DBUG_PRINT("info", ("Type: %s",
             (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
              hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
              hybrid_type == INT_RESULT ? "INT_RESULT" :
              "--ILLEGAL!!!--")));
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
699 700
}

unknown's avatar
unknown committed
701 702

/*
703 704 705
  Set result type for a numeric function of one argument
  (can be also used by a numeric function of many arguments, if the result
  type depends only on the first argument)
unknown's avatar
unknown committed
706 707 708 709

  SYNOPSIS
    Item_func_num1::find_num_type()
*/
710

unknown's avatar
unknown committed
711 712 713 714
void Item_func_num1::find_num_type()
{
  DBUG_ENTER("Item_func_num1::find_num_type");
  DBUG_PRINT("info", ("name %s", func_name()));
715
  switch (hybrid_type= args[0]->result_type()) {
unknown's avatar
unknown committed
716
  case INT_RESULT:
717
    unsigned_flag= args[0]->unsigned_flag;
unknown's avatar
unknown committed
718 719 720 721 722 723 724 725 726 727
    break;
  case STRING_RESULT:
  case REAL_RESULT:
    hybrid_type= REAL_RESULT;
    max_length= float_length(decimals);
    break;
  case DECIMAL_RESULT:
    break;
  default:
    DBUG_ASSERT(0);
728
  }
unknown's avatar
unknown committed
729 730 731 732 733 734
  DBUG_PRINT("info", ("Type: %s",
                      (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
                       hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
                       hybrid_type == INT_RESULT ? "INT_RESULT" :
                       "--ILLEGAL!!!--")));
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
735 736
}

unknown's avatar
unknown committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752

void Item_func_num1::fix_num_length_and_dec()
{
  decimals= args[0]->decimals;
  max_length= args[0]->max_length;
}


void Item_func_numhybrid::fix_length_and_dec()
{
  fix_num_length_and_dec();
  find_num_type();
}


String *Item_func_numhybrid::val_str(String *str)
unknown's avatar
unknown committed
753
{
754
  DBUG_ASSERT(fixed == 1);
755
  switch (hybrid_type) {
unknown's avatar
unknown committed
756 757 758 759
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
760
      return 0;                                 // null is set
unknown's avatar
unknown committed
761 762 763 764 765 766 767
    my_decimal_round(E_DEC_FATAL_ERROR, val, decimals, FALSE, val);
    my_decimal2string(E_DEC_FATAL_ERROR, val, 0, 0, 0, str);
    break;
  }
  case INT_RESULT:
  {
    longlong nr= int_op();
unknown's avatar
unknown committed
768 769
    if (null_value)
      return 0; /* purecov: inspected */
770
    str->set_int(nr, unsigned_flag, &my_charset_bin);
unknown's avatar
unknown committed
771
    break;
unknown's avatar
unknown committed
772
  }
unknown's avatar
unknown committed
773
  case REAL_RESULT:
unknown's avatar
unknown committed
774
  {
775
    double nr= real_op();
unknown's avatar
unknown committed
776 777
    if (null_value)
      return 0; /* purecov: inspected */
778
    str->set_real(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
779 780
    break;
  }
unknown's avatar
unknown committed
781 782
  case STRING_RESULT:
    return str_op(&str_value);
unknown's avatar
unknown committed
783 784
  default:
    DBUG_ASSERT(0);
unknown's avatar
unknown committed
785 786 787 788 789
  }
  return str;
}


unknown's avatar
unknown committed
790 791 792
double Item_func_numhybrid::val_real()
{
  DBUG_ASSERT(fixed == 1);
793
  switch (hybrid_type) {
unknown's avatar
unknown committed
794 795 796 797
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    double result;
798 799
    if (!(val= decimal_op(&decimal_value)))
      return 0.0;                               // null is set
unknown's avatar
unknown committed
800 801 802 803
    my_decimal2double(E_DEC_FATAL_ERROR, val, &result);
    return result;
  }
  case INT_RESULT:
804 805 806 807
  {
    longlong result= int_op();
    return unsigned_flag ? (double) ((ulonglong) result) : (double) result;
  }
unknown's avatar
unknown committed
808 809
  case REAL_RESULT:
    return real_op();
unknown's avatar
unknown committed
810 811 812 813 814 815 816 817
  case STRING_RESULT:
  {
    char *end_not_used;
    int err_not_used;
    String *res= str_op(&str_value);
    return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
			     &end_not_used, &err_not_used) : 0.0);
  }
unknown's avatar
unknown committed
818 819 820 821 822 823 824 825 826 827
  default:
    DBUG_ASSERT(0);
  }
  return 0.0;
}


longlong Item_func_numhybrid::val_int()
{
  DBUG_ASSERT(fixed == 1);
828
  switch (hybrid_type) {
unknown's avatar
unknown committed
829 830 831 832
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
833
      return 0;                                 // null is set
unknown's avatar
unknown committed
834 835 836 837 838 839 840
    longlong result;
    my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result);
    return result;
  }
  case INT_RESULT:
    return int_op();
  case REAL_RESULT:
841
    return (longlong) rint(real_op());
unknown's avatar
unknown committed
842 843 844
  case STRING_RESULT:
  {
    int err_not_used;
unknown's avatar
unknown committed
845 846 847 848
    String *res;
    if (!(res= str_op(&str_value)))
      return 0;

849
    char *end= (char*) res->ptr() + res->length();
unknown's avatar
unknown committed
850
    CHARSET_INFO *cs= str_value.charset();
unknown's avatar
unknown committed
851
    return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used);
unknown's avatar
unknown committed
852
  }
unknown's avatar
unknown committed
853 854 855 856 857 858 859 860 861 862 863
  default:
    DBUG_ASSERT(0);
  }
  return 0;
}


my_decimal *Item_func_numhybrid::val_decimal(my_decimal *decimal_value)
{
  my_decimal *val= decimal_value;
  DBUG_ASSERT(fixed == 1);
864
  switch (hybrid_type) {
unknown's avatar
unknown committed
865 866 867 868 869 870 871 872 873 874 875
  case DECIMAL_RESULT:
    val= decimal_op(decimal_value);
    break;
  case INT_RESULT:
  {
    longlong result= int_op();
    int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, decimal_value);
    break;
  }
  case REAL_RESULT:
  {
876
    double result= (double)real_op();
unknown's avatar
unknown committed
877 878 879 880
    double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value);
    break;
  }
  case STRING_RESULT:
unknown's avatar
unknown committed
881
  {
unknown's avatar
unknown committed
882 883 884 885
    String *res;
    if (!(res= str_op(&str_value)))
      return NULL;

unknown's avatar
unknown committed
886 887 888 889
    str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
                   res->length(), res->charset(), decimal_value);
    break;
  }  
unknown's avatar
unknown committed
890 891 892 893 894 895 896 897
  case ROW_RESULT:
  default:
    DBUG_ASSERT(0);
  }
  return val;
}


898 899
void Item_func_signed::print(String *str)
{
900
  str->append(STRING_WITH_LEN("cast("));
901
  args[0]->print(str);
902
  str->append(STRING_WITH_LEN(" as signed)"));
903 904 905 906

}


907 908
longlong Item_func_signed::val_int_from_str(int *error)
{
unknown's avatar
unknown committed
909 910
  char buff[MAX_FIELD_WIDTH], *end, *start;
  uint32 length;
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
  String tmp(buff,sizeof(buff), &my_charset_bin), *res;
  longlong value;

  /*
    For a string result, we must first get the string and then convert it
    to a longlong
  */

  if (!(res= args[0]->val_str(&tmp)))
  {
    null_value= 1;
    *error= 0;
    return 0;
  }
  null_value= 0;
unknown's avatar
unknown committed
926 927 928 929 930 931 932 933 934 935
  start= (char *)res->ptr();
  length= res->length();

  end= start + length;
  value= my_strtoll10(start, &end, error);
  if (*error > 0 || end != start+ length)
  {
    char err_buff[128];
    String err_tmp(err_buff,(uint32) sizeof(err_buff), system_charset_info);
    err_tmp.copy(start, length, system_charset_info);
936 937 938
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE,
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
unknown's avatar
unknown committed
939 940
                        err_tmp.c_ptr());
  }
941 942 943 944 945 946 947 948 949
  return value;
}


longlong Item_func_signed::val_int()
{
  longlong value;
  int error;

950 951
  if (args[0]->cast_to_int_type() != STRING_RESULT ||
      args[0]->result_as_longlong())
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  {
    value= args[0]->val_int();
    null_value= args[0]->null_value; 
    return value;
  }

  value= val_int_from_str(&error);
  if (value < 0 && error == 0)
  {
    push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
                 "Cast to signed converted positive out-of-range integer to "
                 "it's negative complement");
  }
  return value;
}


969 970
void Item_func_unsigned::print(String *str)
{
971
  str->append(STRING_WITH_LEN("cast("));
972
  args[0]->print(str);
973
  str->append(STRING_WITH_LEN(" as unsigned)"));
974 975 976 977

}


978 979 980 981 982
longlong Item_func_unsigned::val_int()
{
  longlong value;
  int error;

983 984 985 986 987
  if (args[0]->cast_to_int_type() == DECIMAL_RESULT)
  {
    my_decimal tmp, *dec= args[0]->val_decimal(&tmp);
    if (!(null_value= args[0]->null_value))
      my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &value);
988 989
    else
      value= 0;
990 991
    return value;
  }
992 993
  else if (args[0]->cast_to_int_type() != STRING_RESULT ||
           args[0]->result_as_longlong())
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  {
    value= args[0]->val_int();
    null_value= args[0]->null_value; 
    return value;
  }

  value= val_int_from_str(&error);
  if (error < 0)
    push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
                 "Cast to unsigned converted negative integer to it's "
                 "positive complement");
  return value;
}


unknown's avatar
unknown committed
1009 1010 1011
String *Item_decimal_typecast::val_str(String *str)
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
1012 1013
  if (null_value)
    return NULL;
unknown's avatar
unknown committed
1014
  my_decimal2string(E_DEC_FATAL_ERROR, tmp, 0, 0, 0, str);
unknown's avatar
unknown committed
1015 1016 1017 1018 1019 1020 1021 1022
  return str;
}


double Item_decimal_typecast::val_real()
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
  double res;
1023 1024
  if (null_value)
    return 0.0;
unknown's avatar
unknown committed
1025 1026 1027 1028 1029 1030 1031 1032 1033
  my_decimal2double(E_DEC_FATAL_ERROR, tmp, &res);
  return res;
}


longlong Item_decimal_typecast::val_int()
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
  longlong res;
1034 1035
  if (null_value)
    return 0;
unknown's avatar
unknown committed
1036 1037 1038 1039 1040 1041 1042 1043
  my_decimal2int(E_DEC_FATAL_ERROR, tmp, unsigned_flag, &res);
  return res;
}


my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec)
{
  my_decimal tmp_buf, *tmp= args[0]->val_decimal(&tmp_buf);
1044
  bool sign;
unknown's avatar
unknown committed
1045 1046
  uint precision;

1047 1048
  if ((null_value= args[0]->null_value))
    return NULL;
unknown's avatar
unknown committed
1049
  my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec);
1050 1051 1052 1053 1054 1055 1056 1057 1058
  sign= dec->sign();
  if (unsigned_flag)
  {
    if (sign)
    {
      my_decimal_set_zero(dec);
      goto err;
    }
  }
unknown's avatar
unknown committed
1059 1060 1061
  precision= my_decimal_length_to_precision(max_length,
                                            decimals, unsigned_flag);
  if (precision - decimals < (uint) my_decimal_intg(dec))
1062
  {
unknown's avatar
unknown committed
1063
    max_my_decimal(dec, precision, decimals);
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    dec->sign(sign);
    goto err;
  }
  return dec;

err:
  push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR,
                      ER_WARN_DATA_OUT_OF_RANGE,
                      ER(ER_WARN_DATA_OUT_OF_RANGE),
                      name, 1);
unknown's avatar
unknown committed
1074 1075 1076 1077
  return dec;
}


1078 1079
void Item_decimal_typecast::print(String *str)
{
1080 1081 1082 1083 1084
  char len_buf[20*3 + 1];
  char *end;

  uint precision= my_decimal_length_to_precision(max_length, decimals,
                                                 unsigned_flag);
1085
  str->append(STRING_WITH_LEN("cast("));
1086
  args[0]->print(str);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
  str->append(STRING_WITH_LEN(" as decimal("));

  end=int10_to_str(precision, len_buf,10);
  str->append(len_buf, (uint32) (end - len_buf));

  str->append(',');

  end=int10_to_str(decimals, len_buf,10);
  str->append(len_buf, (uint32) (end - len_buf));

  str->append(')');
  str->append(')');
1099 1100 1101
}


unknown's avatar
unknown committed
1102
double Item_func_plus::real_op()
unknown's avatar
unknown committed
1103
{
1104
  double value= args[0]->val_real() + args[1]->val_real();
unknown's avatar
unknown committed
1105 1106 1107 1108 1109
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

unknown's avatar
unknown committed
1110 1111

longlong Item_func_plus::int_op()
unknown's avatar
unknown committed
1112
{
unknown's avatar
unknown committed
1113 1114 1115 1116 1117 1118 1119
  longlong value=args[0]->val_int()+args[1]->val_int();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0;
  return value;
}


1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/*
  Calculate plus of two decimail's

  SYNOPSIS
    decimal_op()
    decimal_value	Buffer that can be used to store result

  RETURN
   0	Value was NULL;  In this case null_value is set
   #	Value of operation as a decimal
*/

unknown's avatar
unknown committed
1132 1133
my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
{
1134 1135 1136
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1137 1138
  if ((null_value= args[0]->null_value))
    return 0;
1139
  val2= args[1]->val_decimal(&value2);
1140
  if (!(null_value= (args[1]->null_value ||
1141 1142
                     (my_decimal_add(E_DEC_FATAL_ERROR, decimal_value, val1,
                                     val2) > 3))))
1143 1144
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
}

/*
  Set precision of results for additive operations (+ and -)

  SYNOPSIS
    Item_func_additive_op::result_precision()
*/
void Item_func_additive_op::result_precision()
{
  decimals= max(args[0]->decimals, args[1]->decimals);
unknown's avatar
unknown committed
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  int max_int_part= max(args[0]->decimal_precision() - args[0]->decimals,
                        args[1]->decimal_precision() - args[1]->decimals);
  int precision= min(max_int_part + 1 + decimals, DECIMAL_MAX_PRECISION);

  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
unknown's avatar
unknown committed
1167 1168
}

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

/*
  The following function is here to allow the user to force
  subtraction of UNSIGNED BIGINT to return negative values.
*/

void Item_func_minus::fix_length_and_dec()
{
  Item_num_op::fix_length_and_dec();
  if (unsigned_flag &&
1179
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
1180 1181 1182 1183
    unsigned_flag=0;
}


unknown's avatar
unknown committed
1184
double Item_func_minus::real_op()
unknown's avatar
unknown committed
1185
{
1186
  double value= args[0]->val_real() - args[1]->val_real();
unknown's avatar
unknown committed
1187 1188 1189 1190 1191
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

unknown's avatar
unknown committed
1192 1193

longlong Item_func_minus::int_op()
unknown's avatar
unknown committed
1194
{
unknown's avatar
unknown committed
1195 1196 1197 1198
  longlong value=args[0]->val_int() - args[1]->val_int();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0;
  return value;
unknown's avatar
unknown committed
1199 1200
}

1201

1202 1203
/* See Item_func_plus::decimal_op for comments */

unknown's avatar
unknown committed
1204 1205
my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
{
1206 1207 1208 1209
  my_decimal value1, *val1;
  my_decimal value2, *val2= 

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1210 1211
  if ((null_value= args[0]->null_value))
    return 0;
1212
  val2= args[1]->val_decimal(&value2);
1213
  if (!(null_value= (args[1]->null_value ||
1214 1215
                     (my_decimal_sub(E_DEC_FATAL_ERROR, decimal_value, val1,
                                     val2) > 3))))
1216 1217
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
1218 1219
}

1220

unknown's avatar
unknown committed
1221
double Item_func_mul::real_op()
unknown's avatar
unknown committed
1222
{
1223
  DBUG_ASSERT(fixed == 1);
1224
  double value= args[0]->val_real() * args[1]->val_real();
unknown's avatar
unknown committed
1225
  if ((null_value=args[0]->null_value || args[1]->null_value))
unknown's avatar
unknown committed
1226
    return 0.0;
unknown's avatar
unknown committed
1227 1228 1229
  return value;
}

unknown's avatar
unknown committed
1230 1231

longlong Item_func_mul::int_op()
unknown's avatar
unknown committed
1232
{
1233
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1234 1235 1236 1237
  longlong value=args[0]->val_int()*args[1]->val_int();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0;
  return value;
unknown's avatar
unknown committed
1238 1239 1240
}


1241 1242
/* See Item_func_plus::decimal_op for comments */

unknown's avatar
unknown committed
1243 1244
my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
{
1245 1246 1247
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1248 1249
  if ((null_value= args[0]->null_value))
    return 0;
1250
  val2= args[1]->val_decimal(&value2);
1251
  if (!(null_value= (args[1]->null_value ||
1252 1253
                     (my_decimal_mul(E_DEC_FATAL_ERROR, decimal_value, val1,
                                    val2) > 3))))
1254 1255
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
1256 1257 1258
}


unknown's avatar
unknown committed
1259 1260
void Item_func_mul::result_precision()
{
unknown's avatar
unknown committed
1261 1262 1263 1264 1265 1266 1267 1268 1269
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE);
  int precision= min(args[0]->decimal_precision() + args[1]->decimal_precision(),
                     DECIMAL_MAX_PRECISION);
  max_length= my_decimal_precision_to_length(precision, decimals,unsigned_flag);
unknown's avatar
unknown committed
1270 1271 1272 1273
}


double Item_func_div::real_op()
unknown's avatar
unknown committed
1274
{
1275
  DBUG_ASSERT(fixed == 1);
1276 1277
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
unknown's avatar
unknown committed
1278 1279 1280 1281 1282
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0.0;
  if (val2 == 0.0)
  {
    signal_divide_by_null();
unknown's avatar
unknown committed
1283
    return 0.0;
unknown's avatar
unknown committed
1284
  }
unknown's avatar
unknown committed
1285 1286 1287
  return value/val2;
}

unknown's avatar
unknown committed
1288

unknown's avatar
unknown committed
1289
my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1290
{
1291 1292
  my_decimal value1, *val1;
  my_decimal value2, *val2;
unknown's avatar
unknown committed
1293
  int err;
1294 1295

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1296 1297
  if ((null_value= args[0]->null_value))
    return 0;
1298
  val2= args[1]->val_decimal(&value2);
unknown's avatar
unknown committed
1299 1300
  if ((null_value= args[1]->null_value))
    return 0;
unknown's avatar
unknown committed
1301 1302 1303 1304 1305 1306
  if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
                           val1, val2, prec_increment)) > 3)
  {
    if (err == E_DEC_DIV_ZERO)
      signal_divide_by_null();
    null_value= 1;
unknown's avatar
unknown committed
1307
    return 0;
1308
  }
unknown's avatar
unknown committed
1309
  return decimal_value;
unknown's avatar
unknown committed
1310 1311 1312 1313 1314
}


void Item_func_div::result_precision()
{
unknown's avatar
unknown committed
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
  uint precision=min(args[0]->decimal_precision() + prec_increment,
                     DECIMAL_MAX_PRECISION);
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
unknown's avatar
unknown committed
1325 1326
}

unknown's avatar
unknown committed
1327

unknown's avatar
unknown committed
1328 1329
void Item_func_div::fix_length_and_dec()
{
unknown's avatar
unknown committed
1330
  DBUG_ENTER("Item_func_div::fix_length_and_dec");
unknown's avatar
unknown committed
1331
  prec_increment= current_thd->variables.div_precincrement;
1332
  Item_num_op::fix_length_and_dec();
1333
  switch(hybrid_type) {
unknown's avatar
unknown committed
1334 1335
  case REAL_RESULT:
  {
unknown's avatar
unknown committed
1336
    decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment;
unknown's avatar
unknown committed
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    set_if_smaller(decimals, NOT_FIXED_DEC);
    max_length=args[0]->max_length - args[0]->decimals + decimals;
    uint tmp=float_length(decimals);
    set_if_smaller(max_length,tmp);
    break;
  }
  case INT_RESULT:
    hybrid_type= DECIMAL_RESULT;
    DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
    result_precision();
    break;
  case DECIMAL_RESULT:
    result_precision();
    break;
  default:
    DBUG_ASSERT(0);
  }
  maybe_null= 1; // devision by zero
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1356 1357
}

1358 1359 1360 1361

/* Integer division */
longlong Item_func_int_div::val_int()
{
1362
  DBUG_ASSERT(fixed == 1);
1363 1364
  longlong value=args[0]->val_int();
  longlong val2=args[1]->val_int();
1365
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1366 1367 1368 1369
    return 0;
  if (val2 == 0)
  {
    signal_divide_by_null();
1370
    return 0;
unknown's avatar
unknown committed
1371
  }
1372 1373 1374
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
1375 1376 1377 1378 1379 1380 1381
}


void Item_func_int_div::fix_length_and_dec()
{
  max_length=args[0]->max_length - args[0]->decimals;
  maybe_null=1;
unknown's avatar
unknown committed
1382
  unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
1383 1384 1385
}


unknown's avatar
unknown committed
1386 1387 1388 1389 1390
longlong Item_func_mod::int_op()
{
  DBUG_ASSERT(fixed == 1);
  longlong value=  args[0]->val_int();
  longlong val2= args[1]->val_int();
1391 1392
  longlong result;

unknown's avatar
unknown committed
1393 1394 1395 1396 1397 1398 1399
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0; /* purecov: inspected */
  if (val2 == 0)
  {
    signal_divide_by_null();
    return 0;
  }
1400 1401

  if (args[0]->unsigned_flag)
1402 1403 1404 1405 1406
    result= args[1]->unsigned_flag ? 
      ((ulonglong) value) % ((ulonglong) val2) : ((ulonglong) value) % val2;
  else
    result= args[1]->unsigned_flag ?
      value % ((ulonglong) val2) : value % val2;
1407

1408
  return result;
unknown's avatar
unknown committed
1409 1410 1411
}

double Item_func_mod::real_op()
unknown's avatar
unknown committed
1412
{
1413
  DBUG_ASSERT(fixed == 1);
1414 1415
  double value= args[0]->val_real();
  double val2=  args[1]->val_real();
unknown's avatar
unknown committed
1416
  if ((null_value= args[0]->null_value || args[1]->null_value))
unknown's avatar
unknown committed
1417
    return 0.0; /* purecov: inspected */
unknown's avatar
unknown committed
1418 1419 1420 1421 1422
  if (val2 == 0.0)
  {
    signal_divide_by_null();
    return 0.0;
  }
unknown's avatar
unknown committed
1423 1424 1425
  return fmod(value,val2);
}

unknown's avatar
unknown committed
1426 1427

my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1428
{
1429 1430 1431 1432
  my_decimal value1, *val1;
  my_decimal value2, *val2;

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1433 1434
  if ((null_value= args[0]->null_value))
    return 0;
1435
  val2= args[1]->val_decimal(&value2);
unknown's avatar
unknown committed
1436 1437 1438
  if ((null_value= args[1]->null_value))
    return 0;
  switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
1439
                         val1, val2)) {
unknown's avatar
unknown committed
1440 1441 1442 1443
  case E_DEC_TRUNCATED:
  case E_DEC_OK:
    return decimal_value;
  case E_DEC_DIV_ZERO:
unknown's avatar
unknown committed
1444
    signal_divide_by_null();
unknown's avatar
unknown committed
1445
  default:
1446
    null_value= 1;
unknown's avatar
unknown committed
1447 1448
    return 0;
  }
unknown's avatar
unknown committed
1449 1450
}

unknown's avatar
unknown committed
1451 1452

void Item_func_mod::result_precision()
unknown's avatar
unknown committed
1453
{
unknown's avatar
unknown committed
1454 1455
  decimals= max(args[0]->decimals, args[1]->decimals);
  max_length= max(args[0]->max_length, args[1]->max_length);
unknown's avatar
unknown committed
1456 1457 1458 1459 1460
}


void Item_func_mod::fix_length_and_dec()
{
1461
  Item_num_op::fix_length_and_dec();
1462
  maybe_null= 1;
1463
  unsigned_flag= args[0]->unsigned_flag;
unknown's avatar
unknown committed
1464 1465 1466
}


unknown's avatar
unknown committed
1467
double Item_func_neg::real_op()
unknown's avatar
unknown committed
1468
{
1469
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1470
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1471 1472 1473
  return -value;
}

unknown's avatar
unknown committed
1474

unknown's avatar
unknown committed
1475
longlong Item_func_neg::int_op()
unknown's avatar
unknown committed
1476
{
unknown's avatar
unknown committed
1477 1478
  longlong value= args[0]->val_int();
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1479 1480 1481
  return -value;
}

unknown's avatar
unknown committed
1482

unknown's avatar
unknown committed
1483
my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1484
{
unknown's avatar
unknown committed
1485 1486 1487 1488 1489
  my_decimal val, *value= args[0]->val_decimal(&val);
  if (!(null_value= args[0]->null_value))
  {
    my_decimal2decimal(value, decimal_value);
    my_decimal_neg(decimal_value);
1490
    return decimal_value;
unknown's avatar
unknown committed
1491
  }
1492
  return 0;
unknown's avatar
unknown committed
1493 1494
}

1495

unknown's avatar
unknown committed
1496
void Item_func_neg::fix_num_length_and_dec()
unknown's avatar
unknown committed
1497
{
unknown's avatar
unknown committed
1498 1499 1500
  decimals= args[0]->decimals;
  /* 1 add because sign can appear */
  max_length= args[0]->max_length + 1;
unknown's avatar
unknown committed
1501 1502
}

unknown's avatar
unknown committed
1503

1504
void Item_func_neg::fix_length_and_dec()
unknown's avatar
unknown committed
1505
{
1506
  DBUG_ENTER("Item_func_neg::fix_length_and_dec");
unknown's avatar
unknown committed
1507
  Item_func_num1::fix_length_and_dec();
1508 1509 1510 1511

  /*
    If this is in integer context keep the context as integer if possible
    (This is how multiplication and other integer functions works)
1512 1513
    Use val() to get value as arg_type doesn't mean that item is
    Item_int or Item_real due to existence of Item_param.
1514
  */
unknown's avatar
unknown committed
1515
  if (hybrid_type == INT_RESULT && args[0]->const_item())
unknown's avatar
unknown committed
1516
  {
unknown's avatar
unknown committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    longlong val= args[0]->val_int();
    if ((ulonglong) val >= (ulonglong) LONGLONG_MIN &&
        ((ulonglong) val != (ulonglong) LONGLONG_MIN ||
          args[0]->type() != INT_ITEM))        
    {
      /*
        Ensure that result is converted to DECIMAL, as longlong can't hold
        the negated number
      */
      hybrid_type= DECIMAL_RESULT;
      DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
    }
unknown's avatar
unknown committed
1529
  }
unknown's avatar
unknown committed
1530
  unsigned_flag= 0;
unknown's avatar
unknown committed
1531
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1532 1533
}

unknown's avatar
unknown committed
1534

unknown's avatar
unknown committed
1535
double Item_func_abs::real_op()
unknown's avatar
unknown committed
1536
{
1537
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1538
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1539 1540 1541
  return fabs(value);
}

unknown's avatar
unknown committed
1542

unknown's avatar
unknown committed
1543
longlong Item_func_abs::int_op()
unknown's avatar
unknown committed
1544
{
unknown's avatar
unknown committed
1545
  longlong value= args[0]->val_int();
1546 1547 1548
  if ((null_value= args[0]->null_value))
    return 0;
  return (value >= 0) || unsigned_flag ? value : -value;
unknown's avatar
unknown committed
1549 1550
}

unknown's avatar
unknown committed
1551

unknown's avatar
unknown committed
1552
my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1553
{
unknown's avatar
unknown committed
1554 1555
  my_decimal val, *value= args[0]->val_decimal(&val);
  if (!(null_value= args[0]->null_value))
unknown's avatar
unknown committed
1556
  {
unknown's avatar
unknown committed
1557 1558 1559
    my_decimal2decimal(value, decimal_value);
    if (decimal_value->sign())
      my_decimal_neg(decimal_value);
1560
    return decimal_value;
unknown's avatar
unknown committed
1561
  }
1562
  return 0;
unknown's avatar
unknown committed
1563 1564 1565 1566 1567 1568
}


void Item_func_abs::fix_length_and_dec()
{
  Item_func_num1::fix_length_and_dec();
1569
  unsigned_flag= args[0]->unsigned_flag;
unknown's avatar
unknown committed
1570 1571
}

unknown's avatar
unknown committed
1572

1573
/* Gateway to natural LOG function */
1574
double Item_func_ln::val_real()
1575
{
1576
  DBUG_ASSERT(fixed == 1);
1577
  double value= args[0]->val_real();
1578
  if ((null_value= args[0]->null_value))
1579
    return 0.0;
1580
  if (value <= 0.0)
1581 1582
  {
    signal_divide_by_null();
1583
    return 0.0;
1584
  }
1585 1586 1587 1588 1589 1590 1591 1592
  return log(value);
}

/* 
 Extended but so slower LOG function
 We have to check if all values are > zero and first one is not one
 as these are the cases then result is not a number.
*/ 
1593
double Item_func_log::val_real()
unknown's avatar
unknown committed
1594
{
1595
  DBUG_ASSERT(fixed == 1);
1596
  double value= args[0]->val_real();
1597
  if ((null_value= args[0]->null_value))
1598
    return 0.0;
1599
  if (value <= 0.0)
1600 1601 1602 1603
  {
    signal_divide_by_null();
    return 0.0;
  }
1604 1605
  if (arg_count == 2)
  {
1606
    double value2= args[1]->val_real();
1607
    if ((null_value= args[1]->null_value))
1608
      return 0.0;
1609
    if (value2 <= 0.0 || value == 1.0)
1610 1611 1612 1613
    {
      signal_divide_by_null();
      return 0.0;
    }
1614 1615
    return log(value2) / log(value);
  }
unknown's avatar
unknown committed
1616 1617 1618
  return log(value);
}

1619
double Item_func_log2::val_real()
1620
{
1621
  DBUG_ASSERT(fixed == 1);
1622
  double value= args[0]->val_real();
1623 1624

  if ((null_value=args[0]->null_value))
1625
    return 0.0;
1626
  if (value <= 0.0)
1627 1628 1629 1630
  {
    signal_divide_by_null();
    return 0.0;
  }
1631
  return log(value) / M_LN2;
1632 1633
}

1634
double Item_func_log10::val_real()
unknown's avatar
unknown committed
1635
{
1636
  DBUG_ASSERT(fixed == 1);
1637
  double value= args[0]->val_real();
1638
  if ((null_value= args[0]->null_value))
1639
    return 0.0;
1640
  if (value <= 0.0)
1641 1642 1643 1644
  {
    signal_divide_by_null();
    return 0.0;
  }
unknown's avatar
unknown committed
1645 1646 1647
  return log10(value);
}

1648
double Item_func_exp::val_real()
unknown's avatar
unknown committed
1649
{
1650
  DBUG_ASSERT(fixed == 1);
1651
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1652 1653 1654 1655 1656
  if ((null_value=args[0]->null_value))
    return 0.0; /* purecov: inspected */
  return exp(value);
}

1657
double Item_func_sqrt::val_real()
unknown's avatar
unknown committed
1658
{
1659
  DBUG_ASSERT(fixed == 1);
1660
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1661 1662 1663 1664 1665
  if ((null_value=(args[0]->null_value || value < 0)))
    return 0.0; /* purecov: inspected */
  return sqrt(value);
}

1666
double Item_func_pow::val_real()
unknown's avatar
unknown committed
1667
{
1668
  DBUG_ASSERT(fixed == 1);
1669 1670
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
unknown's avatar
unknown committed
1671 1672 1673 1674 1675 1676 1677
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
    return 0.0; /* purecov: inspected */
  return pow(value,val2);
}

// Trigonometric functions

1678
double Item_func_acos::val_real()
unknown's avatar
unknown committed
1679
{
1680
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1681
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1682
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1683 1684 1685 1686 1687
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(acos(value));
}

1688
double Item_func_asin::val_real()
unknown's avatar
unknown committed
1689
{
1690
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1691
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1692
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1693 1694 1695 1696 1697
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(asin(value));
}

1698
double Item_func_atan::val_real()
unknown's avatar
unknown committed
1699
{
1700
  DBUG_ASSERT(fixed == 1);
1701
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1702 1703 1704 1705
  if ((null_value=args[0]->null_value))
    return 0.0;
  if (arg_count == 2)
  {
1706
    double val2= args[1]->val_real();
unknown's avatar
unknown committed
1707 1708 1709 1710 1711 1712 1713
    if ((null_value=args[1]->null_value))
      return 0.0;
    return fix_result(atan2(value,val2));
  }
  return fix_result(atan(value));
}

1714
double Item_func_cos::val_real()
unknown's avatar
unknown committed
1715
{
1716
  DBUG_ASSERT(fixed == 1);
1717
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1718 1719 1720 1721 1722
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(cos(value));
}

1723
double Item_func_sin::val_real()
unknown's avatar
unknown committed
1724
{
1725
  DBUG_ASSERT(fixed == 1);
1726
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1727 1728 1729 1730 1731
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(sin(value));
}

1732
double Item_func_tan::val_real()
unknown's avatar
unknown committed
1733
{
1734
  DBUG_ASSERT(fixed == 1);
1735
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(tan(value));
}


// Shift-functions, same as << and >> in C/C++


longlong Item_func_shift_left::val_int()
{
1747
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
  uint shift;
  ulonglong res= ((ulonglong) args[0]->val_int() <<
		  (shift=(uint) args[1]->val_int()));
  if (args[0]->null_value || args[1]->null_value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0));
}

longlong Item_func_shift_right::val_int()
{
1762
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  uint shift;
  ulonglong res= (ulonglong) args[0]->val_int() >>
    (shift=(uint) args[1]->val_int());
  if (args[0]->null_value || args[1]->null_value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return (shift < sizeof(longlong)*8 ? (longlong) res : LL(0));
}


longlong Item_func_bit_neg::val_int()
{
1778
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
  ulonglong res= (ulonglong) args[0]->val_int();
  if ((null_value=args[0]->null_value))
    return 0;
  return ~res;
}


// Conversion functions

void Item_func_integer::fix_length_and_dec()
{
  max_length=args[0]->max_length - args[0]->decimals+1;
  uint tmp=float_length(decimals);
  set_if_smaller(max_length,tmp);
  decimals=0;
}

unknown's avatar
unknown committed
1796
void Item_func_int_val::fix_num_length_and_dec()
unknown's avatar
unknown committed
1797
{
unknown's avatar
unknown committed
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
  max_length= args[0]->max_length - (args[0]->decimals ?
                                     args[0]->decimals + 1 :
                                     0) + 2;
  uint tmp= float_length(decimals);
  set_if_smaller(max_length,tmp);
  decimals= 0;
}


void Item_func_int_val::find_num_type()
{
  DBUG_ENTER("Item_func_int_val::find_num_type");
  DBUG_PRINT("info", ("name %s", func_name()));
  switch(hybrid_type= args[0]->result_type())
  {
  case STRING_RESULT:
  case REAL_RESULT:
    hybrid_type= REAL_RESULT;
    max_length= float_length(decimals);
    break;
  case INT_RESULT:
  case DECIMAL_RESULT:
    /*
      -2 because in most high position can't be used any digit for longlong
      and one position for increasing value during operation
    */
    if ((args[0]->max_length - args[0]->decimals) >=
        (DECIMAL_LONGLONG_DIGITS - 2))
    {
      hybrid_type= DECIMAL_RESULT;
    }
    else
    {
      unsigned_flag= args[0]->unsigned_flag;
      hybrid_type= INT_RESULT;
    }
    break;
  default:
    DBUG_ASSERT(0);
  }
  DBUG_PRINT("info", ("Type: %s",
                      (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
                       hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
                       hybrid_type == INT_RESULT ? "INT_RESULT" :
                       "--ILLEGAL!!!--")));

  DBUG_VOID_RETURN;
}


longlong Item_func_ceiling::int_op()
{
1850 1851 1852 1853 1854 1855 1856 1857 1858
  longlong result;
  switch (args[0]->result_type()) {
  case INT_RESULT:
    result= args[0]->val_int();
    null_value= args[0]->null_value;
    break;
  case DECIMAL_RESULT:
  {
    my_decimal dec_buf, *dec;
1859
    if ((dec= Item_func_ceiling::decimal_op(&dec_buf)))
1860 1861 1862 1863 1864 1865
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
    else
      result= 0;
    break;
  }
  default:
1866
    result= (longlong)Item_func_ceiling::real_op();
1867 1868
  };
  return result;
unknown's avatar
unknown committed
1869 1870
}

unknown's avatar
unknown committed
1871 1872

double Item_func_ceiling::real_op()
unknown's avatar
unknown committed
1873
{
unknown's avatar
unknown committed
1874 1875 1876 1877
  /*
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
    bug)
  */
1878
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1879 1880 1881 1882 1883 1884
  null_value= args[0]->null_value;
  return ceil(value);
}


my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1885
{
unknown's avatar
unknown committed
1886
  my_decimal val, *value= args[0]->val_decimal(&val);
1887 1888 1889 1890 1891
  if (!(null_value= (args[0]->null_value ||
                     my_decimal_ceiling(E_DEC_FATAL_ERROR, value,
                                        decimal_value) > 1)))
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
1892 1893 1894 1895 1896
}


longlong Item_func_floor::int_op()
{
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
  longlong result;
  switch (args[0]->result_type()) {
  case INT_RESULT:
    result= args[0]->val_int();
    null_value= args[0]->null_value;
    break;
  case DECIMAL_RESULT:
  {
    my_decimal dec_buf, *dec;
    if ((dec= Item_func_floor::decimal_op(&dec_buf)))
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
    else
      result= 0;
    break;
  }
  default:
    result= (longlong)Item_func_floor::real_op();
  };
  return result;
unknown's avatar
unknown committed
1916 1917
}

unknown's avatar
unknown committed
1918 1919

double Item_func_floor::real_op()
unknown's avatar
unknown committed
1920
{
unknown's avatar
unknown committed
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
  /*
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
    bug)
  */
  volatile double value= args[0]->val_real();
  null_value= args[0]->null_value;
  return floor(value);
}


my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value)
{
  my_decimal val, *value= args[0]->val_decimal(&val);
1934 1935 1936 1937 1938
  if (!(null_value= (args[0]->null_value ||
                     my_decimal_floor(E_DEC_FATAL_ERROR, value,
                                      decimal_value) > 1)))
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
1939 1940 1941
}


unknown's avatar
unknown committed
1942
void Item_func_round::fix_length_and_dec()
unknown's avatar
unknown committed
1943
{
1944 1945 1946 1947
  int      decimals_to_set;
  longlong val1;
  bool     val1_unsigned;
  
unknown's avatar
unknown committed
1948 1949
  unsigned_flag= args[0]->unsigned_flag;
  if (!args[1]->const_item())
unknown's avatar
unknown committed
1950
  {
unknown's avatar
unknown committed
1951 1952
    max_length= args[0]->max_length;
    decimals= args[0]->decimals;
1953 1954 1955 1956 1957 1958 1959
    if (args[0]->result_type() == DECIMAL_RESULT)
    {
      max_length++;
      hybrid_type= DECIMAL_RESULT;
    }
    else
      hybrid_type= REAL_RESULT;
unknown's avatar
unknown committed
1960 1961
    return;
  }
1962 1963 1964 1965 1966 1967 1968 1969

  val1= args[1]->val_int();
  val1_unsigned= args[1]->unsigned_flag;
  if (val1 < 0)
    decimals_to_set= val1_unsigned ? INT_MAX : 0;
  else
    decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1;

unknown's avatar
unknown committed
1970 1971 1972 1973 1974 1975 1976 1977
  if (args[0]->decimals == NOT_FIXED_DEC)
  {
    max_length= args[0]->max_length;
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
    hybrid_type= REAL_RESULT;
    return;
  }
  
unknown's avatar
unknown committed
1978
  switch (args[0]->result_type()) {
unknown's avatar
unknown committed
1979 1980 1981 1982 1983 1984 1985
  case REAL_RESULT:
  case STRING_RESULT:
    hybrid_type= REAL_RESULT;
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
    max_length= float_length(decimals);
    break;
  case INT_RESULT:
1986
    if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS))
unknown's avatar
unknown committed
1987
    {
1988
      int length_can_increase= test(!truncate && (val1 < 0) && !val1_unsigned);
unknown's avatar
unknown committed
1989
      max_length= args[0]->max_length + length_can_increase;
unknown's avatar
unknown committed
1990 1991 1992 1993 1994
      /* Here we can keep INT_RESULT */
      hybrid_type= INT_RESULT;
      decimals= 0;
      break;
    }
unknown's avatar
unknown committed
1995
    /* fall through */
unknown's avatar
unknown committed
1996 1997 1998 1999 2000
  case DECIMAL_RESULT:
  {
    hybrid_type= DECIMAL_RESULT;
    int decimals_delta= args[0]->decimals - decimals_to_set;
    int precision= args[0]->decimal_precision();
2001 2002 2003 2004
    int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1;

    precision-= decimals_delta - length_increase;
    decimals= decimals_to_set;
unknown's avatar
unknown committed
2005
    max_length= my_decimal_precision_to_length(precision, decimals,
2006
                                               unsigned_flag);
unknown's avatar
unknown committed
2007 2008 2009 2010
    break;
  }
  default:
    DBUG_ASSERT(0); /* This result type isn't handled */
unknown's avatar
unknown committed
2011 2012 2013
  }
}

2014 2015
double my_double_round(double value, longlong dec, bool dec_unsigned,
                       bool truncate)
unknown's avatar
unknown committed
2016
{
2017
  double tmp;
2018 2019
  bool dec_negative= (dec < 0) && !dec_unsigned;
  ulonglong abs_dec= dec_negative ? -dec : dec;
2020 2021 2022 2023 2024
  /*
    tmp2 is here to avoid return the value with 80 bit precision
    This will fix that the test round(0.1,1) = round(0.1,1) is true
  */
  volatile double tmp2;
unknown's avatar
unknown committed
2025

2026 2027
  tmp=(abs_dec < array_elements(log_10) ?
       log_10[abs_dec] : pow(10.0,(double) abs_dec));
unknown's avatar
unknown committed
2028

2029
  if (dec_negative && my_isinf(tmp))
2030
    tmp2= 0;
2031
  else if (!dec_negative && my_isinf(value * tmp))
2032 2033
    tmp2= value;
  else if (truncate)
unknown's avatar
unknown committed
2034 2035
  {
    if (value >= 0)
2036
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
unknown's avatar
unknown committed
2037
    else
2038
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
unknown's avatar
unknown committed
2039
  }
2040 2041 2042
  else
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
  return tmp2;
unknown's avatar
unknown committed
2043 2044 2045
}


2046 2047 2048 2049 2050
double Item_func_round::real_op()
{
  double value= args[0]->val_real();

  if (!(null_value= args[0]->null_value || args[1]->null_value))
2051 2052
    return my_double_round(value, args[1]->val_int(), args[1]->unsigned_flag,
                           truncate);
2053 2054 2055 2056

  return 0.0;
}

2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
/*
  Rounds a given value to a power of 10 specified as the 'to' argument,
  avoiding overflows when the value is close to the ulonglong range boundary.
*/

static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to)
{
  ulonglong tmp= value / to * to;
  return (value - tmp < (to >> 1)) ? tmp : tmp + to;
}

2068

unknown's avatar
unknown committed
2069 2070 2071
longlong Item_func_round::int_op()
{
  longlong value= args[0]->val_int();
2072
  longlong dec= args[1]->val_int();
unknown's avatar
unknown committed
2073
  decimals= 0;
2074
  ulonglong abs_dec;
unknown's avatar
unknown committed
2075 2076
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0;
2077
  if ((dec >= 0) || args[1]->unsigned_flag)
unknown's avatar
unknown committed
2078 2079 2080
    return value; // integer have not digits after point

  abs_dec= -dec;
unknown's avatar
unknown committed
2081 2082 2083 2084 2085 2086 2087
  longlong tmp;
  
  if(abs_dec >= array_elements(log_10_int))
    return 0;
  
  tmp= log_10_int[abs_dec];
  
unknown's avatar
unknown committed
2088
  if (truncate)
2089 2090
    value= (unsigned_flag) ?
      ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp;
unknown's avatar
unknown committed
2091
  else
2092 2093
    value= (unsigned_flag || value >= 0) ?
      my_unsigned_round((ulonglong) value, tmp) :
2094
      -(longlong) my_unsigned_round((ulonglong) -value, tmp);
unknown's avatar
unknown committed
2095
  return value;
unknown's avatar
unknown committed
2096 2097 2098 2099 2100 2101
}


my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
{
  my_decimal val, *value= args[0]->val_decimal(&val);
2102 2103
  longlong dec= args[1]->val_int();
  if (dec > 0 || (dec < 0 && args[1]->unsigned_flag))
unknown's avatar
unknown committed
2104
  {
2105
    dec= min((ulonglong) dec, DECIMAL_MAX_SCALE);
2106
    decimals= (uint8) dec; // to get correct output
unknown's avatar
unknown committed
2107
  }
2108 2109 2110
  else if (dec < INT_MIN)
    dec= INT_MIN;
    
2111
  if (!(null_value= (args[0]->null_value || args[1]->null_value ||
2112
                     my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec,
2113
                                      truncate, decimal_value) > 1)))
2114 2115
    return decimal_value;
  return 0;
unknown's avatar
unknown committed
2116 2117 2118
}


2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
void Item_func_rand::seed_random(Item *arg)
{
  /*
    TODO: do not do reinit 'rand' for every execute of PS/SP if
    args[0] is a constant.
  */
  uint32 tmp= (uint32) arg->val_int();
  randominit(rand, (uint32) (tmp*0x10001L+55555555L),
             (uint32) (tmp*0x10000001L));
}


2131
bool Item_func_rand::fix_fields(THD *thd,Item **ref)
unknown's avatar
unknown committed
2132
{
2133
  if (Item_real_func::fix_fields(thd, ref))
2134
    return TRUE;
2135
  used_tables_cache|= RAND_TABLE_BIT;
unknown's avatar
unknown committed
2136 2137
  if (arg_count)
  {					// Only use argument once in query
2138
    /*
unknown's avatar
unknown committed
2139
      Allocate rand structure once: we must use thd->stmt_arena
2140 2141
      to create rand in proper mem_root if it's a prepared statement or
      stored procedure.
2142 2143 2144

      No need to send a Rand log event if seed was given eg: RAND(seed),
      as it will be replicated in the query as such.
2145 2146
    */
    if (!rand && !(rand= (struct rand_struct*)
unknown's avatar
unknown committed
2147
                   thd->stmt_arena->alloc(sizeof(*rand))))
2148
      return TRUE;
2149 2150 2151

    if (args[0]->const_item())
      seed_random (args[0]);
unknown's avatar
unknown committed
2152
  }
2153
  else
unknown's avatar
unknown committed
2154
  {
2155 2156 2157 2158 2159
    /*
      Save the seed only the first time RAND() is used in the query
      Once events are forwarded rather than recreated,
      the following can be skipped if inside the slave thread
    */
2160 2161 2162 2163 2164 2165
    if (!thd->rand_used)
    {
      thd->rand_used= 1;
      thd->rand_saved_seed1= thd->rand.seed1;
      thd->rand_saved_seed2= thd->rand.seed2;
    }
2166
    rand= &thd->rand;
unknown's avatar
unknown committed
2167
  }
2168
  return FALSE;
2169 2170
}

unknown's avatar
unknown committed
2171 2172 2173 2174 2175 2176
void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

2177

2178
double Item_func_rand::val_real()
2179
{
2180
  DBUG_ASSERT(fixed == 1);
2181 2182
  if (arg_count && !args[0]->const_item())
    seed_random (args[0]);
2183
  return my_rnd(rand);
unknown's avatar
unknown committed
2184 2185 2186 2187
}

longlong Item_func_sign::val_int()
{
2188
  DBUG_ASSERT(fixed == 1);
2189
  double value= args[0]->val_real();
unknown's avatar
unknown committed
2190 2191 2192 2193 2194
  null_value=args[0]->null_value;
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
}


2195
double Item_func_units::val_real()
unknown's avatar
unknown committed
2196
{
2197
  DBUG_ASSERT(fixed == 1);
2198
  double value= args[0]->val_real();
unknown's avatar
unknown committed
2199 2200 2201 2202 2203 2204 2205 2206
  if ((null_value=args[0]->null_value))
    return 0;
  return value*mul+add;
}


void Item_func_min_max::fix_length_and_dec()
{
unknown's avatar
unknown committed
2207
  int max_int_part=0;
2208
  bool datetime_found= FALSE;
unknown's avatar
unknown committed
2209 2210
  decimals=0;
  max_length=0;
unknown's avatar
unknown committed
2211
  maybe_null=0;
unknown's avatar
unknown committed
2212
  cmp_type=args[0]->result_type();
2213

unknown's avatar
unknown committed
2214 2215
  for (uint i=0 ; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
2216 2217
    set_if_bigger(max_length, args[i]->max_length);
    set_if_bigger(decimals, args[i]->decimals);
unknown's avatar
unknown committed
2218
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
unknown's avatar
unknown committed
2219 2220
    if (args[i]->maybe_null)
      maybe_null=1;
unknown's avatar
unknown committed
2221
    cmp_type=item_cmp_type(cmp_type,args[i]->result_type());
2222 2223 2224 2225 2226 2227
    if (args[i]->result_type() != ROW_RESULT && args[i]->is_datetime())
    {
      datetime_found= TRUE;
      if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME)
        datetime_item= args[i];
    }
unknown's avatar
unknown committed
2228
  }
unknown's avatar
unknown committed
2229
  if (cmp_type == STRING_RESULT)
2230
  {
2231
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
2232 2233 2234 2235 2236 2237
    if (datetime_found)
    {
      thd= current_thd;
      compare_as_dates= TRUE;
    }
  }
unknown's avatar
unknown committed
2238 2239 2240
  else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT))
    max_length= my_decimal_precision_to_length(max_int_part+decimals, decimals,
                                            unsigned_flag);
unknown's avatar
unknown committed
2241 2242 2243
}


2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
/*
  Compare item arguments in the DATETIME context.

  SYNOPSIS
    cmp_datetimes()
    value [out]   found least/greatest DATE/DATETIME value

  DESCRIPTION
    Compare item arguments as DATETIME values and return the index of the
    least/greatest argument in the arguments array.
    The correct integer DATE/DATETIME value of the found argument is
    stored to the value pointer, if latter is provided.

  RETURN
   0	If one of arguments is NULL
   #	index of the least/greatest argument
*/

uint Item_func_min_max::cmp_datetimes(ulonglong *value)
{
  ulonglong min_max;
  uint min_max_idx= 0;
  LINT_INIT(min_max);

  for (uint i=0; i < arg_count ; i++)
  {
    Item **arg= args + i;
    bool is_null;
    ulonglong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null);
    if ((null_value= args[i]->null_value))
      return 0;
    if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
    {
      min_max= res;
      min_max_idx= i;
    }
  }
  if (value)
  {
    *value= min_max;
    if (datetime_item->field_type() == MYSQL_TYPE_DATE)
      *value/= 1000000L;
  }
  return min_max_idx;
}


unknown's avatar
unknown committed
2291 2292
String *Item_func_min_max::val_str(String *str)
{
2293
  DBUG_ASSERT(fixed == 1);
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
  if (compare_as_dates)
  {
    String *str_res;
    uint min_max_idx= cmp_datetimes(NULL);
    if (null_value)
      return 0;
    str_res= args[min_max_idx]->val_str(str);
    str_res->set_charset(collation.collation);
    return str_res;
  }
unknown's avatar
unknown committed
2304 2305 2306 2307 2308 2309
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
2310
    str->set_int(nr, unsigned_flag, &my_charset_bin);
unknown's avatar
unknown committed
2311 2312
    return str;
  }
unknown's avatar
unknown committed
2313 2314 2315 2316 2317 2318 2319 2320
  case DECIMAL_RESULT:
  {
    my_decimal dec_buf, *dec_val= val_decimal(&dec_buf);
    if (null_value)
      return 0;
    my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str);
    return str;
  }
unknown's avatar
unknown committed
2321 2322
  case REAL_RESULT:
  {
2323
    double nr= val_real();
unknown's avatar
unknown committed
2324 2325
    if (null_value)
      return 0; /* purecov: inspected */
2326
    str->set_real(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
2327 2328 2329 2330 2331 2332 2333 2334
    return str;
  }
  case STRING_RESULT:
  {
    String *res;
    LINT_INIT(res);
    for (uint i=0; i < arg_count ; i++)
    {
unknown's avatar
unknown committed
2335
      if (i == 0)
unknown's avatar
unknown committed
2336 2337 2338 2339 2340 2341 2342
	res=args[i]->val_str(str);
      else
      {
	String *res2;
	res2= args[i]->val_str(res == str ? &tmp_value : str);
	if (res2)
	{
2343
	  int cmp= sortcmp(res,res2,collation.collation);
unknown's avatar
unknown committed
2344 2345 2346 2347
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
unknown's avatar
unknown committed
2348
      if ((null_value= args[i]->null_value))
2349
        return 0;
unknown's avatar
unknown committed
2350
    }
2351
    res->set_charset(collation.collation);
unknown's avatar
unknown committed
2352 2353
    return res;
  }
2354
  case ROW_RESULT:
unknown's avatar
unknown committed
2355
  default:
unknown's avatar
unknown committed
2356
    // This case should never be chosen
unknown's avatar
unknown committed
2357 2358
    DBUG_ASSERT(0);
    return 0;
unknown's avatar
unknown committed
2359 2360 2361 2362 2363
  }
  return 0;					// Keep compiler happy
}


2364
double Item_func_min_max::val_real()
unknown's avatar
unknown committed
2365
{
2366
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2367
  double value=0.0;
2368 2369
  if (compare_as_dates)
  {
unknown's avatar
unknown committed
2370
    ulonglong result= 0;
2371 2372 2373
    (void)cmp_datetimes(&result);
    return (double)result;
  }
unknown's avatar
unknown committed
2374 2375
  for (uint i=0; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
2376
    if (i == 0)
2377
      value= args[i]->val_real();
unknown's avatar
unknown committed
2378 2379
    else
    {
2380
      double tmp= args[i]->val_real();
unknown's avatar
unknown committed
2381 2382 2383
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
unknown's avatar
unknown committed
2384 2385
    if ((null_value= args[i]->null_value))
      break;
unknown's avatar
unknown committed
2386 2387 2388 2389 2390 2391 2392
  }
  return value;
}


longlong Item_func_min_max::val_int()
{
2393
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2394
  longlong value=0;
2395 2396
  if (compare_as_dates)
  {
unknown's avatar
unknown committed
2397
    ulonglong result= 0;
2398 2399 2400
    (void)cmp_datetimes(&result);
    return (longlong)result;
  }
unknown's avatar
unknown committed
2401 2402
  for (uint i=0; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
2403
    if (i == 0)
2404
      value=args[i]->val_int();
unknown's avatar
unknown committed
2405 2406
    else
    {
2407 2408 2409
      longlong tmp=args[i]->val_int();
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
unknown's avatar
unknown committed
2410
    }
2411 2412
    if ((null_value= args[i]->null_value))
      break;
unknown's avatar
unknown committed
2413 2414 2415 2416
  }
  return value;
}

unknown's avatar
unknown committed
2417 2418 2419 2420

my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
{
  DBUG_ASSERT(fixed == 1);
2421 2422 2423
  my_decimal tmp_buf, *tmp, *res;
  LINT_INIT(res);

2424 2425
  if (compare_as_dates)
  {
unknown's avatar
unknown committed
2426
    ulonglong value= 0;
2427 2428 2429 2430
    (void)cmp_datetimes(&value);
    ulonglong2decimal(value, dec);
    return dec;
  }
unknown's avatar
unknown committed
2431 2432
  for (uint i=0; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
2433
    if (i == 0)
unknown's avatar
unknown committed
2434 2435 2436
      res= args[i]->val_decimal(dec);
    else
    {
2437 2438
      tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
      if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
unknown's avatar
unknown committed
2439 2440 2441
      {
        if (tmp == &tmp_buf)
        {
2442
          /* Move value out of tmp_buf as this will be reused on next loop */
unknown's avatar
unknown committed
2443 2444 2445 2446 2447 2448 2449
          my_decimal2decimal(tmp, dec);
          res= dec;
        }
        else
          res= tmp;
      }
    }
unknown's avatar
unknown committed
2450
    if ((null_value= args[i]->null_value))
2451 2452
    {
      res= 0;
unknown's avatar
unknown committed
2453
      break;
2454
    }
unknown's avatar
unknown committed
2455 2456 2457 2458 2459
  }
  return res;
}


unknown's avatar
unknown committed
2460 2461
longlong Item_func_length::val_int()
{
2462
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) res->length();
}

unknown's avatar
unknown committed
2473

unknown's avatar
unknown committed
2474 2475
longlong Item_func_char_length::val_int()
{
2476
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2477 2478 2479 2480 2481 2482 2483
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
2484
  return (longlong) res->numchars();
unknown's avatar
unknown committed
2485 2486
}

unknown's avatar
unknown committed
2487

unknown's avatar
unknown committed
2488 2489
longlong Item_func_coercibility::val_int()
{
2490
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2491
  null_value= 0;
2492
  return (longlong) args[0]->collation.derivation;
unknown's avatar
unknown committed
2493
}
unknown's avatar
unknown committed
2494

unknown's avatar
unknown committed
2495

2496 2497
void Item_func_locate::fix_length_and_dec()
{
2498
  max_length= MY_INT32_NUM_DECIMAL_DIGITS;
2499
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1);
2500 2501
}

unknown's avatar
unknown committed
2502

unknown's avatar
unknown committed
2503 2504
longlong Item_func_locate::val_int()
{
2505
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2506 2507 2508 2509 2510 2511 2512 2513
  String *a=args[0]->val_str(&value1);
  String *b=args[1]->val_str(&value2);
  if (!a || !b)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
2514 2515 2516
  /* must be longlong to avoid truncation */
  longlong start=  0; 
  longlong start0= 0;
2517
  my_match_t match;
2518

unknown's avatar
unknown committed
2519 2520
  if (arg_count == 3)
  {
2521 2522 2523 2524 2525 2526
    start0= start= args[2]->val_int() - 1;

    if ((start < 0) || (start > a->length()))
      return 0;

    /* start is now sufficiently valid to pass to charpos function */
2527
    start= a->charpos((int) start);
2528 2529

    if (start + b->length() > a->length())
unknown's avatar
unknown committed
2530 2531
      return 0;
  }
2532

unknown's avatar
unknown committed
2533
  if (!b->length())				// Found empty string at start
2534
    return start + 1;
2535
  
2536
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
2537 2538
                                            a->ptr()+start,
                                            (uint) (a->length()-start),
2539 2540 2541
                                            b->ptr(), b->length(),
                                            &match, 1))
    return 0;
2542
  return (longlong) match.mb_len + start0 + 1;
unknown's avatar
unknown committed
2543 2544 2545
}


2546 2547
void Item_func_locate::print(String *str)
{
2548
  str->append(STRING_WITH_LEN("locate("));
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
  args[1]->print(str);
  str->append(',');
  args[0]->print(str);
  if (arg_count == 3)
  {
    str->append(',');
    args[2]->print(str);
  }
  str->append(')');
}


unknown's avatar
unknown committed
2561 2562
longlong Item_func_field::val_int()
{
2563
  DBUG_ASSERT(fixed == 1);
2564

2565 2566 2567
  if (cmp_type == STRING_RESULT)
  {
    String *field;
2568 2569
    if (!(field= args[0]->val_str(&value)))
      return 0;
2570
    for (uint i=1 ; i < arg_count ; i++)
2571 2572
    {
      String *tmp_value=args[i]->val_str(&tmp);
unknown's avatar
Fix:  
unknown committed
2573
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
2574
        return (longlong) (i);
2575 2576 2577 2578
    }
  }
  else if (cmp_type == INT_RESULT)
  {
2579
    longlong val= args[0]->val_int();
unknown's avatar
unknown committed
2580 2581
    if (args[0]->null_value)
      return 0;
2582
    for (uint i=1; i < arg_count ; i++)
2583
    {
2584
      if (val == args[i]->val_int() && !args[i]->null_value)
2585
        return (longlong) (i);
2586 2587
    }
  }
unknown's avatar
unknown committed
2588 2589 2590 2591
  else if (cmp_type == DECIMAL_RESULT)
  {
    my_decimal dec_arg_buf, *dec_arg,
               dec_buf, *dec= args[0]->val_decimal(&dec_buf);
unknown's avatar
unknown committed
2592 2593
    if (args[0]->null_value)
      return 0;
unknown's avatar
unknown committed
2594 2595 2596
    for (uint i=1; i < arg_count; i++)
    {
      dec_arg= args[i]->val_decimal(&dec_arg_buf);
unknown's avatar
unknown committed
2597
      if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec))
unknown's avatar
unknown committed
2598 2599 2600
        return (longlong) (i);
    }
  }
2601
  else
unknown's avatar
unknown committed
2602
  {
2603
    double val= args[0]->val_real();
unknown's avatar
unknown committed
2604 2605
    if (args[0]->null_value)
      return 0;
2606
    for (uint i=1; i < arg_count ; i++)
2607
    {
unknown's avatar
unknown committed
2608
      if (val == args[i]->val_real() && !args[i]->null_value)
2609
        return (longlong) (i);
2610
    }
unknown's avatar
unknown committed
2611 2612 2613 2614
  }
  return 0;
}

unknown's avatar
unknown committed
2615

2616 2617 2618
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
2619 2620
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
2621 2622
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
2623
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1);
2624
}
unknown's avatar
unknown committed
2625

2626

unknown's avatar
unknown committed
2627 2628
longlong Item_func_ascii::val_int()
{
2629
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0);
}

longlong Item_func_ord::val_int()
{
2642
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2643 2644 2645 2646 2647 2648 2649 2650 2651
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  if (!res->length()) return 0;
#ifdef USE_MB
2652
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
2653 2654
  {
    register const char *str=res->ptr();
2655
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
unknown's avatar
unknown committed
2656 2657
    if (!l)
      return (longlong)((uchar) *str);
unknown's avatar
unknown committed
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    while (l--)
      n=(n<<8)|(uint32)((uchar) *str++);
    return (longlong) n;
  }
#endif
  return (longlong) ((uchar) (*res)[0]);
}

	/* Search after a string in a string of strings separated by ',' */
	/* Returns number of found type >= 1 or 0 if not found */
	/* This optimizes searching in enums to bit testing! */

void Item_func_find_in_set::fix_length_and_dec()
{
  decimals=0;
  max_length=3;					// 1-999
  if (args[0]->const_item() && args[1]->type() == FIELD_ITEM)
  {
    Field *field= ((Item_field*) args[1])->field;
2677
    if (field->real_type() == MYSQL_TYPE_SET)
unknown's avatar
unknown committed
2678 2679 2680 2681
    {
      String *find=args[0]->val_str(&value);
      if (find)
      {
2682 2683
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
unknown's avatar
unknown committed
2684 2685 2686 2687 2688 2689
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
2690
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1);
unknown's avatar
unknown committed
2691 2692 2693 2694 2695 2696
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
2697
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
  if (enum_value)
  {
    ulonglong tmp=(ulonglong) args[1]->val_int();
    if (!(null_value=args[1]->null_value || args[0]->null_value))
    {
      if (tmp & enum_bit)
	return enum_value;
    }
    return 0L;
  }

  String *find=args[0]->val_str(&value);
  String *buffer=args[1]->val_str(&value2);
  if (!find || !buffer)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;

  int diff;
  if ((diff=buffer->length() - find->length()) >= 0)
  {
2721 2722 2723 2724 2725 2726 2727 2728 2729
    my_wc_t wc;
    CHARSET_INFO *cs= cmp_collation.collation;
    const char *str_begin= buffer->ptr();
    const char *str_end= buffer->ptr();
    const char *real_end= str_end+buffer->length();
    const uchar *find_str= (const uchar *) find->ptr();
    uint find_str_len= find->length();
    int position= 0;
    while (1)
unknown's avatar
unknown committed
2730
    {
2731 2732 2733
      int symbol_len;
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
                                       (uchar*) real_end)) > 0)
unknown's avatar
unknown committed
2734
      {
2735 2736
        const char *substr_end= str_end + symbol_len;
        bool is_last_item= (substr_end == real_end);
2737 2738
        bool is_separator= (wc == (my_wc_t) separator);
        if (is_separator || is_last_item)
2739 2740
        {
          position++;
2741
          if (is_last_item && !is_separator)
2742 2743 2744 2745 2746 2747 2748 2749 2750
            str_end= substr_end;
          if (!my_strnncoll(cs, (const uchar *) str_begin,
                            str_end - str_begin,
                            find_str, find_str_len))
            return (longlong) position;
          else
            str_begin= substr_end;
        }
        str_end= substr_end;
unknown's avatar
unknown committed
2751
      }
unknown's avatar
unknown committed
2752 2753
      else if (str_end - str_begin == 0 &&
               find_str_len == 0 &&
2754 2755 2756
               wc == (my_wc_t) separator)
        return (longlong) ++position;
      else
unknown's avatar
unknown committed
2757
        return LL(0);
2758
    }
unknown's avatar
unknown committed
2759 2760 2761 2762 2763 2764
  }
  return 0;
}

longlong Item_func_bit_count::val_int()
{
2765
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2766
  ulonglong value= (ulonglong) args[0]->val_int();
2767
  if ((null_value= args[0]->null_value))
unknown's avatar
unknown committed
2768
    return 0; /* purecov: inspected */
unknown's avatar
unknown committed
2769
  return (longlong) my_count_bits(value);
unknown's avatar
unknown committed
2770 2771 2772 2773 2774 2775
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
2776
** Rewritten by monty.
unknown's avatar
unknown committed
2777 2778 2779 2780
****************************************************************************/

#ifdef HAVE_DLOPEN

2781
void udf_handler::cleanup()
unknown's avatar
unknown committed
2782
{
2783
  if (!not_original)
unknown's avatar
unknown committed
2784
  {
2785
    if (initialized)
unknown's avatar
unknown committed
2786
    {
2787 2788
      if (u_d->func_deinit != NULL)
      {
2789
        Udf_func_deinit deinit= u_d->func_deinit;
2790 2791 2792
        (*deinit)(&initid);
      }
      free_udf(u_d);
2793
      initialized= FALSE;
unknown's avatar
unknown committed
2794
    }
2795 2796
    if (buffers)				// Because of bug in ecc
      delete [] buffers;
2797
    buffers= 0;
unknown's avatar
unknown committed
2798 2799 2800 2801 2802
  }
}


bool
2803
udf_handler::fix_fields(THD *thd, Item_result_field *func,
unknown's avatar
unknown committed
2804 2805
			uint arg_count, Item **arguments)
{
2806
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
2807
  uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
2808
#endif
unknown's avatar
unknown committed
2809 2810
  DBUG_ENTER("Item_udf_func::fix_fields");

2811
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
unknown's avatar
unknown committed
2812
    DBUG_RETURN(TRUE);				// Fatal error flag is set!
unknown's avatar
unknown committed
2813

2814
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
unknown's avatar
unknown committed
2815 2816 2817

  if (!tmp_udf)
  {
2818
    my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
unknown's avatar
unknown committed
2819
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2820 2821 2822 2823 2824
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
2825
  func->maybe_null=0;
unknown's avatar
unknown committed
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
  used_tables_cache=0;
  const_item_cache=1;

  if ((f_args.arg_count=arg_count))
  {
    if (!(f_args.arg_type= (Item_result*)
	  sql_alloc(f_args.arg_count*sizeof(Item_result))))

    {
      free_udf(u_d);
unknown's avatar
unknown committed
2836
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2837 2838 2839 2840 2841 2842 2843
    }
    uint i;
    Item **arg,**arg_end;
    for (i=0, arg=arguments, arg_end=arguments+arg_count;
	 arg != arg_end ;
	 arg++,i++)
    {
unknown's avatar
unknown committed
2844
      if (!(*arg)->fixed &&
2845
          (*arg)->fix_fields(thd, arg))
unknown's avatar
unknown committed
2846
	DBUG_RETURN(1);
2847
      // we can't assign 'item' before, because fix_fields() can change arg
unknown's avatar
unknown committed
2848
      Item *item= *arg;
2849
      if (item->check_cols(1))
unknown's avatar
unknown committed
2850
	DBUG_RETURN(TRUE);
2851 2852 2853 2854 2855 2856 2857 2858 2859
      /*
	TODO: We should think about this. It is not always
	right way just to set an UDF result to return my_charset_bin
	if one argument has binary sorting order.
	The result collation should be calculated according to arguments
	derivations in some cases and should not in other cases.
	Moreover, some arguments can represent a numeric input
	which doesn't effect the result character set and collation.
	There is no a general rule for UDF. Everything depends on
unknown's avatar
unknown committed
2860
        the particular user defined function.
2861
      */
2862 2863
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
unknown's avatar
unknown committed
2864
      if (item->maybe_null)
unknown's avatar
unknown committed
2865
	func->maybe_null=1;
unknown's avatar
unknown committed
2866 2867 2868 2869
      func->with_sum_func= func->with_sum_func || item->with_sum_func;
      used_tables_cache|=item->used_tables();
      const_item_cache&=item->const_item();
      f_args.arg_type[i]=item->result_type();
unknown's avatar
unknown committed
2870
    }
unknown's avatar
unknown committed
2871
    //TODO: why all following memory is not allocated with 1 call of sql_alloc?
unknown's avatar
unknown committed
2872 2873
    if (!(buffers=new String[arg_count]) ||
	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
2874 2875 2876 2877 2878 2879 2880
	!(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) ||
	!(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) ||
	!(num_buffer= (char*) sql_alloc(arg_count *
					ALIGN_SIZE(sizeof(double)))) ||
	!(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) ||
	!(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count *
						       sizeof(long))))
unknown's avatar
unknown committed
2881 2882
    {
      free_udf(u_d);
unknown's avatar
unknown committed
2883
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
    }
  }
  func->fix_length_and_dec();
  initid.max_length=func->max_length;
  initid.maybe_null=func->maybe_null;
  initid.const_item=const_item_cache;
  initid.decimals=func->decimals;
  initid.ptr=0;

  if (u_d->func_init)
  {
    char *to=num_buffer;
    for (uint i=0; i < arg_count; i++)
    {
2898 2899 2900 2901 2902 2903
      /*
       For a constant argument i, args->args[i] points to the argument value. 
       For non-constant, args->args[i] is NULL.
      */
      f_args.args[i]= NULL;         /* Non-const unless updated below. */

2904 2905 2906 2907
      f_args.lengths[i]= arguments[i]->max_length;
      f_args.maybe_null[i]= (char) arguments[i]->maybe_null;
      f_args.attributes[i]= arguments[i]->name;
      f_args.attribute_lengths[i]= arguments[i]->name_length;
unknown's avatar
unknown committed
2908

2909
      if (arguments[i]->const_item())
unknown's avatar
unknown committed
2910
      {
2911 2912 2913 2914 2915 2916
        switch (arguments[i]->result_type()) 
        {
        case STRING_RESULT:
        case DECIMAL_RESULT:
        {
          String *res= arguments[i]->val_str(&buffers[i]);
2917 2918
          if (arguments[i]->null_value)
            continue;
2919 2920
          f_args.args[i]= (char*) res->c_ptr();
          f_args.lengths[i]= res->length();
2921 2922 2923 2924
          break;
        }
        case INT_RESULT:
          *((longlong*) to)= arguments[i]->val_int();
2925 2926
          if (arguments[i]->null_value)
            continue;
2927 2928 2929 2930 2931
          f_args.args[i]= to;
          to+= ALIGN_SIZE(sizeof(longlong));
          break;
        case REAL_RESULT:
          *((double*) to)= arguments[i]->val_real();
2932 2933
          if (arguments[i]->null_value)
            continue;
2934 2935 2936 2937 2938 2939 2940 2941 2942
          f_args.args[i]= to;
          to+= ALIGN_SIZE(sizeof(double));
          break;
        case ROW_RESULT:
        default:
          // This case should never be chosen
          DBUG_ASSERT(0);
          break;
        }
unknown's avatar
unknown committed
2943 2944
      }
    }
2945
    thd->net.last_error[0]=0;
2946
    Udf_func_init init= u_d->func_init;
unknown's avatar
unknown committed
2947 2948
    if ((error=(uchar) init(&initid, &f_args, thd->net.last_error)))
    {
2949 2950
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
               u_d->name.str, thd->net.last_error);
unknown's avatar
unknown committed
2951
      free_udf(u_d);
unknown's avatar
unknown committed
2952
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2953 2954 2955 2956
    }
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
    func->maybe_null=initid.maybe_null;
    const_item_cache=initid.const_item;
2957
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
unknown's avatar
unknown committed
2958 2959 2960 2961
  }
  initialized=1;
  if (error)
  {
2962 2963
    my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
             u_d->name.str, ER(ER_UNKNOWN_ERROR));
unknown's avatar
unknown committed
2964
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2965
  }
unknown's avatar
unknown committed
2966
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
}


bool udf_handler::get_arguments()
{
  if (error)
    return 1;					// Got an error earlier
  char *to= num_buffer;
  uint str_count=0;
  for (uint i=0; i < f_args.arg_count; i++)
  {
    f_args.args[i]=0;
    switch (f_args.arg_type[i]) {
    case STRING_RESULT:
unknown's avatar
unknown committed
2981
    case DECIMAL_RESULT:
unknown's avatar
unknown committed
2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
      {
	String *res=args[i]->val_str(&buffers[str_count++]);
	if (!(args[i]->null_value))
	{
	  f_args.args[i]=    (char*) res->ptr();
	  f_args.lengths[i]= res->length();
	  break;
	}
      }
    case INT_RESULT:
      *((longlong*) to) = args[i]->val_int();
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(longlong));
      }
      break;
    case REAL_RESULT:
3000
      *((double*) to)= args[i]->val_real();
unknown's avatar
unknown committed
3001 3002 3003 3004 3005 3006
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(double));
      }
      break;
3007
    case ROW_RESULT:
unknown's avatar
unknown committed
3008
    default:
unknown's avatar
unknown committed
3009
      // This case should never be chosen
unknown's avatar
unknown committed
3010
      DBUG_ASSERT(0);
3011
      break;
unknown's avatar
unknown committed
3012 3013 3014 3015 3016 3017 3018 3019 3020
    }
  }
  return 0;
}

/* This returns (String*) 0 in case of NULL values */

String *udf_handler::val_str(String *str,String *save_str)
{
3021
  uchar is_null_tmp=0;
unknown's avatar
unknown committed
3022
  ulong res_length;
3023
  DBUG_ENTER("udf_handler::val_str");
unknown's avatar
unknown committed
3024 3025

  if (get_arguments())
3026
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3027 3028 3029 3030 3031 3032 3033 3034 3035
  char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
    (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
    u_d->func;

  if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH)
  {						// This happens VERY seldom
    if (str->alloc(MAX_FIELD_WIDTH))
    {
      error=1;
3036
      DBUG_RETURN(0);
unknown's avatar
unknown committed
3037 3038
    }
  }
3039 3040
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
		 &is_null_tmp, &error);
3041
  DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length));
3042
  if (is_null_tmp || !res || error)		// The !res is for safety
unknown's avatar
unknown committed
3043
  {
3044 3045
    DBUG_PRINT("info", ("Null or error"));
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3046 3047 3048 3049
  }
  if (res == str->ptr())
  {
    str->length(res_length);
3050 3051
    DBUG_PRINT("exit", ("str: %s", str->ptr()));
    DBUG_RETURN(str);
unknown's avatar
unknown committed
3052
  }
3053
  save_str->set(res, res_length, str->charset());
3054 3055
  DBUG_PRINT("exit", ("save_str: %s", save_str->ptr()));
  DBUG_RETURN(save_str);
unknown's avatar
unknown committed
3056 3057 3058
}


3059 3060 3061 3062
/*
  For the moment, UDF functions are returning DECIMAL values as strings
*/

unknown's avatar
unknown committed
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf)
{
  char buf[DECIMAL_MAX_STR_LENGTH+1], *end;
  ulong res_length= DECIMAL_MAX_STR_LENGTH;

  if (get_arguments())
  {
    *null_value=1;
    return 0;
  }
  char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
    (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
    u_d->func;

  char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error);
  if (is_null || error)
  {
    *null_value= 1;
    return 0;
  }
3083 3084
  end= res+ res_length;
  str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
unknown's avatar
unknown committed
3085 3086 3087
  return dec_buf;
}

unknown's avatar
unknown committed
3088

3089 3090 3091 3092 3093 3094
void Item_udf_func::cleanup()
{
  udf.cleanup();
  Item_func::cleanup();
}

unknown's avatar
unknown committed
3095

3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
void Item_udf_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
  for (uint i=0 ; i < arg_count ; i++)
  {
    if (i != 0)
      str->append(',');
    args[i]->print_item_w_name(str);
  }
  str->append(')');
}


3110
double Item_func_udf_float::val_real()
unknown's avatar
unknown committed
3111
{
3112
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3113 3114 3115 3116 3117 3118 3119 3120 3121
  DBUG_ENTER("Item_func_udf_float::val");
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
		     args[0]->result_type(), arg_count));
  DBUG_RETURN(udf.val(&null_value));
}


String *Item_func_udf_float::val_str(String *str)
{
3122
  DBUG_ASSERT(fixed == 1);
3123
  double nr= val_real();
unknown's avatar
unknown committed
3124 3125
  if (null_value)
    return 0;					/* purecov: inspected */
3126
  str->set_real(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
3127 3128 3129 3130 3131 3132
  return str;
}


longlong Item_func_udf_int::val_int()
{
3133
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3134 3135 3136 3137 3138 3139 3140
  DBUG_ENTER("Item_func_udf_int::val_int");
  DBUG_RETURN(udf.val_int(&null_value));
}


String *Item_func_udf_int::val_str(String *str)
{
3141
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3142 3143 3144
  longlong nr=val_int();
  if (null_value)
    return 0;
3145
  str->set_int(nr, unsigned_flag, &my_charset_bin);
unknown's avatar
unknown committed
3146 3147 3148
  return str;
}

unknown's avatar
unknown committed
3149 3150 3151 3152

longlong Item_func_udf_decimal::val_int()
{
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
3153
  longlong result;
unknown's avatar
unknown committed
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163
  if (null_value)
    return 0;
  my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
  return result;
}


double Item_func_udf_decimal::val_real()
{
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
3164
  double result;
unknown's avatar
unknown committed
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
  if (null_value)
    return 0.0;
  my_decimal2double(E_DEC_FATAL_ERROR, dec, &result);
  return result;
}


my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf)
{
  DBUG_ASSERT(fixed == 1);
  DBUG_ENTER("Item_func_udf_decimal::val_decimal");
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
                     args[0]->result_type(), arg_count));

  DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
}


String *Item_func_udf_decimal::val_str(String *str)
{
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
  if (null_value)
    return 0;
  if (str->length() < DECIMAL_MAX_STR_LENGTH)
    str->length(DECIMAL_MAX_STR_LENGTH);
  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str);
  return str;
}


void Item_func_udf_decimal::fix_length_and_dec()
{
  fix_num_length_and_dec();
}


unknown's avatar
unknown committed
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
/* Default max_length is max argument length */

void Item_func_udf_str::fix_length_and_dec()
{
  DBUG_ENTER("Item_func_udf_str::fix_length_and_dec");
  max_length=0;
  for (uint i = 0; i < arg_count; i++)
    set_if_bigger(max_length,args[i]->max_length);
  DBUG_VOID_RETURN;
}

String *Item_func_udf_str::val_str(String *str)
{
3215
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3216 3217 3218 3219 3220
  String *res=udf.val_str(str,&str_value);
  null_value = !res;
  return res;
}

3221 3222

/*
3223 3224
   This has to come last in the udf_handler methods, or C for AIX
   version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.)
3225 3226 3227 3228
 */

udf_handler::~udf_handler()
{
3229 3230
  /* Everything should be properly cleaned up by this moment. */
  DBUG_ASSERT(not_original || !(initialized || buffers));
3231 3232
}

unknown's avatar
unknown committed
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
#else
bool udf_handler::get_arguments() { return 0; }
#endif /* HAVE_DLOPEN */

/*
** User level locks
*/

pthread_mutex_t LOCK_user_locks;
static HASH hash_user_locks;

3244
class User_level_lock
unknown's avatar
unknown committed
3245
{
3246 3247
  uchar *key;
  size_t key_length;
unknown's avatar
unknown committed
3248 3249 3250 3251 3252

public:
  int count;
  bool locked;
  pthread_cond_t cond;
unknown's avatar
unknown committed
3253 3254
  my_thread_id thread_id;
  void set_thread(THD *thd) { thread_id= thd->thread_id; }
unknown's avatar
unknown committed
3255

3256
  User_level_lock(const uchar *key_arg,uint length, ulong id) 
unknown's avatar
SCRUM  
unknown committed
3257
    :key_length(length),count(1),locked(1), thread_id(id)
unknown's avatar
unknown committed
3258
  {
3259
    key= (uchar*) my_memdup(key_arg,length,MYF(0));
unknown's avatar
unknown committed
3260 3261 3262
    pthread_cond_init(&cond,NULL);
    if (key)
    {
3263
      if (my_hash_insert(&hash_user_locks,(uchar*) this))
unknown's avatar
unknown committed
3264
      {
3265
	my_free(key,MYF(0));
unknown's avatar
unknown committed
3266 3267 3268 3269
	key=0;
      }
    }
  }
3270
  ~User_level_lock()
unknown's avatar
unknown committed
3271 3272 3273
  {
    if (key)
    {
3274 3275
      hash_delete(&hash_user_locks,(uchar*) this);
      my_free(key, MYF(0));
unknown's avatar
unknown committed
3276 3277 3278 3279
    }
    pthread_cond_destroy(&cond);
  }
  inline bool initialized() { return key != 0; }
3280
  friend void item_user_lock_release(User_level_lock *ull);
3281 3282
  friend uchar *ull_get_key(const User_level_lock *ull, size_t *length,
                            my_bool not_used);
unknown's avatar
unknown committed
3283 3284
};

3285 3286
uchar *ull_get_key(const User_level_lock *ull, size_t *length,
                   my_bool not_used __attribute__((unused)))
unknown's avatar
unknown committed
3287
{
3288 3289
  *length= ull->key_length;
  return ull->key;
unknown's avatar
unknown committed
3290 3291
}

3292 3293 3294

static bool item_user_lock_inited= 0;

unknown's avatar
unknown committed
3295 3296
void item_user_lock_init(void)
{
3297
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
unknown's avatar
unknown committed
3298 3299
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
3300
  item_user_lock_inited= 1;
unknown's avatar
unknown committed
3301 3302 3303 3304
}

void item_user_lock_free(void)
{
3305 3306 3307 3308 3309 3310
  if (item_user_lock_inited)
  {
    item_user_lock_inited= 0;
    hash_free(&hash_user_locks);
    pthread_mutex_destroy(&LOCK_user_locks);
  }
unknown's avatar
unknown committed
3311 3312
}

3313
void item_user_lock_release(User_level_lock *ull)
unknown's avatar
unknown committed
3314 3315
{
  ull->locked=0;
3316
  ull->thread_id= 0;
unknown's avatar
unknown committed
3317 3318 3319 3320 3321 3322
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

unknown's avatar
unknown committed
3323 3324 3325 3326 3327 3328 3329
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

longlong Item_master_pos_wait::val_int()
{
3330
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3331 3332
  THD* thd = current_thd;
  String *log_name = args[0]->val_str(&value);
3333
  int event_count= 0;
unknown's avatar
unknown committed
3334

unknown's avatar
unknown committed
3335 3336 3337 3338 3339 3340
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
3341
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
3342
  longlong pos = (ulong)args[1]->val_int();
3343 3344
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
unknown's avatar
unknown committed
3345 3346 3347 3348
  {
    null_value = 1;
    event_count=0;
  }
3349
#endif
unknown's avatar
unknown committed
3350 3351 3352
  return event_count;
}

3353 3354 3355 3356
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
3357
  User_level_lock* ull;
3358
  struct timespec abstime;
3359 3360
  size_t lock_name_len;
  lock_name_len= strlen(lock_name);
3361 3362 3363 3364 3365 3366 3367 3368
  pthread_mutex_lock(&LOCK_user_locks);

  if (thd->ull)
  {
    item_user_lock_release(thd->ull);
    thd->ull=0;
  }

3369 3370 3371 3372 3373
  /*
    If the lock has not been aquired by some client, we do not want to
    create an entry for it, since we immediately release the lock. In
    this case, we will not be waiting, but rather, just waste CPU and
    memory on the whole deal
3374
  */
3375 3376 3377
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
                                             (uchar*) lock_name,
                                             lock_name_len))))
3378 3379 3380 3381 3382 3383
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

3384 3385 3386 3387
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
3388 3389 3390 3391
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

3392
  set_timespec(abstime,lock_timeout);
unknown's avatar
unknown committed
3393 3394 3395 3396 3397 3398 3399
  while (ull->locked && !thd->killed)
  {
    int error= pthread_cond_timedwait(&ull->cond, &LOCK_user_locks, &abstime);
    if (error == ETIMEDOUT || error == ETIME)
      break;
  }

3400 3401 3402 3403 3404 3405 3406 3407
  if (ull->locked)
  {
    if (!--ull->count)
      delete ull;				// Should never happen
  }
  else
  {
    ull->locked=1;
3408
    ull->set_thread(thd);
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
    thd->ull=ull;
  }
  pthread_mutex_unlock(&LOCK_user_locks);
  pthread_mutex_lock(&thd->mysys_var->mutex);
  thd->proc_info=0;
  thd->mysys_var->current_mutex= 0;
  thd->mysys_var->current_cond=  0;
  pthread_mutex_unlock(&thd->mysys_var->mutex);
  pthread_mutex_lock(&LOCK_user_locks);
  if (thd->ull)
  {
    item_user_lock_release(thd->ull);
    thd->ull=0;
  }
  pthread_mutex_unlock(&LOCK_user_locks);
}

#endif

unknown's avatar
unknown committed
3428 3429 3430 3431 3432 3433 3434 3435 3436
/*
  Get a user level lock. If the thread has an old lock this is first released.
  Returns 1:  Got lock
  Returns 0:  Timeout
  Returns NULL: Error
*/

longlong Item_func_get_lock::val_int()
{
3437
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3438 3439 3440 3441
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
3442
  User_level_lock *ull;
unknown's avatar
unknown committed
3443
  int error;
3444
  DBUG_ENTER("Item_func_get_lock::val_int");
unknown's avatar
unknown committed
3445

3446 3447 3448 3449 3450 3451 3452 3453
  /*
    In slave thread no need to get locks, everything is serialized. Anyway
    there is no way to make GET_LOCK() work on slave like it did on master
    (i.e. make it return exactly the same value) because we don't have the
    same other concurrent threads environment. No matter what we return here,
    it's not guaranteed to be same as on master.
  */
  if (thd->slave_thread)
3454
    DBUG_RETURN(1);
3455

unknown's avatar
unknown committed
3456 3457 3458 3459 3460 3461
  pthread_mutex_lock(&LOCK_user_locks);

  if (!res || !res->length())
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    null_value=1;
3462
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3463
  }
3464 3465
  DBUG_PRINT("info", ("lock %.*s, thd=%ld", res->length(), res->ptr(),
                      (long) thd->real_id));
unknown's avatar
unknown committed
3466 3467 3468 3469 3470 3471 3472 3473
  null_value=0;

  if (thd->ull)
  {
    item_user_lock_release(thd->ull);
    thd->ull=0;
  }

3474
  if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks,
3475 3476
                                              (uchar*) res->ptr(),
                                              (size_t) res->length()))))
unknown's avatar
unknown committed
3477
  {
3478 3479
    ull= new User_level_lock((uchar*) res->ptr(), (size_t) res->length(),
                             thd->thread_id);
unknown's avatar
unknown committed
3480 3481 3482 3483 3484
    if (!ull || !ull->initialized())
    {
      delete ull;
      pthread_mutex_unlock(&LOCK_user_locks);
      null_value=1;				// Probably out of memory
3485
      DBUG_RETURN(0);
unknown's avatar
unknown committed
3486
    }
3487
    ull->set_thread(thd);
unknown's avatar
unknown committed
3488 3489
    thd->ull=ull;
    pthread_mutex_unlock(&LOCK_user_locks);
3490 3491
    DBUG_PRINT("info", ("made new lock"));
    DBUG_RETURN(1);				// Got new lock
unknown's avatar
unknown committed
3492 3493
  }
  ull->count++;
3494
  DBUG_PRINT("info", ("ull->count=%d", ull->count));
unknown's avatar
unknown committed
3495

3496 3497 3498 3499
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks.
  */
unknown's avatar
unknown committed
3500 3501 3502 3503
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

3504
  set_timespec(abstime,timeout);
unknown's avatar
unknown committed
3505 3506 3507
  error= 0;
  while (ull->locked && !thd->killed)
  {
3508
    DBUG_PRINT("info", ("waiting on lock"));
unknown's avatar
unknown committed
3509 3510
    error= pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime);
    if (error == ETIMEDOUT || error == ETIME)
3511 3512
    {
      DBUG_PRINT("info", ("lock wait timeout"));
unknown's avatar
unknown committed
3513
      break;
3514
    }
unknown's avatar
unknown committed
3515 3516 3517
    error= 0;
  }

unknown's avatar
unknown committed
3518 3519 3520
  if (ull->locked)
  {
    if (!--ull->count)
unknown's avatar
unknown committed
3521 3522
    {
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3523
      delete ull;				// Should never happen
unknown's avatar
unknown committed
3524 3525
    }
    if (!error)                                 // Killed (thd->killed != 0)
unknown's avatar
unknown committed
3526 3527 3528 3529 3530
    {
      error=1;
      null_value=1;				// Return NULL
    }
  }
unknown's avatar
unknown committed
3531
  else                                          // We got the lock
unknown's avatar
unknown committed
3532 3533
  {
    ull->locked=1;
3534
    ull->set_thread(thd);
3535
    ull->thread_id= thd->thread_id;
unknown's avatar
unknown committed
3536 3537
    thd->ull=ull;
    error=0;
3538
    DBUG_PRINT("info", ("got the lock"));
unknown's avatar
unknown committed
3539 3540 3541 3542 3543 3544 3545 3546 3547
  }
  pthread_mutex_unlock(&LOCK_user_locks);

  pthread_mutex_lock(&thd->mysys_var->mutex);
  thd->proc_info=0;
  thd->mysys_var->current_mutex= 0;
  thd->mysys_var->current_cond=  0;
  pthread_mutex_unlock(&thd->mysys_var->mutex);

3548
  DBUG_RETURN(!error ? 1 : 0);
unknown's avatar
unknown committed
3549 3550 3551 3552
}


/*
3553 3554 3555 3556 3557
  Release a user level lock.
  Return:
    1 if lock released
    0 if lock wasn't held
    (SQL) NULL if no such lock
unknown's avatar
unknown committed
3558 3559 3560 3561
*/

longlong Item_func_release_lock::val_int()
{
3562
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3563
  String *res=args[0]->val_str(&value);
3564
  User_level_lock *ull;
unknown's avatar
unknown committed
3565
  longlong result;
3566 3567
  THD *thd=current_thd;
  DBUG_ENTER("Item_func_release_lock::val_int");
unknown's avatar
unknown committed
3568 3569 3570
  if (!res || !res->length())
  {
    null_value=1;
3571
    DBUG_RETURN(0);
unknown's avatar
unknown committed
3572
  }
3573
  DBUG_PRINT("info", ("lock %.*s", res->length(), res->ptr()));
unknown's avatar
unknown committed
3574 3575 3576 3577
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
3578
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
3579 3580
                                             (const uchar*) res->ptr(),
                                             (size_t) res->length()))))
unknown's avatar
unknown committed
3581 3582 3583 3584 3585
  {
    null_value=1;
  }
  else
  {
unknown's avatar
unknown committed
3586
    DBUG_PRINT("info", ("ull->locked=%d ull->thread=%lu thd=%lu", 
3587
                        (int) ull->locked,
unknown's avatar
unknown committed
3588 3589
                        (long)ull->thread_id,
                        (long)thd->thread_id));
unknown's avatar
unknown committed
3590
    if (ull->locked && current_thd->thread_id == ull->thread_id)
unknown's avatar
unknown committed
3591
    {
3592
      DBUG_PRINT("info", ("release lock"));
unknown's avatar
unknown committed
3593 3594
      result=1;					// Release is ok
      item_user_lock_release(ull);
3595
      thd->ull=0;
unknown's avatar
unknown committed
3596 3597 3598
    }
  }
  pthread_mutex_unlock(&LOCK_user_locks);
3599
  DBUG_RETURN(result);
unknown's avatar
unknown committed
3600 3601 3602
}


3603
longlong Item_func_last_insert_id::val_int()
unknown's avatar
unknown committed
3604
{
unknown's avatar
unknown committed
3605
  THD *thd= current_thd;
3606
  DBUG_ASSERT(fixed == 1);
3607 3608
  if (arg_count)
  {
unknown's avatar
unknown committed
3609 3610
    longlong value= args[0]->val_int();
    null_value= args[0]->null_value;
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
    /*
      LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as
      documented in the manual. We don't want to touch
      first_successful_insert_id_in_cur_stmt because it would make
      LAST_INSERT_ID(X) take precedence over an generated auto_increment
      value for this row.
    */
    thd->arg_of_last_insert_id_function= TRUE;
    thd->first_successful_insert_id_in_prev_stmt= value;
    return value;
3621
  }
unknown's avatar
unknown committed
3622
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
3623
  return thd->read_first_successful_insert_id_in_prev_stmt();
unknown's avatar
unknown committed
3624 3625 3626 3627 3628 3629
}

/* This function is just used to test speed of different functions */

longlong Item_func_benchmark::val_int()
{
3630
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3631
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
3632
  String tmp(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
3633
  my_decimal tmp_decimal;
unknown's avatar
unknown committed
3634
  THD *thd=current_thd;
3635
  ulong loop_count;
unknown's avatar
unknown committed
3636

unknown's avatar
unknown committed
3637
  loop_count= (ulong) args[0]->val_int();
3638 3639 3640 3641 3642 3643 3644 3645

  if (args[0]->null_value)
  {
    null_value= 1;
    return 0;
  }

  null_value=0;
unknown's avatar
unknown committed
3646 3647
  for (ulong loop=0 ; loop < loop_count && !thd->killed; loop++)
  {
3648
    switch (args[1]->result_type()) {
unknown's avatar
unknown committed
3649
    case REAL_RESULT:
3650
      (void) args[1]->val_real();
unknown's avatar
unknown committed
3651 3652
      break;
    case INT_RESULT:
3653
      (void) args[1]->val_int();
unknown's avatar
unknown committed
3654 3655
      break;
    case STRING_RESULT:
3656
      (void) args[1]->val_str(&tmp);
unknown's avatar
unknown committed
3657
      break;
unknown's avatar
unknown committed
3658 3659 3660
    case DECIMAL_RESULT:
      (void) args[1]->val_decimal(&tmp_decimal);
      break;
3661
    case ROW_RESULT:
unknown's avatar
unknown committed
3662
    default:
unknown's avatar
unknown committed
3663
      // This case should never be chosen
unknown's avatar
unknown committed
3664 3665
      DBUG_ASSERT(0);
      return 0;
unknown's avatar
unknown committed
3666 3667 3668 3669 3670
    }
  }
  return 0;
}

3671

3672 3673
void Item_func_benchmark::print(String *str)
{
3674
  str->append(STRING_WITH_LEN("benchmark("));
3675
  args[0]->print(str);
3676 3677
  str->append(',');
  args[1]->print(str);
3678 3679 3680
  str->append(')');
}

unknown's avatar
unknown committed
3681

3682 3683 3684 3685
/* This function is just used to create tests with time gaps */

longlong Item_func_sleep::val_int()
{
3686 3687 3688
  THD *thd= current_thd;
  struct timespec abstime;
  pthread_cond_t cond;
3689
  int error;
3690

3691
  DBUG_ASSERT(fixed == 1);
3692

3693
  double time= args[0]->val_real();
3694 3695 3696 3697 3698 3699 3700 3701
  set_timespec_nsec(abstime, (ulonglong)(time * ULL(1000000000)));

  pthread_cond_init(&cond, NULL);
  pthread_mutex_lock(&LOCK_user_locks);

  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &cond;

unknown's avatar
unknown committed
3702 3703 3704 3705 3706 3707 3708 3709
  error= 0;
  while (!thd->killed)
  {
    error= pthread_cond_timedwait(&cond, &LOCK_user_locks, &abstime);
    if (error == ETIMEDOUT || error == ETIME)
      break;
    error= 0;
  }
3710 3711 3712 3713 3714 3715 3716 3717 3718

  pthread_mutex_lock(&thd->mysys_var->mutex);
  thd->mysys_var->current_mutex= 0;
  thd->mysys_var->current_cond=  0;
  pthread_mutex_unlock(&thd->mysys_var->mutex);

  pthread_mutex_unlock(&LOCK_user_locks);
  pthread_cond_destroy(&cond);

unknown's avatar
unknown committed
3719
  return test(!error); 		// Return 1 killed
3720 3721 3722
}


unknown's avatar
unknown committed
3723 3724 3725 3726 3727 3728 3729
#define extra_size sizeof(double)

static user_var_entry *get_variable(HASH *hash, LEX_STRING &name,
				    bool create_if_not_exists)
{
  user_var_entry *entry;

3730
  if (!(entry = (user_var_entry*) hash_search(hash, (uchar*) name.str,
unknown's avatar
unknown committed
3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
					      name.length)) &&
      create_if_not_exists)
  {
    uint size=ALIGN_SIZE(sizeof(user_var_entry))+name.length+1+extra_size;
    if (!hash_inited(hash))
      return 0;
    if (!(entry = (user_var_entry*) my_malloc(size,MYF(MY_WME))))
      return 0;
    entry->name.str=(char*) entry+ ALIGN_SIZE(sizeof(user_var_entry))+
      extra_size;
    entry->name.length=name.length;
    entry->value=0;
    entry->length=0;
3744
    entry->update_query_id=0;
3745
    entry->collation.set(NULL, DERIVATION_IMPLICIT, 0);
unknown's avatar
unknown committed
3746
    entry->unsigned_flag= 0;
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
    /*
      If we are here, we were called from a SET or a query which sets a
      variable. Imagine it is this:
      INSERT INTO t SELECT @a:=10, @a:=@a+1.
      Then when we have a Item_func_get_user_var (because of the @a+1) so we
      think we have to write the value of @a to the binlog. But before that,
      we have a Item_func_set_user_var to create @a (@a:=10), in this we mark
      the variable as "already logged" (line below) so that it won't be logged
      by Item_func_get_user_var (because that's not necessary).
    */
unknown's avatar
unknown committed
3757
    entry->used_query_id=current_thd->query_id;
unknown's avatar
unknown committed
3758 3759
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
3760
    if (my_hash_insert(hash,(uchar*) entry))
unknown's avatar
unknown committed
3761 3762 3763 3764 3765 3766 3767 3768
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

3769
/*
3770 3771
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
3772
*/
3773

3774
bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
unknown's avatar
unknown committed
3775
{
3776
  DBUG_ASSERT(fixed == 0);
3777
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
3778
  if (Item_func::fix_fields(thd, ref) ||
unknown's avatar
unknown committed
3779
      !(entry= get_variable(&thd->user_vars, name, 1)))
unknown's avatar
unknown committed
3780
    return TRUE;
3781 3782 3783 3784 3785
  /* 
     Remember the last query which updated it, this way a query can later know
     if this variable is a constant item in the query (it is if update_query_id
     is different from query_id).
  */
3786
  entry->update_query_id= thd->query_id;
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
  /*
    As it is wrong and confusing to associate any 
    character set with NULL, @a should be latin2
    after this query sequence:

      SET @a=_latin2'string';
      SET @a=NULL;

    I.e. the second query should not change the charset
    to the current default value, but should keep the 
    original value assigned during the first query.
    In order to do it, we don't copy charset
    from the argument if the argument is NULL
    and the variable has previously been initialized.
  */
3802 3803
  null_item= (args[0]->type() == NULL_ITEM);
  if (!entry->collation.collation || !null_item)
3804 3805
    entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
  collation.set(entry->collation.collation, DERIVATION_IMPLICIT);
3806
  cached_result_type= args[0]->result_type();
unknown's avatar
unknown committed
3807
  return FALSE;
unknown's avatar
unknown committed
3808 3809 3810 3811 3812 3813 3814 3815 3816
}


void
Item_func_set_user_var::fix_length_and_dec()
{
  maybe_null=args[0]->maybe_null;
  max_length=args[0]->max_length;
  decimals=args[0]->decimals;
3817
  collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
3818 3819
}

3820

unknown's avatar
unknown committed
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
/*
  Mark field in read_map

  NOTES
    This is used by filesort to register used fields in a a temporary
    column read set or to register used fields in a view
*/

bool Item_func_set_user_var::register_field_in_read_map(uchar *arg)
{
  TABLE *table= (TABLE *) arg;
  if (result_field->table == table || !table)
    bitmap_set_bit(result_field->table->read_set, result_field->field_index);
  return 0;
}


unknown's avatar
unknown committed
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
/*
  Set value to user variable.

  SYNOPSYS
    update_hash()
    entry    - pointer to structure representing variable
    set_null - should we set NULL value ?
    ptr      - pointer to buffer with new value
    length   - length of new value
    type     - type of new value
    cs       - charset info for new value
    dv       - derivation for new value
3850
    unsigned_arg - indiates if a value of type INT_RESULT is unsigned
unknown's avatar
unknown committed
3851 3852 3853 3854 3855 3856 3857

  RETURN VALUE
    False - success, True - failure
*/

static bool
update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length,
3858 3859
            Item_result type, CHARSET_INFO *cs, Derivation dv,
            bool unsigned_arg)
unknown's avatar
unknown committed
3860
{
unknown's avatar
unknown committed
3861
  if (set_null)
unknown's avatar
unknown committed
3862 3863 3864 3865
  {
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
    if (entry->value && entry->value != pos)
      my_free(entry->value,MYF(0));
3866 3867
    entry->value= 0;
    entry->length= 0;
unknown's avatar
unknown committed
3868 3869 3870
  }
  else
  {
3871 3872
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
unknown's avatar
unknown committed
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
    if (length <= extra_size)
    {
      /* Save value in value struct */
      char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
      if (entry->value != pos)
      {
	if (entry->value)
	  my_free(entry->value,MYF(0));
	entry->value=pos;
      }
    }
    else
    {
      /* Allocate variable */
      if (entry->length != length)
      {
	char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
	if (entry->value == pos)
	  entry->value=0;
3892 3893 3894
        entry->value= (char*) my_realloc(entry->value, length,
                                         MYF(MY_ALLOW_ZERO_PTR | MY_WME));
        if (!entry->value)
unknown's avatar
unknown committed
3895
	  return 1;
unknown's avatar
unknown committed
3896 3897
      }
    }
3898 3899 3900 3901 3902
    if (type == STRING_RESULT)
    {
      length--;					// Fix length change above
      entry->value[length]= 0;			// Store end \0
    }
unknown's avatar
unknown committed
3903
    memcpy(entry->value,ptr,length);
unknown's avatar
unknown committed
3904 3905
    if (type == DECIMAL_RESULT)
      ((my_decimal*)entry->value)->fix_buffer_pointer();
unknown's avatar
unknown committed
3906
    entry->length= length;
3907
    entry->collation.set(cs, dv);
unknown's avatar
unknown committed
3908
    entry->unsigned_flag= unsigned_arg;
unknown's avatar
unknown committed
3909
  }
3910
  entry->type=type;
3911
  return 0;
unknown's avatar
unknown committed
3912
}
unknown's avatar
unknown committed
3913

unknown's avatar
unknown committed
3914 3915

bool
3916 3917
Item_func_set_user_var::update_hash(void *ptr, uint length,
                                    Item_result res_type,
3918 3919
                                    CHARSET_INFO *cs, Derivation dv,
                                    bool unsigned_arg)
unknown's avatar
unknown committed
3920
{
3921 3922 3923 3924 3925
  /*
    If we set a variable explicitely to NULL then keep the old
    result type of the variable
  */
  if ((null_value= args[0]->null_value) && null_item)
3926
    res_type= entry->type;                      // Don't change type of item
unknown's avatar
unknown committed
3927
  if (::update_hash(entry, (null_value= args[0]->null_value),
3928
                    ptr, length, res_type, cs, dv, unsigned_arg))
unknown's avatar
unknown committed
3929 3930 3931 3932 3933 3934
  {
    current_thd->fatal_error();     // Probably end of memory
    null_value= 1;
    return 1;
  }
  return 0;
unknown's avatar
unknown committed
3935 3936 3937
}


3938 3939
/* Get the value of a variable as a double */

unknown's avatar
unknown committed
3940
double user_var_entry::val_real(my_bool *null_value)
unknown's avatar
unknown committed
3941
{
3942 3943 3944 3945 3946 3947 3948 3949
  if ((*null_value= (value == 0)))
    return 0.0;

  switch (type) {
  case REAL_RESULT:
    return *(double*) value;
  case INT_RESULT:
    return (double) *(longlong*) value;
unknown's avatar
unknown committed
3950 3951 3952 3953 3954 3955
  case DECIMAL_RESULT:
  {
    double result;
    my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *)value, &result);
    return result;
  }
3956
  case STRING_RESULT:
unknown's avatar
unknown committed
3957
    return my_atof(value);                      // This is null terminated
3958 3959 3960
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
3961
  }
3962
  return 0.0;					// Impossible
unknown's avatar
unknown committed
3963 3964 3965
}


3966 3967 3968
/* Get the value of a variable as an integer */

longlong user_var_entry::val_int(my_bool *null_value)
unknown's avatar
unknown committed
3969
{
3970 3971 3972 3973 3974 3975 3976 3977
  if ((*null_value= (value == 0)))
    return LL(0);

  switch (type) {
  case REAL_RESULT:
    return (longlong) *(double*) value;
  case INT_RESULT:
    return *(longlong*) value;
unknown's avatar
unknown committed
3978 3979 3980
  case DECIMAL_RESULT:
  {
    longlong result;
3981
    my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, &result);
unknown's avatar
unknown committed
3982 3983
    return result;
  }
unknown's avatar
unknown committed
3984
  case STRING_RESULT:
unknown's avatar
unknown committed
3985 3986 3987 3988
  {
    int error;
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
  }
3989 3990 3991
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
3992
  }
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
  return LL(0);					// Impossible
}


/* Get the value of a variable as a string */

String *user_var_entry::val_str(my_bool *null_value, String *str,
				uint decimals)
{
  if ((*null_value= (value == 0)))
    return (String*) 0;

  switch (type) {
  case REAL_RESULT:
4007
    str->set_real(*(double*) value, decimals, &my_charset_bin);
4008 4009
    break;
  case INT_RESULT:
4010 4011 4012 4013
    if (!unsigned_flag)
      str->set(*(longlong*) value, &my_charset_bin);
    else
      str->set(*(ulonglong*) value, &my_charset_bin);
4014
    break;
unknown's avatar
unknown committed
4015 4016 4017
  case DECIMAL_RESULT:
    my_decimal2string(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, 0, 0, str);
    break;
4018
  case STRING_RESULT:
unknown's avatar
unknown committed
4019
    if (str->copy(value, length, collation.collation))
4020
      str= 0;					// EOM error
4021 4022 4023
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
4024
  }
4025
  return(str);
unknown's avatar
unknown committed
4026 4027
}

unknown's avatar
unknown committed
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054
/* Get the value of a variable as a decimal */

my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val)
{
  if ((*null_value= (value == 0)))
    return 0;

  switch (type) {
  case REAL_RESULT:
    double2my_decimal(E_DEC_FATAL_ERROR, *(double*) value, val);
    break;
  case INT_RESULT:
    int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) value, 0, val);
    break;
  case DECIMAL_RESULT:
    val= (my_decimal *)value;
    break;
  case STRING_RESULT:
    str2my_decimal(E_DEC_FATAL_ERROR, value, length, collation.collation, val);
    break;
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
  }
  return(val);
}

4055 4056
/*
  This functions is invoked on SET @variable or @variable:= expression.
unknown's avatar
unknown committed
4057
  Evaluate (and check expression), store results.
4058 4059 4060 4061 4062

  SYNOPSYS
    Item_func_set_user_var::check()

  NOTES
unknown's avatar
unknown committed
4063 4064
    For now it always return OK. All problem with value evaluating
    will be caught by thd->net.report_error check in sql_set_variables().
4065 4066

  RETURN
unknown's avatar
unknown committed
4067
    FALSE OK.
4068 4069 4070
*/

bool
4071
Item_func_set_user_var::check(bool use_result_field)
4072 4073
{
  DBUG_ENTER("Item_func_set_user_var::check");
unknown's avatar
unknown committed
4074 4075
  if (use_result_field && !result_field)
    use_result_field= FALSE;
4076 4077 4078 4079

  switch (cached_result_type) {
  case REAL_RESULT:
  {
4080 4081
    save_result.vreal= use_result_field ? result_field->val_real() :
                        args[0]->val_real();
4082 4083 4084 4085
    break;
  }
  case INT_RESULT:
  {
4086 4087 4088 4089
    save_result.vint= use_result_field ? result_field->val_int() :
                       args[0]->val_int();
    unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag:
                    args[0]->unsigned_flag;
4090 4091 4092 4093
    break;
  }
  case STRING_RESULT:
  {
4094 4095
    save_result.vstr= use_result_field ? result_field->val_str(&value) :
                       args[0]->val_str(&value);
4096 4097
    break;
  }
unknown's avatar
unknown committed
4098 4099
  case DECIMAL_RESULT:
  {
4100 4101 4102
    save_result.vdec= use_result_field ?
                       result_field->val_decimal(&decimal_buff) :
                       args[0]->val_decimal(&decimal_buff);
unknown's avatar
unknown committed
4103 4104
    break;
  }
4105 4106
  case ROW_RESULT:
  default:
unknown's avatar
unknown committed
4107
    // This case should never be chosen
4108 4109 4110
    DBUG_ASSERT(0);
    break;
  }
unknown's avatar
unknown committed
4111
  DBUG_RETURN(FALSE);
4112 4113
}

4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125

/*
  This functions is invoked on SET @variable or @variable:= expression.

  SYNOPSIS
    Item_func_set_user_var::update()

  NOTES
    We have to store the expression as such in the variable, independent of
    the value method used by the user

  RETURN
unknown's avatar
unknown committed
4126
    0	OK
4127 4128 4129 4130
    1	EOM Error

*/

unknown's avatar
unknown committed
4131 4132 4133
bool
Item_func_set_user_var::update()
{
4134 4135 4136 4137
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

unknown's avatar
unknown committed
4138 4139
  switch (cached_result_type) {
  case REAL_RESULT:
unknown's avatar
unknown committed
4140
  {
4141
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
unknown's avatar
unknown committed
4142
		     REAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, 0);
unknown's avatar
unknown committed
4143
    break;
unknown's avatar
unknown committed
4144
  }
unknown's avatar
unknown committed
4145
  case INT_RESULT:
4146
  {
4147
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
4148
                     INT_RESULT, &my_charset_bin, DERIVATION_IMPLICIT,
4149
                     unsigned_flag);
unknown's avatar
unknown committed
4150
    break;
unknown's avatar
unknown committed
4151
  }
unknown's avatar
unknown committed
4152
  case STRING_RESULT:
unknown's avatar
unknown committed
4153
  {
4154
    if (!save_result.vstr)					// Null value
unknown's avatar
unknown committed
4155
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
unknown's avatar
unknown committed
4156
		       DERIVATION_IMPLICIT, 0);
4157
    else
4158 4159 4160
      res= update_hash((void*) save_result.vstr->ptr(),
		       save_result.vstr->length(), STRING_RESULT,
		       save_result.vstr->charset(),
unknown's avatar
unknown committed
4161
		       DERIVATION_IMPLICIT, 0);
unknown's avatar
unknown committed
4162 4163
    break;
  }
unknown's avatar
unknown committed
4164 4165 4166 4167
  case DECIMAL_RESULT:
  {
    if (!save_result.vdec)					// Null value
      res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin,
unknown's avatar
unknown committed
4168
                       DERIVATION_IMPLICIT, 0);
unknown's avatar
unknown committed
4169 4170 4171
    else
      res= update_hash((void*) save_result.vdec,
                       sizeof(my_decimal), DECIMAL_RESULT,
unknown's avatar
unknown committed
4172
                       &my_charset_bin, DERIVATION_IMPLICIT, 0);
unknown's avatar
unknown committed
4173 4174
    break;
  }
4175
  case ROW_RESULT:
unknown's avatar
unknown committed
4176
  default:
unknown's avatar
unknown committed
4177
    // This case should never be chosen
unknown's avatar
unknown committed
4178 4179 4180
    DBUG_ASSERT(0);
    break;
  }
4181
  DBUG_RETURN(res);
unknown's avatar
unknown committed
4182 4183 4184
}


4185
double Item_func_set_user_var::val_real()
unknown's avatar
unknown committed
4186
{
4187
  DBUG_ASSERT(fixed == 1);
4188
  check(0);
4189
  update();					// Store expression
unknown's avatar
unknown committed
4190
  return entry->val_real(&null_value);
unknown's avatar
unknown committed
4191 4192
}

4193
longlong Item_func_set_user_var::val_int()
unknown's avatar
unknown committed
4194
{
4195
  DBUG_ASSERT(fixed == 1);
4196
  check(0);
4197 4198
  update();					// Store expression
  return entry->val_int(&null_value);
unknown's avatar
unknown committed
4199 4200
}

4201
String *Item_func_set_user_var::val_str(String *str)
unknown's avatar
unknown committed
4202
{
4203
  DBUG_ASSERT(fixed == 1);
4204
  check(0);
4205 4206
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
unknown's avatar
unknown committed
4207 4208 4209
}


unknown's avatar
unknown committed
4210 4211 4212
my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
{
  DBUG_ASSERT(fixed == 1);
4213
  check(0);
unknown's avatar
unknown committed
4214 4215 4216 4217 4218
  update();					// Store expression
  return entry->val_decimal(&null_value, val);
}


unknown's avatar
unknown committed
4219
double Item_func_set_user_var::val_result()
4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
{
  DBUG_ASSERT(fixed == 1);
  check(TRUE);
  update();					// Store expression
  return entry->val_real(&null_value);
}

longlong Item_func_set_user_var::val_int_result()
{
  DBUG_ASSERT(fixed == 1);
  check(TRUE);
  update();					// Store expression
  return entry->val_int(&null_value);
}

unknown's avatar
unknown committed
4235
String *Item_func_set_user_var::str_result(String *str)
4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
{
  DBUG_ASSERT(fixed == 1);
  check(TRUE);
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
}


my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
{
  DBUG_ASSERT(fixed == 1);
  check(TRUE);
  update();					// Store expression
  return entry->val_decimal(&null_value, val);
unknown's avatar
unknown committed
4250 4251 4252
}


unknown's avatar
unknown committed
4253 4254
void Item_func_set_user_var::print(String *str)
{
4255
  str->append(STRING_WITH_LEN("(@"));
4256
  str->append(name.str, name.length);
4257
  str->append(STRING_WITH_LEN(":="));
unknown's avatar
unknown committed
4258 4259 4260 4261 4262
  args[0]->print(str);
  str->append(')');
}


4263 4264
void Item_func_set_user_var::print_as_stmt(String *str)
{
4265
  str->append(STRING_WITH_LEN("set @"));
4266
  str->append(name.str, name.length);
4267
  str->append(STRING_WITH_LEN(":="));
4268 4269 4270 4271
  args[0]->print(str);
  str->append(')');
}

4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg)
{
  if (result_field)
  {
    check(1);
    update();
    return protocol->store(result_field);
  }
  return Item::send(protocol, str_arg);
}
4282

unknown's avatar
unknown committed
4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
void Item_func_set_user_var::make_field(Send_field *tmp_field)
{
  if (result_field)
  {
    result_field->make_field(tmp_field);
    DBUG_ASSERT(tmp_field->table_name != 0);
    if (Item::name)
      tmp_field->col_name=Item::name;               // Use user supplied name
  }
  else
    Item::make_field(tmp_field);
}
4295

4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334

/*
  Save the value of a user variable into a field

  SYNOPSIS
    save_in_field()
      field           target field to save the value to
      no_conversion   flag indicating whether conversions are allowed

  DESCRIPTION
    Save the function value into a field and update the user variable
    accordingly. If a result field is defined and the target field doesn't
    coincide with it then the value from the result field will be used as
    the new value of the user variable.

    The reason to have this method rather than simply using the result
    field in the val_xxx() methods is that the value from the result field
    not always can be used when the result field is defined.
    Let's consider the following cases:
    1) when filling a tmp table the result field is defined but the value of it
    is undefined because it has to be produced yet. Thus we can't use it.
    2) on execution of an INSERT ... SELECT statement the save_in_field()
    function will be called to fill the data in the new record. If the SELECT
    part uses a tmp table then the result field is defined and should be
    used in order to get the correct result.

    The difference between the SET_USER_VAR function and regular functions
    like CONCAT is that the Item_func objects for the regular functions are
    replaced by Item_field objects after the values of these functions have
    been stored in a tmp table. Yet an object of the Item_field class cannot
    be used to update a user variable.
    Due to this we have to handle the result field in a special way here and
    in the Item_func_set_user_var::send() function.

  RETURN VALUES
    FALSE       Ok
    TRUE        Error
*/

4335 4336
int Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
                                          bool can_use_result_field)
4337
{
4338 4339
  bool use_result_field= (!can_use_result_field ? 0 :
                          (result_field && result_field != field));
4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
  int error;

  /* Update the value of the user variable */
  check(use_result_field);
  update();

  if (result_type() == STRING_RESULT ||
      result_type() == REAL_RESULT &&
      field->result_type() == STRING_RESULT)
  {
    String *result;
    CHARSET_INFO *cs= collation.collation;
    char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
    str_value.set_quick(buff, sizeof(buff), cs);
    result= entry->val_str(&null_value, &str_value, decimals);

    if (null_value)
    {
      str_value.set_quick(0, 0, cs);
      return set_field_to_null_with_conversions(field, no_conversions);
    }

    /* NOTE: If null_value == FALSE, "result" must be not NULL.  */

    field->set_notnull();
    error=field->store(result->ptr(),result->length(),cs);
    str_value.set_quick(0, 0, cs);
  }
  else if (result_type() == REAL_RESULT)
  {
    double nr= entry->val_real(&null_value);
    if (null_value)
      return set_field_to_null(field);
    field->set_notnull();
    error=field->store(nr);
  }
  else if (result_type() == DECIMAL_RESULT)
  {
    my_decimal decimal_value;
4379
    my_decimal *val= entry->val_decimal(&null_value, &decimal_value);
4380 4381 4382
    if (null_value)
      return set_field_to_null(field);
    field->set_notnull();
4383
    error=field->store_decimal(val);
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396
  }
  else
  {
    longlong nr= entry->val_int(&null_value);
    if (null_value)
      return set_field_to_null_with_conversions(field, no_conversions);
    field->set_notnull();
    error=field->store(nr, unsigned_flag);
  }
  return error;
}


unknown's avatar
unknown committed
4397 4398 4399
String *
Item_func_get_user_var::val_str(String *str)
{
4400
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
4401
  DBUG_ENTER("Item_func_get_user_var::val_str");
4402
  if (!var_entry)
4403
    DBUG_RETURN((String*) 0);			// No such variable
4404
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
unknown's avatar
unknown committed
4405 4406 4407
}


4408
double Item_func_get_user_var::val_real()
unknown's avatar
unknown committed
4409
{
4410
  DBUG_ASSERT(fixed == 1);
4411 4412
  if (!var_entry)
    return 0.0;					// No such variable
unknown's avatar
unknown committed
4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
  return (var_entry->val_real(&null_value));
}


my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
{
  DBUG_ASSERT(fixed == 1);
  if (!var_entry)
    return 0;
  return var_entry->val_decimal(&null_value, dec);
unknown's avatar
unknown committed
4423 4424 4425 4426 4427
}


longlong Item_func_get_user_var::val_int()
{
4428
  DBUG_ASSERT(fixed == 1);
4429 4430 4431
  if (!var_entry)
    return LL(0);				// No such variable
  return (var_entry->val_int(&null_value));
unknown's avatar
unknown committed
4432 4433 4434
}


4435
/*
4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
  Get variable by name and, if necessary, put the record of variable 
  use into the binary log.
  
  SYNOPSIS
    get_var_with_binlog()
      thd        Current thread
      name       Variable name 
      out_entry  [out] variable structure or NULL. The pointer is set 
                 regardless of whether function succeeded or not.

4446 4447 4448 4449
  When a user variable is invoked from an update query (INSERT, UPDATE etc),
  stores this variable and its value in thd->user_var_events, so that it can be
  written to the binlog (will be written just before the query is written, see
  log.cc).
4450

4451
  RETURN
4452
    0  OK
unknown's avatar
unknown committed
4453
    1  Failed to put appropriate record into binary log
4454

4455 4456
*/

4457 4458
int get_var_with_binlog(THD *thd, enum_sql_command sql_command,
                        LEX_STRING &name, user_var_entry **out_entry)
unknown's avatar
unknown committed
4459
{
4460
  BINLOG_USER_VAR_EVENT *user_var_event;
4461 4462
  user_var_entry *var_entry;
  var_entry= get_variable(&thd->user_vars, name, 0);
4463

4464 4465
  /*
    Any reference to user-defined variable which is done from stored
4466 4467 4468
    function or trigger affects their execution and the execution of the
    calling statement. We must log all such variables even if they are 
    not involved in table-updating statements.
4469 4470 4471
  */
  if (!(opt_bin_log && 
       (is_update_query(sql_command) || thd->in_sub_stmt)))
4472 4473 4474 4475
  {
    *out_entry= var_entry;
    return 0;
  }
4476 4477

  if (!var_entry)
unknown's avatar
unknown committed
4478
  {
4479
    /*
4480 4481 4482 4483
      If the variable does not exist, it's NULL, but we want to create it so
      that it gets into the binlog (if it didn't, the slave could be
      influenced by a variable of the same name previously set by another
      thread).
unknown's avatar
unknown committed
4484 4485
      We create it like if it had been explicitly set with SET before.
      The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
4486 4487 4488
      sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
      in dispatch_command()). Instead of building a one-element list to pass to
      sql_set_variables(), we could instead manually call check() and update();
4489 4490
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
4491 4492 4493

      Manipulation with lex is necessary since free_underlaid_joins
      is going to release memory belonging to the main query.
4494 4495 4496
    */

    List<set_var_base> tmp_var_list;
4497 4498
    LEX *sav_lex= thd->lex, lex_tmp;
    thd->lex= &lex_tmp;
4499
    lex_start(thd);
4500 4501
    tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
                                                                       new Item_null())));
4502 4503
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
4504 4505
    {
      thd->lex= sav_lex;
4506
      goto err;
4507 4508
    }
    thd->lex= sav_lex;
4509 4510 4511
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
4512 4513
  else if (var_entry->used_query_id == thd->query_id ||
           mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
4514 4515 4516 4517 4518 4519 4520 4521 4522
  {
    /* 
       If this variable was already stored in user_var_events by this query
       (because it's used in more than one place in the query), don't store
       it.
    */
    *out_entry= var_entry;
    return 0;
  }
4523 4524 4525 4526

  uint size;
  /*
    First we need to store value of var_entry, when the next situation
unknown's avatar
unknown committed
4527
    appears:
4528 4529
    > set @a:=1;
    > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
4530
    We have to write to binlog value @a= 1.
4531

4532 4533 4534 4535
    We allocate the user_var_event on user_var_events_alloc pool, not on
    the this-statement-execution pool because in SPs user_var_event objects 
    may need to be valid after current [SP] statement execution pool is
    destroyed.
4536
  */
4537 4538 4539
  size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;
  if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
        alloc_root(thd->user_var_events_alloc, size)))
4540
    goto err;
4541

4542 4543 4544 4545 4546 4547 4548 4549 4550 4551
  user_var_event->value= (char*) user_var_event +
    ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
  user_var_event->user_var_event= var_entry;
  user_var_event->type= var_entry->type;
  user_var_event->charset_number= var_entry->collation.collation->number;
  if (!var_entry->value)
  {
    /* NULL value*/
    user_var_event->length= 0;
    user_var_event->value= 0;
unknown's avatar
unknown committed
4552
  }
4553 4554 4555 4556 4557 4558 4559 4560
  else
  {
    user_var_event->length= var_entry->length;
    memcpy(user_var_event->value, var_entry->value,
           var_entry->length);
  }
  /* Mark that this variable has been used by this query */
  var_entry->used_query_id= thd->query_id;
4561
  if (insert_dynamic(&thd->user_var_events, (uchar*) &user_var_event))
4562
    goto err;
4563

4564 4565
  *out_entry= var_entry;
  return 0;
4566

unknown's avatar
unknown committed
4567
err:
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
  *out_entry= var_entry;
  return 1;
}

void Item_func_get_user_var::fix_length_and_dec()
{
  THD *thd=current_thd;
  int error;
  maybe_null=1;
  decimals=NOT_FIXED_DEC;
  max_length=MAX_BLOB_WIDTH;
4579

4580
  error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
4581

4582 4583 4584 4585 4586
  /*
    If the variable didn't exist it has been created as a STRING-type.
    'var_entry' is NULL only if there occured an error during the call to
    get_var_with_binlog.
  */
4587
  if (var_entry)
4588
  {
4589 4590 4591 4592
    m_cached_result_type= var_entry->type;
    unsigned_flag= var_entry->unsigned_flag;
    max_length= var_entry->length;

4593
    collation.set(var_entry->collation);
4594
    switch(m_cached_result_type) {
4595 4596
    case REAL_RESULT:
      max_length= DBL_DIG + 8;
unknown's avatar
unknown committed
4597
      break;
4598 4599
    case INT_RESULT:
      max_length= MAX_BIGINT_WIDTH;
unknown's avatar
unknown committed
4600
      decimals=0;
4601 4602 4603 4604
      break;
    case STRING_RESULT:
      max_length= MAX_BLOB_WIDTH;
      break;
unknown's avatar
unknown committed
4605
    case DECIMAL_RESULT:
unknown's avatar
unknown committed
4606 4607
      max_length= DECIMAL_MAX_STR_LENGTH;
      decimals= DECIMAL_MAX_SCALE;
unknown's avatar
unknown committed
4608
      break;
unknown's avatar
unknown committed
4609
    case ROW_RESULT:                            // Keep compiler happy
unknown's avatar
unknown committed
4610 4611
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
4612
      break;
4613 4614
    }
  }
4615
  else
4616 4617
  {
    collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
4618
    null_value= 1;
4619 4620
    m_cached_result_type= STRING_RESULT;
    max_length= MAX_BLOB_WIDTH;
4621
  }
4622

4623 4624
  if (error)
    thd->fatal_error();
4625

unknown's avatar
unknown committed
4626
  return;
unknown's avatar
unknown committed
4627 4628 4629
}


4630
bool Item_func_get_user_var::const_item() const
4631
{
4632
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
4633
}
unknown's avatar
unknown committed
4634 4635 4636 4637


enum Item_result Item_func_get_user_var::result_type() const
{
4638
  return m_cached_result_type;
unknown's avatar
unknown committed
4639 4640
}

unknown's avatar
unknown committed
4641 4642 4643

void Item_func_get_user_var::print(String *str)
{
4644
  str->append(STRING_WITH_LEN("(@"));
unknown's avatar
unknown committed
4645 4646 4647 4648
  str->append(name.str,name.length);
  str->append(')');
}

4649

4650
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
4651 4652 4653 4654 4655 4656
{
  /* Assume we don't have rtti */
  if (this == item)
    return 1;					// Same item is same.
  /* Check if other type is also a get_user_var() object */
  if (item->type() != FUNC_ITEM ||
4657
      ((Item_func*) item)->functype() != functype())
unknown's avatar
unknown committed
4658 4659 4660 4661 4662 4663 4664
    return 0;
  Item_func_get_user_var *other=(Item_func_get_user_var*) item;
  return (name.length == other->name.length &&
	  !memcmp(name.str, other->name.str, name.length));
}


4665
bool Item_func_get_user_var::set_value(THD *thd,
4666
                                       sp_rcontext * /*ctx*/, Item **it)
4667
{
4668
  Item_func_set_user_var *suv= new Item_func_set_user_var(get_name(), *it);
4669 4670 4671 4672
  /*
    Item_func_set_user_var is not fixed after construction, call
    fix_fields().
  */
4673
  return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update());
4674 4675 4676
}


4677
bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
unknown's avatar
unknown committed
4678 4679
{
  DBUG_ASSERT(fixed == 0);
4680
  if (Item::fix_fields(thd, ref) ||
unknown's avatar
unknown committed
4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697
      !(entry= get_variable(&thd->user_vars, name, 1)))
    return TRUE;
  entry->type= STRING_RESULT;
  /*
    Let us set the same collation which is used for loading
    of fields in LOAD DATA INFILE.
    (Since Item_user_var_as_out_param is used only there).
  */
  entry->collation.set(thd->variables.collation_database);
  entry->update_query_id= thd->query_id;
  return FALSE;
}


void Item_user_var_as_out_param::set_null_value(CHARSET_INFO* cs)
{
  if (::update_hash(entry, TRUE, 0, 0, STRING_RESULT, cs,
4698
                    DERIVATION_IMPLICIT, 0 /* unsigned_arg */))
unknown's avatar
unknown committed
4699 4700 4701 4702 4703 4704 4705 4706
    current_thd->fatal_error();			// Probably end of memory
}


void Item_user_var_as_out_param::set_value(const char *str, uint length,
                                           CHARSET_INFO* cs)
{
  if (::update_hash(entry, FALSE, (void*)str, length, STRING_RESULT, cs,
4707
                    DERIVATION_IMPLICIT, 0 /* unsigned_arg */))
unknown's avatar
unknown committed
4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746
    current_thd->fatal_error();			// Probably end of memory
}


double Item_user_var_as_out_param::val_real()
{
  DBUG_ASSERT(0);
  return 0.0;
}


longlong Item_user_var_as_out_param::val_int()
{
  DBUG_ASSERT(0);
  return 0;
}


String* Item_user_var_as_out_param::val_str(String *str)
{
  DBUG_ASSERT(0);
  return 0;
}


my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
{
  DBUG_ASSERT(0);
  return 0;
}


void Item_user_var_as_out_param::print(String *str)
{
  str->append('@');
  str->append(name.str,name.length);
}


4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
Item_func_get_system_var::
Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
                       LEX_STRING *component_arg, const char *name_arg,
                       size_t name_len_arg)
  :var(var_arg), var_type(var_type_arg), component(*component_arg)
{
  /* set_name() will allocate the name */
  set_name(name_arg, name_len_arg, system_charset_info);
}


bool
unknown's avatar
unknown committed
4759
Item_func_get_system_var::fix_fields(THD *thd, Item **ref)
4760
{
4761
  Item *item;
4762
  DBUG_ENTER("Item_func_get_system_var::fix_fields");
4763

4764 4765 4766 4767 4768
  /*
    Evaluate the system variable and substitute the result (a basic constant)
    instead of this item. If the variable can not be evaluated,
    the error is reported in sys_var::item().
  */
4769
  if (!(item= var->item(thd, var_type, &component)))
4770 4771 4772 4773 4774 4775 4776 4777
    DBUG_RETURN(1);                             // Impossible
  item->set_name(name, 0, system_charset_info); // don't allocate a new name
  thd->change_item_tree(ref, item);

  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
4778 4779
longlong Item_func_inet_aton::val_int()
{
4780
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
4781 4782 4783 4784 4785
  uint byte_result = 0;
  ulonglong result = 0;			// We are ready for 64 bit addresses
  const char *p,* end;
  char c = '.'; // we mark c to indicate invalid IP in case length is 0
  char buff[36];
4786
  int dot_count= 0;
unknown's avatar
unknown committed
4787

unknown's avatar
unknown committed
4788
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
unknown's avatar
unknown committed
4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804
  if (!(s = args[0]->val_str(&tmp)))		// If null value
    goto err;
  null_value=0;

  end= (p = s->ptr()) + s->length();
  while (p < end)
  {
    c = *p++;
    int digit = (int) (c - '0');		// Assume ascii
    if (digit >= 0 && digit <= 9)
    {
      if ((byte_result = byte_result * 10 + digit) > 255)
	goto err;				// Wrong address
    }
    else if (c == '.')
    {
4805
      dot_count++;
unknown's avatar
unknown committed
4806 4807 4808 4809 4810 4811 4812
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
4813
  {
4814 4815 4816 4817 4818 4819
    /*
      Handle short-forms addresses according to standard. Examples:
      127		-> 0.0.0.127
      127.1		-> 127.0.0.1
      127.2.1		-> 127.2.0.1
    */
unknown's avatar
unknown committed
4820
    switch (dot_count) {
4821 4822
    case 1: result<<= 8; /* Fall through */
    case 2: result<<= 8; /* Fall through */
4823
    }
unknown's avatar
unknown committed
4824
    return (result << 8) + (ulonglong) byte_result;
4825
  }
unknown's avatar
unknown committed
4826 4827 4828 4829 4830 4831

err:
  null_value=1;
  return 0;
}

unknown's avatar
unknown committed
4832

4833
void Item_func_match::init_search(bool no_order)
4834
{
unknown's avatar
unknown committed
4835
  DBUG_ENTER("Item_func_match::init_search");
4836 4837

  /* Check if init_search() has been called before */
4838
  if (ft_handler)
unknown's avatar
unknown committed
4839
    DBUG_VOID_RETURN;
4840

4841
  if (key == NO_SUCH_KEY)
4842 4843
  {
    List<Item> fields;
4844
    fields.push_back(new Item_string(" ",1, cmp_collation.collation));
4845 4846
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
4847
    concat_ws=new Item_func_concat_ws(fields);
unknown's avatar
unknown committed
4848 4849 4850
    /*
      Above function used only to get value and do not need fix_fields for it:
      Item_string - basic constant
unknown's avatar
unknown committed
4851 4852
      fields - fix_fields() was already called for this arguments
      Item_func_concat_ws - do not need fix_fields() to produce value
unknown's avatar
unknown committed
4853
    */
4854
    concat_ws->quick_fix_field();
4855
  }
4856

4857 4858
  if (master)
  {
4859 4860
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
4861 4862
    ft_handler=master->ft_handler;
    join_key=master->join_key;
unknown's avatar
unknown committed
4863
    DBUG_VOID_RETURN;
4864 4865
  }

unknown's avatar
unknown committed
4866
  String *ft_tmp= 0;
4867

4868
  // MATCH ... AGAINST (NULL) is meaningless, but possible
4869
  if (!(ft_tmp=key_item()->val_str(&value)))
4870
  {
4871 4872
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
4873 4874
  }

4875 4876
  if (ft_tmp->charset() != cmp_collation.collation)
  {
4877
    uint dummy_errors;
4878
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
4879
                      cmp_collation.collation, &dummy_errors);
4880
    ft_tmp= &search_value;
4881 4882
  }

4883 4884
  if (join_key && !no_order)
    flags|=FT_SORTED;
4885
  ft_handler=table->file->ft_init_ext(flags, key, ft_tmp);
4886 4887 4888

  if (join_key)
    table->file->ft_handler=ft_handler;
unknown's avatar
unknown committed
4889 4890

  DBUG_VOID_RETURN;
4891 4892
}

unknown's avatar
unknown committed
4893

4894
bool Item_func_match::fix_fields(THD *thd, Item **ref)
unknown's avatar
unknown committed
4895
{
4896
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
4897
  Item *item;
4898
  LINT_INIT(item);				// Safe as arg_count is > 1
unknown's avatar
unknown committed
4899

4900 4901 4902
  maybe_null=1;
  join_key=0;

4903 4904 4905 4906 4907
  /*
    const_item is assumed in quite a bit of places, so it would be difficult
    to remove;  If it would ever to be removed, this should include
    modifications to find_best and auto_close as complement to auto_init code
    above.
4908
   */
4909
  if (Item_func::fix_fields(thd, ref) ||
4910
      !args[0]->const_during_execution())
4911 4912
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
unknown's avatar
unknown committed
4913
    return TRUE;
4914
  }
unknown's avatar
unknown committed
4915

4916 4917
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
unknown's avatar
unknown committed
4918
  {
4919
    item=args[i];
unknown's avatar
unknown committed
4920
    if (item->type() == Item::REF_ITEM)
4921 4922
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
4923
      key=NO_SUCH_KEY;
unknown's avatar
unknown committed
4924
  }
4925 4926
  /*
    Check that all columns come from the same table.
4927
    We've already checked that columns in MATCH are fields so
4928 4929 4930
    PARAM_TABLE_BIT can only appear from AGAINST argument.
  */
  if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
4931
    key=NO_SUCH_KEY;
4932

4933
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
4934 4935
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
unknown's avatar
unknown committed
4936
    return TRUE;
4937
  }
4938
  table=((Item_field *)item)->field->table;
4939
  if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT))
4940
  {
unknown's avatar
unknown committed
4941
    my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
unknown's avatar
unknown committed
4942
    return 1;
4943
  }
4944
  table->fulltext_searched=1;
4945 4946
  return agg_arg_collations_for_comparison(cmp_collation,
                                           args+1, arg_count-1, 0);
unknown's avatar
unknown committed
4947
}
4948

unknown's avatar
unknown committed
4949 4950 4951
bool Item_func_match::fix_index()
{
  Item_field *item;
4952
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
4953
  uint max_cnt=0, mkeys=0, i;
4954

4955
  if (key == NO_SUCH_KEY)
4956
    return 0;
4957 4958 4959
  
  if (!table) 
    goto err;
unknown's avatar
unknown committed
4960

4961
  for (keynr=0 ; keynr < table->s->keys ; keynr++)
unknown's avatar
unknown committed
4962
  {
4963
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
4964
        (table->s->keys_in_use.is_set(keynr)))
unknown's avatar
unknown committed
4965
    {
4966
      ft_to_key[fts]=keynr;
unknown's avatar
unknown committed
4967 4968 4969 4970 4971 4972
      ft_cnt[fts]=0;
      fts++;
    }
  }

  if (!fts)
4973
    goto err;
unknown's avatar
unknown committed
4974

4975
  for (i=1; i < arg_count; i++)
unknown's avatar
unknown committed
4976
  {
4977
    item=(Item_field*)args[i];
4978
    for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
4979
    {
4980
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
unknown's avatar
unknown committed
4981 4982 4983 4984 4985
      uint key_parts=ft_key->key_parts;

      for (uint part=0 ; part < key_parts ; part++)
      {
	if (item->field->eq(ft_key->key_part[part].field))
4986
	  ft_cnt[keynr]++;
unknown's avatar
unknown committed
4987 4988 4989 4990
      }
    }
  }

4991
  for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
4992
  {
4993
    if (ft_cnt[keynr] > max_cnt)
unknown's avatar
unknown committed
4994
    {
4995
      mkeys=0;
4996 4997
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
4998 4999
      continue;
    }
5000
    if (max_cnt && ft_cnt[keynr] == max_cnt)
5001 5002
    {
      mkeys++;
5003 5004
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
5005
      continue;
unknown's avatar
unknown committed
5006 5007 5008
    }
  }

5009
  for (keynr=0 ; keynr <= mkeys ; keynr++)
unknown's avatar
unknown committed
5010
  {
5011 5012
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
5013
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
5014
      continue;
unknown's avatar
unknown committed
5015

5016
    key=ft_to_key[keynr];
5017

5018 5019 5020
    return 0;
  }

5021
err:
5022
  if (flags & FT_BOOL)
5023
  {
5024
    key=NO_SUCH_KEY;
5025 5026
    return 0;
  }
unknown's avatar
unknown committed
5027 5028
  my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
             ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
5029
  return 1;
5030 5031
}

5032

5033
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
5034
{
unknown's avatar
unknown committed
5035 5036
  if (item->type() != FUNC_ITEM ||
      ((Item_func*)item)->functype() != FT_FUNC ||
5037
      flags != ((Item_func_match*)item)->flags)
5038 5039 5040 5041 5042
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
5043
      key_item()->eq(ifm->key_item(), binary_cmp))
5044
    return 1;
unknown's avatar
unknown committed
5045 5046 5047 5048

  return 0;
}

5049

5050
double Item_func_match::val_real()
unknown's avatar
unknown committed
5051
{
5052
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
5053
  DBUG_ENTER("Item_func_match::val");
unknown's avatar
unknown committed
5054
  if (ft_handler == NULL)
unknown's avatar
unknown committed
5055
    DBUG_RETURN(-1.0);
unknown's avatar
unknown committed
5056

5057
  if (key != NO_SUCH_KEY && table->null_row) /* NULL row from an outer join */
unknown's avatar
unknown committed
5058
    DBUG_RETURN(0.0);
unknown's avatar
unknown committed
5059

unknown's avatar
unknown committed
5060 5061 5062
  if (join_key)
  {
    if (table->file->ft_handler)
unknown's avatar
unknown committed
5063
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
unknown's avatar
unknown committed
5064 5065 5066
    join_key=0;
  }

5067
  if (key == NO_SUCH_KEY)
unknown's avatar
unknown committed
5068
  {
5069 5070
    String *a= concat_ws->val_str(&value);
    if ((null_value= (a == 0)) || !a->length())
unknown's avatar
unknown committed
5071 5072
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
5073
				      (uchar *)a->ptr(), a->length()));
unknown's avatar
unknown committed
5074
  }
unknown's avatar
unknown committed
5075 5076
  DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                 table->record[0], 0));
unknown's avatar
unknown committed
5077 5078
}

5079 5080
void Item_func_match::print(String *str)
{
5081
  str->append(STRING_WITH_LEN("(match "));
unknown's avatar
unknown committed
5082
  print_args(str, 1);
5083
  str->append(STRING_WITH_LEN(" against ("));
5084
  args[0]->print(str);
unknown's avatar
unknown committed
5085
  if (flags & FT_BOOL)
5086
    str->append(STRING_WITH_LEN(" in boolean mode"));
unknown's avatar
unknown committed
5087
  else if (flags & FT_EXPAND)
5088 5089
    str->append(STRING_WITH_LEN(" with query expansion"));
  str->append(STRING_WITH_LEN("))"));
5090
}
unknown's avatar
unknown committed
5091

unknown's avatar
unknown committed
5092 5093
longlong Item_func_bit_xor::val_int()
{
5094
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
5095 5096
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
5097
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
5098 5099 5100 5101
    return 0;
  return (longlong) (arg1 ^ arg2);
}

5102

5103 5104 5105 5106
/***************************************************************************
  System variables
****************************************************************************/

5107 5108 5109 5110 5111 5112 5113 5114
/*
  Return value of an system variable base[.name] as a constant item

  SYNOPSIS
    get_system_var()
    thd			Thread handler
    var_type		global / session
    name		Name of base or system variable
unknown's avatar
unknown committed
5115
    component		Component
5116 5117 5118 5119 5120 5121 5122 5123

  NOTES
    If component.str = 0 then the variable name is in 'name'

  RETURN
    0	error
    #	constant item
*/
5124

5125 5126 5127

Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
		     LEX_STRING component)
5128
{
5129 5130 5131
  sys_var *var;
  LEX_STRING *base_name, *component_name;

5132 5133 5134 5135 5136 5137 5138 5139 5140 5141
  if (component.str)
  {
    base_name= &component;
    component_name= &name;
  }
  else
  {
    base_name= &name;
    component_name= &component;			// Empty string
  }
unknown's avatar
unknown committed
5142

unknown's avatar
unknown committed
5143
  if (!(var= find_sys_var(thd, base_name->str, base_name->length)))
unknown's avatar
unknown committed
5144
    return 0;
5145 5146 5147 5148
  if (component.str)
  {
    if (!var->is_struct())
    {
5149
      my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
5150 5151 5152
      return 0;
    }
  }
unknown's avatar
unknown committed
5153
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
5154

5155 5156
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);

5157
  return new Item_func_get_system_var(var, var_type, component_name,
5158
                                      NULL, 0);
5159 5160 5161
}


unknown's avatar
unknown committed
5162 5163
/*
  Check a user level lock.
5164 5165 5166 5167 5168 5169 5170 5171

  SYNOPSIS:
    val_int()

  RETURN VALUES
    1		Available
    0		Already taken
    NULL	Error
unknown's avatar
unknown committed
5172 5173
*/

5174
longlong Item_func_is_free_lock::val_int()
unknown's avatar
unknown committed
5175
{
5176
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
5177
  String *res=args[0]->val_str(&value);
5178
  User_level_lock *ull;
unknown's avatar
unknown committed
5179 5180

  null_value=0;
5181
  if (!res || !res->length())
unknown's avatar
unknown committed
5182 5183 5184 5185 5186 5187
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
5188 5189
  ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(),
                                       (size_t) res->length());
unknown's avatar
unknown committed
5190 5191 5192 5193 5194
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
unknown's avatar
unknown committed
5195

unknown's avatar
SCRUM  
unknown committed
5196 5197
longlong Item_func_is_used_lock::val_int()
{
5198
  DBUG_ASSERT(fixed == 1);
unknown's avatar
SCRUM  
unknown committed
5199
  String *res=args[0]->val_str(&value);
5200
  User_level_lock *ull;
unknown's avatar
SCRUM  
unknown committed
5201 5202 5203 5204 5205 5206

  null_value=1;
  if (!res || !res->length())
    return 0;
  
  pthread_mutex_lock(&LOCK_user_locks);
5207 5208
  ull= (User_level_lock *) hash_search(&hash_user_locks, (uchar*) res->ptr(),
                                       (size_t) res->length());
unknown's avatar
SCRUM  
unknown committed
5209 5210 5211 5212 5213 5214 5215 5216
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 0;

  null_value=0;
  return ull->thread_id;
}

5217

5218 5219 5220 5221 5222 5223 5224 5225 5226
longlong Item_func_row_count::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->row_count_func;
}


5227 5228


5229
Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name)
5230
  :Item_func(), context(context_arg), m_name(name), m_sp(NULL), sp_result_field(NULL)
5231
{
unknown's avatar
unknown committed
5232
  maybe_null= 1;
5233
  m_name->init_qname(current_thd);
unknown's avatar
unknown committed
5234 5235
  dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
  dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
5236 5237
}

unknown's avatar
unknown committed
5238

5239 5240
Item_func_sp::Item_func_sp(Name_resolution_context *context_arg,
                           sp_name *name, List<Item> &list)
5241
  :Item_func(list), context(context_arg), m_name(name), m_sp(NULL),sp_result_field(NULL)
5242
{
unknown's avatar
unknown committed
5243
  maybe_null= 1;
5244
  m_name->init_qname(current_thd);
unknown's avatar
unknown committed
5245 5246
  dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
  dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
5247 5248
}

unknown's avatar
unknown committed
5249

5250 5251 5252
void
Item_func_sp::cleanup()
{
5253
  if (sp_result_field)
5254
  {
5255 5256
    delete sp_result_field;
    sp_result_field= NULL;
5257
  }
5258
  m_sp= NULL;
5259
  dummy_table->alias= NULL;
5260 5261
  Item_func::cleanup();
}
unknown's avatar
unknown committed
5262

5263 5264 5265
const char *
Item_func_sp::func_name() const
{
5266
  THD *thd= current_thd;
unknown's avatar
unknown committed
5267
  /* Calculate length to avoid reallocation of string for sure */
5268
  uint len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) +
5269 5270
              m_name->m_name.length)*2 + //characters*quoting
             2 +                         // ` and `
5271 5272
             (m_name->m_explicit_name ?
              3 : 0) +                   // '`', '`' and '.' for the db
5273 5274
             1 +                         // end of string
             ALIGN_SIZE(1));             // to avoid String reallocation
unknown's avatar
unknown committed
5275
  String qname((char *)alloc_root(thd->mem_root, len), len,
5276
               system_charset_info);
5277

5278
  qname.length(0);
5279 5280 5281 5282 5283
  if (m_name->m_explicit_name)
  {
    append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
    qname.append('.');
  }
5284 5285
  append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
  return qname.ptr();
5286 5287
}

5288

5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306

/**
  @brief Initialize the result field by creating a temporary dummy table
    and assign it to a newly created field object. Meta data used to
    create the field is fetched from the sp_head belonging to the stored
    proceedure found in the stored procedure functon cache.
  
  @note This function should be called from fix_fields to init the result
    field. It is some what related to Item_field.

  @see Item_field

  @param thd A pointer to the session and thread context.

  @return Function return error status.
  @retval TRUE is returned on an error
  @retval FALSE is returned on success.
*/
5307

5308 5309
bool
Item_func_sp::init_result_field(THD *thd)
unknown's avatar
unknown committed
5310
{
unknown's avatar
unknown committed
5311
  LEX_STRING empty_name= { C_STRING_WITH_LEN("") };
5312
  TABLE_SHARE *share;
5313
  DBUG_ENTER("Item_func_sp::init_result_field");
unknown's avatar
unknown committed
5314

5315 5316
  DBUG_ASSERT(m_sp == NULL);
  DBUG_ASSERT(sp_result_field == NULL);
unknown's avatar
unknown committed
5317

5318 5319
  if (!(m_sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, m_name,
                               &thd->sp_func_cache, TRUE)))
unknown's avatar
unknown committed
5320
  {
5321 5322 5323
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
    context->process_error(thd);
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5324
  }
5325 5326 5327 5328 5329 5330

  /*
     A Field need to be attached to a Table.
     Below we "create" a dummy table by initializing 
     the needed pointers.
   */
unknown's avatar
unknown committed
5331 5332 5333
  
  share= dummy_table->s;
  dummy_table->alias = "";
5334 5335 5336 5337 5338 5339
  dummy_table->maybe_null = maybe_null;
  dummy_table->in_use= thd;
  dummy_table->copy_blobs= TRUE;
  share->table_cache_key = empty_name;
  share->table_name = empty_name;

5340 5341
  if (!(sp_result_field= m_sp->create_result_field(max_length, name,
                                                   dummy_table)))
unknown's avatar
unknown committed
5342
  {
5343
   DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5344
  }
5345 5346
  
  if (sp_result_field->pack_length() > sizeof(result_buf))
unknown's avatar
unknown committed
5347
  {
5348 5349 5350 5351
    void *tmp;
    if (!(tmp= sql_alloc(sp_result_field->pack_length())))
      DBUG_RETURN(TRUE);
    sp_result_field->move_field((uchar*) tmp);
unknown's avatar
unknown committed
5352
  }
5353 5354
  else
    sp_result_field->move_field(result_buf);
5355 5356 5357 5358
  
  sp_result_field->null_ptr= (uchar *) &null_value;
  sp_result_field->null_bit= 1;
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
5359 5360
}

5361

5362 5363
/**
  @brief Initialize local members with values from the Field interface.
unknown's avatar
unknown committed
5364

5365 5366
  @note called from Item::fix_fields.
*/
5367

5368 5369 5370
void Item_func_sp::fix_length_and_dec()
{
  DBUG_ENTER("Item_func_sp::fix_length_and_dec");
unknown's avatar
unknown committed
5371

5372 5373 5374 5375 5376 5377 5378 5379 5380 5381
  DBUG_ASSERT(sp_result_field);
  decimals= sp_result_field->decimals();
  max_length= sp_result_field->field_length;
  collation.set(sp_result_field->charset());
  maybe_null= 1;
  unsigned_flag= test(sp_result_field->flags & UNSIGNED_FLAG);

  DBUG_VOID_RETURN;
}

5382

5383 5384 5385 5386 5387 5388
/**
  @brief Execute function & store value in field.

  @return Function returns error status.
  @retval FALSE on success.
  @retval TRUE if an error occurred.
unknown's avatar
unknown committed
5389 5390
*/

5391
bool
5392
Item_func_sp::execute()
5393
{
5394
  THD *thd= current_thd;
5395
  
5396 5397
  /* Execute function and store the return value in the field. */

5398
  if (execute_impl(thd))
5399 5400 5401
  {
    null_value= 1;
    context->process_error(thd);
5402 5403
    if (thd->killed)
      thd->send_kill_message();
5404 5405 5406 5407 5408
    return TRUE;
  }

  /* Check that the field (the value) is not NULL. */

5409
  null_value= sp_result_field->is_null();
5410 5411

  return null_value;
5412 5413 5414
}


5415 5416 5417 5418 5419 5420 5421 5422 5423 5424
/**
   @brief Execute function and store the return value in the field.

   @note This function was intended to be the concrete implementation of
    the interface function execute. This was never realized.

   @return The error state.
   @retval FALSE on success
   @retval TRUE if an error occurred.
*/
5425
bool
5426
Item_func_sp::execute_impl(THD *thd)
5427
{
5428
  bool err_status= TRUE;
5429
  Sub_statement_state statement_state;
5430 5431 5432
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  Security_context *save_security_ctx= thd->security_ctx;
#endif
5433

5434 5435
  DBUG_ENTER("Item_func_sp::execute_impl");

5436 5437 5438 5439 5440 5441 5442
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  if (context->security_ctx)
  {
    /* Set view definer security context */
    thd->security_ctx= context->security_ctx;
  }
#endif
5443
  if (sp_check_access(thd))
5444
    goto error;
5445

5446 5447 5448 5449
  /*
    Throw an error if a non-deterministic function is called while
    statement-based replication (SBR) is active.
  */
5450
  if (!m_sp->m_chistics->detistic && !trust_function_creators &&
5451 5452 5453 5454 5455 5456 5457
      (mysql_bin_log.is_open() &&
       thd->variables.binlog_format == BINLOG_FORMAT_STMT))
  {
    my_error(ER_BINLOG_ROW_RBR_TO_SBR, MYF(0));
    goto error;
  }

5458 5459 5460 5461 5462
  /*
    Disable the binlogging if this is not a SELECT statement. If this is a
    SELECT, leave binlogging on, so execute_function() code writes the
    function call into binlog.
  */
5463
  thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
5464
  err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field); 
5465
  thd->restore_sub_statement_state(&statement_state);
unknown's avatar
unknown committed
5466

5467
error:
5468
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
5469
  thd->security_ctx= save_security_ctx;
5470
#endif
5471

5472
  DBUG_RETURN(err_status);
5473 5474
}

5475

unknown's avatar
unknown committed
5476 5477 5478 5479
void
Item_func_sp::make_field(Send_field *tmp_field)
{
  DBUG_ENTER("Item_func_sp::make_field");
5480 5481
  DBUG_ASSERT(sp_result_field);
  sp_result_field->make_field(tmp_field);
unknown's avatar
unknown committed
5482 5483 5484 5485
  DBUG_VOID_RETURN;
}


5486 5487
enum enum_field_types
Item_func_sp::field_type() const
5488
{
5489
  DBUG_ENTER("Item_func_sp::field_type");
5490 5491
  DBUG_ASSERT(sp_result_field);
  DBUG_RETURN(sp_result_field->type());
5492 5493
}

5494 5495
Item_result
Item_func_sp::result_type() const
5496
{
5497 5498
  DBUG_ENTER("Item_func_sp::result_type");
  DBUG_PRINT("info", ("m_sp = %p", m_sp));
5499 5500
  DBUG_ASSERT(sp_result_field);
  DBUG_RETURN(sp_result_field->result_type());
5501 5502
}

5503 5504 5505
longlong Item_func_found_rows::val_int()
{
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
5506
  return current_thd->found_rows();
5507
}
unknown's avatar
unknown committed
5508

unknown's avatar
unknown committed
5509

unknown's avatar
unknown committed
5510 5511 5512 5513 5514
Field *
Item_func_sp::tmp_table_field(TABLE *t_arg)
{
  DBUG_ENTER("Item_func_sp::tmp_table_field");

5515 5516
  DBUG_ASSERT(sp_result_field);
  DBUG_RETURN(sp_result_field);
unknown's avatar
unknown committed
5517
}
5518

unknown's avatar
unknown committed
5519

5520 5521
/**
  @brief Checks if requested access to function can be granted to user.
5522 5523
    If function isn't found yet, it searches function first.
    If function can't be found or user don't have requested access
unknown's avatar
unknown committed
5524
    error is raised.
5525 5526 5527 5528 5529 5530 5531

  @param thd thread handler

  @return Indication if the access was granted or not.
  @retval FALSE Access is granted.
  @retval TRUE Requested access can't be granted or function doesn't exists.
    
5532
*/
unknown's avatar
unknown committed
5533

5534
bool
5535
Item_func_sp::sp_check_access(THD *thd)
5536
{
5537 5538
  DBUG_ENTER("Item_func_sp::sp_check_access");
  DBUG_ASSERT(m_sp);
unknown's avatar
unknown committed
5539
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5540
  if (check_routine_access(thd, EXECUTE_ACL,
unknown's avatar
unknown committed
5541
			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
5542
    DBUG_RETURN(TRUE);
5543
#endif
unknown's avatar
unknown committed
5544

5545
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
5546
}
5547

5548

5549 5550 5551 5552
bool
Item_func_sp::fix_fields(THD *thd, Item **ref)
{
  bool res;
5553
  DBUG_ENTER("Item_func_sp::fix_fields");
5554
  DBUG_ASSERT(fixed == 0);
5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565
 
  /*
    We must call init_result_field before Item_func::fix_fields() 
    to make m_sp and result_field members available to fix_length_and_dec(),
    which is called from Item_func::fix_fields().
  */
  res= init_result_field(thd);

  if (res)
    DBUG_RETURN(res);

5566
  res= Item_func::fix_fields(thd, ref);
5567 5568 5569 5570 5571

  if (res)
    DBUG_RETURN(res);

  if (thd->lex->view_prepare_mode)
unknown's avatar
unknown committed
5572
  {
5573 5574
    /*
      Here we check privileges of the stored routine only during view
5575 5576 5577 5578 5579 5580 5581
      creation, in order to validate the view.  A runtime check is
      perfomed in Item_func_sp::execute(), and this method is not
      called during context analysis.  Notice, that during view
      creation we do not infer into stored routine bodies and do not
      check privileges of its statements, which would probably be a
      good idea especially if the view has SQL SECURITY DEFINER and
      the used stored procedure has SQL SECURITY DEFINER.
5582
    */
5583
    res= sp_check_access(thd);
5584
#ifndef NO_EMBEDDED_ACCESS_CHECKS
5585 5586 5587
    /*
      Try to set and restore the security context to see whether it's valid
    */
5588
    Security_context *save_secutiry_ctx;
5589 5590
    res= set_routine_security_ctx(thd, m_sp, false, &save_secutiry_ctx);
    if (!res)
5591
      m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx);
5592
    
5593
#endif /* ! NO_EMBEDDED_ACCESS_CHECKS */
unknown's avatar
unknown committed
5594
  }
5595

unknown's avatar
unknown committed
5596
  if (!m_sp->m_chistics->detistic)
5597 5598 5599 5600 5601
  {
    used_tables_cache |= RAND_TABLE_BIT;
    const_item_cache= FALSE;
  }

5602
  DBUG_RETURN(res);
5603
}
5604 5605


unknown's avatar
unknown committed
5606 5607 5608
void Item_func_sp::update_used_tables()
{
  Item_func::update_used_tables();
5609

unknown's avatar
unknown committed
5610
  if (!m_sp->m_chistics->detistic)
5611 5612 5613 5614
  {
    used_tables_cache |= RAND_TABLE_BIT;
    const_item_cache= FALSE;
  }
unknown's avatar
unknown committed
5615
}
5616 5617


5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639
/*
  uuid_short handling.

  The short uuid is defined as a longlong that contains the following bytes:

  Bytes  Comment
  1      Server_id & 255
  4      Startup time of server in seconds
  3      Incrementor

  This means that an uuid is guaranteed to be unique
  even in a replication environment if the following holds:

  - The last byte of the server id is unique
  - If you between two shutdown of the server don't get more than
    an average of 2^24 = 16M calls to uuid_short() per second.
*/

ulonglong uuid_value;

void uuid_short_init()
{
5640 5641
  uuid_value= ((((ulonglong) server_id) << 56) + 
               (((ulonglong) server_start_time) << 24));
5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652
}


longlong Item_func_uuid_short::val_int()
{
  ulonglong val;
  pthread_mutex_lock(&LOCK_uuid_generator);
  val= uuid_value++;
  pthread_mutex_unlock(&LOCK_uuid_generator);
  return (longlong) val;
}