item_func.cc 121 KB
Newer Older
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1
/* Copyright (C) 2000-2003 MySQL AB
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

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

20
#ifdef USE_PRAGMA_IMPLEMENTATION
bk@work.mysql.com's avatar
bk@work.mysql.com committed
21 22 23 24
#pragma implementation				// gcc: Class implementation
#endif

#include "mysql_priv.h"
25
#include "slave.h"				// for wait_for_master_pos
bk@work.mysql.com's avatar
bk@work.mysql.com 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"
34

monty@mysql.com's avatar
monty@mysql.com committed
35 36 37 38 39
#ifdef NO_EMBEDDED_ACCESS_CHECKS
#define sp_restore_security_context(A,B) while (0) {}
#endif


40 41 42 43 44 45 46 47 48 49
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;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
50 51 52 53 54 55 56 57
/* return TRUE if item is a constant */

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

58

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

    while ((item=li++))
    {
monty@mysql.com's avatar
monty@mysql.com committed
72
      *(save_args++)= item;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
73 74 75 76 77 78
      with_sum_func|=item->with_sum_func;
    }
  }
  list.empty();					// Fields are used
}

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

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

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

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

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

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

    Sets as a side effect the following class variables:
      maybe_null	Set if any argument may return NULL
      with_sum_func	Set if any of the arguments contains a sum function
konstantin@mysql.com's avatar
konstantin@mysql.com committed
124
      used_tables_cache Set to union of the tables used by arguments
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
125 126 127

      str_value.charset If this is a string function, set this to the
			character set for the first argument.
128
			If any argument is binary, this is set to binary
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
129 130 131 132 133 134 135

   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
136 137
  FALSE	ok
  TRUE	Got error.  Stored with my_error().
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
138 139
*/

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

149
  used_tables_cache= not_null_tables_cache= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
150 151
  const_item_cache=1;

152
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
153
    return TRUE;				// Fatal error if flag is set!
bk@work.mysql.com's avatar
bk@work.mysql.com committed
154 155 156 157
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
158
      Item *item;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
159 160 161 162
      /*
	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
      */
163
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg)))
164
	return TRUE;				/* purecov: inspected */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
165
      item= *arg;
166 167 168 169 170 171 172 173 174 175 176 177 178 179

      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
      }

180
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
181
	maybe_null=1;
182

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

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
196 197 198 199 200 201 202 203 204 205 206 207 208
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);
}
209

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

    switch (order) {
    case(PREFIX):
mskold@mysql.com's avatar
mskold@mysql.com committed
219
      (*traverser)(this, argument);
220 221 222 223 224 225 226 227 228 229
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
      {
	(*arg)->traverse_cond(traverser, argument, order);
      }
      break;
    case (POSTFIX):
      for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
      {
	(*arg)->traverse_cond(traverser, argument, order);
      }
mskold@mysql.com's avatar
mskold@mysql.com committed
230
      (*traverser)(this, argument);
231 232 233 234
    }
  }
}

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
235

236

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/*
  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)
259 260 261 262 263 264
{
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
265
      Item *new_item= (*arg)->transform(transformer, argument);
266 267
      if (!new_item)
	return 0;
monty@mysql.com's avatar
monty@mysql.com committed
268 269
      if (*arg != new_item)
        current_thd->change_item_tree(arg, new_item);
270 271
    }
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
272
  return (this->*transformer)(argument);
273 274 275
}


276 277
/* See comments in Item_cmp_func::split_sum_func() */

278 279
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
                               List<Item> &fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
280
{
281 282
  Item **arg, **arg_end;
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
283
    (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
}


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

305 306 307 308 309 310 311

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
312 313 314 315
void Item_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
316
  print_args(str, 0);
317 318 319 320
  str->append(')');
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
321
void Item_func::print_args(String *str, uint from)
322
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
323
  for (uint i=from ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
324
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
325
    if (i != from)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
      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(')');
}

monty@mysql.com's avatar
monty@mysql.com committed
346

347
bool Item_func::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
348 349 350 351 352 353 354 355 356 357 358
{
  /* 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++)
359
    if (!args[i]->eq(item_func->args[i], binary_cmp))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
360 361 362 363
      return 0;
  return 1;
}

364

365
Field *Item_func::tmp_table_field(TABLE *table)
366
{
367 368
  Field *field;
  LINT_INIT(field);
369

370
  switch (result_type()) {
371 372
  case INT_RESULT:
    if (max_length > 11)
373
      field= new Field_longlong(max_length, maybe_null, name, unsigned_flag);
374
    else
375
      field= new Field_long(max_length, maybe_null, name, unsigned_flag);
376 377
    break;
  case REAL_RESULT:
378
    field= new Field_double(max_length, maybe_null, name, decimals);
379 380
    break;
  case STRING_RESULT:
381
    return make_string_field(table);
382
    break;
383
  case DECIMAL_RESULT:
384 385 386 387
    field= new Field_new_decimal(my_decimal_precision_to_length(decimal_precision(),
                                                                decimals,
                                                                unsigned_flag),
                                 maybe_null, name, decimals, unsigned_flag);
388
    break;
389
  case ROW_RESULT:
390
  default:
391
    // This case should never be chosen
392
    DBUG_ASSERT(0);
393
    field= 0;
394
    break;
395
  }
396 397 398
  if (field)
    field->init(table);
  return field;
399 400
}

401

402 403 404 405 406 407 408
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;
}

409

bk@work.mysql.com's avatar
bk@work.mysql.com committed
410 411
String *Item_real_func::val_str(String *str)
{
412
  DBUG_ASSERT(fixed == 1);
413
  double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
414 415
  if (null_value)
    return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
416
  str->set(nr,decimals, &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
417 418 419 420
  return str;
}


421 422 423 424 425 426 427 428 429 430 431
my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value)
{
  DBUG_ASSERT(fixed);
  double nr= val_real();
  if (null_value)
    return 0; /* purecov: inspected */
  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
  return decimal_value;
}


432
void Item_func::fix_num_length_and_dec()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
433
{
434
  uint fl_length= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
435
  decimals=0;
436
  for (uint i=0 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
437 438
  {
    set_if_bigger(decimals,args[i]->decimals);
439 440
    set_if_bigger(fl_length, args[i]->max_length);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
441
  max_length=float_length(decimals);
442 443 444 445
  if (fl_length > max_length)
  {
    decimals= NOT_FIXED_DEC;
    max_length= float_length(NOT_FIXED_DEC);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
446
  }
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
}


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()
{
464
  int max_int_part= 0;
465
  decimals= 0;
466
  unsigned_flag= 1;
467
  for (uint i=0 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
468
  {
469
    set_if_bigger(decimals, args[i]->decimals);
470 471
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
    set_if_smaller(unsigned_flag, args[i]->unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
472
  }
473 474 475
  int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
476 477 478
}


479 480 481 482 483 484 485 486
/*
  Set max_length of if it is maximum length of its arguments

  SYNOPSIS
    Item_func::count_only_length()
*/

void Item_func::count_only_length()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
487
{
488
  max_length= 0;
489
  unsigned_flag= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
490
  for (uint i=0 ; i < arg_count ; i++)
491
  {
492
    set_if_bigger(max_length, args[i]->max_length);
493 494
    set_if_bigger(unsigned_flag, args[i]->unsigned_flag);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
495 496
}

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

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



533 534 535 536 537 538 539 540 541 542
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;
}


543
Item *Item_func::get_tmp_table_item(THD *thd)
544 545 546
{
  if (!with_sum_func && !const_item())
    return new Item_field(result_field);
547
  return copy_or_same(thd);
548 549
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
550 551
String *Item_int_func::val_str(String *str)
{
552
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
553 554 555
  longlong nr=val_int();
  if (null_value)
    return 0;
556
  if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
557
    str->set(nr,&my_charset_bin);
558
  else
monty@mysql.com's avatar
monty@mysql.com committed
559
    str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
560 561 562
  return str;
}

563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
void Item_func_connection_id::fix_length_and_dec()
{
  Item_int_func::fix_length_and_dec();
  max_length= 10;
}


bool Item_func_connection_id::fix_fields(THD *thd, Item **ref)
{
  if (Item_int_func::fix_fields(thd, ref))
    return TRUE;

  /*
    To replicate CONNECTION_ID() properly we should use
    pseudo_thread_id on slave, which contains the value of thread_id
    on master.
  */
  value= ((thd->slave_thread) ?
          thd->variables.pseudo_thread_id :
          thd->thread_id);

  return FALSE;
}


589
/*
590 591
  Check arguments here to determine result's type for a numeric
  function of two arguments.
592 593 594

  SYNOPSIS
    Item_num_op::find_num_type()
595
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
596 597 598

void Item_num_op::find_num_type(void)
{
599 600 601 602 603 604 605 606
  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)
607
  {
608 609 610 611 612 613 614 615 616
    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();
  }
617
  else
618
  {
619
    DBUG_ASSERT(r0 == INT_RESULT && r1 == INT_RESULT);
620
    decimals= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
621
    hybrid_type=INT_RESULT;
622
    result_precision();
623
  }
624 625 626 627 628 629
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
630 631
}

632 633

/*
634 635 636
  Set result type for a numeric function of one argument
  (can be also used by a numeric function of many arguments, if the result
  type depends only on the first argument)
637 638 639 640

  SYNOPSIS
    Item_func_num1::find_num_type()
*/
641

642 643 644 645
void Item_func_num1::find_num_type()
{
  DBUG_ENTER("Item_func_num1::find_num_type");
  DBUG_PRINT("info", ("name %s", func_name()));
646
  switch (hybrid_type= args[0]->result_type()) {
647
  case INT_RESULT:
648
    unsigned_flag= args[0]->unsigned_flag;
649 650 651 652 653 654 655 656 657 658
    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);
659
  }
660 661 662 663 664 665
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
666 667
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

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)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
684
{
685
  DBUG_ASSERT(fixed == 1);
686
  switch (hybrid_type) {
687 688 689 690
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
691
      return 0;                                 // null is set
692 693 694 695 696 697 698
    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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
699 700
    if (null_value)
      return 0; /* purecov: inspected */
701
    if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
702
      str->set(nr,&my_charset_bin);
703
    else
monty@mysql.com's avatar
monty@mysql.com committed
704
      str->set((ulonglong) nr,&my_charset_bin);
705
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
706
  }
707
  case REAL_RESULT:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
708
  {
709
    double nr= real_op();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
710 711
    if (null_value)
      return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
712
    str->set(nr,decimals,&my_charset_bin);
713 714
    break;
  }
715 716
  case STRING_RESULT:
    return str_op(&str_value);
717 718
  default:
    DBUG_ASSERT(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
719 720 721 722 723
  }
  return str;
}


724 725 726
double Item_func_numhybrid::val_real()
{
  DBUG_ASSERT(fixed == 1);
727
  switch (hybrid_type) {
728 729 730 731
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    double result;
732 733
    if (!(val= decimal_op(&decimal_value)))
      return 0.0;                               // null is set
734 735 736 737 738 739 740
    my_decimal2double(E_DEC_FATAL_ERROR, val, &result);
    return result;
  }
  case INT_RESULT:
    return (double)int_op();
  case REAL_RESULT:
    return real_op();
741 742 743 744 745 746 747 748
  case STRING_RESULT:
  {
    char *end_not_used;
    int err_not_used;
    String *res= str_op(&str_value);
    return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
			     &end_not_used, &err_not_used) : 0.0);
  }
749 750 751 752 753 754 755 756 757 758
  default:
    DBUG_ASSERT(0);
  }
  return 0.0;
}


longlong Item_func_numhybrid::val_int()
{
  DBUG_ASSERT(fixed == 1);
759
  switch (hybrid_type) {
760 761 762 763
  case DECIMAL_RESULT:
  {
    my_decimal decimal_value, *val;
    if (!(val= decimal_op(&decimal_value)))
764
      return 0;                                 // null is set
765 766 767 768 769 770 771
    longlong result;
    my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result);
    return result;
  }
  case INT_RESULT:
    return int_op();
  case REAL_RESULT:
772
    return (longlong) rint(real_op());
773 774 775
  case STRING_RESULT:
  {
    int err_not_used;
andrey@lmy004's avatar
andrey@lmy004 committed
776 777 778 779
    String *res;
    if (!(res= str_op(&str_value)))
      return 0;

780
    char *end= (char*) res->ptr() + res->length();
781
    CHARSET_INFO *cs= str_value.charset();
andrey@lmy004's avatar
andrey@lmy004 committed
782
    return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used);
783
  }
784 785 786 787 788 789 790 791 792 793 794
  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);
795
  switch (hybrid_type) {
796 797 798 799 800 801 802 803 804 805 806
  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:
  {
807
    double result= (double)real_op();
808 809 810 811
    double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value);
    break;
  }
  case STRING_RESULT:
812
  {
andrey@lmy004's avatar
andrey@lmy004 committed
813 814 815 816
    String *res;
    if (!(res= str_op(&str_value)))
      return NULL;

817 818 819 820
    str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
                   res->length(), res->charset(), decimal_value);
    break;
  }  
