item_func.cc 106 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2003 MySQL AB
unknown's avatar
unknown committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

   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
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   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 */

#ifdef __GNUC__
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
unknown's avatar
unknown committed
25
#include "slave.h"				// for wait_for_master_pos
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

35 36 37 38 39 40 41 42 43 44
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
45 46
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
			      const char *fname)
47
{
48 49 50 51
  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
           c1.collation->name, c1.derivation_name(),
           c2.collation->name, c2.derivation_name(),
           fname);
52 53
}

54
static void my_coll_agg_error(DTCollation &c1,
unknown's avatar
unknown committed
55 56 57 58
			       DTCollation &c2,
			       DTCollation &c3,
			       const char *fname)
{
59 60 61 62 63
  my_error(ER_CANT_AGGREGATE_3COLLATIONS, MYF(0),
           c1.collation->name, c1.derivation_name(),
           c2.collation->name, c2.derivation_name(),
           c3.collation->name, c3.derivation_name(),
           fname);
unknown's avatar
unknown committed
64 65
}

unknown's avatar
unknown committed
66 67

static void my_coll_agg_error(Item** args, uint count, const char *fname)
unknown's avatar
unknown committed
68
{
unknown's avatar
unknown committed
69
  if (count == 2)
unknown's avatar
unknown committed
70
    my_coll_agg_error(args[0]->collation, args[1]->collation, fname);
unknown's avatar
unknown committed
71
  else if (count == 3)
unknown's avatar
unknown committed
72 73 74 75 76
    my_coll_agg_error(args[0]->collation,
		      args[1]->collation,
		      args[2]->collation,
		      fname);
  else
77
    my_error(ER_CANT_AGGREGATE_NCOLLATIONS, MYF(0), fname);
unknown's avatar
unknown committed
78 79
}

unknown's avatar
unknown committed
80

81
bool Item_func::agg_arg_collations(DTCollation &c, Item **av, uint count,
82
                                   uint flags)
unknown's avatar
unknown committed
83 84
{
  uint i;
85 86
  c.nagg= 0;
  c.strong= 0;
87
  c.set(av[0]->collation);
unknown's avatar
unknown committed
88
  for (i= 1; i < count; i++)
unknown's avatar
unknown committed
89
  {
90
    if (c.aggregate(av[i]->collation, flags))
unknown's avatar
unknown committed
91
    {
unknown's avatar
unknown committed
92
      my_coll_agg_error(av, count, func_name());
unknown's avatar
unknown committed
93 94 95
      return TRUE;
    }
  }
unknown's avatar
unknown committed
96 97 98 99 100 101
  if ((flags & MY_COLL_DISALLOW_NONE) &&
      c.derivation == DERIVATION_NONE)
  {
    my_coll_agg_error(av, count, func_name());
    return TRUE;
  }
unknown's avatar
unknown committed
102 103 104
  return FALSE;
}

unknown's avatar
unknown committed
105

106
bool Item_func::agg_arg_collations_for_comparison(DTCollation &c,
107
						  Item **av, uint count,
108
                                                  uint flags)
unknown's avatar
unknown committed
109
{
unknown's avatar
unknown committed
110
  return (agg_arg_collations(c, av, count, flags | MY_COLL_DISALLOW_NONE));
unknown's avatar
unknown committed
111 112 113
}


unknown's avatar
unknown committed
114 115 116 117 118 119 120 121
/* 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
122

unknown's avatar
unknown committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

/* 
  Collect arguments' character sets together.
  We allow to apply automatic character set conversion in some cases.
  The conditions when conversion is possible are:
  - arguments A and B have different charsets
  - A wins according to coercibility rules
    (i.e. a column is stronger than a string constant,
     an explicit COLLATE clause is stronger than a column)
  - character set of A is either superset for character set of B,
    or B is a string constant which can be converted into the
    character set of A without data loss.
    
  If all of the above is true, then it's possible to convert
  B into the character set of A, and then compare according
  to the collation of A.
  
  For functions with more than two arguments:

    collect(A,B,C) ::= collect(collect(A,B),C)
*/

bool Item_func::agg_arg_charsets(DTCollation &coll,
                                 Item **args, uint nargs, uint flags)
{
  Item **arg, **last, *safe_args[2];
  if (agg_arg_collations(coll, args, nargs, flags))
    return TRUE;

  /*
    For better error reporting: save the first and the second argument.
    We need this only if the the number of args is 3 or 2:
    - for a longer argument list, "Illegal mix of collations"
      doesn't display each argument's characteristics.
    - if nargs is 1, then this error cannot happen.
  */
  if (nargs >=2 && nargs <= 3)
  {
    safe_args[0]= args[0];
    safe_args[1]= args[1];
  }

  THD *thd= current_thd;
unknown's avatar
unknown committed
166
  Item_arena *arena, backup;
unknown's avatar
unknown committed
167 168 169 170 171
  bool res= FALSE;
  /*
    In case we're in statement prepare, create conversion item
    in its memory: it will be reused on each execute.
  */
unknown's avatar
unknown committed
172
  arena= thd->change_arena_if_needed(&backup);
unknown's avatar
unknown committed
173 174 175 176

  for (arg= args, last= args + nargs; arg < last; arg++)
  {
    Item* conv;
177
    uint32 dummy_offset;
unknown's avatar
unknown committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    if (!String::needs_conversion(0, coll.collation,
                                  (*arg)->collation.collation,
                                  &dummy_offset))
      continue;

    if (!(conv= (*arg)->safe_charset_converter(coll.collation)))
    {
      if (nargs >=2 && nargs <= 3)
      {
        /* restore the original arguments for better error message */
        args[0]= safe_args[0];
        args[1]= safe_args[1];
      }
      my_coll_agg_error(args, nargs, func_name());
      res= TRUE;
      break; // we cannot return here, we need to restore "arena".
    }
unknown's avatar
unknown committed
195 196
    if ((*arg)->type() == FIELD_ITEM)
      ((Item_field *)(*arg))->no_const_subst= 1;
unknown's avatar
unknown committed
197 198 199 200 201
    /*
      We do not check conv->fixed, because Item_func_conv_charset which can
      be return by safe_charset_converter can't be fixed at creation, also
      it do not need tables (second argument) for name resolving
    */
unknown's avatar
unknown committed
202
    *arg= conv;
unknown's avatar
unknown committed
203
    conv->fix_fields(thd, 0, arg);
unknown's avatar
unknown committed
204
  }
unknown's avatar
unknown committed
205
  if (arena)
unknown's avatar
unknown committed
206 207 208 209 210 211
    thd->restore_backup_item_arena(arena, &backup);
  return res;
}



212
void Item_func::set_arguments(List<Item> &list)
unknown's avatar
unknown committed
213
{
214
  allowed_arg_cols= 1;
unknown's avatar
unknown committed
215 216 217 218
  arg_count=list.elements;
  if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
  {
    uint i=0;
unknown's avatar
unknown committed
219
    List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
220 221 222 223 224 225 226 227 228 229 230
    Item *item;

    while ((item=li++))
    {
      args[i++]= item;
      with_sum_func|=item->with_sum_func;
    }
  }
  list.empty();					// Fields are used
}

231 232 233 234 235 236
Item_func::Item_func(List<Item> &list)
  :allowed_arg_cols(1)
{
  set_arguments(list);
}

237
Item_func::Item_func(THD *thd, Item_func *item)
238
  :Item_result_field(thd, item),
239 240 241 242 243
   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)
244 245 246 247 248 249 250 251 252 253
{
  if (arg_count)
  {
    if (arg_count <=2)
      args= tmp_arg;
    else
    {
      if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
	return;
    }
254
    memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count);
255 256 257
  }
}

unknown's avatar
unknown committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

/*
  Resolve references to table column for a function and it's argument

  SYNOPSIS:
  fix_fields()
  thd		Thread object
  tables	List of all open tables involved in the query
  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
277
      used_tables_cache Set to union of the tables used by arguments
unknown's avatar
unknown committed
278 279 280

      str_value.charset If this is a string function, set this to the
			character set for the first argument.
281
			If any argument is binary, this is set to binary
unknown's avatar
unknown committed
282 283 284 285 286 287 288

   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
289 290
  FALSE	ok
  TRUE	Got error.  Stored with my_error().
unknown's avatar
unknown committed
291 292
*/

unknown's avatar
unknown committed
293
bool
unknown's avatar
unknown committed
294
Item_func::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
295
{
296
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
297
  Item **arg,**arg_end;
298
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
299
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
300
#endif
301

302
  used_tables_cache= not_null_tables_cache= 0;
unknown's avatar
unknown committed
303 304
  const_item_cache=1;

unknown's avatar
unknown committed
305
  if (check_stack_overrun(thd, buff))
unknown's avatar
unknown committed
306
    return TRUE;				// Fatal error if flag is set!
unknown's avatar
unknown committed
307 308 309 310
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
unknown's avatar
unknown committed
311
      Item *item;
unknown's avatar
merge  
unknown committed
312 313 314 315
      /*
	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
      */
316
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, tables, arg)))
unknown's avatar
unknown committed
317
	return TRUE;				/* purecov: inspected */
unknown's avatar
unknown committed
318
      item= *arg;
319 320 321 322 323 324 325 326 327 328 329 330 331 332

      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
333
      if (item->maybe_null)
unknown's avatar
unknown committed
334
	maybe_null=1;
335

unknown's avatar
unknown committed
336
      with_sum_func= with_sum_func || item->with_sum_func;
337 338 339
      used_tables_cache|=     item->used_tables();
      not_null_tables_cache|= item->not_null_tables();
      const_item_cache&=      item->const_item();
unknown's avatar
unknown committed
340 341 342
    }
  }
  fix_length_and_dec();
unknown's avatar
unknown committed
343 344
  if (thd->net.report_error) // An error inside fix_length_and_dec occured
    return TRUE;
345
  fixed= 1;
unknown's avatar
unknown committed
346
  return FALSE;
unknown's avatar
unknown committed
347 348
}

unknown's avatar
unknown committed
349 350 351 352 353 354 355 356 357 358 359 360 361
bool Item_func::walk (Item_processor processor, byte *argument)
{
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
      if ((*arg)->walk(processor, argument))
	return 1;
    }
  }
  return (this->*processor)(argument);
}
362

unknown's avatar
unknown committed
363

unknown's avatar
unknown committed
364

unknown's avatar
unknown committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
/*
  Transform an Item_func object with a transformer callback function
   
  SYNOPSIS
    transform()
    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
  
  DESCRIPTION
    The function recursively applies the transform method with the
    same transformer to each argument the function.
    If the call of the method for a member item returns a new item
    the old item is substituted for a new one.
    After this the transform method is applied to the root node
    of the Item_func object. 
     
  RETURN VALUES
    Item returned as the result of transformation of the root node 
*/

Item *Item_func::transform(Item_transformer transformer, byte *argument)
387 388 389 390 391 392
{
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
unknown's avatar
unknown committed
393
      Item *new_item= (*arg)->transform(transformer, argument);
394 395
      if (!new_item)
	return 0;
unknown's avatar
unknown committed
396 397
      if (*arg != new_item)
        current_thd->change_item_tree(arg, new_item);
398 399
    }
  }
unknown's avatar
unknown committed
400
  return (this->*transformer)(argument);
401 402 403
}


404 405
/* See comments in Item_cmp_func::split_sum_func() */

406 407
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
                               List<Item> &fields)
unknown's avatar
unknown committed
408
{
409 410
  Item **arg, **arg_end;
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
411
    (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg);
unknown's avatar
unknown committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
}


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;
}

433 434 435 436 437 438 439

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


unknown's avatar
unknown committed
440 441 442 443
void Item_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
unknown's avatar
unknown committed
444
  print_args(str, 0);
445 446 447 448
  str->append(')');
}