821 822 823 824 825 826 827 828
  case ROW_RESULT:
  default:
    DBUG_ASSERT(0);
  }
  return val;
}


829 830
void Item_func_signed::print(String *str)
{
831
  str->append(STRING_WITH_LEN("cast("));
832
  args[0]->print(str);
833
  str->append(STRING_WITH_LEN(" as signed)"));
834 835 836 837

}


838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
longlong Item_func_signed::val_int_from_str(int *error)
{
  char buff[MAX_FIELD_WIDTH], *end;
  String tmp(buff,sizeof(buff), &my_charset_bin), *res;
  longlong value;

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

  if (!(res= args[0]->val_str(&tmp)))
  {
    null_value= 1;
    *error= 0;
    return 0;
  }
  null_value= 0;
  end= (char*) res->ptr()+ res->length();
  value= my_strtoll10(res->ptr(), &end, error);
  if (*error > 0 || end != res->ptr()+ res->length())
    push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
                        ER_TRUNCATED_WRONG_VALUE,
                        ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
                        res->c_ptr());
  return value;
}


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

  if (args[0]->cast_to_int_type() != STRING_RESULT)
  {
    value= args[0]->val_int();
    null_value= args[0]->null_value; 
    return value;
  }

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


890 891
void Item_func_unsigned::print(String *str)
{
892
  str->append(STRING_WITH_LEN("cast("));
893
  args[0]->print(str);
894
  str->append(STRING_WITH_LEN(" as unsigned)"));
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
longlong Item_func_unsigned::val_int()
{
  longlong value;
  int error;

  if (args[0]->cast_to_int_type() != STRING_RESULT)
  {
    value= args[0]->val_int();
    null_value= args[0]->null_value; 
    return value;
  }

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


920 921 922
String *Item_decimal_typecast::val_str(String *str)
{
  my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
923 924
  if (null_value)
    return NULL;
925 926 927 928 929 930 931 932 933
  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;
934 935
  if (null_value)
    return 0.0;
936 937 938 939 940 941 942 943 944
  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;
945 946
  if (null_value)
    return 0;
947 948 949 950 951 952 953 954
  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);
955 956
  if ((null_value= args[0]->null_value))
    return NULL;
957 958 959 960 961
  my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec);
  return dec;
}


962 963
void Item_decimal_typecast::print(String *str)
{
964
  str->append(STRING_WITH_LEN("cast("));
965
  args[0]->print(str);
966
  str->append(STRING_WITH_LEN(" as decimal)"));
967 968 969
}


970
double Item_func_plus::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
971
{
972
  double value= args[0]->val_real() + args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
973 974 975 976 977
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

978 979

longlong Item_func_plus::int_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
980
{
981 982 983 984 985 986 987
  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;
}


988 989 990 991 992 993 994 995 996 997 998 999
/*
  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
*/

1000 1001
my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
{
1002 1003 1004
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
1005 1006
  if ((null_value= args[0]->null_value))
    return 0;
1007
  val2= args[1]->val_decimal(&value2);
1008
  if (!(null_value= (args[1]->null_value ||
1009 1010
                     (my_decimal_add(E_DEC_FATAL_ERROR, decimal_value, val1,
                                     val2) > 3))))
1011 1012
    return decimal_value;
  return 0;
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
}

/*
  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);
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
  int max_int_part= max(args[0]->decimal_precision() - args[0]->decimals,
                        args[1]->decimal_precision() - args[1]->decimals);
  int precision= min(max_int_part + 1 + decimals, DECIMAL_MAX_PRECISION);

  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1035 1036
}

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

/*
  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 &&
1047
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
1048 1049 1050 1051
    unsigned_flag=0;
}


1052
double Item_func_minus::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1053
{
1054
  double value= args[0]->val_real() - args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1055 1056 1057 1058 1059
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

1060 1061

longlong Item_func_minus::int_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1062
{
1063 1064 1065 1066
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1067 1068
}

1069

1070 1071
/* See Item_func_plus::decimal_op for comments */

1072 1073
my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
{
1074 1075 1076 1077
  my_decimal value1, *val1;
  my_decimal value2, *val2= 

  val1= args[0]->val_decimal(&value1);
1078 1079
  if ((null_value= args[0]->null_value))
    return 0;
1080
  val2= args[1]->val_decimal(&value2);
1081
  if (!(null_value= (args[1]->null_value ||
1082 1083
                     (my_decimal_sub(E_DEC_FATAL_ERROR, decimal_value, val1,
                                     val2) > 3))))
1084 1085
    return decimal_value;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1086 1087
}

1088

1089
double Item_func_mul::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1090
{
1091
  DBUG_ASSERT(fixed == 1);
1092
  double value= args[0]->val_real() * args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1093
  if ((null_value=args[0]->null_value || args[1]->null_value))
1094
    return 0.0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1095 1096 1097
  return value;
}

1098 1099

longlong Item_func_mul::int_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1100
{
1101
  DBUG_ASSERT(fixed == 1);
1102 1103 1104 1105
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1106 1107 1108
}


1109 1110
/* See Item_func_plus::decimal_op for comments */

1111 1112
my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
{
1113 1114 1115
  my_decimal value1, *val1;
  my_decimal value2, *val2;
  val1= args[0]->val_decimal(&value1);
1116 1117
  if ((null_value= args[0]->null_value))
    return 0;
1118
  val2= args[1]->val_decimal(&value2);
1119
  if (!(null_value= (args[1]->null_value ||
1120 1121
                     (my_decimal_mul(E_DEC_FATAL_ERROR, decimal_value, val1,
                                    val2) > 3))))
1122 1123
    return decimal_value;
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1124 1125 1126
}


1127 1128
void Item_func_mul::result_precision()
{
1129 1130 1131 1132 1133 1134 1135 1136 1137
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE);
  int precision= min(args[0]->decimal_precision() + args[1]->decimal_precision(),
                     DECIMAL_MAX_PRECISION);
  max_length= my_decimal_precision_to_length(precision, decimals,unsigned_flag);
1138 1139 1140 1141
}


double Item_func_div::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1142
{
1143
  DBUG_ASSERT(fixed == 1);
1144 1145
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
1146 1147 1148 1149 1150
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0.0;
  if (val2 == 0.0)
  {
    signal_divide_by_null();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1151
    return 0.0;
1152
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1153 1154 1155
  return value/val2;
}

1156

1157
my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1158
{
1159 1160
  my_decimal value1, *val1;
  my_decimal value2, *val2;
1161
  int err;
1162 1163

  val1= args[0]->val_decimal(&value1);
1164 1165
  if ((null_value= args[0]->null_value))
    return 0;
1166
  val2= args[1]->val_decimal(&value2);
1167 1168
  if ((null_value= args[1]->null_value))
    return 0;
1169 1170 1171 1172 1173 1174
  if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
                           val1, val2, prec_increment)) > 3)
  {
    if (err == E_DEC_DIV_ZERO)
      signal_divide_by_null();
    null_value= 1;
1175
    return 0;
1176
  }
1177
  return decimal_value;
1178 1179 1180 1181 1182
}


void Item_func_div::result_precision()
{
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
  uint precision=min(args[0]->decimal_precision() + prec_increment,
                     DECIMAL_MAX_PRECISION);
  /* Integer operations keep unsigned_flag if one of arguments is unsigned */
  if (result_type() == INT_RESULT)
    unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
  else
    unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
  decimals= min(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
  max_length= my_decimal_precision_to_length(precision, decimals,
                                             unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1193 1194
}

1195

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1196 1197
void Item_func_div::fix_length_and_dec()
{
1198
  DBUG_ENTER("Item_func_div::fix_length_and_dec");
1199
  prec_increment= current_thd->variables.div_precincrement;
1200
  Item_num_op::fix_length_and_dec();
1201
  switch(hybrid_type) {
1202 1203
  case REAL_RESULT:
  {
1204
    decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment;
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1224 1225
}

1226 1227 1228 1229

/* Integer division */
longlong Item_func_int_div::val_int()
{
1230
  DBUG_ASSERT(fixed == 1);
1231 1232
  longlong value=args[0]->val_int();
  longlong val2=args[1]->val_int();
1233
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
1234 1235 1236 1237
    return 0;
  if (val2 == 0)
  {
    signal_divide_by_null();
1238
    return 0;
1239
  }
1240 1241 1242
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
1243 1244 1245 1246 1247 1248 1249
}


void Item_func_int_div::fix_length_and_dec()
{
  max_length=args[0]->max_length - args[0]->decimals;
  maybe_null=1;
1250
  unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
1251 1252 1253
}


1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
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()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1270
{
1271
  DBUG_ASSERT(fixed == 1);
1272 1273
  double value= args[0]->val_real();
  double val2=  args[1]->val_real();
1274
  if ((null_value= args[0]->null_value || args[1]->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1275
    return 0.0; /* purecov: inspected */
1276 1277 1278 1279 1280
  if (val2 == 0.0)
  {
    signal_divide_by_null();
    return 0.0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1281 1282 1283
  return fmod(value,val2);
}

1284 1285

my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1286
{
1287 1288 1289 1290
  my_decimal value1, *val1;
  my_decimal value2, *val2;

  val1= args[0]->val_decimal(&value1);
1291 1292
  if ((null_value= args[0]->null_value))
    return 0;
1293
  val2= args[1]->val_decimal(&value2);
1294 1295 1296
  if ((null_value= args[1]->null_value))
    return 0;
  switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
1297
                         val1, val2)) {
1298 1299 1300 1301
  case E_DEC_TRUNCATED:
  case E_DEC_OK:
    return decimal_value;
  case E_DEC_DIV_ZERO:
1302
    signal_divide_by_null();
1303
  default:
1304
    null_value= 1;
1305 1306
    return 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1307 1308
}

1309 1310

void Item_func_mod::result_precision()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1311
{
1312 1313
  decimals= max(args[0]->decimals, args[1]->decimals);
  max_length= max(args[0]->max_length, args[1]->max_length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1314 1315 1316
}


1317
double Item_func_neg::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1318
{
1319
  double value= args[0]->val_real();
1320
  null_value= args[0]->null_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1321 1322 1323
  return -value;
}

1324

1325
longlong Item_func_neg::int_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1326
{
1327 1328
  longlong value= args[0]->val_int();
  null_value= args[0]->null_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1329 1330 1331
  return -value;
}

1332

1333
my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1334
{
1335 1336 1337 1338 1339
  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);
1340
    return decimal_value;
1341
  }
1342
  return 0;
1343 1344
}

1345

1346
void Item_func_neg::fix_num_length_and_dec()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1347
{
1348 1349 1350
  decimals= args[0]->decimals;
  /* 1 add because sign can appear */
  max_length= args[0]->max_length + 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1351 1352
}

1353

1354
void Item_func_neg::fix_length_and_dec()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1355
{
1356
  DBUG_ENTER("Item_func_neg::fix_length_and_dec");
1357
  Item_func_num1::fix_length_and_dec();
1358 1359 1360 1361

  /*
    If this is in integer context keep the context as integer if possible
    (This is how multiplication and other integer functions works)
1362 1363
    Use val() to get value as arg_type doesn't mean that item is
    Item_int or Item_real due to existence of Item_param.
1364
  */
1365 1366
  if (hybrid_type == INT_RESULT &&
      args[0]->type() == INT_ITEM &&
1367
      ((ulonglong) args[0]->val_int() >= (ulonglong) LONGLONG_MIN))
1368 1369
  {
    /*
1370 1371
      Ensure that result is converted to DECIMAL, as longlong can't hold
      the negated number
1372
    */
1373 1374
    hybrid_type= DECIMAL_RESULT;
    DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
1375
  }
1376
  unsigned_flag= 0;
1377
  DBUG_VOID_RETURN;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1378 1379
}

1380

1381
double Item_func_abs::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1382
{
1383
  double value= args[0]->val_real();
1384
  null_value= args[0]->null_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1385 1386 1387
  return fabs(value);
}

1388

1389
longlong Item_func_abs::int_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1390
{
1391 1392
  longlong value= args[0]->val_int();
  null_value= args[0]->null_value;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1393 1394 1395
  return value >= 0 ? value : -value;
}

1396

1397
my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1398
{
1399 1400
  my_decimal val, *value= args[0]->val_decimal(&val);
  if (!(null_value= args[0]->null_value))
1401
  {
1402 1403 1404
    my_decimal2decimal(value, decimal_value);
    if (decimal_value->sign())
      my_decimal_neg(decimal_value);
1405
    return decimal_value;
1406
  }
1407
  return 0;
1408 1409 1410 1411 1412 1413
}


void Item_func_abs::fix_length_and_dec()
{
  Item_func_num1::fix_length_and_dec();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1414 1415
}

1416

1417
/* Gateway to natural LOG function */
1418
double Item_func_ln::val_real()
1419
{
1420
  DBUG_ASSERT(fixed == 1);
1421
  double value= args[0]->val_real();
1422
  if ((null_value= args[0]->null_value))
1423
    return 0.0;
1424
  if (value <= 0.0)
1425 1426
  {
    signal_divide_by_null();
1427
    return 0.0;
1428
  }
1429 1430 1431 1432 1433 1434 1435 1436
  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.
*/ 
1437
double Item_func_log::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1438
{
1439
  DBUG_ASSERT(fixed == 1);
1440
  double value= args[0]->val_real();
1441
  if ((null_value= args[0]->null_value))
1442
    return 0.0;
1443
  if (value <= 0.0)
1444 1445 1446 1447
  {
    signal_divide_by_null();
    return 0.0;
  }
1448 1449
  if (arg_count == 2)
  {
1450
    double value2= args[1]->val_real();
1451
    if ((null_value= args[1]->null_value))
1452
      return 0.0;
1453
    if (value2 <= 0.0 || value == 1.0)
1454 1455 1456 1457
    {
      signal_divide_by_null();
      return 0.0;
    }
1458 1459
    return log(value2) / log(value);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1460 1461 1462
  return log(value);
}

1463
double Item_func_log2::val_real()
1464
{
1465
  DBUG_ASSERT(fixed == 1);
1466
  double value= args[0]->val_real();
1467 1468

  if ((null_value=args[0]->null_value))
1469
    return 0.0;
1470
  if (value <= 0.0)
1471 1472 1473 1474
  {
    signal_divide_by_null();
    return 0.0;
  }
1475
  return log(value) / M_LN2;
1476 1477
}

1478
double Item_func_log10::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479
{
1480
  DBUG_ASSERT(fixed == 1);
1481
  double value= args[0]->val_real();
1482
  if ((null_value= args[0]->null_value))
1483
    return 0.0;
1484
  if (value <= 0.0)
1485 1486 1487 1488
  {
    signal_divide_by_null();
    return 0.0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1489 1490 1491
  return log10(value);
}

1492
double Item_func_exp::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1493
{
1494
  DBUG_ASSERT(fixed == 1);
1495
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1496 1497 1498 1499 1500
  if ((null_value=args[0]->null_value))
    return 0.0; /* purecov: inspected */
  return exp(value);
}

1501
double Item_func_sqrt::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1502
{
1503
  DBUG_ASSERT(fixed == 1);
1504
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1505 1506 1507 1508 1509
  if ((null_value=(args[0]->null_value || value < 0)))
    return 0.0; /* purecov: inspected */
  return sqrt(value);
}

1510
double Item_func_pow::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1511
{
1512
  DBUG_ASSERT(fixed == 1);
1513 1514
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1515 1516 1517 1518 1519 1520 1521
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
    return 0.0; /* purecov: inspected */
  return pow(value,val2);
}

// Trigonometric functions

1522
double Item_func_acos::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1523
{
1524
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1525
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1526
  volatile double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1527 1528 1529 1530 1531
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(acos(value));
}

1532
double Item_func_asin::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1533
{
1534
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1535
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1536
  volatile double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1537 1538 1539 1540 1541
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(asin(value));
}

1542
double Item_func_atan::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1543
{
1544
  DBUG_ASSERT(fixed == 1);
1545
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1546 1547 1548 1549
  if ((null_value=args[0]->null_value))
    return 0.0;
  if (arg_count == 2)
  {
1550
    double val2= args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1551 1552 1553 1554 1555 1556 1557
    if ((null_value=args[1]->null_value))
      return 0.0;
    return fix_result(atan2(value,val2));
  }
  return fix_result(atan(value));
}

1558
double Item_func_cos::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559
{
1560
  DBUG_ASSERT(fixed == 1);
1561
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1562 1563 1564 1565 1566
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(cos(value));
}

1567
double Item_func_sin::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1568
{
1569
  DBUG_ASSERT(fixed == 1);
1570
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1571 1572 1573 1574 1575
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(sin(value));
}

1576
double Item_func_tan::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1577
{
1578
  DBUG_ASSERT(fixed == 1);
1579
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
  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()
{
1591
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
  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()
{
1606
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
  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()
{
1622
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
  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;
}

1640
void Item_func_int_val::fix_num_length_and_dec()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1641
{
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
  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()
{
1694 1695 1696 1697 1698 1699 1700 1701 1702
  longlong result;
  switch (args[0]->result_type()) {
  case INT_RESULT:
    result= args[0]->val_int();
    null_value= args[0]->null_value;
    break;
  case DECIMAL_RESULT:
  {
    my_decimal dec_buf, *dec;
1703
    if ((dec= Item_func_ceiling::decimal_op(&dec_buf)))
1704 1705 1706 1707 1708 1709
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
    else
      result= 0;
    break;
  }
  default:
1710
    result= (longlong)Item_func_ceiling::real_op();
1711 1712
  };
  return result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1713 1714
}

1715 1716

double Item_func_ceiling::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1717
{
1718 1719 1720 1721
  /*
    the volatile's for BUG #3051 to calm optimizer down (because of gcc's
    bug)
  */
1722
  volatile double value= args[0]->val_real();
1723 1724 1725 1726 1727 1728
  null_value= args[0]->null_value;
  return ceil(value);
}


my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1729
{
1730
  my_decimal val, *value= args[0]->val_decimal(&val);
1731 1732 1733 1734 1735
  if (!(null_value= (args[0]->null_value ||
                     my_decimal_ceiling(E_DEC_FATAL_ERROR, value,
                                        decimal_value) > 1)))
    return decimal_value;
  return 0;
1736 1737 1738 1739 1740
}


longlong Item_func_floor::int_op()
{
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
  longlong result;
  switch (args[0]->result_type()) {
  case INT_RESULT:
    result= args[0]->val_int();
    null_value= args[0]->null_value;
    break;
  case DECIMAL_RESULT:
  {
    my_decimal dec_buf, *dec;
    if ((dec= Item_func_floor::decimal_op(&dec_buf)))
      my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
    else
      result= 0;
    break;
  }
  default:
    result= (longlong)Item_func_floor::real_op();
  };
  return result;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1760 1761
}

1762 1763

double Item_func_floor::real_op()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1764
{
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  /*
    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);
1778 1779 1780 1781 1782
  if (!(null_value= (args[0]->null_value ||
                     my_decimal_floor(E_DEC_FATAL_ERROR, value,
                                      decimal_value) > 1)))
    return decimal_value;
  return 0;
1783 1784 1785
}


1786
void Item_func_round::fix_length_and_dec()
1787
{
1788 1789
  unsigned_flag= args[0]->unsigned_flag;
  if (!args[1]->const_item())
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1790
  {
1791 1792 1793 1794 1795 1796
    max_length= args[0]->max_length;
    decimals= args[0]->decimals;
    hybrid_type= REAL_RESULT;
    return;
  }
  
1797
  int decimals_to_set= max((int)args[1]->val_int(), 0);
1798 1799 1800 1801 1802 1803 1804 1805
  if (args[0]->decimals == NOT_FIXED_DEC)
  {
    max_length= args[0]->max_length;
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
    hybrid_type= REAL_RESULT;
    return;
  }
  
1806
  switch (args[0]->result_type()) {
1807 1808 1809 1810 1811 1812 1813
  case REAL_RESULT:
  case STRING_RESULT:
    hybrid_type= REAL_RESULT;
    decimals= min(decimals_to_set, NOT_FIXED_DEC);
    max_length= float_length(decimals);
    break;
  case INT_RESULT:
1814
    if (!decimals_to_set &&
1815
        (truncate || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS)))
1816
    {
1817 1818
      int length_can_increase= test(!truncate && (args[1]->val_int() < 0));
      max_length= args[0]->max_length + length_can_increase;
1819 1820 1821 1822 1823
      /* Here we can keep INT_RESULT */
      hybrid_type= INT_RESULT;
      decimals= 0;
      break;
    }
1824
    /* fall through */
1825 1826 1827 1828 1829
  case DECIMAL_RESULT:
  {
    hybrid_type= DECIMAL_RESULT;
    int decimals_delta= args[0]->decimals - decimals_to_set;
    int precision= args[0]->decimal_precision();
1830 1831 1832 1833
    int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1;

    precision-= decimals_delta - length_increase;
    decimals= decimals_to_set;
1834
    max_length= my_decimal_precision_to_length(precision, decimals,
1835
                                               unsigned_flag);
1836 1837 1838 1839
    break;
  }
  default:
    DBUG_ASSERT(0); /* This result type isn't handled */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1840 1841 1842
  }
}

1843
double my_double_round(double value, int dec, bool truncate)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1844
{
1845
  double tmp;
1846
  uint abs_dec= abs(dec);
1847 1848 1849 1850 1851
  /*
    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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1852

1853 1854
  tmp=(abs_dec < array_elements(log_10) ?
       log_10[abs_dec] : pow(10.0,(double) abs_dec));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1855 1856

  if (truncate)
1857 1858
  {
    if (value >= 0)
1859
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
1860
    else
1861
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
1862
  }
1863 1864 1865
  else
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
  return tmp2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1866 1867 1868
}


1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
double Item_func_round::real_op()
{
  double value= args[0]->val_real();
  int dec= (int) args[1]->val_int();

  if (!(null_value= args[0]->null_value || args[1]->null_value))
    return my_double_round(value, dec, truncate);

  return 0.0;
}


1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
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;
gunnar@mysql.com's avatar
gunnar@mysql.com committed
1893 1894 1895 1896 1897 1898 1899
  longlong tmp;
  
  if(abs_dec >= array_elements(log_10_int))
    return 0;
  
  tmp= log_10_int[abs_dec];
  
1900 1901 1902
  if (truncate)
  {
    if (unsigned_flag)
gunnar@mysql.com's avatar
gunnar@mysql.com committed
1903
      value= (ulonglong(value)/tmp)*tmp;
1904
    else
gunnar@mysql.com's avatar
gunnar@mysql.com committed
1905
      value= (value/tmp)*tmp;
1906 1907
  }
  else
gunnar@mysql.com's avatar
gunnar@mysql.com committed
1908 1909 1910 1911 1912 1913 1914 1915 1916
  {
    if (unsigned_flag)
      value= ((ulonglong(value)+(tmp>>1))/tmp)*tmp;
    else if ( value >= 0)
      value= ((value+(tmp>>1))/tmp)*tmp;
    else
      value= ((value-(tmp>>1))/tmp)*tmp;
  }
  return value;
1917 1918 1919 1920 1921 1922 1923 1924
}


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)
1925 1926 1927
  {
    decimals= min(dec, DECIMAL_MAX_SCALE); // to get correct output
  }
1928 1929 1930 1931 1932
  if (!(null_value= (args[0]->null_value || args[1]->null_value ||
                     my_decimal_round(E_DEC_FATAL_ERROR, value, dec, truncate,
                                      decimal_value) > 1)))
    return decimal_value;
  return 0;
1933 1934 1935
}


1936
bool Item_func_rand::fix_fields(THD *thd,Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1937
{
1938
  if (Item_real_func::fix_fields(thd, ref))
1939
    return TRUE;
1940
  used_tables_cache|= RAND_TABLE_BIT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1941 1942
  if (arg_count)
  {					// Only use argument once in query
1943 1944 1945 1946 1947
    if (!args[0]->const_during_execution())
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "RAND");
      return TRUE;
    }
1948
    /*
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1949
      Allocate rand structure once: we must use thd->stmt_arena
1950 1951
      to create rand in proper mem_root if it's a prepared statement or
      stored procedure.
1952 1953 1954

      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.
1955 1956
    */
    if (!rand && !(rand= (struct rand_struct*)
konstantin@mysql.com's avatar
konstantin@mysql.com committed
1957
                   thd->stmt_arena->alloc(sizeof(*rand))))
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
      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));
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1973
  }
1974
  else
nick@mysql.com's avatar
nick@mysql.com committed
1975
  {
1976 1977 1978 1979 1980
    /*
      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
    */
1981 1982 1983 1984 1985 1986
    if (!thd->rand_used)
    {
      thd->rand_used= 1;
      thd->rand_saved_seed1= thd->rand.seed1;
      thd->rand_saved_seed2= thd->rand.seed2;
    }
1987
    rand= &thd->rand;
nick@mysql.com's avatar
nick@mysql.com committed
1988
  }
1989
  return FALSE;
1990 1991
}

1992 1993 1994 1995 1996 1997
void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

1998

1999
double Item_func_rand::val_real()
2000
{
2001
  DBUG_ASSERT(fixed == 1);
2002
  return my_rnd(rand);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2003 2004 2005 2006
}

longlong Item_func_sign::val_int()
{
2007
  DBUG_ASSERT(fixed == 1);
2008
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2009 2010 2011 2012 2013
  null_value=args[0]->null_value;
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
}


2014
double Item_func_units::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2015
{
2016
  DBUG_ASSERT(fixed == 1);
2017
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2018 2019 2020 2021 2022 2023 2024 2025
  if ((null_value=args[0]->null_value))
    return 0;
  return value*mul+add;
}


void Item_func_min_max::fix_length_and_dec()
{
2026
  int max_int_part=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2027 2028
  decimals=0;
  max_length=0;
2029
  maybe_null=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2030
  cmp_type=args[0]->result_type();
2031

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2032 2033
  for (uint i=0 ; i < arg_count ; i++)
  {
2034 2035
    set_if_bigger(max_length, args[i]->max_length);
    set_if_bigger(decimals, args[i]->decimals);
2036
    set_if_bigger(max_int_part, args[i]->decimal_int_part());
2037 2038
    if (args[i]->maybe_null)
      maybe_null=1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2039 2040
    cmp_type=item_cmp_type(cmp_type,args[i]->result_type());
  }
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2041
  if (cmp_type == STRING_RESULT)
bar@mysql.com's avatar
bar@mysql.com committed
2042
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV);
2043 2044 2045
  else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT))
    max_length= my_decimal_precision_to_length(max_int_part+decimals, decimals,
                                            unsigned_flag);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2046 2047 2048 2049 2050
}


String *Item_func_min_max::val_str(String *str)
{
2051
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2052 2053 2054 2055 2056 2057
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
2058
    if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
2059
      str->set(nr,&my_charset_bin);
2060
    else
monty@mysql.com's avatar
monty@mysql.com committed
2061
      str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2062 2063
    return str;
  }
2064 2065 2066 2067 2068 2069 2070 2071
  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;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2072 2073
  case REAL_RESULT:
  {
2074
    double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2075 2076
    if (null_value)
      return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
2077
    str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2078 2079 2080 2081 2082 2083 2084 2085
    return str;
  }
  case STRING_RESULT:
  {
    String *res;
    LINT_INIT(res);
    for (uint i=0; i < arg_count ; i++)
    {
2086
      if (i == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2087 2088 2089 2090 2091 2092 2093
	res=args[i]->val_str(str);
      else
      {
	String *res2;
	res2= args[i]->val_str(res == str ? &tmp_value : str);
	if (res2)
	{
2094
	  int cmp= sortcmp(res,res2,collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2095 2096 2097 2098
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
2099
      if ((null_value= args[i]->null_value))
2100
        return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2101
    }
2102
    res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2103 2104
    return res;
  }
2105
  case ROW_RESULT:
2106
  default:
2107
    // This case should never be chosen
2108 2109
    DBUG_ASSERT(0);
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2110 2111 2112 2113 2114
  }
  return 0;					// Keep compiler happy
}


2115
double Item_func_min_max::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2116
{
2117
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2118 2119 2120
  double value=0.0;
  for (uint i=0; i < arg_count ; i++)
  {
2121
    if (i == 0)
2122
      value= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2123 2124
    else
    {
2125
      double tmp= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2126 2127 2128
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
2129 2130
    if ((null_value= args[i]->null_value))
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2131 2132 2133 2134 2135 2136 2137
  }
  return value;
}


longlong Item_func_min_max::val_int()
{
2138
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2139 2140 2141
  longlong value=0;
  for (uint i=0; i < arg_count ; i++)
  {
2142
    if (i == 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2143 2144 2145 2146 2147 2148 2149
      value=args[i]->val_int();
    else
    {
      longlong tmp=args[i]->val_int();
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
2150 2151
    if ((null_value= args[i]->null_value))
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2152 2153 2154 2155
  }
  return value;
}

2156 2157 2158 2159

my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
{
  DBUG_ASSERT(fixed == 1);
2160 2161 2162
  my_decimal tmp_buf, *tmp, *res;
  LINT_INIT(res);

2163 2164
  for (uint i=0; i < arg_count ; i++)
  {
2165
    if (i == 0)
2166 2167 2168
      res= args[i]->val_decimal(dec);
    else
    {
2169 2170
      tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
      if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
2171 2172 2173
      {
        if (tmp == &tmp_buf)
        {
2174
          /* Move value out of tmp_buf as this will be reused on next loop */
2175 2176 2177 2178 2179 2180 2181
          my_decimal2decimal(tmp, dec);
          res= dec;
        }
        else
          res= tmp;
      }
    }
2182
    if ((null_value= args[i]->null_value))
2183 2184
    {
      res= 0;
2185
      break;
2186
    }
2187 2188 2189 2190 2191
  }
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2192 2193
longlong Item_func_length::val_int()
{
2194
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) res->length();
}

2205

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2206 2207
longlong Item_func_char_length::val_int()
{
2208
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2209 2210 2211 2212 2213 2214 2215
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
2216
  return (longlong) res->numchars();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2217 2218
}

2219

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2220 2221
longlong Item_func_coercibility::val_int()
{
2222
  DBUG_ASSERT(fixed == 1);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2223
  null_value= 0;
2224
  return (longlong) args[0]->collation.derivation;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2225
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2226

2227

2228 2229 2230
void Item_func_locate::fix_length_and_dec()
{
  maybe_null=0; max_length=11;
bar@mysql.com's avatar
bar@mysql.com committed
2231
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
2232 2233
}

2234

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2235 2236
longlong Item_func_locate::val_int()
{
2237
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2238 2239 2240 2241 2242 2243 2244 2245
  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;
2246 2247
  uint start=0;
  uint start0=0;
2248
  my_match_t match;
2249

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2250 2251
  if (arg_count == 3)
  {
2252 2253 2254
    start0= start =(uint) args[2]->val_int()-1;
    start=a->charpos(start);
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2255 2256 2257
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
2258

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2259 2260
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
2261
  
2262
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
2263
                                            a->ptr()+start, a->length()-start,
2264 2265 2266 2267
                                            b->ptr(), b->length(),
                                            &match, 1))
    return 0;
  return (longlong) match.mblen + start0 + 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2268 2269 2270
}


2271 2272
void Item_func_locate::print(String *str)
{
2273
  str->append(STRING_WITH_LEN("locate("));
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
  args[1]->print(str);
  str->append(',');
  args[0]->print(str);
  if (arg_count == 3)
  {
    str->append(',');
    args[2]->print(str);
  }
  str->append(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2286 2287
longlong Item_func_field::val_int()
{
2288
  DBUG_ASSERT(fixed == 1);
2289

2290 2291 2292
  if (cmp_type == STRING_RESULT)
  {
    String *field;
2293 2294
    if (!(field= args[0]->val_str(&value)))
      return 0;
2295
    for (uint i=1 ; i < arg_count ; i++)
2296 2297
    {
      String *tmp_value=args[i]->val_str(&tmp);
bar@bar.mysql.r18.ru's avatar
Fix:  
bar@bar.mysql.r18.ru committed
2298
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
2299
        return (longlong) (i);
2300 2301 2302 2303
    }
  }
  else if (cmp_type == INT_RESULT)
  {
2304
    longlong val= args[0]->val_int();
serg@serg.mylan's avatar
serg@serg.mylan committed
2305 2306
    if (args[0]->null_value)
      return 0;
2307
    for (uint i=1; i < arg_count ; i++)
2308
    {
2309
      if (val == args[i]->val_int() && !args[i]->null_value)
2310
        return (longlong) (i);
2311 2312
    }
  }
2313 2314 2315 2316
  else if (cmp_type == DECIMAL_RESULT)
  {
    my_decimal dec_arg_buf, *dec_arg,
               dec_buf, *dec= args[0]->val_decimal(&dec_buf);
serg@serg.mylan's avatar
serg@serg.mylan committed
2317 2318
    if (args[0]->null_value)
      return 0;
2319 2320 2321
    for (uint i=1; i < arg_count; i++)
    {
      dec_arg= args[i]->val_decimal(&dec_arg_buf);
monty@mysql.com's avatar
monty@mysql.com committed
2322
      if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec))
2323 2324 2325
        return (longlong) (i);
    }
  }
2326
  else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2327
  {
2328
    double val= args[0]->val_real();
serg@serg.mylan's avatar
serg@serg.mylan committed
2329 2330
    if (args[0]->null_value)
      return 0;
2331
    for (uint i=1; i < arg_count ; i++)
2332
    {
monty@mysql.com's avatar
monty@mysql.com committed
2333
      if (val == args[i]->val_real() && !args[i]->null_value)
2334
        return (longlong) (i);
2335
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2336 2337 2338 2339
  }
  return 0;
}

2340

2341 2342 2343
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
2344 2345
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
2346 2347
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
bar@mysql.com's avatar
bar@mysql.com committed
2348
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV);
2349
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2350

2351

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2352 2353
longlong Item_func_ascii::val_int()
{
2354
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
  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()
{
2367
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2368 2369 2370 2371 2372 2373 2374 2375 2376
  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
2377
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2378 2379
  {
    register const char *str=res->ptr();
2380
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2381 2382
    if (!l)
      return (longlong)((uchar) *str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
    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)
      {
2407 2408
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2409 2410 2411 2412 2413 2414
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
2415
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2416 2417 2418 2419 2420 2421
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
2422
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445
  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)
  {
2446 2447 2448 2449 2450 2451 2452 2453 2454
    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)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2455
    {
2456 2457 2458
      int symbol_len;
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
                                       (uchar*) real_end)) > 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2459
      {
2460 2461
        const char *substr_end= str_end + symbol_len;
        bool is_last_item= (substr_end == real_end);
2462 2463
        bool is_separator= (wc == (my_wc_t) separator);
        if (is_separator || is_last_item)
2464 2465
        {
          position++;
2466
          if (is_last_item && !is_separator)
2467 2468 2469 2470 2471 2472 2473 2474 2475
            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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2476
      }
serg@serg.mylan's avatar
serg@serg.mylan committed
2477 2478
      else if (str_end - str_begin == 0 &&
               find_str_len == 0 &&
2479 2480 2481
               wc == (my_wc_t) separator)
        return (longlong) ++position;
      else
serg@serg.mylan's avatar
serg@serg.mylan committed
2482
        return LL(0);
2483
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2484 2485 2486 2487 2488 2489
  }
  return 0;
}

longlong Item_func_bit_count::val_int()
{
2490
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2491
  ulonglong value= (ulonglong) args[0]->val_int();
2492
  if ((null_value= args[0]->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2493
    return 0; /* purecov: inspected */
2494
  return (longlong) my_count_bits(value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2495 2496 2497 2498 2499 2500
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
2501
** Rewritten by monty.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2502 2503 2504 2505
****************************************************************************/

#ifdef HAVE_DLOPEN

2506
void udf_handler::cleanup()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2507
{
2508
  if (!not_original)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2509
  {
2510
    if (initialized)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2511
    {
2512 2513 2514 2515 2516 2517 2518
      if (u_d->func_deinit != NULL)
      {
        void (*deinit)(UDF_INIT *) = (void (*)(UDF_INIT*))
        u_d->func_deinit;
        (*deinit)(&initid);
      }
      free_udf(u_d);
2519
      initialized= FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2520
    }
2521 2522
    if (buffers)				// Because of bug in ecc
      delete [] buffers;
2523
    buffers= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2524 2525 2526 2527 2528
  }
}


bool
2529
udf_handler::fix_fields(THD *thd, Item_result_field *func,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2530 2531
			uint arg_count, Item **arguments)
{
2532 2533 2534
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2535 2536
  DBUG_ENTER("Item_udf_func::fix_fields");

2537
  if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
2538
    DBUG_RETURN(TRUE);				// Fatal error flag is set!
2539

2540
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2541 2542 2543

  if (!tmp_udf)
  {
2544
    my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
2545
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2546 2547 2548 2549 2550
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
2551
  func->maybe_null=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
  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);
2562
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2563 2564 2565 2566 2567 2568 2569
    }
    uint i;
    Item **arg,**arg_end;
    for (i=0, arg=arguments, arg_end=arguments+arg_count;
	 arg != arg_end ;
	 arg++,i++)
    {
2570
      if (!(*arg)->fixed &&
2571
          (*arg)->fix_fields(thd, arg))
2572
	DBUG_RETURN(1);
2573
      // we can't assign 'item' before, because fix_fields() can change arg
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2574
      Item *item= *arg;
2575
      if (item->check_cols(1))
2576
	DBUG_RETURN(TRUE);
2577 2578 2579 2580 2581 2582 2583 2584 2585
      /*
	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
2586
        the particular user defined function.
2587
      */
2588 2589
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
2590
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2591
	func->maybe_null=1;
2592 2593 2594 2595
      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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2596
    }
2597
    //TODO: why all following memory is not allocated with 1 call of sql_alloc?
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2598 2599
    if (!(buffers=new String[arg_count]) ||
	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
2600 2601 2602 2603 2604 2605 2606
	!(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))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2607 2608
    {
      free_udf(u_d);
2609
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
    }
  }
  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;
2625 2626 2627 2628
      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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2629 2630 2631 2632

      switch(arguments[i]->type()) {
      case Item::STRING_ITEM:			// Constant string !
      {
2633
	String *res=arguments[i]->val_str(&buffers[i]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
	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:
2648
	*((double*) to)= arguments[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(double));
	}
	break;
      default:					// Skip these
	break;
      }
    }
2659
    thd->net.last_error[0]=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2660 2661 2662 2663 2664
    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)))
    {
2665 2666
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
               u_d->name.str, thd->net.last_error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2667
      free_udf(u_d);
2668
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2669 2670 2671 2672
    }
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
    func->maybe_null=initid.maybe_null;
    const_item_cache=initid.const_item;
2673
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2674 2675 2676 2677
  }
  initialized=1;
  if (error)
  {
2678 2679
    my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
             u_d->name.str, ER(ER_UNKNOWN_ERROR));
2680
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2681
  }
2682
  DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
}


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:
2697
    case DECIMAL_RESULT:
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
      {
	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:
2716
      *((double*) to)= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2717 2718 2719 2720 2721 2722
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(double));
      }
      break;
2723
    case ROW_RESULT:
2724
    default:
2725
      // This case should never be chosen
2726
      DBUG_ASSERT(0);
2727
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2728 2729 2730 2731 2732 2733 2734 2735 2736
    }
  }
  return 0;
}

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

String *udf_handler::val_str(String *str,String *save_str)
{
2737
  uchar is_null_tmp=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
  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;
    }
  }
2754 2755 2756
  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
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2757 2758 2759 2760 2761 2762 2763 2764
  {
    return 0;
  }
  if (res == str->ptr())
  {
    str->length(res_length);
    return str;
  }
2765
  save_str->set(res, res_length, str->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2766 2767 2768 2769
  return save_str;
}


2770 2771 2772 2773
/*
  For the moment, UDF functions are returning DECIMAL values as strings
*/

2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
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;
  }
2794 2795
  end= res+ res_length;
  str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
2796 2797 2798
  return dec_buf;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2799

2800 2801 2802 2803 2804 2805
void Item_udf_func::cleanup()
{
  udf.cleanup();
  Item_func::cleanup();
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2806

2807
double Item_func_udf_float::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2808
{
2809
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2810 2811 2812 2813 2814 2815 2816 2817 2818
  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)
{
2819
  DBUG_ASSERT(fixed == 1);
2820
  double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2821 2822
  if (null_value)
    return 0;					/* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
2823
  str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2824 2825 2826 2827 2828 2829
  return str;
}


longlong Item_func_udf_int::val_int()
{
2830
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2831 2832 2833 2834 2835 2836 2837
  DBUG_ENTER("Item_func_udf_int::val_int");
  DBUG_RETURN(udf.val_int(&null_value));
}


String *Item_func_udf_int::val_str(String *str)
{
2838
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2839 2840 2841
  longlong nr=val_int();
  if (null_value)
    return 0;
2842
  if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
2843
    str->set(nr,&my_charset_bin);
2844
  else
monty@mysql.com's avatar
monty@mysql.com committed
2845
    str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2846 2847 2848
  return str;
}

2849 2850 2851 2852

longlong Item_func_udf_decimal::val_int()
{
  my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
2853
  longlong result;
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
  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);
2864
  double result;
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
  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();
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
/* 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)
{
2915
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2916 2917 2918 2919 2920
  String *res=udf.val_str(str,&str_value);
  null_value = !res;
  return res;
}

2921 2922

/*
2923 2924
   This has to come last in the udf_handler methods, or C for AIX
   version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.)
2925 2926 2927 2928
 */

udf_handler::~udf_handler()
{
2929 2930
  /* Everything should be properly cleaned up by this moment. */
  DBUG_ASSERT(not_original || !(initialized || buffers));
2931 2932
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
#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;

2944
class User_level_lock
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2945 2946 2947 2948 2949 2950 2951 2952 2953
{
  char *key;
  uint key_length;

public:
  int count;
  bool locked;
  pthread_cond_t cond;
  pthread_t thread;
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
2954
  ulong thread_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2955

2956
  User_level_lock(const char *key_arg,uint length, ulong id) 
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
2957
    :key_length(length),count(1),locked(1), thread_id(id)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2958 2959 2960 2961 2962
  {
    key=(char*) my_memdup((byte*) key_arg,length,MYF(0));
    pthread_cond_init(&cond,NULL);
    if (key)
    {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2963
      if (my_hash_insert(&hash_user_locks,(byte*) this))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2964 2965 2966 2967 2968 2969
      {
	my_free((gptr) key,MYF(0));
	key=0;
      }
    }
  }
2970
  ~User_level_lock()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2971 2972 2973 2974 2975 2976 2977 2978 2979
  {
    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; }
2980 2981 2982
  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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2983 2984
};

2985
char *ull_get_key(const User_level_lock *ull, uint *length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2986 2987 2988 2989 2990 2991
		  my_bool not_used __attribute__((unused)))
{
  *length=(uint) ull->key_length;
  return (char*) ull->key;
}

2992 2993 2994

static bool item_user_lock_inited= 0;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2995 2996
void item_user_lock_init(void)
{
2997
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
2998 2999
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
3000
  item_user_lock_inited= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3001 3002 3003 3004
}

void item_user_lock_free(void)
{
3005 3006 3007 3008 3009 3010
  if (item_user_lock_inited)
  {
    item_user_lock_inited= 0;
    hash_free(&hash_user_locks);
    pthread_mutex_destroy(&LOCK_user_locks);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3011 3012
}

3013
void item_user_lock_release(User_level_lock *ull)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3014 3015
{
  ull->locked=0;
3016
  ull->thread_id= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3017 3018 3019 3020 3021 3022
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

3023 3024 3025 3026 3027 3028 3029
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

longlong Item_master_pos_wait::val_int()
{
3030
  DBUG_ASSERT(fixed == 1);
3031 3032
  THD* thd = current_thd;
  String *log_name = args[0]->val_str(&value);
3033
  int event_count= 0;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3034

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3035 3036 3037 3038 3039 3040
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3041
  longlong pos = (ulong)args[1]->val_int();
3042
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
3043
#ifdef HAVE_REPLICATION
3044
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
3045 3046 3047 3048
  {
    null_value = 1;
    event_count=0;
  }
3049
#endif
3050 3051 3052
  return event_count;
}

3053 3054 3055 3056
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
3057
  User_level_lock* ull;
3058
  struct timespec abstime;
3059
  int lock_name_len;
3060 3061 3062 3063 3064 3065 3066 3067 3068
  lock_name_len=strlen(lock_name);
  pthread_mutex_lock(&LOCK_user_locks);

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

3069 3070 3071 3072 3073
  /*
    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
3074
  */
3075
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, lock_name,
3076 3077 3078 3079 3080 3081 3082
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

3083 3084 3085 3086
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
3087 3088 3089 3090
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

3091
  set_timespec(abstime,lock_timeout);
monty@mysql.com's avatar
monty@mysql.com committed
3092 3093 3094 3095 3096 3097 3098
  while (ull->locked && !thd->killed)
  {
    int error= pthread_cond_timedwait(&ull->cond, &LOCK_user_locks, &abstime);
    if (error == ETIMEDOUT || error == ETIME)
      break;
  }

3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
  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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3127 3128 3129 3130 3131 3132 3133 3134 3135
/*
  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()
{
3136
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3137 3138 3139 3140
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
3141
  User_level_lock *ull;
monty@mysql.com's avatar
monty@mysql.com committed
3142
  int error;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3143

3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
  /*
    In slave thread no need to get locks, everything is serialized. Anyway
    there is no way to make GET_LOCK() work on slave like it did on master
    (i.e. make it return exactly the same value) because we don't have the
    same other concurrent threads environment. No matter what we return here,
    it's not guaranteed to be same as on master.
  */
  if (thd->slave_thread)
    return 1;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
  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;
  }

3170 3171 3172
  if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks,
                                              (byte*) res->ptr(),
                                              res->length()))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3173
  {
3174
    ull=new User_level_lock(res->ptr(),res->length(), thd->thread_id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
    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++;

3189 3190 3191 3192
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3193 3194 3195 3196
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

3197
  set_timespec(abstime,timeout);
monty@mysql.com's avatar
monty@mysql.com committed
3198 3199 3200 3201 3202 3203 3204 3205 3206
  error= 0;
  while (ull->locked && !thd->killed)
  {
    error= pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime);
    if (error == ETIMEDOUT || error == ETIME)
      break;
    error= 0;
  }

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3207 3208 3209
  if (ull->locked)
  {
    if (!--ull->count)
monty@mysql.com's avatar
monty@mysql.com committed
3210 3211
    {
      DBUG_ASSERT(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3212
      delete ull;				// Should never happen
monty@mysql.com's avatar
monty@mysql.com committed
3213 3214
    }
    if (!error)                                 // Killed (thd->killed != 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3215 3216 3217 3218 3219
    {
      error=1;
      null_value=1;				// Return NULL
    }
  }
monty@mysql.com's avatar
monty@mysql.com committed
3220
  else                                          // We got the lock
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3221 3222 3223
  {
    ull->locked=1;
    ull->thread=thd->real_id;
3224
    ull->thread_id= thd->thread_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
    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;
}


/*
3241 3242 3243 3244 3245
  Release a user level lock.
  Return:
    1 if lock released
    0 if lock wasn't held
    (SQL) NULL if no such lock
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3246 3247 3248 3249
*/

longlong Item_func_release_lock::val_int()
{
3250
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3251
  String *res=args[0]->val_str(&value);
3252
  User_level_lock *ull;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
  longlong result;
  if (!res || !res->length())
  {
    null_value=1;
    return 0;
  }
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
3263 3264 3265
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
                                             (const byte*) res->ptr(),
                                             res->length()))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
  {
    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;
}


3283
longlong Item_func_last_insert_id::val_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3284
{
3285
  THD *thd= current_thd;
3286
  DBUG_ASSERT(fixed == 1);
3287 3288
  if (arg_count)
  {
3289 3290 3291 3292
    longlong value= args[0]->val_int();
    thd->insert_id(value);
    null_value= args[0]->null_value;
    return value;                       // Avoid side effect of insert_id()
3293
  }
3294 3295
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
  return thd->insert_id();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3296 3297 3298 3299 3300 3301
}

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

longlong Item_func_benchmark::val_int()
{
3302
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3303
  char buff[MAX_FIELD_WIDTH];
3304
  String tmp(buff,sizeof(buff), &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3305 3306 3307 3308 3309 3310
  THD *thd=current_thd;

  for (ulong loop=0 ; loop < loop_count && !thd->killed; loop++)
  {
    switch (args[0]->result_type()) {
    case REAL_RESULT:
3311
      (void) args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3312 3313 3314 3315 3316 3317 3318
      break;
    case INT_RESULT:
      (void) args[0]->val_int();
      break;
    case STRING_RESULT:
      (void) args[0]->val_str(&tmp);
      break;
3319
    case ROW_RESULT:
3320
    default:
3321
      // This case should never be chosen
3322 3323
      DBUG_ASSERT(0);
      return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3324 3325 3326 3327 3328
    }
  }
  return 0;
}

3329

3330 3331
void Item_func_benchmark::print(String *str)
{
3332
  str->append(STRING_WITH_LEN("benchmark("));
3333
  char buffer[20];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3334 3335 3336
  // my_charset_bin is good enough for numbers
  String st(buffer, sizeof(buffer), &my_charset_bin);
  st.set((ulonglong)loop_count, &my_charset_bin);
3337 3338 3339 3340 3341 3342
  str->append(st);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}

monty@mysql.com's avatar
monty@mysql.com committed
3343

3344 3345 3346 3347
/* This function is just used to create tests with time gaps */

longlong Item_func_sleep::val_int()
{
3348 3349 3350
  THD *thd= current_thd;
  struct timespec abstime;
  pthread_cond_t cond;
3351
  int error;
3352

3353
  DBUG_ASSERT(fixed == 1);
3354

3355
  double time= args[0]->val_real();
3356 3357 3358 3359 3360 3361 3362 3363
  set_timespec_nsec(abstime, (ulonglong)(time * ULL(1000000000)));

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

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

monty@mysql.com's avatar
monty@mysql.com committed
3364 3365 3366 3367 3368 3369 3370 3371
  error= 0;
  while (!thd->killed)
  {
    error= pthread_cond_timedwait(&cond, &LOCK_user_locks, &abstime);
    if (error == ETIMEDOUT || error == ETIME)
      break;
    error= 0;
  }
3372 3373 3374 3375 3376 3377 3378 3379 3380

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

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

monty@mysql.com's avatar
monty@mysql.com committed
3381
  return test(!error); 		// Return 1 killed
3382 3383 3384
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
#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;
3406
    entry->update_query_id=0;
3407
    entry->collation.set(NULL, DERIVATION_IMPLICIT);
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
    /*
      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).
    */
3418
    entry->used_query_id=current_thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3419 3420
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
3421
    if (my_hash_insert(hash,(byte*) entry))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3422 3423 3424 3425 3426 3427 3428 3429
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

3430
/*
3431 3432
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
3433
*/
3434

3435
bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3436
{
3437
  DBUG_ASSERT(fixed == 0);
3438
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
3439
  if (Item_func::fix_fields(thd, ref) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3440
      !(entry= get_variable(&thd->user_vars, name, 1)))
3441
    return TRUE;
3442 3443 3444 3445 3446
  /* 
     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).
  */
3447
  entry->update_query_id= thd->query_id;
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
  /*
    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.
  */
3463 3464
  null_item= (args[0]->type() == NULL_ITEM);
  if (!entry->collation.collation || !null_item)
3465 3466
    entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
  collation.set(entry->collation.collation, DERIVATION_IMPLICIT);
3467
  cached_result_type= args[0]->result_type();
3468
  return FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3469 3470 3471 3472 3473 3474 3475 3476 3477
}


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;
3478
  collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3479 3480
}

3481

3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
/*
  Set value to user variable.

  SYNOPSYS
    update_hash()
    entry    - pointer to structure representing variable
    set_null - should we set NULL value ?
    ptr      - pointer to buffer with new value
    length   - length of new value
    type     - type of new value
    cs       - charset info for new value
    dv       - derivation for new value

  RETURN VALUE
    False - success, True - failure
*/

static bool
update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length,
            Item_result type, CHARSET_INFO *cs, Derivation dv)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3502
{
3503
  if (set_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3504 3505 3506 3507
  {
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
    if (entry->value && entry->value != pos)
      my_free(entry->value,MYF(0));
3508 3509
    entry->value= 0;
    entry->length= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3510 3511 3512
  }
  else
  {
3513 3514
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535
    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))))
3536
	  return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3537 3538
      }
    }
3539 3540 3541 3542 3543
    if (type == STRING_RESULT)
    {
      length--;					// Fix length change above
      entry->value[length]= 0;			// Store end \0
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3544
    memcpy(entry->value,ptr,length);
3545 3546
    if (type == DECIMAL_RESULT)
      ((my_decimal*)entry->value)->fix_buffer_pointer();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3547
    entry->length= length;
3548
    entry->collation.set(cs, dv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3549
  }
3550
  entry->type=type;
3551
  return 0;
3552
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3553

3554 3555 3556 3557 3558

bool
Item_func_set_user_var::update_hash(void *ptr, uint length, Item_result type,
                                    CHARSET_INFO *cs, Derivation dv)
{
3559 3560 3561 3562 3563 3564
  /*
    If we set a variable explicitely to NULL then keep the old
    result type of the variable
  */
  if ((null_value= args[0]->null_value) && null_item)
    type= entry->type;                          // Don't change type of item
3565 3566 3567 3568 3569 3570 3571 3572
  if (::update_hash(entry, (null_value= args[0]->null_value),
                    ptr, length, type, cs, dv))
  {
    current_thd->fatal_error();     // Probably end of memory
    null_value= 1;
    return 1;
  }
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3573 3574 3575
}


3576 3577
/* Get the value of a variable as a double */

3578
double user_var_entry::val_real(my_bool *null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3579
{
3580 3581 3582 3583 3584 3585 3586 3587
  if ((*null_value= (value == 0)))
    return 0.0;

  switch (type) {
  case REAL_RESULT:
    return *(double*) value;
  case INT_RESULT:
    return (double) *(longlong*) value;
3588 3589 3590 3591 3592 3593
  case DECIMAL_RESULT:
  {
    double result;
    my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *)value, &result);
    return result;
  }
3594
  case STRING_RESULT:
serg@serg.mylan's avatar
serg@serg.mylan committed
3595
    return my_atof(value);                      // This is null terminated
3596 3597 3598
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3599
  }
3600
  return 0.0;					// Impossible
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3601 3602 3603
}


3604 3605 3606
/* Get the value of a variable as an integer */

longlong user_var_entry::val_int(my_bool *null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3607
{
3608 3609 3610 3611 3612 3613 3614 3615
  if ((*null_value= (value == 0)))
    return LL(0);

  switch (type) {
  case REAL_RESULT:
    return (longlong) *(double*) value;
  case INT_RESULT:
    return *(longlong*) value;
3616 3617 3618
  case DECIMAL_RESULT:
  {
    longlong result;
3619
    my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, &result);
3620 3621
    return result;
  }
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3622
  case STRING_RESULT:
monty@mysql.com's avatar
monty@mysql.com committed
3623 3624 3625 3626
  {
    int error;
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
  }
3627 3628 3629
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3630
  }
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
  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:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3645
    str->set(*(double*) value, decimals, &my_charset_bin);
3646 3647
    break;
  case INT_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3648
    str->set(*(longlong*) value, &my_charset_bin);
3649
    break;
3650 3651 3652
  case DECIMAL_RESULT:
    my_decimal2string(E_DEC_FATAL_ERROR, (my_decimal *)value, 0, 0, 0, str);
    break;
3653
  case STRING_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3654
    if (str->copy(value, length, collation.collation))
3655
      str= 0;					// EOM error
3656 3657 3658
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3659
  }
3660
  return(str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3661 3662
}

3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
/* 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);
}

3690 3691
/*
  This functions is invoked on SET @variable or @variable:= expression.
3692
  Evaluate (and check expression), store results.
3693 3694 3695 3696 3697

  SYNOPSYS
    Item_func_set_user_var::check()

  NOTES
3698 3699
    For now it always return OK. All problem with value evaluating
    will be caught by thd->net.report_error check in sql_set_variables().
3700 3701

  RETURN
3702
    FALSE OK.
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
*/

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

  switch (cached_result_type) {
  case REAL_RESULT:
  {
3713
    save_result.vreal= args[0]->val_real();
3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
    break;
  }
  case INT_RESULT:
  {
    save_result.vint= args[0]->val_int();
    break;
  }
  case STRING_RESULT:
  {
    save_result.vstr= args[0]->val_str(&value);
    break;
  }
3726 3727 3728 3729 3730
  case DECIMAL_RESULT:
  {
    save_result.vdec= args[0]->val_decimal(&decimal_buff);
    break;
  }
3731 3732
  case ROW_RESULT:
  default:
3733
    // This case should never be chosen
3734 3735 3736
    DBUG_ASSERT(0);
    break;
  }
3737
  DBUG_RETURN(FALSE);
3738 3739
}