unknown's avatar
unknown committed
449
void Item_func::print_args(String *str, uint from)
450
{
unknown's avatar
unknown committed
451
  for (uint i=from ; i < arg_count ; i++)
unknown's avatar
unknown committed
452
  {
unknown's avatar
unknown committed
453
    if (i != from)
unknown's avatar
unknown committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      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
474

475
bool Item_func::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
476 477 478 479 480 481 482 483 484 485 486
{
  /* 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;
  if (arg_count != item_func->arg_count ||
      func_name() != item_func->func_name())
    return 0;
  for (uint i=0; i < arg_count ; i++)
487
    if (!args[i]->eq(item_func->args[i], binary_cmp))
unknown's avatar
unknown committed
488 489 490 491
      return 0;
  return 1;
}

492

493 494 495 496 497
Field *Item_func::tmp_table_field(TABLE *t_arg)
{
  Field *res;
  LINT_INIT(res);

unknown's avatar
unknown committed
498
  switch (result_type()) {
499 500 501 502 503 504 505 506 507 508 509 510
  case INT_RESULT:
    if (max_length > 11)
      res= new Field_longlong(max_length, maybe_null, name, t_arg,
			      unsigned_flag);
    else
      res= new Field_long(max_length, maybe_null, name, t_arg,
			  unsigned_flag);
    break;
  case REAL_RESULT:
    res= new Field_double(max_length, maybe_null, name, t_arg, decimals);
    break;
  case STRING_RESULT:
511
    res= make_string_field(t_arg);
512
    break;
unknown's avatar
unknown committed
513 514 515 516
  case DECIMAL_RESULT:
    res= new Field_new_decimal(max_length + (decimals?1:0), maybe_null,
                               name, t_arg, decimals);
    break;
517
  case ROW_RESULT:
unknown's avatar
unknown committed
518
  default:
unknown's avatar
unknown committed
519
    // This case should never be chosen
unknown's avatar
unknown committed
520 521
    DBUG_ASSERT(0);
    break;
522 523 524 525
  }
  return res;
}

unknown's avatar
unknown committed
526 527 528 529 530 531 532
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;
}

533

unknown's avatar
unknown committed
534 535
String *Item_real_func::val_str(String *str)
{
536
  DBUG_ASSERT(fixed == 1);
537
  double nr= val_real();
unknown's avatar
unknown committed
538 539
  if (null_value)
    return 0; /* purecov: inspected */
unknown's avatar
unknown committed
540
  str->set(nr,decimals, &my_charset_bin);
unknown's avatar
unknown committed
541 542 543 544
  return str;
}


unknown's avatar
unknown committed
545
void Item_func::fix_num_length_and_dec()
unknown's avatar
unknown committed
546
{
unknown's avatar
unknown committed
547 548
  decimals= 0;
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
549
  {
unknown's avatar
unknown committed
550
    set_if_bigger(decimals, args[i]->decimals);
unknown's avatar
unknown committed
551
  }
unknown's avatar
unknown committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  max_length= float_length(decimals);
}


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()
{
  uint32 length= 0;
  decimals= 0;
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
573
  {
unknown's avatar
unknown committed
574 575
    set_if_bigger(decimals, args[i]->decimals);
    set_if_bigger(length, (args[i]->max_length - args[i]->decimals));
unknown's avatar
unknown committed
576
  }
unknown's avatar
unknown committed
577 578 579 580 581 582
  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
583 584 585
}


unknown's avatar
unknown committed
586 587 588 589 590 591 592 593
/*
  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
594
{
unknown's avatar
unknown committed
595
  max_length= 0;
unknown's avatar
unknown committed
596
  for (uint i=0 ; i < arg_count ; i++)
unknown's avatar
unknown committed
597
    set_if_bigger(max_length, args[i]->max_length);
unknown's avatar
unknown committed
598 599
}

unknown's avatar
unknown committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635

/*
  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
636 637 638 639 640 641 642 643 644 645
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;
}


646
Item *Item_func::get_tmp_table_item(THD *thd)
647 648 649
{
  if (!with_sum_func && !const_item())
    return new Item_field(result_field);
650
  return copy_or_same(thd);
651 652
}

unknown's avatar
unknown committed
653 654
String *Item_int_func::val_str(String *str)
{
655
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
656 657 658
  longlong nr=val_int();
  if (null_value)
    return 0;
659
  if (!unsigned_flag)
unknown's avatar
unknown committed
660
    str->set(nr,&my_charset_bin);
661
  else
unknown's avatar
unknown committed
662
    str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
663 664 665
  return str;
}

unknown's avatar
unknown committed
666

667
/*
unknown's avatar
unknown committed
668 669 670 671 672
  Check arguments here to determine result's type for function with two
  arguments.

  SYNOPSIS
    Item_num_op::find_num_type()
673
*/
unknown's avatar
unknown committed
674 675 676

void Item_num_op::find_num_type(void)
{
unknown's avatar
unknown committed
677 678 679 680 681 682 683 684
  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)
685
  {
unknown's avatar
unknown committed
686 687 688 689 690 691 692 693 694 695 696 697
    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();
  }
  else if (r0 == INT_RESULT && r1 == INT_RESULT)
  {
    decimals= 0;
unknown's avatar
unknown committed
698
    hybrid_type=INT_RESULT;
699
    unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
unknown's avatar
unknown committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    result_precision();
  }
  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;
}


/*
  Set result type of function if it (type) is depends only on first argument

  SYNOPSIS
    Item_func_num1::find_num_type()
*/
717

unknown's avatar
unknown committed
718 719 720 721
void Item_func_num1::find_num_type()
{
  DBUG_ENTER("Item_func_num1::find_num_type");
  DBUG_PRINT("info", ("name %s", func_name()));
722
  switch (hybrid_type= args[0]->result_type()) {
unknown's avatar
unknown committed
723
  case INT_RESULT:
724
    unsigned_flag= args[0]->unsigned_flag;
unknown's avatar
unknown committed
725 726 727 728 729 730 731 732 733 734
    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);
735
  }
unknown's avatar
unknown committed
736 737 738 739 740 741
  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
742 743
}

unknown's avatar
unknown committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759

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
760
{
761
  DBUG_ASSERT(fixed == 1);
762
  switch (hybrid_type) {
unknown's avatar
unknown committed
763 764 765 766
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
767
      return 0;                                 // null is set
unknown's avatar
unknown committed
768 769 770 771 772 773 774
    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
775 776
    if (null_value)
      return 0; /* purecov: inspected */
777
    if (!unsigned_flag)
unknown's avatar
unknown committed
778
      str->set(nr,&my_charset_bin);
779
    else
unknown's avatar
unknown committed
780
      str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
781
    break;
unknown's avatar
unknown committed
782
  }
unknown's avatar
unknown committed
783
  case REAL_RESULT:
unknown's avatar
unknown committed
784
  {
785
    double nr= real_op();
unknown's avatar
unknown committed
786 787
    if (null_value)
      return 0; /* purecov: inspected */
unknown's avatar
unknown committed
788
    str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
789 790 791 792
    break;
  }
  default:
    DBUG_ASSERT(0);
unknown's avatar
unknown committed
793 794 795 796 797
  }
  return str;
}


unknown's avatar
unknown committed
798 799 800
double Item_func_numhybrid::val_real()
{
  DBUG_ASSERT(fixed == 1);
801
  switch (hybrid_type) {
unknown's avatar
unknown committed
802 803 804 805
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    double result;
806 807
    if (!(val= decimal_op(&decimal_value)))
      return 0.0;                               // null is set
unknown's avatar
unknown committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    my_decimal2double(E_DEC_FATAL_ERROR, val, &result);
    return result;
  }
  case INT_RESULT:
    return (double)int_op();
  case REAL_RESULT:
    return real_op();
  default:
    DBUG_ASSERT(0);
  }
  return 0.0;
}


longlong Item_func_numhybrid::val_int()
{
  DBUG_ASSERT(fixed == 1);
825
  switch (hybrid_type) {
unknown's avatar
unknown committed
826 827 828 829
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
830
      return 0;                                 // null is set
unknown's avatar
unknown committed
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
    longlong result;
    my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result);
    return result;
  }
  case INT_RESULT:
    return int_op();
  case REAL_RESULT:
    return (longlong)real_op();
  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);
850
  switch (hybrid_type) {
unknown's avatar
unknown committed
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
  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:
  {
    double result= int_op();
    double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value);
    break;
  }
  case STRING_RESULT:
  case ROW_RESULT:
  default:
    DBUG_ASSERT(0);
  }
  return val;
}


875 876
void Item_func_signed::print(String *str)
{
877
  str->append("cast(", 5);
878
  args[0]->print(str);
879
  str->append(" as signed)", 11);
880 881 882 883 884 885

}


void Item_func_unsigned::print(String *str)
{
886
  str->append("cast(", 5);
887
  args[0]->print(str);
888
  str->append(" as unsigned)", 13);
889 890 891 892

}


unknown's avatar
unknown committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
String *Item_decimal_typecast::val_str(String *str)
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
  my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, &tmp_buf);
  my_decimal2string(E_DEC_FATAL_ERROR, &tmp_buf, 0, 0, 0, str);
  return str;
}


double Item_decimal_typecast::val_real()
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
  double res;
  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;
  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);
  my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec);
  return dec;
}


double Item_func_plus::real_op()
unknown's avatar
unknown committed
929
{
930
  double value= args[0]->val_real() + args[1]->val_real();
unknown's avatar
unknown committed
931 932 933 934 935
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

unknown's avatar
unknown committed
936 937

longlong Item_func_plus::int_op()
unknown's avatar
unknown committed
938
{
unknown's avatar
unknown committed
939 940 941 942 943 944 945
  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;
}


946 947 948 949 950 951 952 953 954 955 956 957
/*
  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
958 959
my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
{
960 961 962
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
963 964
  if ((null_value= args[0]->null_value))
    return 0;
965 966 967 968
  val2= args[1]->val_decimal(&value2);
  if ((null_value= (args[1]->null_value ||
                    my_decimal_add(E_DEC_FATAL_ERROR, decimal_value, val1,
                                   val2) > 1)))
unknown's avatar
unknown committed
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    return 0;
  return decimal_value;
}

/*
  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);
  max_length= (max(args[0]->max_length - args[0]->decimals,
                   args[1]->max_length - args[1]->decimals) +
               decimals + 1);
unknown's avatar
unknown committed
985 986
}

987 988 989 990 991 992 993 994 995 996

/*
  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 &&
997
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
998 999 1000 1001
    unsigned_flag=0;
}


unknown's avatar
unknown committed
1002
double Item_func_minus::real_op()
unknown's avatar
unknown committed
1003
{
1004
  double value= args[0]->val_real() - args[1]->val_real();
unknown's avatar
unknown committed
1005 1006 1007 1008 1009
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

unknown's avatar
unknown committed
1010 1011

longlong Item_func_minus::int_op()
unknown's avatar
unknown committed
1012
{
unknown's avatar
unknown committed
1013 1014 1015 1016 1017 1018 1019
  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;
}


1020 1021
/* See Item_func_plus::decimal_op for comments */

unknown's avatar
unknown committed
1022 1023
my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
{
1024 1025 1026 1027
  my_decimal value1, *val1;
  my_decimal value2, *val2= 

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1028 1029
  if ((null_value= args[0]->null_value))
    return 0;
1030 1031 1032 1033
  val2= args[1]->val_decimal(&value2);
  if ((null_value= (args[1]->null_value ||
                    my_decimal_sub(E_DEC_FATAL_ERROR, decimal_value, val1,
                                   val2) > 1)))
unknown's avatar
unknown committed
1034 1035
    return 0;
  return decimal_value;
unknown's avatar
unknown committed
1036 1037
}

1038

unknown's avatar
unknown committed
1039
double Item_func_mul::real_op()
unknown's avatar
unknown committed
1040
{
1041
  DBUG_ASSERT(fixed == 1);
1042
  double value= args[0]->val_real() * args[1]->val_real();
unknown's avatar
unknown committed
1043
  if ((null_value=args[0]->null_value || args[1]->null_value))
unknown's avatar
unknown committed
1044
    return 0.0;
unknown's avatar
unknown committed
1045 1046 1047
  return value;
}

unknown's avatar
unknown committed
1048 1049

longlong Item_func_mul::int_op()
unknown's avatar
unknown committed
1050
{
1051
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1052 1053 1054 1055 1056 1057 1058
  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;
}


1059 1060
/* See Item_func_plus::decimal_op for comments */

unknown's avatar
unknown committed
1061 1062
my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
{
1063 1064 1065
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1066 1067
  if ((null_value= args[0]->null_value))
    return 0;
1068 1069 1070 1071
  val2= args[1]->val_decimal(&value2);
  if ((null_value= (args[1]->null_value ||
                    my_decimal_mul(E_DEC_FATAL_ERROR, decimal_value, val1,
                                   val2) > 1)))
unknown's avatar
unknown committed
1072 1073
    return 0;
  return decimal_value;
unknown's avatar
unknown committed
1074 1075 1076
}


unknown's avatar
unknown committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
void Item_func_mul::result_precision()
{
  decimals= args[0]->decimals + args[1]->decimals;
  max_length= ((args[0]->max_length - args[0]->decimals) +
               (args[1]->max_length - args[1]->decimals) +
               decimals);
}


double Item_func_div::real_op()
unknown's avatar
unknown committed
1087
{
1088
  DBUG_ASSERT(fixed == 1);
1089 1090
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
unknown's avatar
unknown committed
1091 1092 1093 1094 1095
  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
1096
    return 0.0;
unknown's avatar
unknown committed
1097
  }
unknown's avatar
unknown committed
1098 1099 1100
  return value/val2;
}

unknown's avatar
unknown committed
1101

unknown's avatar
unknown committed
1102
my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1103
{
1104 1105 1106 1107
  my_decimal value1, *val1;
  my_decimal value2, *val2;

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1108 1109
  if ((null_value= args[0]->null_value))
    return 0;
1110
  val2= args[1]->val_decimal(&value2);
unknown's avatar
unknown committed
1111 1112 1113
  if ((null_value= args[1]->null_value))
    return 0;
  switch (my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
1114
                         val1, val2, DECIMAL_DIV_SCALE_INCREASE)) {
unknown's avatar
unknown committed
1115 1116 1117 1118 1119 1120
  case E_DEC_TRUNCATED:
  case E_DEC_OK:
    return decimal_value;
  case E_DEC_DIV_ZERO:
    signal_divide_by_null();
  default:
1121
    null_value= 1;                              // Safety
unknown's avatar
unknown committed
1122
    return 0;
1123
  }
unknown's avatar
unknown committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
}


void Item_func_div::result_precision()
{
  decimals= (args[0]->decimals + args[0]->decimals +
             DECIMAL_DIV_SCALE_INCREASE);
  max_length= ((args[0]->max_length - args[0]->decimals) +
               (args[1]->max_length - args[1]->decimals) +
               decimals);
unknown's avatar
unknown committed
1134 1135
}

unknown's avatar
unknown committed
1136

unknown's avatar
unknown committed
1137 1138
void Item_func_div::fix_length_and_dec()
{
unknown's avatar
unknown committed
1139 1140
  DBUG_ENTER("Item_func_div::fix_length_and_dec");
  Item_num_op::fix_length_and_dec();
1141
  switch(hybrid_type) {
unknown's avatar
unknown committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  case REAL_RESULT:
  {
    decimals=max(args[0]->decimals,args[1]->decimals)+2;
    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
1164 1165
}

1166 1167 1168 1169

/* Integer division */
longlong Item_func_int_div::val_int()
{
1170
  DBUG_ASSERT(fixed == 1);
1171 1172
  longlong value=args[0]->val_int();
  longlong val2=args[1]->val_int();
1173
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
1174 1175 1176 1177
    return 0;
  if (val2 == 0)
  {
    signal_divide_by_null();
1178
    return 0;
unknown's avatar
unknown committed
1179
  }
1180 1181 1182
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
1183 1184 1185 1186 1187 1188 1189
}


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
1190
  unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
1191 1192 1193
}


unknown's avatar
unknown committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
longlong Item_func_mod::int_op()
{
  DBUG_ASSERT(fixed == 1);
  longlong value=  args[0]->val_int();
  longlong val2= args[1]->val_int();
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0; /* purecov: inspected */
  if (val2 == 0)
  {
    signal_divide_by_null();
    return 0;
  }
  return value % val2;
}

double Item_func_mod::real_op()
unknown's avatar
unknown committed
1210
{
1211
  DBUG_ASSERT(fixed == 1);
1212 1213
  double value= args[0]->val_real();
  double val2=  args[1]->val_real();
unknown's avatar
unknown committed
1214
  if ((null_value= args[0]->null_value || args[1]->null_value))
unknown's avatar
unknown committed
1215
    return 0.0; /* purecov: inspected */
unknown's avatar
unknown committed
1216 1217 1218 1219 1220
  if (val2 == 0.0)
  {
    signal_divide_by_null();
    return 0.0;
  }
unknown's avatar
unknown committed
1221 1222 1223
  return fmod(value,val2);
}

unknown's avatar
unknown committed
1224 1225

my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1226
{
1227 1228 1229 1230
  my_decimal value1, *val1;
  my_decimal value2, *val2;

  val1= args[0]->val_decimal(&value1);
unknown's avatar
unknown committed
1231 1232
  if ((null_value= args[0]->null_value))
    return 0;
1233
  val2= args[1]->val_decimal(&value2);
unknown's avatar
unknown committed
1234 1235 1236
  if ((null_value= args[1]->null_value))
    return 0;
  switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
1237
                         val1, val2)) {
unknown's avatar
unknown committed
1238 1239 1240 1241
  case E_DEC_TRUNCATED:
  case E_DEC_OK:
    return decimal_value;
  case E_DEC_DIV_ZERO:
unknown's avatar
unknown committed
1242
    signal_divide_by_null();
unknown's avatar
unknown committed
1243
  default:
1244
    null_value= 1;
unknown's avatar
unknown committed
1245 1246
    return 0;
  }
unknown's avatar
unknown committed
1247 1248
}

unknown's avatar
unknown committed
1249 1250

void Item_func_mod::result_precision()
unknown's avatar
unknown committed
1251
{
unknown's avatar
unknown committed
1252 1253
  decimals= max(args[0]->decimals, args[1]->decimals);
  max_length= max(args[0]->max_length, args[1]->max_length);
unknown's avatar
unknown committed
1254 1255 1256
}


unknown's avatar
unknown committed
1257
double Item_func_neg::real_op()
unknown's avatar
unknown committed
1258
{
1259
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1260 1261 1262 1263 1264 1265 1266 1267 1268
  null_value= args[0]->null_value;
  return -value;
}


longlong Item_func_neg::int_op()
{
  longlong value= args[0]->val_int();
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1269 1270 1271
  return -value;
}

unknown's avatar
unknown committed
1272

unknown's avatar
unknown committed
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
{
  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);
  }
  return decimal_value;
}


void Item_func_neg::fix_num_length_and_dec()
unknown's avatar
unknown committed
1286
{
unknown's avatar
unknown committed
1287 1288 1289 1290
  decimals= args[0]->decimals;
  /* 1 add because sign can appear */
  max_length= args[0]->max_length + 1;
  unsigned_flag= 0;
unknown's avatar
unknown committed
1291 1292
}

unknown's avatar
unknown committed
1293

1294
void Item_func_neg::fix_length_and_dec()
unknown's avatar
unknown committed
1295
{
1296
  DBUG_ENTER("Item_func_neg::fix_length_and_dec");
unknown's avatar
unknown committed
1297
  Item_func_num1::fix_length_and_dec();
1298 1299 1300 1301 1302

  /*
    If this is in integer context keep the context as integer if possible
    (This is how multiplication and other integer functions works)
  */
unknown's avatar
unknown committed
1303 1304 1305 1306
  if (hybrid_type == INT_RESULT &&
      args[0]->type() == INT_ITEM &&
      ((ulonglong) ((Item_uint*) args[0])->value >=
       (ulonglong) LONGLONG_MIN))
unknown's avatar
unknown committed
1307 1308
  {
    /*
1309 1310
      Ensure that result is converted to DECIMAL, as longlong can't hold
      the negated number
unknown's avatar
unknown committed
1311
    */
unknown's avatar
unknown committed
1312 1313
    hybrid_type= DECIMAL_RESULT;
    DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
unknown's avatar
unknown committed
1314
  }
unknown's avatar
unknown committed
1315
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1316 1317
}

unknown's avatar
unknown committed
1318

unknown's avatar
unknown committed
1319
double Item_func_abs::real_op()
unknown's avatar
unknown committed
1320
{
1321
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1322
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1323 1324 1325
  return fabs(value);
}

unknown's avatar
unknown committed
1326

unknown's avatar
unknown committed
1327
longlong Item_func_abs::int_op()
unknown's avatar
unknown committed
1328
{
unknown's avatar
unknown committed
1329 1330
  longlong value= args[0]->val_int();
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1331 1332 1333
  return value >= 0 ? value : -value;
}

unknown's avatar
unknown committed
1334

unknown's avatar
unknown committed
1335
my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1336
{
unknown's avatar
unknown committed
1337 1338
  my_decimal val, *value= args[0]->val_decimal(&val);
  if (!(null_value= args[0]->null_value))
unknown's avatar
unknown committed
1339
  {
unknown's avatar
unknown committed
1340 1341 1342
    my_decimal2decimal(value, decimal_value);
    if (decimal_value->sign())
      my_decimal_neg(decimal_value);
unknown's avatar
unknown committed
1343
  }
unknown's avatar
unknown committed
1344 1345 1346 1347 1348 1349 1350 1351 1352
  return decimal_value;
}


void Item_func_abs::fix_length_and_dec()
{
  Item_func_num1::fix_length_and_dec();
  if (hybrid_type == INT_RESULT)
    unsigned_flag= 1;
unknown's avatar
unknown committed
1353 1354
}

unknown's avatar
unknown committed
1355