3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751

/*
  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
3752
    0	OK
3753 3754 3755 3756
    1	EOM Error

*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3757 3758 3759
bool
Item_func_set_user_var::update()
{
3760 3761 3762 3763
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3764 3765
  switch (cached_result_type) {
  case REAL_RESULT:
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3766
  {
3767
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
3768
		     REAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3769
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3770
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3771
  case INT_RESULT:
3772
  {
3773
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
3774
		     INT_RESULT, &my_charset_bin, DERIVATION_IMPLICIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3775
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3776
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3777
  case STRING_RESULT:
3778
  {
3779
    if (!save_result.vstr)					// Null value
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3780
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
3781
		       DERIVATION_IMPLICIT);
3782
    else
3783 3784 3785
      res= update_hash((void*) save_result.vstr->ptr(),
		       save_result.vstr->length(), STRING_RESULT,
		       save_result.vstr->charset(),
3786
		       DERIVATION_IMPLICIT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3787 3788
    break;
  }
3789 3790 3791 3792
  case DECIMAL_RESULT:
  {
    if (!save_result.vdec)					// Null value
      res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin,
3793
                       DERIVATION_IMPLICIT);
3794 3795 3796
    else
      res= update_hash((void*) save_result.vdec,
                       sizeof(my_decimal), DECIMAL_RESULT,
3797
                       &my_charset_bin, DERIVATION_IMPLICIT);
3798 3799
    break;
  }
3800
  case ROW_RESULT:
3801
  default:
3802
    // This case should never be chosen
3803 3804 3805
    DBUG_ASSERT(0);
    break;
  }
3806
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3807 3808 3809
}


3810
double Item_func_set_user_var::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3811
{
3812
  DBUG_ASSERT(fixed == 1);
3813
  check();
3814
  update();					// Store expression
3815
  return entry->val_real(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3816 3817
}

3818
longlong Item_func_set_user_var::val_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3819
{
3820
  DBUG_ASSERT(fixed == 1);
3821
  check();
3822 3823
  update();					// Store expression
  return entry->val_int(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3824 3825
}

3826
String *Item_func_set_user_var::val_str(String *str)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3827
{
3828
  DBUG_ASSERT(fixed == 1);
3829
  check();
3830 3831
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3832 3833 3834
}


3835 3836 3837 3838 3839 3840 3841 3842 3843
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);
}


3844 3845
void Item_func_set_user_var::print(String *str)
{
3846
  str->append(STRING_WITH_LEN("(@"));
3847
  str->append(name.str, name.length);
3848
  str->append(STRING_WITH_LEN(":="));
3849 3850 3851 3852 3853
  args[0]->print(str);
  str->append(')');
}


3854 3855
void Item_func_set_user_var::print_as_stmt(String *str)
{
3856
  str->append(STRING_WITH_LEN("set @"));
3857
  str->append(name.str, name.length);
3858
  str->append(STRING_WITH_LEN(":="));
3859 3860 3861 3862 3863
  args[0]->print(str);
  str->append(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
3864 3865 3866
String *
Item_func_get_user_var::val_str(String *str)
{
3867
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
3868
  DBUG_ENTER("Item_func_get_user_var::val_str");
3869
  if (!var_entry)
3870
    DBUG_RETURN((String*) 0);			// No such variable
3871
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3872 3873 3874
}


3875
double Item_func_get_user_var::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3876
{
3877
  DBUG_ASSERT(fixed == 1);
3878 3879
  if (!var_entry)
    return 0.0;					// No such variable
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
  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);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3890 3891 3892 3893 3894
}


longlong Item_func_get_user_var::val_int()
{
3895
  DBUG_ASSERT(fixed == 1);
3896 3897 3898
  if (!var_entry)
    return LL(0);				// No such variable
  return (var_entry->val_int(&null_value));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3899 3900 3901
}


3902
/*
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
  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.

3913 3914 3915 3916
  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).
3917

3918
  RETURN
3919
    0  OK
3920
    1  Failed to put appropriate record into binary log
3921

3922 3923
*/