1356
/* Gateway to natural LOG function */
1357
double Item_func_ln::val_real()
1358
{
1359
  DBUG_ASSERT(fixed == 1);
1360
  double value= args[0]->val_real();
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
  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.
*/ 
1371
double Item_func_log::val_real()
unknown's avatar
unknown committed
1372
{
1373
  DBUG_ASSERT(fixed == 1);
1374
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1375
  if ((null_value=(args[0]->null_value || value <= 0.0)))
1376 1377 1378
    return 0.0;
  if (arg_count == 2)
  {
1379
    double value2= args[1]->val_real();
1380 1381 1382 1383
    if ((null_value=(args[1]->null_value || value2 <= 0.0 || value == 1.0)))
      return 0.0;
    return log(value2) / log(value);
  }
unknown's avatar
unknown committed
1384 1385 1386
  return log(value);
}

1387
double Item_func_log2::val_real()
1388
{
1389
  DBUG_ASSERT(fixed == 1);
1390
  double value= args[0]->val_real();
1391 1392
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
1393
  return log(value) / M_LN2;
1394 1395
}

1396
double Item_func_log10::val_real()
unknown's avatar
unknown committed
1397
{
1398
  DBUG_ASSERT(fixed == 1);
1399
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1400 1401 1402 1403 1404
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0; /* purecov: inspected */
  return log10(value);
}

1405
double Item_func_exp::val_real()
unknown's avatar
unknown committed
1406
{
1407
  DBUG_ASSERT(fixed == 1);
1408
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1409 1410 1411 1412 1413
  if ((null_value=args[0]->null_value))
    return 0.0; /* purecov: inspected */
  return exp(value);
}

1414
double Item_func_sqrt::val_real()
unknown's avatar
unknown committed
1415
{
1416
  DBUG_ASSERT(fixed == 1);
1417
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1418 1419 1420 1421 1422
  if ((null_value=(args[0]->null_value || value < 0)))
    return 0.0; /* purecov: inspected */
  return sqrt(value);
}

1423
double Item_func_pow::val_real()
unknown's avatar
unknown committed
1424
{
1425
  DBUG_ASSERT(fixed == 1);
1426 1427
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
unknown's avatar
unknown committed
1428 1429 1430 1431 1432 1433 1434
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
    return 0.0; /* purecov: inspected */
  return pow(value,val2);
}

// Trigonometric functions

1435
double Item_func_acos::val_real()
unknown's avatar
unknown committed
1436
{
1437
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1438
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1439
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1440 1441 1442 1443 1444
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(acos(value));
}

1445
double Item_func_asin::val_real()
unknown's avatar
unknown committed
1446
{
1447
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1448
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1449
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1450 1451 1452 1453 1454
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(asin(value));
}

1455
double Item_func_atan::val_real()
unknown's avatar
unknown committed
1456
{
1457
  DBUG_ASSERT(fixed == 1);
1458
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1459 1460 1461 1462
  if ((null_value=args[0]->null_value))
    return 0.0;
  if (arg_count == 2)
  {
1463
    double val2= args[1]->val_real();
unknown's avatar
unknown committed
1464 1465 1466 1467 1468 1469 1470
    if ((null_value=args[1]->null_value))
      return 0.0;
    return fix_result(atan2(value,val2));
  }
  return fix_result(atan(value));
}

1471
double Item_func_cos::val_real()
unknown's avatar
unknown committed
1472
{
1473
  DBUG_ASSERT(fixed == 1);
1474
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1475 1476 1477 1478 1479
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(cos(value));
}

1480
double Item_func_sin::val_real()
unknown's avatar
unknown committed
1481
{
1482
  DBUG_ASSERT(fixed == 1);
1483
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1484 1485 1486 1487 1488
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(sin(value));
}

1489
double Item_func_tan::val_real()
unknown's avatar
unknown committed
1490
{
1491
  DBUG_ASSERT(fixed == 1);
1492
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
  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()
{
1504
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
  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()
{
1519
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  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()
{
1535
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
  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
1553
void Item_func_int_val::fix_num_length_and_dec()
unknown's avatar
unknown committed
1554
{
unknown's avatar
unknown committed
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
  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()
{
  /*
    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;
unknown's avatar
unknown committed
1613 1614 1615
  return (longlong) ceil(value);
}

unknown's avatar
unknown committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

double Item_func_ceiling::real_op()
{
  /*
    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 ceil(value);
}


my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
unknown's avatar
unknown committed
1630
{
unknown's avatar
unknown committed
1631
  my_decimal val, *value= args[0]->val_decimal(&val);
1632 1633 1634
  if ((null_value= (args[0]->null_value ||
                    my_decimal_ceiling(E_DEC_FATAL_ERROR, value,
                                       decimal_value) > 1)))
unknown's avatar
unknown committed
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    return 0;
  return decimal_value;
}


longlong Item_func_floor::int_op()
{
  /*
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
    bug)
  */
1646
  volatile double value= args[0]->val_real();
unknown's avatar
unknown committed
1647
  null_value= args[0]->null_value;
unknown's avatar
unknown committed
1648 1649 1650
  return (longlong) floor(value);
}

unknown's avatar
unknown committed
1651 1652

double Item_func_floor::real_op()
unknown's avatar
unknown committed
1653
{
unknown's avatar
unknown committed
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  /*
    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);
1667 1668 1669
  if ((null_value= (args[0]->null_value ||
                    my_decimal_floor(E_DEC_FATAL_ERROR, value,
                                     decimal_value) > 1)))
unknown's avatar
unknown committed
1670 1671 1672 1673 1674 1675 1676 1677 1678
    return 0;
  return decimal_value;
}


void Item_func_round::fix_num_length_and_dec()
{
  max_length= args[0]->max_length;
  decimals= NOT_FIXED_DEC;
unknown's avatar
unknown committed
1679 1680 1681 1682 1683 1684
  if (args[1]->const_item())
  {
    int tmp=(int) args[1]->val_int();
    if (tmp < 0)
      decimals=0;
    else
unknown's avatar
unknown committed
1685
      decimals=min(tmp, NOT_FIXED_DEC);
unknown's avatar
unknown committed
1686 1687 1688
  }
}

unknown's avatar
unknown committed
1689
double Item_func_round::real_op()
unknown's avatar
unknown committed
1690
{
1691
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1692
  int dec=(int) args[1]->val_int();
unknown's avatar
unknown committed
1693 1694
  if (dec > 0)
    decimals= dec; // to get correct output
unknown's avatar
unknown committed
1695
  uint abs_dec=abs(dec);
1696 1697 1698 1699 1700 1701
  double tmp;
  /*
    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
1702 1703 1704

  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
1705 1706
  tmp=(abs_dec < array_elements(log_10) ?
       log_10[abs_dec] : pow(10.0,(double) abs_dec));
unknown's avatar
unknown committed
1707 1708

  if (truncate)
unknown's avatar
unknown committed
1709 1710
  {
    if (value >= 0)
1711
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
unknown's avatar
unknown committed
1712
    else
1713
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
unknown's avatar
unknown committed
1714
  }
1715 1716 1717
  else
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
  return tmp2;
unknown's avatar
unknown committed
1718 1719 1720
}


unknown's avatar
unknown committed
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
longlong Item_func_round::int_op()
{
  longlong value= args[0]->val_int();
  int dec=(int) args[1]->val_int();
  decimals= 0;
  uint abs_dec;
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0;
  if (dec >= 0)
    return value; // integer have not digits after point

  abs_dec= -dec;
  double tmp;
  /*
    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;

  tmp= (abs_dec < array_elements(log_10) ?
        log_10[abs_dec] : pow(10.0, (double) abs_dec));

  if (truncate)
  {
    if (unsigned_flag)
1746
      tmp2= floor(ulonglong2double(value)/tmp)*tmp;
unknown's avatar
unknown committed
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    else if (value >= 0)
      tmp2= floor(((double)value)/tmp)*tmp;
    else
      tmp2= ceil(((double)value)/tmp)*tmp;
  }
  else
    tmp2= rint(((double)value)/tmp)*tmp;
  return (longlong)tmp2;
}


my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
{
  my_decimal val, *value= args[0]->val_decimal(&val);
  int dec=(int) args[1]->val_int();
  if (dec > 0)
    decimals= dec; // to get correct output
1764 1765 1766
  if ((null_value= (args[0]->null_value || args[1]->null_value ||
                    my_decimal_round(E_DEC_FATAL_ERROR, value, dec, truncate,
                                     decimal_value) > 1)))
unknown's avatar
unknown committed
1767 1768 1769 1770 1771
    return 0;
  return decimal_value;
}


1772 1773
bool Item_func_rand::fix_fields(THD *thd, struct st_table_list *tables,
                                Item **ref)
unknown's avatar
unknown committed
1774
{
1775 1776
  if (Item_real_func::fix_fields(thd, tables, ref))
    return TRUE;
1777
  used_tables_cache|= RAND_TABLE_BIT;
unknown's avatar
unknown committed
1778 1779
  if (arg_count)
  {					// Only use argument once in query
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
    /*
      Allocate rand structure once: we must use thd->current_arena
      to create rand in proper mem_root if it's a prepared statement or
      stored procedure.
    */
    if (!rand && !(rand= (struct rand_struct*)
                   thd->current_arena->alloc(sizeof(*rand))))
      return TRUE;
    /*
      PARAM_ITEM is returned if we're in statement prepare and consequently
      no placeholder value is set yet.
    */
    if (args[0]->type() != PARAM_ITEM)
    {
      /*
        TODO: do not do reinit 'rand' for every execute of PS/SP if
        args[0] is a constant.
      */
      uint32 tmp= (uint32) args[0]->val_int();
      randominit(rand, (uint32) (tmp*0x10001L+55555555L),
                 (uint32) (tmp*0x10000001L));
    }
unknown's avatar
unknown committed
1802
  }
1803
  else
unknown's avatar
unknown committed
1804
  {
1805 1806 1807
    /*
      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.
unknown's avatar
unknown committed
1808

1809 1810 1811 1812
      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
    */
unknown's avatar
unknown committed
1813 1814 1815
    thd->rand_used=1;
    thd->rand_saved_seed1=thd->rand.seed1;
    thd->rand_saved_seed2=thd->rand.seed2;
1816
    rand= &thd->rand;
unknown's avatar
unknown committed
1817
  }
1818
  return FALSE;
1819 1820
}

unknown's avatar
unknown committed
1821 1822 1823 1824 1825 1826
void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

1827

1828
double Item_func_rand::val_real()
1829
{
1830
  DBUG_ASSERT(fixed == 1);
1831
  return my_rnd(rand);
unknown's avatar
unknown committed
1832 1833 1834 1835
}

longlong Item_func_sign::val_int()
{
1836
  DBUG_ASSERT(fixed == 1);
1837
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1838 1839 1840 1841 1842
  null_value=args[0]->null_value;
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
}


1843
double Item_func_units::val_real()
unknown's avatar
unknown committed
1844
{
1845
  DBUG_ASSERT(fixed == 1);
1846
  double value= args[0]->val_real();
unknown's avatar
unknown committed
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
  if ((null_value=args[0]->null_value))
    return 0;
  return value*mul+add;
}


void Item_func_min_max::fix_length_and_dec()
{
  decimals=0;
  max_length=0;
  maybe_null=1;
  cmp_type=args[0]->result_type();
1859

unknown's avatar
unknown committed
1860 1861
  for (uint i=0 ; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
1862 1863
    set_if_bigger(max_length, args[i]->max_length);
    set_if_bigger(decimals, args[i]->decimals);
unknown's avatar
unknown committed
1864 1865 1866 1867
    if (!args[i]->maybe_null)
      maybe_null=0;
    cmp_type=item_cmp_type(cmp_type,args[i]->result_type());
  }
unknown's avatar
unknown committed
1868
  if (cmp_type == STRING_RESULT)
unknown's avatar
unknown committed
1869
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV);
unknown's avatar
unknown committed
1870 1871 1872 1873 1874
}


String *Item_func_min_max::val_str(String *str)
{
1875
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1876 1877 1878 1879 1880 1881
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
1882
    if (!unsigned_flag)
unknown's avatar
unknown committed
1883
      str->set(nr,&my_charset_bin);
1884
    else
unknown's avatar
unknown committed
1885
      str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
1886 1887
    return str;
  }
unknown's avatar
unknown committed
1888 1889 1890 1891 1892 1893 1894 1895
  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
1896 1897
  case REAL_RESULT:
  {
1898
    double nr= val_real();
unknown's avatar
unknown committed
1899 1900
    if (null_value)
      return 0; /* purecov: inspected */
unknown's avatar
unknown committed
1901
    str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
    return str;
  }
  case STRING_RESULT:
  {
    String *res;
    LINT_INIT(res);
    null_value=1;
    for (uint i=0; i < arg_count ; i++)
    {
      if (null_value)
      {
	res=args[i]->val_str(str);
	null_value=args[i]->null_value;
      }
      else
      {
	String *res2;
	res2= args[i]->val_str(res == str ? &tmp_value : str);
	if (res2)
	{
1922
	  int cmp= sortcmp(res,res2,collation.collation);
unknown's avatar
unknown committed
1923 1924 1925 1926 1927
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
    }
unknown's avatar
unknown committed
1928 1929
    if (res)					// If !NULL
      res->set_charset(collation.collation);
unknown's avatar
unknown committed
1930 1931
    return res;
  }
1932
  case ROW_RESULT:
unknown's avatar
unknown committed
1933
  default:
unknown's avatar
unknown committed
1934
    // This case should never be chosen
unknown's avatar
unknown committed
1935 1936
    DBUG_ASSERT(0);
    return 0;
unknown's avatar
unknown committed
1937 1938 1939 1940 1941
  }
  return 0;					// Keep compiler happy
}


1942
double Item_func_min_max::val_real()
unknown's avatar
unknown committed
1943
{
1944
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1945 1946 1947 1948 1949 1950
  double value=0.0;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
1951
      value= args[i]->val_real();
unknown's avatar
unknown committed
1952 1953 1954 1955
      null_value=args[i]->null_value;
    }
    else
    {
1956
      double tmp= args[i]->val_real();
unknown's avatar
unknown committed
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
  }
  return value;
}


longlong Item_func_min_max::val_int()
{
1967
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
  longlong value=0;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
      value=args[i]->val_int();
      null_value=args[i]->null_value;
    }
    else
    {
      longlong tmp=args[i]->val_int();
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
  }
  return value;
}

unknown's avatar
unknown committed
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020

my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
{
  DBUG_ASSERT(fixed == 1);
  my_decimal tmp_buf, *tmp, *res= NULL;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
      res= args[i]->val_decimal(dec);
      null_value= args[i]->null_value;
    }
    else
    {
      tmp= args[i]->val_decimal(&tmp_buf);
      if (args[i]->null_value)
        continue;
      if ((my_decimal_cmp(tmp, res) * cmp_sign) < 0)
      {
        if (tmp == &tmp_buf)
        {
          my_decimal2decimal(tmp, dec);
          res= dec;
        }
        else
          res= tmp;
      }
    }
  }
  return res;
}


unknown's avatar
unknown committed
2021 2022
longlong Item_func_length::val_int()
{
2023
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
  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
2034

unknown's avatar
unknown committed
2035 2036
longlong Item_func_char_length::val_int()
{
2037
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2038 2039 2040 2041 2042 2043 2044
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
2045
  return (longlong) res->numchars();
unknown's avatar
unknown committed
2046 2047
}

unknown's avatar
unknown committed
2048

unknown's avatar
unknown committed
2049 2050
longlong Item_func_coercibility::val_int()
{
2051
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2052 2053 2054 2055 2056 2057
  if (args[0]->null_value)
  {
    null_value= 1;
    return 0;
  }
  null_value= 0;
2058
  return (longlong) args[0]->collation.derivation;
unknown's avatar
unknown committed
2059
}
unknown's avatar
unknown committed
2060

unknown's avatar
unknown committed
2061

2062 2063 2064
void Item_func_locate::fix_length_and_dec()
{
  maybe_null=0; max_length=11;
unknown's avatar
unknown committed
2065
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
2066 2067
}

unknown's avatar
unknown committed
2068

unknown's avatar
unknown committed
2069 2070
longlong Item_func_locate::val_int()
{
2071
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2072 2073 2074 2075 2076 2077 2078 2079
  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;
2080 2081
  uint start=0;
  uint start0=0;
2082
  my_match_t match;
2083

unknown's avatar
unknown committed
2084 2085
  if (arg_count == 3)
  {
2086 2087 2088
    start0= start =(uint) args[2]->val_int()-1;
    start=a->charpos(start);
    
unknown's avatar
unknown committed
2089 2090 2091
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
2092

unknown's avatar
unknown committed
2093 2094
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
2095
  
2096
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
2097
                                            a->ptr()+start, a->length()-start,
2098 2099 2100 2101
                                            b->ptr(), b->length(),
                                            &match, 1))
    return 0;
  return (longlong) match.mblen + start0 + 1;
unknown's avatar
unknown committed
2102 2103 2104
}


2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
void Item_func_locate::print(String *str)
{
  str->append("locate(", 7);
  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
2120 2121
longlong Item_func_field::val_int()
{
2122
  DBUG_ASSERT(fixed == 1);
2123 2124 2125
  if (cmp_type == STRING_RESULT)
  {
    String *field;
2126
    if (!(field=args[0]->val_str(&value)))
2127
      return 0;					// -1 if null ?
2128
    for (uint i=1 ; i < arg_count ; i++)
2129 2130
    {
      String *tmp_value=args[i]->val_str(&tmp);
unknown's avatar
Fix:  
unknown committed
2131
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
2132
        return (longlong) (i);
2133 2134 2135 2136
    }
  }
  else if (cmp_type == INT_RESULT)
  {
2137
    longlong val= args[0]->val_int();
2138 2139
    if (args[0]->is_null())
      return 0;
2140
    for (uint i=1; i < arg_count ; i++)
2141
    {
2142
      if (val == args[i]->val_int() && ! args[i]->is_null())
2143
 	return (longlong) (i);
2144 2145
    }
  }
unknown's avatar
unknown committed
2146 2147 2148 2149 2150 2151 2152 2153 2154
  else if (cmp_type == DECIMAL_RESULT)
  {
    my_decimal dec_arg_buf, *dec_arg,
               dec_buf, *dec= args[0]->val_decimal(&dec_buf);
    if (args[0]->is_null())
      return 0;
    for (uint i=1; i < arg_count; i++)
    {
      dec_arg= args[i]->val_decimal(&dec_arg_buf);
2155
      if (!args[i]->is_null() && !my_decimal_cmp(dec_arg, dec))
unknown's avatar
unknown committed
2156 2157 2158
        return (longlong) (i);
    }
  }
2159
  else
unknown's avatar
unknown committed
2160
  {
2161
    double val= args[0]->val_real();
2162 2163
    if (args[0]->is_null())
      return 0;
2164
    for (uint i=1; i < arg_count ; i++)
2165
    {
2166
      if (val == args[i]->val_real() && ! args[i]->is_null())
2167
 	return (longlong) (i);
2168
    }
unknown's avatar
unknown committed
2169 2170 2171 2172
  }
  return 0;
}

unknown's avatar
unknown committed
2173

2174 2175 2176
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
2177 2178
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
2179 2180
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
unknown's avatar
unknown committed
2181
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV);
2182
}
unknown's avatar
unknown committed
2183

2184

unknown's avatar
unknown committed
2185 2186
longlong Item_func_ascii::val_int()
{
2187
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
  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()
{
2200
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2201 2202 2203 2204 2205 2206 2207 2208 2209
  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
2210
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
2211 2212
  {
    register const char *str=res->ptr();
2213
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
unknown's avatar
unknown committed
2214 2215
    if (!l)
      return (longlong)((uchar) *str);
unknown's avatar
unknown committed
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
    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;
    if (field->real_type() == FIELD_TYPE_SET)
    {
      String *find=args[0]->val_str(&value);
      if (find)
      {
2240 2241
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
unknown's avatar
unknown committed
2242 2243 2244 2245 2246 2247
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
unknown's avatar
unknown committed
2248
  agg_arg_collations_for_comparison(cmp_collation, args, 2);
unknown's avatar
unknown committed
2249 2250 2251 2252 2253 2254
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
2255
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
  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)
  {
2279 2280 2281 2282 2283 2284 2285 2286 2287
    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
2288
    {
2289 2290 2291
      int symbol_len;
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
                                       (uchar*) real_end)) > 0)
unknown's avatar
unknown committed
2292
      {
2293 2294
        const char *substr_end= str_end + symbol_len;
        bool is_last_item= (substr_end == real_end);
2295 2296
        bool is_separator= (wc == (my_wc_t) separator);
        if (is_separator || is_last_item)
2297 2298
        {
          position++;
2299
          if (is_last_item && !is_separator)
2300 2301 2302 2303 2304 2305 2306 2307 2308
            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
2309
      }
2310 2311 2312 2313 2314 2315 2316
      else if (str_end - str_begin == 0 && 
               find_str_len == 0 && 
               wc == (my_wc_t) separator)
        return (longlong) ++position;
      else
        return (longlong) 0;
    }
unknown's avatar
unknown committed
2317 2318 2319 2320 2321 2322
  }
  return 0;
}

longlong Item_func_bit_count::val_int()
{
2323
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2324 2325 2326 2327 2328 2329
  ulonglong value= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
unknown's avatar
unknown committed
2330
  return (longlong) my_count_bits(value);
unknown's avatar
unknown committed
2331 2332 2333 2334 2335 2336
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
2337
** Rewritten by monty.
unknown's avatar
unknown committed
2338 2339 2340 2341 2342 2343
****************************************************************************/

#ifdef HAVE_DLOPEN

udf_handler::~udf_handler()
{
2344
  if (!not_original)
unknown's avatar
unknown committed
2345
  {
2346
    if (initialized)
unknown's avatar
unknown committed
2347
    {
2348 2349 2350 2351 2352 2353 2354
      if (u_d->func_deinit != NULL)
      {
        void (*deinit)(UDF_INIT *) = (void (*)(UDF_INIT*))
        u_d->func_deinit;
        (*deinit)(&initid);
      }
      free_udf(u_d);
unknown's avatar
unknown committed
2355
    }
2356 2357
    if (buffers)				// Because of bug in ecc
      delete [] buffers;
unknown's avatar
unknown committed
2358 2359 2360 2361 2362
  }
}


bool
unknown's avatar
unknown committed
2363
udf_handler::fix_fields(THD *thd, TABLE_LIST *tables, Item_result_field *func,
unknown's avatar
unknown committed
2364 2365
			uint arg_count, Item **arguments)
{
2366
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
2367
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
2368
#endif
unknown's avatar
unknown committed
2369 2370
  DBUG_ENTER("Item_udf_func::fix_fields");

unknown's avatar
unknown committed
2371
  if (check_stack_overrun(thd, buff))
unknown's avatar
unknown committed
2372
    DBUG_RETURN(TRUE);				// Fatal error flag is set!
unknown's avatar
unknown committed
2373

2374
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
unknown's avatar
unknown committed
2375 2376 2377

  if (!tmp_udf)
  {
2378
    my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
unknown's avatar
unknown committed
2379
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2380 2381 2382 2383 2384
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
2385
  func->maybe_null=0;
unknown's avatar
unknown committed
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
  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
2396
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2397 2398 2399 2400 2401 2402 2403
    }
    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
2404
      if (!(*arg)->fixed &&
unknown's avatar
unknown committed
2405
          (*arg)->fix_fields(thd, tables, arg))
unknown's avatar
unknown committed
2406
	DBUG_RETURN(1);
2407
      // we can't assign 'item' before, because fix_fields() can change arg
unknown's avatar
unknown committed
2408
      Item *item= *arg;
2409
      if (item->check_cols(1))
unknown's avatar
unknown committed
2410
	DBUG_RETURN(TRUE);
2411 2412 2413 2414 2415 2416 2417 2418 2419
      /*
	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
2420
        the particular user defined function.
2421
      */
2422 2423
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
unknown's avatar
unknown committed
2424
      if (item->maybe_null)
unknown's avatar
unknown committed
2425
	func->maybe_null=1;
unknown's avatar
unknown committed
2426 2427 2428 2429
      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
2430
    }
unknown's avatar
unknown committed
2431
    //TODO: why all following memory is not allocated with 1 call of sql_alloc?
unknown's avatar
unknown committed
2432 2433
    if (!(buffers=new String[arg_count]) ||
	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
2434 2435 2436 2437 2438 2439 2440
	!(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
2441 2442
    {
      free_udf(u_d);
unknown's avatar
unknown committed
2443
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    }
  }
  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++)
    {
      f_args.args[i]=0;
2459 2460 2461 2462
      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
2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481

      switch(arguments[i]->type()) {
      case Item::STRING_ITEM:			// Constant string !
      {
	String *res=arguments[i]->val_str((String *) 0);
	if (arguments[i]->null_value)
	  continue;
	f_args.args[i]=    (char*) res->ptr();
	break;
      }
      case Item::INT_ITEM:
	*((longlong*) to) = arguments[i]->val_int();
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(longlong));
	}
	break;
      case Item::REAL_ITEM:
2482
	*((double*) to)= arguments[i]->val_real();
unknown's avatar
unknown committed
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(double));
	}
	break;
      default:					// Skip these
	break;
      }
    }
2493
    thd->net.last_error[0]=0;
unknown's avatar
unknown committed
2494 2495 2496 2497 2498
    my_bool (*init)(UDF_INIT *, UDF_ARGS *, char *)=
      (my_bool (*)(UDF_INIT *, UDF_ARGS *,  char *))
      u_d->func_init;
    if ((error=(uchar) init(&initid, &f_args, thd->net.last_error)))
    {
2499 2500
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
               u_d->name.str, thd->net.last_error);
unknown's avatar
unknown committed
2501
      free_udf(u_d);
unknown's avatar
unknown committed
2502
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2503 2504 2505 2506
    }
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
    func->maybe_null=initid.maybe_null;
    const_item_cache=initid.const_item;
2507
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
unknown's avatar
unknown committed
2508 2509 2510 2511
  }
  initialized=1;
  if (error)
  {
2512 2513
    my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
             u_d->name.str, ER(ER_UNKNOWN_ERROR));
unknown's avatar
unknown committed
2514
    DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
2515
  }
unknown's avatar
unknown committed
2516
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
}


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
2531
    case DECIMAL_RESULT:
unknown's avatar
unknown committed
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
      {
	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:
2550
      *((double*) to)= args[i]->val_real();
unknown's avatar
unknown committed
2551 2552 2553 2554 2555 2556
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(double));
      }
      break;
2557
    case ROW_RESULT:
unknown's avatar
unknown committed
2558
    default:
unknown's avatar
unknown committed
2559
      // This case should never be chosen
unknown's avatar
unknown committed
2560
      DBUG_ASSERT(0);
2561
      break;
unknown's avatar
unknown committed
2562 2563 2564 2565 2566 2567 2568 2569 2570
    }
  }
  return 0;
}

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

String *udf_handler::val_str(String *str,String *save_str)
{
2571
  uchar is_null_tmp=0;
unknown's avatar
unknown committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
  ulong res_length;

  if (get_arguments())
    return 0;
  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;
      return 0;
    }
  }
2588 2589 2590
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
		 &is_null_tmp, &error);
  if (is_null_tmp || !res || error)		// The !res is for safety
unknown's avatar
unknown committed
2591 2592 2593 2594 2595 2596 2597 2598
  {
    return 0;
  }
  if (res == str->ptr())
  {
    str->length(res_length);
    return str;
  }
2599
  save_str->set(res, res_length, str->charset());
unknown's avatar
unknown committed
2600 2601 2602 2603
  return save_str;
}


2604 2605 2606 2607
/*
  For the moment, UDF functions are returning DECIMAL values as strings
*/

unknown's avatar
unknown committed
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
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;
  }
2628 2629
  end= res+ res_length;
  str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
unknown's avatar
unknown committed
2630 2631 2632
  return dec_buf;
}

unknown's avatar
unknown committed
2633

2634
double Item_func_udf_float::val_real()
unknown's avatar
unknown committed
2635
{
2636
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2637 2638 2639 2640 2641 2642 2643 2644 2645
  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)
{
2646
  DBUG_ASSERT(fixed == 1);
2647
  double nr= val_real();
unknown's avatar
unknown committed
2648 2649
  if (null_value)
    return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
2650
  str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
2651 2652 2653 2654 2655 2656
  return str;
}


longlong Item_func_udf_int::val_int()
{
2657
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
  DBUG_ENTER("Item_func_udf_int::val_int");
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
		     args[0]->result_type(), arg_count));

  DBUG_RETURN(udf.val_int(&null_value));
}


String *Item_func_udf_int::val_str(String *str)
{
2668
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2669 2670 2671
  longlong nr=val_int();
  if (null_value)
    return 0;
2672
  if (!unsigned_flag)
unknown's avatar
unknown committed
2673
    str->set(nr,&my_charset_bin);
2674
  else
unknown's avatar
unknown committed
2675
    str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
2676 2677 2678
  return str;
}

unknown's avatar
unknown committed
2679 2680 2681 2682

longlong Item_func_udf_decimal::val_int()
{
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
2683
  longlong result;
unknown's avatar
unknown committed
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
  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);
2694
  double result;
unknown's avatar
unknown committed
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
  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
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
/* 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)
{
2745
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
  String *res=udf.val_str(str,&str_value);
  null_value = !res;
  return res;
}

#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;

2762
class User_level_lock
unknown's avatar
unknown committed
2763 2764 2765 2766 2767 2768 2769 2770 2771
{
  char *key;
  uint key_length;

public:
  int count;
  bool locked;
  pthread_cond_t cond;
  pthread_t thread;
unknown's avatar
SCRUM  
unknown committed
2772
  ulong thread_id;
unknown's avatar
unknown committed
2773

2774
  User_level_lock(const char *key_arg,uint length, ulong id) 
unknown's avatar
SCRUM  
unknown committed
2775
    :key_length(length),count(1),locked(1), thread_id(id)
unknown's avatar
unknown committed
2776 2777 2778 2779 2780
  {
    key=(char*) my_memdup((byte*) key_arg,length,MYF(0));
    pthread_cond_init(&cond,NULL);
    if (key)
    {
unknown's avatar
SCRUM  
unknown committed
2781
      if (my_hash_insert(&hash_user_locks,(byte*) this))
unknown's avatar
unknown committed
2782 2783 2784 2785 2786 2787
      {
	my_free((gptr) key,MYF(0));
	key=0;
      }
    }
  }
2788
  ~User_level_lock()
unknown's avatar
unknown committed
2789 2790 2791 2792 2793 2794 2795 2796 2797
  {
    if (key)
    {
      hash_delete(&hash_user_locks,(byte*) this);
      my_free((gptr) key,MYF(0));
    }
    pthread_cond_destroy(&cond);
  }
  inline bool initialized() { return key != 0; }
2798 2799 2800
  friend void item_user_lock_release(User_level_lock *ull);
  friend char *ull_get_key(const User_level_lock *ull, uint *length,
                           my_bool not_used);
unknown's avatar
unknown committed
2801 2802
};

2803
char *ull_get_key(const User_level_lock *ull, uint *length,
unknown's avatar
unknown committed
2804 2805 2806 2807 2808 2809
		  my_bool not_used __attribute__((unused)))
{
  *length=(uint) ull->key_length;
  return (char*) ull->key;
}

2810 2811 2812

static bool item_user_lock_inited= 0;

unknown's avatar
unknown committed
2813 2814
void item_user_lock_init(void)
{
2815
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
unknown's avatar
unknown committed
2816 2817
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
2818
  item_user_lock_inited= 1;
unknown's avatar
unknown committed
2819 2820 2821 2822
}

void item_user_lock_free(void)
{
2823 2824 2825 2826 2827 2828
  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
2829 2830
}

2831
void item_user_lock_release(User_level_lock *ull)
unknown's avatar
unknown committed
2832 2833
{
  ull->locked=0;
unknown's avatar
unknown committed
2834 2835 2836
  if (mysql_bin_log.is_open())
  {
    char buf[256];
unknown's avatar
unknown committed
2837 2838
    const char *command="DO RELEASE_LOCK(\"";
    String tmp(buf,sizeof(buf), system_charset_info);
2839
    tmp.copy(command, strlen(command), tmp.charset());
unknown's avatar
unknown committed
2840
    tmp.append(ull->key,ull->key_length);
2841
    tmp.append("\")", 2);
unknown's avatar
unknown committed
2842
    Query_log_event qev(current_thd, tmp.ptr(), tmp.length(), 0, FALSE);
2843
    qev.error_code=0; // this query is always safe to run on slave
unknown's avatar
unknown committed
2844 2845
    mysql_bin_log.write(&qev);
  }
unknown's avatar
unknown committed
2846 2847 2848 2849 2850 2851
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

unknown's avatar
unknown committed
2852 2853 2854 2855 2856 2857 2858
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

longlong Item_master_pos_wait::val_int()
{
2859
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2860 2861
  THD* thd = current_thd;
  String *log_name = args[0]->val_str(&value);
2862
  int event_count= 0;
unknown's avatar
unknown committed
2863

unknown's avatar
unknown committed
2864 2865 2866 2867 2868 2869
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
unknown's avatar
unknown committed
2870
  longlong pos = (ulong)args[1]->val_int();
2871
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
unknown's avatar
SCRUM  
unknown committed
2872
#ifdef HAVE_REPLICATION
2873
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
unknown's avatar
unknown committed
2874 2875 2876 2877
  {
    null_value = 1;
    event_count=0;
  }
2878
#endif
unknown's avatar
unknown committed
2879 2880 2881
  return event_count;
}

2882 2883 2884 2885
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
2886
  User_level_lock* ull;
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
  struct timespec abstime;
  int lock_name_len,error=0;
  lock_name_len=strlen(lock_name);
  pthread_mutex_lock(&LOCK_user_locks);

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

2898 2899 2900 2901 2902
  /*
    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
2903
  */
2904
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, lock_name,
2905 2906 2907 2908 2909 2910 2911
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