3924 3925
int get_var_with_binlog(THD *thd, enum_sql_command sql_command,
                        LEX_STRING &name, user_var_entry **out_entry)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3926
{
3927
  BINLOG_USER_VAR_EVENT *user_var_event;
3928 3929
  user_var_entry *var_entry;
  var_entry= get_variable(&thd->user_vars, name, 0);
3930 3931

  if (!(opt_bin_log && is_update_query(sql_command)))
3932 3933 3934 3935
  {
    *out_entry= var_entry;
    return 0;
  }
3936 3937

  if (!var_entry)
3938
  {
3939
    /*
3940 3941 3942 3943
      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).
3944 3945
      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;'.
3946 3947 3948
      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();
3949 3950
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
3951 3952 3953

      Manipulation with lex is necessary since free_underlaid_joins
      is going to release memory belonging to the main query.
3954 3955 3956
    */

    List<set_var_base> tmp_var_list;
3957 3958 3959
    LEX *sav_lex= thd->lex, lex_tmp;
    thd->lex= &lex_tmp;
    lex_start(thd, NULL, 0);
3960 3961
    tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
                                                                       new Item_null())));
3962 3963
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
3964 3965
    {
      thd->lex= sav_lex;
3966
      goto err;
3967 3968
    }
    thd->lex= sav_lex;
3969 3970 3971
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
3972 3973
  else if (var_entry->used_query_id == thd->query_id ||
           mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
3974 3975 3976 3977 3978 3979 3980 3981 3982
  {
    /* 
       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;
  }
3983 3984 3985 3986

  uint size;
  /*
    First we need to store value of var_entry, when the next situation
3987
    appears:
3988 3989
    > set @a:=1;
    > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
3990 3991 3992 3993 3994 3995
    We have to write to binlog value @a= 1.
    
    We allocate the user_var_event on user_var_events_alloc pool, not on
    the this-statement-execution pool because in SPs user_var_event objects 
    may need to be valid after current [SP] statement execution pool is
    destroyed.
3996
  */
3997 3998 3999
  size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;
  if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
        alloc_root(thd->user_var_events_alloc, size)))
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011
    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;
4012
  }
4013 4014 4015 4016 4017 4018 4019 4020 4021 4022
  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;
4023 4024 4025
  
  *out_entry= var_entry;
  return 0;
4026

4027
err:
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
  *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;
4040

4041
  error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
4042 4043

  if (var_entry)
4044
  {
4045
    collation.set(var_entry->collation);
4046 4047 4048
    switch (var_entry->type) {
    case REAL_RESULT:
      max_length= DBL_DIG + 8;
4049
      break;
4050 4051
    case INT_RESULT:
      max_length= MAX_BIGINT_WIDTH;
4052
      decimals=0;
4053 4054 4055 4056
      break;
    case STRING_RESULT:
      max_length= MAX_BLOB_WIDTH;
      break;
4057
    case DECIMAL_RESULT:
4058 4059
      max_length= DECIMAL_MAX_STR_LENGTH;
      decimals= DECIMAL_MAX_SCALE;
4060
      break;
monty@mysql.com's avatar
monty@mysql.com committed
4061
    case ROW_RESULT:                            // Keep compiler happy
4062 4063
    default:
      DBUG_ASSERT(0);
monty@mysql.com's avatar
monty@mysql.com committed
4064
      break;
4065 4066
    }
  }
4067
  else
4068 4069
  {
    collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
4070
    null_value= 1;
4071
  }
4072

4073 4074
  if (error)
    thd->fatal_error();
4075

4076
  return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4077 4078 4079
}