2912 2913 2914 2915
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
2916 2917 2918 2919
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

2920
  set_timespec(abstime,lock_timeout);
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
	 != ETIME && error != ETIMEDOUT && ull->locked) ;
  if (ull->locked)
  {
    if (!--ull->count)
      delete ull;				// Should never happen
  }
  else
  {
    ull->locked=1;
    ull->thread=thd->real_id;
    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
2952 2953 2954 2955 2956 2957 2958 2959 2960
/*
  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()
{
2961
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2962 2963 2964 2965
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
2966
  User_level_lock *ull;
unknown's avatar
unknown committed
2967
  int error=0;
unknown's avatar
unknown committed
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984

  pthread_mutex_lock(&LOCK_user_locks);

  if (!res || !res->length())
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    null_value=1;
    return 0;
  }
  null_value=0;

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

2985 2986 2987
  if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks,
                                              (byte*) res->ptr(),
                                              res->length()))))
unknown's avatar
unknown committed
2988
  {
2989
    ull=new User_level_lock(res->ptr(),res->length(), thd->thread_id);
unknown's avatar
unknown committed
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
    if (!ull || !ull->initialized())
    {
      delete ull;
      pthread_mutex_unlock(&LOCK_user_locks);
      null_value=1;				// Probably out of memory
      return 0;
    }
    ull->thread=thd->real_id;
    thd->ull=ull;
    pthread_mutex_unlock(&LOCK_user_locks);
    return 1;					// Got new lock
  }
  ull->count++;

3004 3005 3006 3007
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks.
  */
unknown's avatar
unknown committed
3008 3009 3010 3011
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

3012
  set_timespec(abstime,timeout);
unknown's avatar
unknown committed
3013 3014
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
3015
	 != ETIME && error != ETIMEDOUT && error != EINVAL && ull->locked) ;
unknown's avatar
unknown committed
3016 3017
  if (thd->killed)
    error=EINTR;				// Return NULL
unknown's avatar
unknown committed
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
  if (ull->locked)
  {
    if (!--ull->count)
      delete ull;				// Should never happen
    if (error != ETIME && error != ETIMEDOUT)
    {
      error=1;
      null_value=1;				// Return NULL
    }
  }
  else
  {
    ull->locked=1;
    ull->thread=thd->real_id;
    thd->ull=ull;
    error=0;
  }
  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);

  return !error ? 1 : 0;
}


/*
3048 3049 3050 3051 3052
  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
3053 3054 3055 3056
*/

longlong Item_func_release_lock::val_int()
{
3057
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3058
  String *res=args[0]->val_str(&value);
3059
  User_level_lock *ull;
unknown's avatar
unknown committed
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
  longlong result;
  if (!res || !res->length())
  {
    null_value=1;
    return 0;
  }
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
3070 3071 3072
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
                                             (const byte*) res->ptr(),
                                             res->length()))))
unknown's avatar
unknown committed
3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
  {
    null_value=1;
  }
  else
  {
    if (ull->locked && pthread_equal(pthread_self(),ull->thread))
    {
      result=1;					// Release is ok
      item_user_lock_release(ull);
      current_thd->ull=0;
    }
  }
  pthread_mutex_unlock(&LOCK_user_locks);
  return result;
}


3090
longlong Item_func_last_insert_id::val_int()
unknown's avatar
unknown committed
3091
{
unknown's avatar
unknown committed
3092
  THD *thd= current_thd;
3093
  DBUG_ASSERT(fixed == 1);
3094 3095
  if (arg_count)
  {
unknown's avatar
unknown committed
3096 3097 3098 3099
    longlong value= args[0]->val_int();
    thd->insert_id(value);
    null_value= args[0]->null_value;
    return value;                       // Avoid side effect of insert_id()
3100
  }
unknown's avatar
unknown committed
3101 3102
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
  return thd->insert_id();
unknown's avatar
unknown committed
3103 3104 3105 3106 3107 3108
}

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

longlong Item_func_benchmark::val_int()
{
3109
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3110
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
3111
  String tmp(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
3112 3113 3114 3115 3116 3117
  THD *thd=current_thd;

  for (ulong loop=0 ; loop < loop_count && !thd->killed; loop++)
  {
    switch (args[0]->result_type()) {
    case REAL_RESULT:
3118
      (void) args[0]->val_real();
unknown's avatar
unknown committed
3119 3120 3121 3122 3123 3124 3125
      break;
    case INT_RESULT:
      (void) args[0]->val_int();
      break;
    case STRING_RESULT:
      (void) args[0]->val_str(&tmp);
      break;
3126
    case ROW_RESULT:
unknown's avatar
unknown committed
3127
    default:
unknown's avatar
unknown committed
3128
      // This case should never be chosen
unknown's avatar
unknown committed
3129 3130
      DBUG_ASSERT(0);
      return 0;
unknown's avatar
unknown committed
3131 3132 3133 3134 3135
    }
  }
  return 0;
}

3136

3137 3138 3139 3140
void Item_func_benchmark::print(String *str)
{
  str->append("benchmark(", 10);
  char buffer[20];
unknown's avatar
unknown committed
3141 3142 3143
  // my_charset_bin is good enough for numbers
  String st(buffer, sizeof(buffer), &my_charset_bin);
  st.set((ulonglong)loop_count, &my_charset_bin);
3144 3145 3146 3147 3148 3149
  str->append(st);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}

unknown's avatar
unknown committed
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
#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;

  if (!(entry = (user_var_entry*) hash_search(hash, (byte*) name.str,
					      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;
3171
    entry->update_query_id=0;
3172
    entry->collation.set(NULL, DERIVATION_IMPLICIT);
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
    /*
      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
3183
    entry->used_query_id=current_thd->query_id;
unknown's avatar
unknown committed
3184 3185
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
unknown's avatar
SCRUM  
unknown committed
3186
    if (my_hash_insert(hash,(byte*) entry))
unknown's avatar
unknown committed
3187 3188 3189 3190 3191 3192 3193 3194
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

3195
/*
3196 3197
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
3198
*/
3199

unknown's avatar
unknown committed
3200 3201
bool Item_func_set_user_var::fix_fields(THD *thd, TABLE_LIST *tables,
					Item **ref)
unknown's avatar
unknown committed
3202
{
3203
  DBUG_ASSERT(fixed == 0);
3204
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
unknown's avatar
unknown committed
3205
  if (Item_func::fix_fields(thd, tables, ref) ||
unknown's avatar
unknown committed
3206
      !(entry= get_variable(&thd->user_vars, name, 1)))
unknown's avatar
unknown committed
3207
    return TRUE;
3208 3209 3210 3211 3212
  /* 
     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).
  */
3213
  entry->update_query_id= thd->query_id;
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
  /*
    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.
  */
  if (!entry->collation.collation || !args[0]->null_value)
3230 3231
    entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
  collation.set(entry->collation.collation, DERIVATION_IMPLICIT);
3232
  cached_result_type= args[0]->result_type();
unknown's avatar
unknown committed
3233
  return FALSE;
unknown's avatar
unknown committed
3234 3235 3236 3237 3238 3239 3240 3241 3242
}


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;
3243
  collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
3244 3245
}

3246

unknown's avatar
unknown committed
3247
bool Item_func_set_user_var::update_hash(void *ptr, uint length,
3248
					 Item_result type,
3249
					 CHARSET_INFO *cs,
3250
					 Derivation dv)
unknown's avatar
unknown committed
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
{
  if ((null_value=args[0]->null_value))
  {
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
    if (entry->value && entry->value != pos)
      my_free(entry->value,MYF(0));
    entry->value=0;
    entry->length=0;
  }
  else
  {
3262 3263
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
unknown's avatar
unknown committed
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
    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;
	if (!(entry->value=(char*) my_realloc(entry->value, length,
					      MYF(MY_ALLOW_ZERO_PTR))))
	  goto err;
      }
    }
3288 3289 3290 3291 3292
    if (type == STRING_RESULT)
    {
      length--;					// Fix length change above
      entry->value[length]= 0;			// Store end \0
    }
unknown's avatar
unknown committed
3293
    memcpy(entry->value,ptr,length);
unknown's avatar
unknown committed
3294 3295
    if (type == DECIMAL_RESULT)
      ((my_decimal*)entry->value)->fix_buffer_pointer();
unknown's avatar
unknown committed
3296 3297
    entry->length= length;
    entry->type=type;
3298
    entry->collation.set(cs, dv);
unknown's avatar
unknown committed
3299
  }
3300
  return 0;
unknown's avatar
unknown committed
3301 3302

 err:
3303
  current_thd->fatal_error();			// Probably end of memory
unknown's avatar
unknown committed
3304 3305
  null_value= 1;
  return 1;
unknown's avatar
unknown committed
3306 3307 3308
}


3309 3310
/* Get the value of a variable as a double */

unknown's avatar
unknown committed
3311
double user_var_entry::val_real(my_bool *null_value)
unknown's avatar
unknown committed
3312
{
3313 3314 3315 3316 3317 3318 3319 3320
  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
3321 3322 3323 3324 3325 3326
  case DECIMAL_RESULT:
  {
    double result;
    my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *)value, &result);
    return result;
  }
3327
  case STRING_RESULT:
unknown's avatar
unknown committed
3328
    return my_atof(value);                      // This is null terminated
3329 3330 3331
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
3332
  }
3333
  return 0.0;					// Impossible
unknown's avatar
unknown committed
3334 3335 3336
}


3337 3338 3339
/* Get the value of a variable as an integer */

longlong user_var_entry::val_int(my_bool *null_value)
unknown's avatar
unknown committed
3340
{
3341 3342 3343 3344 3345 3346 3347 3348
  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
3349 3350 3351 3352 3353 3354
  case DECIMAL_RESULT:
  {
    longlong result;
    my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *)value, 1, &result);
    return result;
  }
unknown's avatar
unknown committed
3355
  case STRING_RESULT:
unknown's avatar
unknown committed
3356 3357 3358 3359
  {
    int error;
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
  }
3360 3361 3362
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
3363
  }
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
  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:
unknown's avatar
unknown committed
3378
    str->set(*(double*) value, decimals, &my_charset_bin);
3379 3380
    break;
  case INT_RESULT:
unknown's avatar
unknown committed
3381
    str->set(*(longlong*) value, &my_charset_bin);
3382
    break;
unknown's avatar
unknown committed
3383 3384 3385
  case DECIMAL_RESULT:
    my_decimal2string(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, 0, 0, str);
    break;
3386
  case STRING_RESULT:
unknown's avatar
unknown committed
3387
    if (str->copy(value, length, collation.collation))
3388
      str= 0;					// EOM error
3389 3390 3391
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
3392
  }
3393
  return(str);
unknown's avatar
unknown committed
3394 3395
}

unknown's avatar
unknown committed
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
/* 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);
}

3423 3424
/*
  This functions is invoked on SET @variable or @variable:= expression.
unknown's avatar
unknown committed
3425
  Evaluate (and check expression), store results.
3426 3427 3428 3429 3430

  SYNOPSYS
    Item_func_set_user_var::check()

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

  RETURN
unknown's avatar
unknown committed
3435
    FALSE OK.
3436 3437 3438 3439 3440 3441 3442 3443 3444 3445
*/

bool
Item_func_set_user_var::check()
{
  DBUG_ENTER("Item_func_set_user_var::check");

  switch (cached_result_type) {
  case REAL_RESULT:
  {
3446
    save_result.vreal= args[0]->val_real();
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
    break;
  }
  case INT_RESULT:
  {
    save_result.vint= args[0]->val_int();
    break;
  }
  case STRING_RESULT:
  {
    save_result.vstr= args[0]->val_str(&value);
    break;
  }
unknown's avatar
unknown committed
3459 3460 3461 3462 3463
  case DECIMAL_RESULT:
  {
    save_result.vdec= args[0]->val_decimal(&decimal_buff);
    break;
  }
3464 3465
  case ROW_RESULT:
  default:
unknown's avatar
unknown committed
3466
    // This case should never be chosen
3467 3468 3469
    DBUG_ASSERT(0);
    break;
  }
unknown's avatar
unknown committed
3470
  DBUG_RETURN(FALSE);
3471 3472
}

3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484

/*
  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
3485
    0	OK
3486 3487 3488 3489
    1	EOM Error

*/

unknown's avatar
unknown committed
3490 3491 3492
bool
Item_func_set_user_var::update()
{
3493 3494 3495 3496
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

unknown's avatar
unknown committed
3497 3498
  switch (cached_result_type) {
  case REAL_RESULT:
unknown's avatar
unknown committed
3499
  {
3500 3501
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
		     REAL_RESULT, &my_charset_bin, DERIVATION_NONE);
unknown's avatar
unknown committed
3502
    break;
unknown's avatar
unknown committed
3503
  }
unknown's avatar
unknown committed
3504
  case INT_RESULT:
3505
  {
3506 3507
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
		     INT_RESULT, &my_charset_bin, DERIVATION_NONE);
unknown's avatar
unknown committed
3508
    break;
unknown's avatar
unknown committed
3509
  }
unknown's avatar
unknown committed
3510
  case STRING_RESULT:
unknown's avatar
unknown committed
3511
  {
3512
    if (!save_result.vstr)					// Null value
unknown's avatar
unknown committed
3513 3514
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
		       DERIVATION_NONE);
3515
    else
3516 3517 3518
      res= update_hash((void*) save_result.vstr->ptr(),
		       save_result.vstr->length(), STRING_RESULT,
		       save_result.vstr->charset(),
3519
		       DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
3520 3521
    break;
  }