4080
bool Item_func_get_user_var::const_item() const
4081
{
4082
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
4083
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095


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

4096 4097 4098

void Item_func_get_user_var::print(String *str)
{
4099
  str->append(STRING_WITH_LEN("(@"));
4100 4101 4102 4103
  str->append(name.str,name.length);
  str->append(')');
}

4104

4105
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
4106 4107 4108 4109 4110 4111
{
  /* 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 ||
4112
      ((Item_func*) item)->functype() != functype())
4113 4114 4115 4116 4117 4118 4119
    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));
}


4120
bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
4121 4122
{
  DBUG_ASSERT(fixed == 0);
4123
  if (Item::fix_fields(thd, ref) ||
4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189
      !(entry= get_variable(&thd->user_vars, name, 1)))
    return TRUE;
  entry->type= STRING_RESULT;
  /*
    Let us set the same collation which is used for loading
    of fields in LOAD DATA INFILE.
    (Since Item_user_var_as_out_param is used only there).
  */
  entry->collation.set(thd->variables.collation_database);
  entry->update_query_id= thd->query_id;
  return FALSE;
}


void Item_user_var_as_out_param::set_null_value(CHARSET_INFO* cs)
{
  if (::update_hash(entry, TRUE, 0, 0, STRING_RESULT, cs,
                    DERIVATION_IMPLICIT))
    current_thd->fatal_error();			// Probably end of memory
}


void Item_user_var_as_out_param::set_value(const char *str, uint length,
                                           CHARSET_INFO* cs)
{
  if (::update_hash(entry, FALSE, (void*)str, length, STRING_RESULT, cs,
                    DERIVATION_IMPLICIT))
    current_thd->fatal_error();			// Probably end of memory
}


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


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


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


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


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


4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201
Item_func_get_system_var::
Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
                       LEX_STRING *component_arg, const char *name_arg,
                       size_t name_len_arg)
  :var(var_arg), var_type(var_type_arg), component(*component_arg)
{
  /* set_name() will allocate the name */
  set_name(name_arg, name_len_arg, system_charset_info);
}


bool
4202
Item_func_get_system_var::fix_fields(THD *thd, Item **ref)
4203
{
4204
  Item *item;
4205
  DBUG_ENTER("Item_func_get_system_var::fix_fields");
4206

4207 4208 4209 4210 4211
  /*
    Evaluate the system variable and substitute the result (a basic constant)
    instead of this item. If the variable can not be evaluated,
    the error is reported in sys_var::item().
  */
4212
  if (!(item= var->item(thd, var_type, &component)))
4213 4214 4215 4216 4217 4218 4219 4220
    DBUG_RETURN(1);                             // Impossible
  item->set_name(name, 0, system_charset_info); // don't allocate a new name
  thd->change_item_tree(ref, item);

  DBUG_RETURN(0);
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
4221 4222
longlong Item_func_inet_aton::val_int()
{
4223
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4224 4225 4226 4227 4228
  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];
4229
  int dot_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4230

4231
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
  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 == '.')
    {
4248
      dot_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4249 4250 4251 4252 4253 4254 4255
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
4256
  {
4257 4258 4259 4260 4261 4262
    /*
      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
    */
4263
    switch (dot_count) {
4264 4265
    case 1: result<<= 8; /* Fall through */
    case 2: result<<= 8; /* Fall through */
4266
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4267
    return (result << 8) + (ulonglong) byte_result;
4268
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4269 4270 4271 4272 4273 4274

err:
  null_value=1;
  return 0;
}

4275

4276
void Item_func_match::init_search(bool no_order)
4277
{
4278
  DBUG_ENTER("Item_func_match::init_search");
4279 4280

  /* Check if init_search() has been called before */
4281
  if (ft_handler)
4282
    DBUG_VOID_RETURN;
4283

4284
  if (key == NO_SUCH_KEY)
4285 4286
  {
    List<Item> fields;
4287
    fields.push_back(new Item_string(" ",1, cmp_collation.collation));
4288 4289
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
4290
    concat=new Item_func_concat_ws(fields);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4291 4292 4293
    /*
      Above function used only to get value and do not need fix_fields for it:
      Item_string - basic constant
monty@mysql.com's avatar
monty@mysql.com committed
4294 4295
      fields - fix_fields() was already called for this arguments
      Item_func_concat_ws - do not need fix_fields() to produce value
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4296 4297
    */
    concat->quick_fix_field();
4298
  }
4299

4300 4301
  if (master)
  {
4302 4303
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
4304 4305
    ft_handler=master->ft_handler;
    join_key=master->join_key;
4306
    DBUG_VOID_RETURN;
4307 4308
  }

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
4309
  String *ft_tmp= 0;
4310

4311
  // MATCH ... AGAINST (NULL) is meaningless, but possible
4312
  if (!(ft_tmp=key_item()->val_str(&value)))
4313
  {
4314 4315
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
4316 4317
  }

4318 4319
  if (ft_tmp->charset() != cmp_collation.collation)
  {
4320
    uint dummy_errors;
4321
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
4322
                      cmp_collation.collation, &dummy_errors);
4323
    ft_tmp= &search_value;
4324 4325
  }

4326 4327
  if (join_key && !no_order)
    flags|=FT_SORTED;
4328
  ft_handler=table->file->ft_init_ext(flags, key, ft_tmp);
4329 4330 4331

  if (join_key)
    table->file->ft_handler=ft_handler;
4332 4333

  DBUG_VOID_RETURN;
4334 4335
}

4336

4337
bool Item_func_match::fix_fields(THD *thd, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4338
{
4339
  DBUG_ASSERT(fixed == 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4340
  Item *item;
4341
  LINT_INIT(item);				// Safe as arg_count is > 1
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4342

4343 4344 4345
  maybe_null=1;
  join_key=0;

4346 4347 4348 4349 4350
  /*
    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.
4351
   */
4352
  if (Item_func::fix_fields(thd, ref) ||
4353
      !args[0]->const_during_execution())
4354 4355
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
4356
    return TRUE;
4357
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4358

4359 4360
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4361
  {
4362
    item=args[i];
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
4363
    if (item->type() == Item::REF_ITEM)
4364 4365
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
4366
      key=NO_SUCH_KEY;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4367
  }
4368 4369
  /*
    Check that all columns come from the same table.
4370
    We've already checked that columns in MATCH are fields so
4371 4372 4373
    PARAM_TABLE_BIT can only appear from AGAINST argument.
  */
  if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
4374
    key=NO_SUCH_KEY;
4375

4376
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
4377 4378
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
4379
    return TRUE;
4380
  }
4381
  table=((Item_field *)item)->field->table;
monty@mysql.com's avatar
monty@mysql.com committed
4382
  if (!(table->file->table_flags() & HA_CAN_FULLTEXT))
4383
  {
monty@mysql.com's avatar
monty@mysql.com committed
4384
    my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4385
    return 1;
4386
  }
4387 4388
  table->fulltext_searched=1;
  return agg_arg_collations_for_comparison(cmp_collation, args+1, arg_count-1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4389
}
4390

bk@work.mysql.com's avatar
bk@work.mysql.com committed
4391 4392 4393
bool Item_func_match::fix_index()
{
  Item_field *item;
4394
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
4395
  uint max_cnt=0, mkeys=0, i;
4396

4397
  if (key == NO_SUCH_KEY)
4398
    return 0;
4399 4400 4401
  
  if (!table) 
    goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4402

4403
  for (keynr=0 ; keynr < table->s->keys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4404
  {
4405
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
4406
        (table->keys_in_use_for_query.is_set(keynr)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4407
    {
4408
      ft_to_key[fts]=keynr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4409 4410 4411 4412 4413 4414
      ft_cnt[fts]=0;
      fts++;
    }
  }

  if (!fts)
4415
    goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4416

4417
  for (i=1; i < arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4418
  {
4419
    item=(Item_field*)args[i];
4420
    for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4421
    {
4422
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4423 4424 4425 4426 4427
      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))
4428
	  ft_cnt[keynr]++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4429 4430 4431 4432
      }
    }
  }

4433
  for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4434
  {
4435
    if (ft_cnt[keynr] > max_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4436
    {
4437
      mkeys=0;
4438 4439
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
4440 4441
      continue;
    }
4442
    if (max_cnt && ft_cnt[keynr] == max_cnt)
4443 4444
    {
      mkeys++;
4445 4446
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
4447
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4448 4449 4450
    }
  }

4451
  for (keynr=0 ; keynr <= mkeys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4452
  {
4453 4454
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
4455
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
4456
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4457

4458
    key=ft_to_key[keynr];
4459

4460 4461 4462
    return 0;
  }

4463
err:
4464
  if (flags & FT_BOOL)
4465
  {
4466
    key=NO_SUCH_KEY;
4467 4468
    return 0;
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4469 4470
  my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
             ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
4471
  return 1;
4472 4473
}

4474

4475
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
4476
{
4477 4478
  if (item->type() != FUNC_ITEM ||
      ((Item_func*)item)->functype() != FT_FUNC ||
4479
      flags != ((Item_func_match*)item)->flags)
4480 4481 4482 4483 4484
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
4485
      key_item()->eq(ifm->key_item(), binary_cmp))
4486
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
4487 4488 4489 4490

  return 0;
}

4491

4492
double Item_func_match::val_real()
4493
{
4494
  DBUG_ASSERT(fixed == 1);
4495
  DBUG_ENTER("Item_func_match::val");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
4496
  if (ft_handler == NULL)
4497
    DBUG_RETURN(-1.0);
4498

4499
  if (table->null_row) /* NULL row from an outer join */
monty@mysql.com's avatar
monty@mysql.com committed
4500
    DBUG_RETURN(0.0);
4501

4502 4503 4504
  if (join_key)
  {
    if (table->file->ft_handler)
4505
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
4506 4507 4508
    join_key=0;
  }

4509
  if (key == NO_SUCH_KEY)
4510
  {
4511 4512
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
4513 4514 4515
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
				      (byte *)a->ptr(), a->length()));
4516
  }
monty@mysql.com's avatar
monty@mysql.com committed
4517 4518
  DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                 table->record[0], 0));
4519 4520
}

4521 4522
void Item_func_match::print(String *str)
{
4523
  str->append(STRING_WITH_LEN("(match "));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4524
  print_args(str, 1);
4525
  str->append(STRING_WITH_LEN(" against ("));
4526
  args[0]->print(str);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4527
  if (flags & FT_BOOL)
4528
    str->append(STRING_WITH_LEN(" in boolean mode"));
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4529
  else if (flags & FT_EXPAND)
4530 4531
    str->append(STRING_WITH_LEN(" with query expansion"));
  str->append(STRING_WITH_LEN("))"));
4532
}
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
4533

4534 4535
longlong Item_func_bit_xor::val_int()
{
4536
  DBUG_ASSERT(fixed == 1);
4537 4538
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
4539
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
4540 4541 4542 4543
    return 0;
  return (longlong) (arg1 ^ arg2);
}

4544

4545 4546 4547 4548
/***************************************************************************
  System variables
****************************************************************************/

4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565
/*
  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
*/
4566

4567 4568 4569

Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
		     LEX_STRING component)
4570
{
4571 4572 4573
  sys_var *var;
  LEX_STRING *base_name, *component_name;

4574 4575 4576 4577 4578 4579 4580 4581 4582 4583
  if (component.str)
  {
    base_name= &component;
    component_name= &name;
  }
  else
  {
    base_name= &name;
    component_name= &component;			// Empty string
  }
4584

4585
  if (!(var= find_sys_var(base_name->str, base_name->length)))
4586
    return 0;
4587 4588 4589 4590
  if (component.str)
  {
    if (!var->is_struct())
    {
4591
      my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
4592 4593 4594
      return 0;
    }
  }
pem@mysql.com's avatar
pem@mysql.com committed
4595
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
4596

4597 4598
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);

4599
  return new Item_func_get_system_var(var, var_type, component_name,
4600
                                      NULL, 0);
4601 4602 4603
}


4604 4605
/*
  Check a user level lock.
4606 4607 4608 4609 4610 4611 4612 4613

  SYNOPSIS:
    val_int()

  RETURN VALUES
    1		Available
    0		Already taken
    NULL	Error
4614 4615
*/

4616
longlong Item_func_is_free_lock::val_int()
4617
{
4618
  DBUG_ASSERT(fixed == 1);
4619
  String *res=args[0]->val_str(&value);
4620
  User_level_lock *ull;
4621 4622

  null_value=0;
4623
  if (!res || !res->length())
4624 4625 4626 4627 4628 4629
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
4630
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
4631 4632 4633 4634 4635 4636
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
4637

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
4638 4639
longlong Item_func_is_used_lock::val_int()
{
4640
  DBUG_ASSERT(fixed == 1);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
4641
  String *res=args[0]->val_str(&value);
4642
  User_level_lock *ull;
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
4643 4644 4645 4646 4647 4648

  null_value=1;
  if (!res || !res->length())
    return 0;
  
  pthread_mutex_lock(&LOCK_user_locks);
4649
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
4650 4651 4652 4653 4654 4655 4656 4657 4658
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 0;

  null_value=0;
  return ull->thread_id;
}

4659

4660 4661 4662 4663 4664 4665 4666 4667 4668
longlong Item_func_row_count::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->row_count_func;
}


4669 4670 4671
Item_func_sp::Item_func_sp(Name_resolution_context *context_arg, sp_name *name)
  :Item_func(), context(context_arg), m_name(name), m_sp(NULL),
   result_field(NULL)
4672
{
4673
  maybe_null= 1;
4674
  m_name->init_qname(current_thd);
4675 4676
  dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
  dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
4677 4678
}

monty@mysql.com's avatar
monty@mysql.com committed
4679

4680 4681 4682 4683
Item_func_sp::Item_func_sp(Name_resolution_context *context_arg,
                           sp_name *name, List<Item> &list)
  :Item_func(list), context(context_arg), m_name(name), m_sp(NULL),
   result_field(NULL)
4684
{
4685
  maybe_null= 1;
4686
  m_name->init_qname(current_thd);
4687 4688
  dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
  dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
4689 4690
}

4691

4692 4693 4694 4695 4696 4697 4698 4699
void
Item_func_sp::cleanup()
{
  if (result_field)
  {
    delete result_field;
    result_field= NULL;
  }
4700
  m_sp= NULL;
4701 4702
  Item_func::cleanup();
}
monty@mysql.com's avatar
monty@mysql.com committed
4703

4704 4705 4706
const char *
Item_func_sp::func_name() const
{
4707
  THD *thd= current_thd;
4708
  /* Calculate length to avoid reallocation of string for sure */
4709 4710 4711 4712
  uint len= ((m_name->m_db.length +
              m_name->m_name.length)*2 + //characters*quoting
             2 +                         // ` and `
             1 +                         // .
4713 4714
             1 +                         // end of string
             ALIGN_SIZE(1));             // to avoid String reallocation
monty@mysql.com's avatar
monty@mysql.com committed
4715
  String qname((char *)alloc_root(thd->mem_root, len), len,
4716
               system_charset_info);
4717

4718 4719 4720 4721 4722
  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();
4723 4724
}

4725

4726 4727 4728
Field *
Item_func_sp::sp_result_field(void) const
{
pem@mysql.comhem.se's avatar
pem@mysql.comhem.se committed
4729
  Field *field;
4730
  DBUG_ENTER("Item_func_sp::sp_result_field");
4731 4732 4733 4734
  DBUG_PRINT("info", ("sp: %s, flags: %x, level: %lu",
                      (m_sp ? "YES" : "NO"),
                      (m_sp ? m_sp->m_flags : (uint)0),
                      (m_sp ? m_sp->m_recursion_level : (ulong)0)));
4735 4736

  if (!m_sp)
4737
  {
4738 4739 4740
    THD *thd= current_thd;
    if (!(m_sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, m_name,
                                &thd->sp_func_cache, TRUE)))
4741
    {
4742 4743
      my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
      DBUG_RETURN(0);
4744 4745
    }
  }
4746
  if (!dummy_table->alias)
4747 4748
  {
    char *empty_name= (char *) "";
4749 4750
    dummy_table->alias= empty_name;
    dummy_table->maybe_null= maybe_null;
4751
    dummy_table->in_use= current_thd;
4752 4753 4754
    dummy_table->s->table_cache_key.str = empty_name;
    dummy_table->s->table_name.str= empty_name;
    dummy_table->s->db.str= empty_name;
4755
  }
4756 4757 4758
  if (!(field= m_sp->create_result_field(max_length, name, dummy_table)))
    my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));

4759
  DBUG_RETURN(field);
4760 4761 4762
}


4763 4764 4765 4766 4767 4768 4769 4770
/*
  Execute function & store value in field

  RETURN
   0  value <> NULL
   1  value =  NULL  or error
*/

4771
bool
4772 4773
Item_func_sp::execute(Field **flp)
{
4774
  THD *thd= current_thd;
4775
  Field *f;
4776 4777 4778 4779 4780 4781

  /*
    Get field in virtual tmp table to store result. Create the field if
    invoked first time.
  */
  
4782 4783
  if (!(f= *flp))
  {
4784 4785
    if (!(*flp= f= sp_result_field()))
    {
4786 4787 4788
      /* Error set by sp_result_field() */
      null_value= 1;
      return TRUE;
4789 4790 4791
    }

    f->move_field((f->pack_length() > sizeof(result_buf)) ?
4792 4793 4794 4795
                  sql_alloc(f->pack_length()) : result_buf);
    f->null_ptr= (uchar *)&null_value;
    f->null_bit= 1;
  }
4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810

  /* Execute function and store the return value in the field. */

  if (execute_impl(thd, f))
  {
    null_value= 1;
    context->process_error(thd);
    return TRUE;
  }

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

  null_value= f->is_null();

  return null_value;
4811 4812 4813
}


4814 4815
bool
Item_func_sp::execute_impl(THD *thd, Field *return_value_fld)
4816
{
4817
  bool err_status= TRUE;
4818
  Sub_statement_state statement_state;
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4819
  Security_context *save_security_ctx= thd->security_ctx, *save_ctx_func;
4820

4821 4822
  DBUG_ENTER("Item_func_sp::execute_impl");

4823 4824 4825 4826 4827 4828 4829 4830
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  if (context->security_ctx)
  {
    /* Set view definer security context */
    thd->security_ctx= context->security_ctx;
  }
#endif
  if (find_and_check_access(thd, EXECUTE_ACL, &save_ctx_func))
4831
    goto error;
4832

4833 4834 4835 4836 4837
  /*
    Disable the binlogging if this is not a SELECT statement. If this is a
    SELECT, leave binlogging on, so execute_function() code writes the
    function call into binlog.
  */
4838
  thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
4839
  err_status= m_sp->execute_function(thd, args, arg_count, return_value_fld);
4840
  thd->restore_sub_statement_state(&statement_state);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4841

4842 4843
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  sp_restore_security_context(thd, save_ctx_func);
4844
error:
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4845
  thd->security_ctx= save_security_ctx;
4846 4847 4848
#else
error:
#endif
4849
  DBUG_RETURN(err_status);
4850 4851
}

4852

4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868
void
Item_func_sp::make_field(Send_field *tmp_field)
{
  Field *field;
  DBUG_ENTER("Item_func_sp::make_field");
  if ((field= sp_result_field()))
  {
    field->make_field(tmp_field);
    delete field;
    DBUG_VOID_RETURN;
  }
  init_make_field(tmp_field, MYSQL_TYPE_VARCHAR);  
  DBUG_VOID_RETURN;
}


4869 4870
enum enum_field_types
Item_func_sp::field_type() const
4871
{
4872
  Field *field;
4873
  DBUG_ENTER("Item_func_sp::field_type");
4874

4875 4876
  if (result_field)
    DBUG_RETURN(result_field->type());
4877
  if ((field= sp_result_field()))
4878
  {
4879 4880 4881
    enum_field_types result= field->type();
    delete field;
    DBUG_RETURN(result);
4882
  }
4883
  DBUG_RETURN(MYSQL_TYPE_VARCHAR);
4884 4885
}

4886

4887 4888
Item_result
Item_func_sp::result_type() const
4889
{
4890
  Field *field;
4891 4892
  DBUG_ENTER("Item_func_sp::result_type");
  DBUG_PRINT("info", ("m_sp = %p", m_sp));
4893

4894 4895
  if (result_field)
    DBUG_RETURN(result_field->result_type());
4896
  if ((field= sp_result_field()))
4897
  {
4898 4899 4900
    Item_result result= field->result_type();
    delete field;
    DBUG_RETURN(result);
4901
  }
4902
  DBUG_RETURN(STRING_RESULT);
4903 4904 4905 4906 4907
}

void
Item_func_sp::fix_length_and_dec()
{
4908
  Field *field;
4909 4910
  DBUG_ENTER("Item_func_sp::fix_length_and_dec");

4911 4912 4913
  if (result_field)
  {
    decimals= result_field->decimals();
4914
    max_length= result_field->field_length;
4915
    collation.set(result_field->charset());
4916 4917 4918
    DBUG_VOID_RETURN;
  }

4919
  if (!(field= sp_result_field()))
4920 4921
  {
    context->process_error(current_thd);
4922
    DBUG_VOID_RETURN;
4923
  }
4924
  decimals= field->decimals();
monty@mishka.local's avatar
merge  
monty@mishka.local committed
4925
  max_length= field->field_length;
4926
  collation.set(field->charset());
monty@mishka.local's avatar
merge  
monty@mishka.local committed
4927
  maybe_null= 1;
4928
  delete field;
4929 4930
  DBUG_VOID_RETURN;
}
monty@mysql.com's avatar
monty@mysql.com committed
4931 4932


4933 4934 4935
longlong Item_func_found_rows::val_int()
{
  DBUG_ASSERT(fixed == 1);
4936
  return current_thd->found_rows();
4937
}
4938

4939

4940 4941 4942
Field *
Item_func_sp::tmp_table_field(TABLE *t_arg)
{
4943
  Field *field= 0;
4944 4945 4946
  DBUG_ENTER("Item_func_sp::tmp_table_field");

  if (m_sp)
4947
    field= m_sp->create_result_field(max_length, (const char*) name, t_arg);
4948
  
4949 4950
  if (!field) 
    field= Item_func::tmp_table_field(t_arg);
4951

4952
  if (!field)
4953 4954
    my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));

4955
  DBUG_RETURN(field);
4956
}
4957

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4958

4959
/*
4960
  Find the function and check access rights to the function
4961 4962

  SYNOPSIS
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4963 4964
    find_and_check_access()
    thd           thread handler
4965
    want_access   requested access
monty@mysql.com's avatar
monty@mysql.com committed
4966
    save          backup of security context
4967 4968

  RETURN
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4969 4970
    FALSE    Access granted
    TRUE     Requested access can't be granted or function doesn't exists
monty@mysql.com's avatar
monty@mysql.com committed
4971
	     In this case security context is not changed and *save = 0
4972 4973 4974 4975 4976

  NOTES
    Checks if requested access to function can be granted to user.
    If function isn't found yet, it searches function first.
    If function can't be found or user don't have requested access
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4977
    error is raised.
4978 4979
    If security context sp_ctx is provided and access can be granted then
    switch back to previous context isn't performed.
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4980 4981
    In case of access error or if context is not provided then
    find_and_check_access() switches back to previous security context.
4982
*/
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4983

4984
bool
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4985
Item_func_sp::find_and_check_access(THD *thd, ulong want_access,
monty@mysql.com's avatar
monty@mysql.com committed
4986
                                    Security_context **save)
4987
{
monty@mysql.com's avatar
monty@mysql.com committed
4988 4989 4990
  bool res= TRUE;

  *save= 0;                                     // Safety if error
4991 4992
  if (! m_sp && ! (m_sp= sp_find_routine(thd, TYPE_ENUM_FUNCTION, m_name,
                                         &thd->sp_func_cache, TRUE)))
4993 4994 4995 4996 4997
  {
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
    goto error;
  }

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
4998
#ifndef NO_EMBEDDED_ACCESS_CHECKS
4999
  if (check_routine_access(thd, want_access,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5000
			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
5001 5002
    goto error;

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5003
  sp_change_security_context(thd, m_sp, save);
monty@mysql.com's avatar
monty@mysql.com committed
5004 5005 5006 5007 5008 5009 5010 5011 5012 5013
  /*
    If we changed context to run as another user, we need to check the
    access right for the new context again as someone may have deleted
    this person the right to use the procedure

    TODO:
      Cache if the definer has the right to use the object on the first
      usage and only reset the cache if someone does a GRANT statement
      that 'may' affect this.
  */
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5014
  if (*save &&
5015
      check_routine_access(thd, want_access,
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
5016
			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
5017
  {
monty@mysql.com's avatar
monty@mysql.com committed
5018 5019 5020
    sp_restore_security_context(thd, *save);
    *save= 0;                                   // Safety
    goto error;
5021 5022
  }
#endif
monty@mysql.com's avatar
monty@mysql.com committed
5023 5024 5025
  res= FALSE;                                   // no error

error:
5026
  return res;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
5027
}
5028 5029 5030 5031 5032 5033 5034

bool
Item_func_sp::fix_fields(THD *thd, Item **ref)
{
  bool res;
  DBUG_ASSERT(fixed == 0);
  res= Item_func::fix_fields(thd, ref);
5035
  if (!res && thd->lex->view_prepare_mode)
monty@mysql.com's avatar
monty@mysql.com committed
5036
  {
5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
    /*
      Here we check privileges of the stored routine only during view
      creation, in order to validate the view. A runtime check is perfomed
      in Item_func_sp::execute(), and this method is not called during
      context analysis. We do not need to restore the security context
      changed in find_and_check_access because all view structures created
      in CREATE VIEW are not used for execution.  Notice, that during view
      creation we do not infer into stored routine bodies and do not check
      privileges of its statements, which would probably be a good idea
      especially if the view has SQL SECURITY DEFINER and the used stored
5047
      procedure has SQL SECURITY DEFINER
5048
    */
monty@mysql.com's avatar
monty@mysql.com committed
5049 5050 5051 5052
    Security_context *save_ctx;
    if (!(res= find_and_check_access(thd, EXECUTE_ACL, &save_ctx)))
      sp_restore_security_context(thd, save_ctx);
  }
5053 5054
  return res;
}