unknown's avatar
unknown committed
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532
  case DECIMAL_RESULT:
  {
    if (!save_result.vdec)					// Null value
      res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin,
                       DERIVATION_NONE);
    else
      res= update_hash((void*) save_result.vdec,
                       sizeof(my_decimal), DECIMAL_RESULT,
                       &my_charset_bin, DERIVATION_NONE);
    break;
  }
3533
  case ROW_RESULT:
unknown's avatar
unknown committed
3534
  default:
unknown's avatar
unknown committed
3535
    // This case should never be chosen
unknown's avatar
unknown committed
3536 3537 3538
    DBUG_ASSERT(0);
    break;
  }
3539
  DBUG_RETURN(res);
unknown's avatar
unknown committed
3540 3541 3542
}


3543
double Item_func_set_user_var::val_real()
unknown's avatar
unknown committed
3544
{
3545
  DBUG_ASSERT(fixed == 1);
3546
  check();
3547
  update();					// Store expression
unknown's avatar
unknown committed
3548
  return entry->val_real(&null_value);
unknown's avatar
unknown committed
3549 3550
}

3551
longlong Item_func_set_user_var::val_int()
unknown's avatar
unknown committed
3552
{
3553
  DBUG_ASSERT(fixed == 1);
3554
  check();
3555 3556
  update();					// Store expression
  return entry->val_int(&null_value);
unknown's avatar
unknown committed
3557 3558
}

3559
String *Item_func_set_user_var::val_str(String *str)
unknown's avatar
unknown committed
3560
{
3561
  DBUG_ASSERT(fixed == 1);
3562
  check();
3563 3564
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
unknown's avatar
unknown committed
3565 3566 3567
}


unknown's avatar
unknown committed
3568 3569 3570 3571 3572 3573 3574 3575 3576
my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
{
  DBUG_ASSERT(fixed == 1);
  check();
  update();					// Store expression
  return entry->val_decimal(&null_value, val);
}


unknown's avatar
unknown committed
3577 3578
void Item_func_set_user_var::print(String *str)
{
3579 3580 3581
  str->append("(@", 2);
  str->append(name.str, name.length);
  str->append(":=", 2);
unknown's avatar
unknown committed
3582 3583 3584 3585 3586
  args[0]->print(str);
  str->append(')');
}


3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
void Item_func_set_user_var::print_as_stmt(String *str)
{
  str->append("set @", 5);
  str->append(name.str, name.length);
  str->append(":=", 2);
  args[0]->print(str);
  str->append(')');
}


unknown's avatar
unknown committed
3597 3598 3599
String *
Item_func_get_user_var::val_str(String *str)
{
3600
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3601
  DBUG_ENTER("Item_func_get_user_var::val_str");
3602
  if (!var_entry)
3603
    DBUG_RETURN((String*) 0);			// No such variable
3604
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
unknown's avatar
unknown committed
3605 3606 3607
}


3608
double Item_func_get_user_var::val_real()
unknown's avatar
unknown committed
3609
{
3610
  DBUG_ASSERT(fixed == 1);
3611 3612
  if (!var_entry)
    return 0.0;					// No such variable
unknown's avatar
unknown committed
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
  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
3623 3624 3625 3626 3627
}


longlong Item_func_get_user_var::val_int()
{
3628
  DBUG_ASSERT(fixed == 1);
3629 3630 3631
  if (!var_entry)
    return LL(0);				// No such variable
  return (var_entry->val_int(&null_value));
unknown's avatar
unknown committed
3632 3633 3634
}


3635
/*
3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
  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.

3646 3647 3648 3649
  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).
3650 3651 3652
  
  RETURN
    0  OK 
unknown's avatar
unknown committed
3653
    1  Failed to put appropriate record into binary log
3654
    
3655 3656
*/

3657 3658
int get_var_with_binlog(THD *thd, LEX_STRING &name, 
                        user_var_entry **out_entry)
unknown's avatar
unknown committed
3659
{
3660
  BINLOG_USER_VAR_EVENT *user_var_event;
3661 3662
  user_var_entry *var_entry;
  var_entry= get_variable(&thd->user_vars, name, 0);
3663
  
unknown's avatar
unknown committed
3664
  if (!(opt_bin_log && is_update_query(thd->lex->sql_command)))
3665 3666 3667 3668
  {
    *out_entry= var_entry;
    return 0;
  }
3669 3670

  if (!var_entry)
unknown's avatar
unknown committed
3671
  {
3672
    /*
3673 3674 3675 3676
      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
3677 3678
      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;'.
3679 3680 3681
      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();
3682 3683
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
3684 3685 3686 3687 3688
    */

    List<set_var_base> tmp_var_list;
    tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
                                                                       new Item_null())));
3689 3690
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
3691 3692 3693 3694 3695
      goto err;
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
  else if (var_entry->used_query_id == thd->query_id)
3696 3697 3698 3699 3700 3701 3702 3703 3704
  {
    /* 
       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;
  }
3705 3706 3707 3708

  uint size;
  /*
    First we need to store value of var_entry, when the next situation
unknown's avatar
unknown committed
3709
    appears:
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727
    > set @a:=1;
    > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
    We have to write to binlog value @a= 1;
  */
  size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;      
  if (!(user_var_event= (BINLOG_USER_VAR_EVENT *) thd->alloc(size)))
    goto err;
  
  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
3728
  }
3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
  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;
  if (insert_dynamic(&thd->user_var_events, (gptr) &user_var_event))
    goto err;
3739 3740 3741
  
  *out_entry= var_entry;
  return 0;
3742

unknown's avatar
unknown committed
3743
err:
3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
  *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;
3756

3757
  error= get_var_with_binlog(thd, name, &var_entry);
3758 3759

  if (var_entry)
3760
  {
3761
    collation.set(var_entry->collation);
3762 3763 3764 3765 3766 3767 3768 3769 3770
    switch (var_entry->type) {
    case REAL_RESULT:
      max_length= DBL_DIG + 8;
    case INT_RESULT:
      max_length= MAX_BIGINT_WIDTH;
      break;
    case STRING_RESULT:
      max_length= MAX_BLOB_WIDTH;
      break;
unknown's avatar
unknown committed
3771 3772 3773 3774
    case DECIMAL_RESULT:
      max_length= DECIMAL_MAX_LENGTH;
      decimals= min(DECIMAL_MAX_LENGTH / 2, NOT_FIXED_DEC - 1);
      break;
unknown's avatar
unknown committed
3775
    case ROW_RESULT:                            // Keep compiler happy
unknown's avatar
unknown committed
3776 3777
    default:
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3778
      break;
3779 3780
    }
  }
3781 3782 3783
  else
    null_value= 1;

3784 3785
  if (error)
    thd->fatal_error();
3786

unknown's avatar
unknown committed
3787
  return;
unknown's avatar
unknown committed
3788 3789 3790
}


3791
bool Item_func_get_user_var::const_item() const
3792
{
3793
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
3794
}
unknown's avatar
unknown committed
3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806


enum Item_result Item_func_get_user_var::result_type() const
{
  user_var_entry *entry;
  if (!(entry = (user_var_entry*) hash_search(&current_thd->user_vars,
					      (byte*) name.str,
					      name.length)))
    return STRING_RESULT;
  return entry->type;
}

unknown's avatar
unknown committed
3807 3808 3809

void Item_func_get_user_var::print(String *str)
{
3810
  str->append("(@", 2);
unknown's avatar
unknown committed
3811 3812 3813 3814
  str->append(name.str,name.length);
  str->append(')');
}

3815

3816
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
{
  /* 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 ||
      ((Item_func*) item)->func_name() != func_name())
    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));
}


unknown's avatar
unknown committed
3831 3832
longlong Item_func_inet_aton::val_int()
{
3833
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3834 3835 3836 3837 3838
  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];
3839
  int dot_count= 0;
unknown's avatar
unknown committed
3840

unknown's avatar
unknown committed
3841
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
unknown's avatar
unknown committed
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
  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 == '.')
    {
3858
      dot_count++;
unknown's avatar
unknown committed
3859 3860 3861 3862 3863 3864 3865
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
3866
  {
3867 3868 3869 3870 3871 3872
    /*
      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
3873
    switch (dot_count) {
3874 3875
    case 1: result<<= 8; /* Fall through */
    case 2: result<<= 8; /* Fall through */
3876
    }
unknown's avatar
unknown committed
3877
    return (result << 8) + (ulonglong) byte_result;
3878
  }
unknown's avatar
unknown committed
3879 3880 3881 3882 3883 3884

err:
  null_value=1;
  return 0;
}

unknown's avatar
unknown committed
3885

3886
void Item_func_match::init_search(bool no_order)
3887
{
unknown's avatar
unknown committed
3888
  DBUG_ENTER("Item_func_match::init_search");
3889 3890

  /* Check if init_search() has been called before */
3891
  if (ft_handler)
unknown's avatar
unknown committed
3892
    DBUG_VOID_RETURN;
3893

3894
  if (key == NO_SUCH_KEY)
3895 3896
  {
    List<Item> fields;
3897
    fields.push_back(new Item_string(" ",1, cmp_collation.collation));
3898 3899
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
3900
    concat=new Item_func_concat_ws(fields);
unknown's avatar
unknown committed
3901 3902 3903
    /*
      Above function used only to get value and do not need fix_fields for it:
      Item_string - basic constant
unknown's avatar
unknown committed
3904 3905
      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
3906 3907
    */
    concat->quick_fix_field();
3908
  }
3909

3910 3911
  if (master)
  {
3912 3913
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
3914 3915
    ft_handler=master->ft_handler;
    join_key=master->join_key;
unknown's avatar
unknown committed
3916
    DBUG_VOID_RETURN;
3917 3918
  }

unknown's avatar
unknown committed
3919
  String *ft_tmp= 0;
3920

3921
  // MATCH ... AGAINST (NULL) is meaningless, but possible
3922
  if (!(ft_tmp=key_item()->val_str(&value)))
3923
  {
3924 3925
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
3926 3927
  }

3928 3929
  if (ft_tmp->charset() != cmp_collation.collation)
  {
3930
    uint dummy_errors;
3931
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
3932
                      cmp_collation.collation, &dummy_errors);
3933
    ft_tmp= &search_value;
3934 3935
  }

3936 3937
  if (join_key && !no_order)
    flags|=FT_SORTED;
3938
  ft_handler=table->file->ft_init_ext(flags, key, ft_tmp);
3939 3940 3941

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

  DBUG_VOID_RETURN;
3944 3945
}

unknown's avatar
unknown committed
3946

unknown's avatar
unknown committed
3947
bool Item_func_match::fix_fields(THD *thd, TABLE_LIST *tlist, Item **ref)
unknown's avatar
unknown committed
3948
{
3949
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
3950
  Item *item;
3951
  LINT_INIT(item);				// Safe as arg_count is > 1
unknown's avatar
unknown committed
3952

3953 3954 3955
  maybe_null=1;
  join_key=0;

3956 3957 3958 3959 3960
  /*
    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.
3961
   */
3962 3963
  if (Item_func::fix_fields(thd, tlist, ref) ||
      !args[0]->const_during_execution())
3964 3965
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
unknown's avatar
unknown committed
3966
    return TRUE;
3967
  }
unknown's avatar
unknown committed
3968

3969 3970
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
unknown's avatar
unknown committed
3971
  {
3972
    item=args[i];
unknown's avatar
unknown committed
3973
    if (item->type() == Item::REF_ITEM)
3974 3975
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
3976
      key=NO_SUCH_KEY;
unknown's avatar
unknown committed
3977
  }
3978 3979
  /*
    Check that all columns come from the same table.
3980
    We've already checked that columns in MATCH are fields so
3981 3982 3983
    PARAM_TABLE_BIT can only appear from AGAINST argument.
  */
  if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
3984
    key=NO_SUCH_KEY;
3985

3986
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
3987 3988
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
unknown's avatar
unknown committed
3989
    return TRUE;
3990
  }
3991 3992 3993
  table=((Item_field *)item)->field->table;
  table->fulltext_searched=1;
  return agg_arg_collations_for_comparison(cmp_collation, args+1, arg_count-1);
unknown's avatar
unknown committed
3994
}
3995

unknown's avatar
unknown committed
3996 3997 3998
bool Item_func_match::fix_index()
{
  Item_field *item;
3999
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
4000
  uint max_cnt=0, mkeys=0, i;
4001

4002
  if (key == NO_SUCH_KEY)
4003
    return 0;
unknown's avatar
unknown committed
4004

4005
  for (keynr=0 ; keynr < table->s->keys ; keynr++)
unknown's avatar
unknown committed
4006
  {
4007
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
4008
        (table->keys_in_use_for_query.is_set(keynr)))
unknown's avatar
unknown committed
4009
    {
4010
      ft_to_key[fts]=keynr;
unknown's avatar
unknown committed
4011 4012 4013 4014 4015 4016
      ft_cnt[fts]=0;
      fts++;
    }
  }

  if (!fts)
4017
    goto err;
unknown's avatar
unknown committed
4018

4019
  for (i=1; i < arg_count; i++)
unknown's avatar
unknown committed
4020
  {
4021
    item=(Item_field*)args[i];
4022
    for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
4023
    {
4024
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
unknown's avatar
unknown committed
4025 4026 4027 4028 4029
      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))
4030
	  ft_cnt[keynr]++;
unknown's avatar
unknown committed
4031 4032 4033 4034
      }
    }
  }

4035
  for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
4036
  {
4037
    if (ft_cnt[keynr] > max_cnt)
unknown's avatar
unknown committed
4038
    {
4039
      mkeys=0;
4040 4041
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
4042 4043
      continue;
    }
4044
    if (max_cnt && ft_cnt[keynr] == max_cnt)
4045 4046
    {
      mkeys++;
4047 4048
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
4049
      continue;
unknown's avatar
unknown committed
4050 4051 4052
    }
  }

4053
  for (keynr=0 ; keynr <= mkeys ; keynr++)
unknown's avatar
unknown committed
4054
  {
4055 4056
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
4057
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
4058
      continue;
unknown's avatar
unknown committed
4059

4060
    key=ft_to_key[keynr];
4061

4062 4063 4064
    return 0;
  }

4065
err:
4066
  if (flags & FT_BOOL)
4067
  {
4068
    key=NO_SUCH_KEY;
4069 4070
    return 0;
  }
unknown's avatar
unknown committed
4071 4072
  my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
             ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
4073
  return 1;
4074 4075
}

4076

4077
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
4078
{
4079 4080
  if (item->type() != FUNC_ITEM || ((Item_func*)item)->functype() != FT_FUNC ||
      flags != ((Item_func_match*)item)->flags)
4081 4082 4083 4084 4085
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
4086
      key_item()->eq(ifm->key_item(), binary_cmp))
4087
    return 1;
unknown's avatar
unknown committed
4088 4089 4090 4091

  return 0;
}

4092

4093
double Item_func_match::val_real()
unknown's avatar
unknown committed
4094
{
4095
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
4096
  DBUG_ENTER("Item_func_match::val");
unknown's avatar
unknown committed
4097
  if (ft_handler == NULL)
unknown's avatar
unknown committed
4098
    DBUG_RETURN(-1.0);
unknown's avatar
unknown committed
4099

unknown's avatar
unknown committed
4100 4101 4102
  if (table->null_row) /* NULL row from an outer join */
    return 0.0;

unknown's avatar
unknown committed
4103 4104 4105
  if (join_key)
  {
    if (table->file->ft_handler)
unknown's avatar
unknown committed
4106
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
unknown's avatar
unknown committed
4107 4108 4109
    join_key=0;
  }

4110
  if (key == NO_SUCH_KEY)
unknown's avatar
unknown committed
4111
  {
4112 4113
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
unknown's avatar
unknown committed
4114 4115 4116
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
				      (byte *)a->ptr(), a->length()));
unknown's avatar
unknown committed
4117 4118
  }
  else
4119 4120
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                   table->record[0], 0));
unknown's avatar
unknown committed
4121 4122
}

4123 4124
void Item_func_match::print(String *str)
{
4125
  str->append("(match ", 7);
unknown's avatar
unknown committed
4126
  print_args(str, 1);
4127
  str->append(" against (", 10);
4128
  args[0]->print(str);
unknown's avatar
unknown committed
4129
  if (flags & FT_BOOL)
4130
    str->append(" in boolean mode", 16);
unknown's avatar
unknown committed
4131 4132
  else if (flags & FT_EXPAND)
    str->append(" with query expansion", 21);
4133
  str->append("))", 2);
4134
}
unknown's avatar
unknown committed
4135

unknown's avatar
unknown committed
4136 4137
longlong Item_func_bit_xor::val_int()
{
4138
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
4139 4140
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
4141
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
4142 4143 4144 4145
    return 0;
  return (longlong) (arg1 ^ arg2);
}

4146

4147 4148 4149 4150
/***************************************************************************
  System variables
****************************************************************************/

4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171
/*
  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
    component		Component.

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

  RETURN
    0	error
    #	constant item
*/
  

Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
		     LEX_STRING component)
4172
{
4173 4174
  if (component.str == 0 &&
      !my_strcasecmp(system_charset_info, name.str, "VERSION"))
4175 4176 4177
    return new Item_string("@@VERSION", server_version,
			   (uint) strlen(server_version),
			   system_charset_info);
unknown's avatar
unknown committed
4178 4179 4180

  Item *item;
  sys_var *var;
4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *pos;
  LEX_STRING *base_name, *component_name;

  if (component.str)
  {
    base_name= &component;
    component_name= &name;
  }
  else
  {
    base_name= &name;
    component_name= &component;			// Empty string
  }
unknown's avatar
unknown committed
4194

4195
  if (!(var= find_sys_var(base_name->str, base_name->length)))
unknown's avatar
unknown committed
4196
    return 0;
4197 4198 4199 4200
  if (component.str)
  {
    if (!var->is_struct())
    {
4201
      my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
4202 4203 4204 4205
      return 0;
    }
  }
  if (!(item=var->item(thd, var_type, component_name)))
unknown's avatar
unknown committed
4206
    return 0;					// Impossible
unknown's avatar
unknown committed
4207
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
unknown's avatar
unknown committed
4208 4209
  buff[0]='@';
  buff[1]='@';
unknown's avatar
unknown committed
4210 4211 4212 4213 4214
  pos=buff+2;
  if (var_type == OPT_SESSION)
    pos=strmov(pos,"session.");
  else if (var_type == OPT_GLOBAL)
    pos=strmov(pos,"global.");
4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
  
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
  set_if_smaller(base_name->length, MAX_SYS_VAR_LENGTH);

  if (component_name->str)
  {
    memcpy(pos, component_name->str, component_name->length);
    pos+= component_name->length;
    *pos++= '.';
  }
  memcpy(pos, base_name->str, base_name->length);
  pos+= base_name->length;

unknown's avatar
unknown committed
4228
  // set_name() will allocate the name
4229
  item->set_name(buff,(uint) (pos-buff), system_charset_info);
unknown's avatar
unknown committed
4230
  return item;
4231
}
unknown's avatar
unknown committed
4232

unknown's avatar
unknown committed
4233

4234 4235
Item *get_system_var(THD *thd, enum_var_type var_type, const char *var_name,
		     uint length, const char *item_name)
4236 4237 4238
{
  Item *item;
  sys_var *var;
4239 4240 4241
  LEX_STRING null_lex_string;

  null_lex_string.str= 0;
4242 4243 4244

  var= find_sys_var(var_name, length);
  DBUG_ASSERT(var != 0);
4245
  if (!(item=var->item(thd, var_type, &null_lex_string)))
unknown's avatar
unknown committed
4246
    return 0;						// Impossible
unknown's avatar
unknown committed
4247
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
unknown's avatar
unknown committed
4248
  item->set_name(item_name, 0, system_charset_info);	// Will use original name
4249 4250 4251 4252
  return item;
}


unknown's avatar
unknown committed
4253 4254
/*
  Check a user level lock.
4255 4256 4257 4258 4259 4260 4261 4262

  SYNOPSIS:
    val_int()

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

4265
longlong Item_func_is_free_lock::val_int()
unknown's avatar
unknown committed
4266
{
4267
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
4268
  String *res=args[0]->val_str(&value);
4269
  User_level_lock *ull;
unknown's avatar
unknown committed
4270 4271

  null_value=0;
4272
  if (!res || !res->length())
unknown's avatar
unknown committed
4273 4274 4275 4276 4277 4278
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
4279
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
unknown's avatar
unknown committed
4280 4281 4282 4283 4284 4285
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
unknown's avatar
unknown committed
4286

unknown's avatar
SCRUM  
unknown committed
4287 4288
longlong Item_func_is_used_lock::val_int()
{
4289
  DBUG_ASSERT(fixed == 1);
unknown's avatar
SCRUM  
unknown committed
4290
  String *res=args[0]->val_str(&value);
4291
  User_level_lock *ull;
unknown's avatar
SCRUM  
unknown committed
4292 4293 4294 4295 4296 4297

  null_value=1;
  if (!res || !res->length())
    return 0;
  
  pthread_mutex_lock(&LOCK_user_locks);
4298
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
unknown's avatar
SCRUM  
unknown committed
4299 4300 4301 4302 4303 4304 4305 4306 4307
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 0;

  null_value=0;
  return ull->thread_id;
}

4308

4309 4310 4311 4312 4313 4314 4315 4316 4317
longlong Item_func_row_count::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->row_count_func;
}


4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
Item_func_sp::Item_func_sp(sp_name *name)
  :Item_func(), m_name(name), m_sp(NULL)
{
  m_name->init_qname(current_thd);
}

Item_func_sp::Item_func_sp(sp_name *name, List<Item> &list)
  :Item_func(list), m_name(name), m_sp(NULL)
{
  m_name->init_qname(current_thd);
}

const char *
Item_func_sp::func_name() const
{
4333
  THD *thd= current_thd;
unknown's avatar
unknown committed
4334
  /* Calculate length to avoid reallocation of string for sure */
4335 4336 4337 4338
  uint len= ((m_name->m_db.length +
              m_name->m_name.length)*2 + //characters*quoting
             2 +                         // ` and `
             1 +                         // .
4339 4340
             1 +                         // end of string
             ALIGN_SIZE(1));             // to avoid String reallocation
unknown's avatar
unknown committed
4341
  String qname((char *)alloc_root(thd->mem_root, len), len,
4342
               system_charset_info);
4343

4344 4345 4346 4347 4348
  qname.length(0);
  append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
  qname.append('.');
  append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
  return qname.ptr();
4349 4350
}

4351

4352 4353 4354 4355 4356
int
Item_func_sp::execute(Item **itp)
{
  DBUG_ENTER("Item_func_sp::execute");
  THD *thd= current_thd;
4357
  int res;
4358 4359 4360
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  st_sp_security_context save_ctx;
#endif
4361

4362
  if (! m_sp)
4363
    m_sp= sp_find_function(thd, m_name, TRUE); // cache only
4364
  if (! m_sp)
4365
  {
unknown's avatar
unknown committed
4366
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
4367
    DBUG_RETURN(-1);
4368
  }
4369

4370 4371 4372 4373 4374
#ifndef EMBEDDED_LIBRARY
  my_bool nsok= thd->net.no_send_ok;
  thd->net.no_send_ok= TRUE;
#endif

4375
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4376 4377 4378
  if (check_procedure_access(thd, EXECUTE_ACL, 
			     m_sp->m_db.str, m_sp->m_name.str, 0))
      DBUG_RETURN(-1);
4379
  sp_change_security_context(thd, m_sp, &save_ctx);
4380 4381 4382 4383 4384 4385 4386
  if (save_ctx.changed && 
      check_procedure_access(thd, EXECUTE_ACL, 
			     m_sp->m_db.str, m_sp->m_name.str, 0))
  {
    sp_restore_security_context(thd, m_sp, &save_ctx);
    DBUG_RETURN(-1);
  }
4387
#endif
4388

4389
  /*
unknown's avatar
unknown committed
4390
    We don't need to suppress sending of OK packet here (by setting
4391 4392 4393
    thd->net.no_send_ok to true), because we are not allowing statements
    in functions now.
  */
4394 4395
  res= m_sp->execute_function(thd, args, arg_count, itp);

4396
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4397
  sp_restore_security_context(thd, m_sp, &save_ctx);
4398
#endif
4399

4400 4401 4402
#ifndef EMBEDDED_LIBRARY
  thd->net.no_send_ok= nsok;
#endif
4403
  DBUG_RETURN(res);
4404 4405
}

4406

4407 4408
enum enum_field_types
Item_func_sp::field_type() const
4409
{
4410
  DBUG_ENTER("Item_func_sp::field_type");
4411

4412
  if (! m_sp)
4413
    m_sp= sp_find_function(current_thd, m_name, TRUE); // cache only
4414 4415
  if (m_sp)
  {
4416 4417
    DBUG_PRINT("info", ("m_returns = %d", m_sp->m_returns));
    DBUG_RETURN(m_sp->m_returns);
4418
  }
unknown's avatar
unknown committed
4419
  my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
4420
  DBUG_RETURN(MYSQL_TYPE_VARCHAR);
4421 4422
}

4423

4424 4425
Item_result
Item_func_sp::result_type() const
4426
{
4427 4428
  DBUG_ENTER("Item_func_sp::result_type");
  DBUG_PRINT("info", ("m_sp = %p", m_sp));
4429

4430
  if (! m_sp)
4431
    m_sp= sp_find_function(current_thd, m_name, TRUE); // cache only
4432
  if (m_sp)
4433
  {
4434
    DBUG_RETURN(m_sp->result());
4435
  }
unknown's avatar
unknown committed
4436
  my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
4437
  DBUG_RETURN(STRING_RESULT);
4438 4439 4440 4441 4442 4443 4444
}

void
Item_func_sp::fix_length_and_dec()
{
  DBUG_ENTER("Item_func_sp::fix_length_and_dec");

4445
  if (! m_sp)
4446
    m_sp= sp_find_function(current_thd, m_name, TRUE); // cache only
4447 4448
  if (! m_sp)
  {
unknown's avatar
unknown committed
4449
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
4450 4451
  }
  else
4452 4453 4454 4455
  {
    switch (m_sp->result()) {
    case STRING_RESULT:
      maybe_null= 1;
4456
      max_length= MAX_BLOB_WIDTH;
4457 4458 4459 4460 4461 4462 4463 4464 4465
      break;
    case REAL_RESULT:
      decimals= NOT_FIXED_DEC;
      max_length= float_length(decimals);
      break;
    case INT_RESULT:
      decimals= 0;
      max_length= 21;
      break;
unknown's avatar
unknown committed
4466 4467 4468 4469
    case DECIMAL_RESULT:
      // TODO: where to find real precision and scale?
      decimals= min(DECIMAL_MAX_LENGTH / 2, NOT_FIXED_DEC - 1);
      max_length= DECIMAL_MAX_LENGTH;
4470 4471
    case ROW_RESULT:
    default:
unknown's avatar
unknown committed
4472
      // This case should never be chosen
4473 4474
      DBUG_ASSERT(0);
      break;
4475 4476 4477 4478
    }
  }
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
4479 4480


4481 4482 4483 4484 4485 4486 4487
longlong Item_func_found_rows::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->found_rows();
}