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

   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
unknown's avatar
unknown committed
21 22
#pragma implementation				// gcc: Class implementation
#endif
23 24

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

unknown's avatar
unknown committed
31

32 33 34 35 36 37 38 39 40 41
bool check_reserved_words(LEX_STRING *name)
{
  if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") ||
      !my_strcasecmp(system_charset_info, name->str, "LOCAL") ||
      !my_strcasecmp(system_charset_info, name->str, "SESSION"))
    return TRUE;
  return FALSE;
}


unknown's avatar
unknown committed
42 43 44 45 46 47 48 49
/* return TRUE if item is a constant */

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

unknown's avatar
unknown committed
50

51
void Item_func::set_arguments(List<Item> &list)
unknown's avatar
unknown committed
52
{
53
  allowed_arg_cols= 1;
unknown's avatar
unknown committed
54 55 56 57
  arg_count=list.elements;
  if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
  {
    uint i=0;
unknown's avatar
unknown committed
58
    List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
59 60 61 62 63 64 65 66 67 68 69
    Item *item;

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

70 71 72 73 74 75
Item_func::Item_func(List<Item> &list)
  :allowed_arg_cols(1)
{
  set_arguments(list);
}

76
Item_func::Item_func(THD *thd, Item_func *item)
77
  :Item_result_field(thd, item),
78 79 80 81 82
   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)
83 84 85 86 87 88 89 90 91 92
{
  if (arg_count)
  {
    if (arg_count <=2)
      args= tmp_arg;
    else
    {
      if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
	return;
    }
93
    memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count);
94 95 96
  }
}

unknown's avatar
unknown committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

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

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

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

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

      str_value.charset If this is a string function, set this to the
			character set for the first argument.
120
			If any argument is binary, this is set to binary
unknown's avatar
unknown committed
121 122 123 124 125 126 127 128 129 130 131

   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
  0	ok
  1	Got error.  Stored with my_error().
*/

unknown's avatar
unknown committed
132
bool
unknown's avatar
unknown committed
133
Item_func::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
134
{
135
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
136
  Item **arg,**arg_end;
137
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
138
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
139
#endif
140

141
  used_tables_cache= not_null_tables_cache= 0;
unknown's avatar
unknown committed
142 143
  const_item_cache=1;

unknown's avatar
unknown committed
144
  if (check_stack_overrun(thd, buff))
145
    return 1;					// Fatal error if flag is set!
unknown's avatar
unknown committed
146 147 148 149
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
unknown's avatar
unknown committed
150
      Item *item;
unknown's avatar
merge  
unknown committed
151 152 153 154
      /*
	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
      */
155
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, tables, arg)))
unknown's avatar
unknown committed
156
	return 1;				/* purecov: inspected */
157

unknown's avatar
unknown committed
158
      item= *arg;
159 160 161 162 163 164 165 166 167 168 169 170 171 172

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

unknown's avatar
unknown committed
173
      if (item->maybe_null)
unknown's avatar
unknown committed
174
	maybe_null=1;
175

unknown's avatar
unknown committed
176
      with_sum_func= with_sum_func || item->with_sum_func;
177 178 179
      used_tables_cache|=     item->used_tables();
      not_null_tables_cache|= item->not_null_tables();
      const_item_cache&=      item->const_item();
unknown's avatar
unknown committed
180 181 182
    }
  }
  fix_length_and_dec();
unknown's avatar
unknown committed
183
  if (thd->net.last_errno) // An error inside fix_length_and_dec occured
184
    return 1;
185
  fixed= 1;
unknown's avatar
unknown committed
186 187 188
  return 0;
}

unknown's avatar
unknown committed
189 190 191 192 193 194 195 196 197 198 199 200 201
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);
}
202

203

204 205
/* See comments in Item_cmp_func::split_sum_func() */

206 207
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
                               List<Item> &fields)
unknown's avatar
unknown committed
208
{
unknown's avatar
unknown committed
209 210
  Item **arg, **arg_end;
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
211
    (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg);
unknown's avatar
unknown committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
}


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

233 234 235 236 237 238 239

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


unknown's avatar
unknown committed
240 241 242 243
void Item_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
unknown's avatar
unknown committed
244
  print_args(str, 0);
245 246 247 248
  str->append(')');
}


unknown's avatar
unknown committed
249
void Item_func::print_args(String *str, uint from)
250
{
unknown's avatar
unknown committed
251
  for (uint i=from ; i < arg_count ; i++)
unknown's avatar
unknown committed
252
  {
unknown's avatar
unknown committed
253
    if (i != from)
unknown's avatar
unknown committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
      str->append(',');
    args[i]->print(str);
  }
}


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

unknown's avatar
unknown committed
274

275
bool Item_func::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
276 277 278 279 280 281 282 283 284 285 286
{
  /* 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++)
287
    if (!args[i]->eq(item_func->args[i], binary_cmp))
unknown's avatar
unknown committed
288 289 290 291
      return 0;
  return 1;
}

292 293 294 295 296
Field *Item_func::tmp_table_field(TABLE *t_arg)
{
  Field *res;
  LINT_INIT(res);

unknown's avatar
unknown committed
297
  switch (result_type()) {
298 299 300 301 302 303 304 305 306 307 308 309 310
  case INT_RESULT:
    if (max_length > 11)
      res= new Field_longlong(max_length, maybe_null, name, t_arg,
			      unsigned_flag);
    else
      res= new Field_long(max_length, maybe_null, name, t_arg,
			  unsigned_flag);
    break;
  case REAL_RESULT:
    res= new Field_double(max_length, maybe_null, name, t_arg, decimals);
    break;
  case STRING_RESULT:
    if (max_length > 255)
311
      res= new Field_blob(max_length, maybe_null, name, t_arg, collation.collation);
312
    else
313
      res= new Field_string(max_length, maybe_null, name, t_arg, collation.collation);
314
    break;
315
  case ROW_RESULT:
unknown's avatar
unknown committed
316
  default:
unknown's avatar
unknown committed
317 318 319
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
320 321 322 323 324
  }
  return res;
}


unknown's avatar
unknown committed
325 326
String *Item_real_func::val_str(String *str)
{
327
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
328 329 330
  double nr=val();
  if (null_value)
    return 0; /* purecov: inspected */
unknown's avatar
unknown committed
331
  str->set(nr,decimals, &my_charset_bin);
unknown's avatar
unknown committed
332 333 334 335 336 337
  return str;
}


String *Item_num_func::val_str(String *str)
{
338
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
339 340 341 342 343
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
344
    if (!unsigned_flag)
unknown's avatar
unknown committed
345
      str->set(nr,&my_charset_bin);
346
    else
unknown's avatar
unknown committed
347
      str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
348 349 350 351 352 353
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
unknown's avatar
unknown committed
354
    str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
355 356 357 358 359 360 361 362 363 364 365 366 367
  }
  return str;
}


void Item_func::fix_num_length_and_dec()
{
  decimals=0;
  for (uint i=0 ; i < arg_count ; i++)
    set_if_bigger(decimals,args[i]->decimals);
  max_length=float_length(decimals);
}

368
Item *Item_func::get_tmp_table_item(THD *thd)
369 370
{
  if (!with_sum_func && !const_item())
unknown's avatar
unknown committed
371
    return new Item_field(result_field);
372
  return copy_or_same(thd);
373 374
}

unknown's avatar
unknown committed
375 376
String *Item_int_func::val_str(String *str)
{
377
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
378 379 380
  longlong nr=val_int();
  if (null_value)
    return 0;
381
  if (!unsigned_flag)
unknown's avatar
unknown committed
382
    str->set(nr,&my_charset_bin);
383
  else
unknown's avatar
unknown committed
384
    str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
385 386 387
  return str;
}

388 389 390 391
/*
  Change from REAL_RESULT (default) to INT_RESULT if both arguments are
  integers
*/
unknown's avatar
unknown committed
392 393 394 395 396

void Item_num_op::find_num_type(void)
{
  if (args[0]->result_type() == INT_RESULT &&
      args[1]->result_type() == INT_RESULT)
397
  {
unknown's avatar
unknown committed
398
    hybrid_type=INT_RESULT;
399 400
    unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
  }
unknown's avatar
unknown committed
401 402 403 404
}

String *Item_num_op::val_str(String *str)
{
405
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
406 407 408 409 410
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
411
    if (!unsigned_flag)
unknown's avatar
unknown committed
412
      str->set(nr,&my_charset_bin);
413
    else
unknown's avatar
unknown committed
414
      str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
415 416 417 418 419 420
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
unknown's avatar
unknown committed
421
    str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
422 423 424 425 426
  }
  return str;
}


427 428
void Item_func_signed::print(String *str)
{
429
  str->append("cast(", 5);
430
  args[0]->print(str);
431
  str->append(" as signed)", 11);
432 433 434 435

}


436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
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;
}


488 489
void Item_func_unsigned::print(String *str)
{
490
  str->append("cast(", 5);
491
  args[0]->print(str);
492
  str->append(" as unsigned)", 13);
493 494 495 496

}


497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
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;
}


unknown's avatar
unknown committed
518 519
double Item_func_plus::val()
{
520
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
521 522 523 524 525 526 527 528
  double value=args[0]->val()+args[1]->val();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

longlong Item_func_plus::val_int()
{
529
  DBUG_ASSERT(fixed == 1);
530 531 532 533 534 535 536 537
  if (hybrid_type == INT_RESULT)
  {
    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;
  }
  return (longlong) Item_func_plus::val();
unknown's avatar
unknown committed
538 539
}

540 541 542 543 544 545 546 547 548 549

/*
  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 &&
550
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
551 552 553 554
    unsigned_flag=0;
}


unknown's avatar
unknown committed
555 556
double Item_func_minus::val()
{
557
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
558 559 560 561 562 563 564 565
  double value=args[0]->val() - args[1]->val();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

longlong Item_func_minus::val_int()
{
566
  DBUG_ASSERT(fixed == 1);
567 568 569 570 571 572 573 574
  if (hybrid_type == INT_RESULT)
  {
    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;
  }
  return (longlong) Item_func_minus::val();
unknown's avatar
unknown committed
575 576
}

577

unknown's avatar
unknown committed
578 579
double Item_func_mul::val()
{
580
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
581 582 583 584 585 586 587 588
  double value=args[0]->val()*args[1]->val();
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0; /* purecov: inspected */
  return value;
}

longlong Item_func_mul::val_int()
{
589
  DBUG_ASSERT(fixed == 1);
590 591 592 593 594 595 596 597
  if (hybrid_type == INT_RESULT)
  {
    longlong value=args[0]->val_int()*args[1]->val_int();
    if ((null_value=args[0]->null_value || args[1]->null_value))
      return 0; /* purecov: inspected */
    return value;
  }
  return (longlong) Item_func_mul::val();
unknown's avatar
unknown committed
598 599 600 601 602
}


double Item_func_div::val()
{
603
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
604 605 606 607 608 609 610 611 612
  double value=args[0]->val();
  double val2=args[1]->val();
  if ((null_value= val2 == 0.0 || args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value/val2;
}

longlong Item_func_div::val_int()
{
613
  DBUG_ASSERT(fixed == 1);
614 615 616 617 618 619 620 621 622
  if (hybrid_type == INT_RESULT)
  {
    longlong value=args[0]->val_int();
    longlong val2=args[1]->val_int();
    if ((null_value= val2 == 0 || args[0]->null_value || args[1]->null_value))
      return 0;
    return value/val2;
  }
  return (longlong) Item_func_div::val();
unknown's avatar
unknown committed
623 624 625 626 627
}

void Item_func_div::fix_length_and_dec()
{
  decimals=max(args[0]->decimals,args[1]->decimals)+2;
628
  set_if_smaller(decimals, NOT_FIXED_DEC);
unknown's avatar
unknown committed
629 630 631 632 633 634
  max_length=args[0]->max_length - args[0]->decimals + decimals;
  uint tmp=float_length(decimals);
  set_if_smaller(max_length,tmp);
  maybe_null=1;
}

635 636 637 638

/* Integer division */
longlong Item_func_int_div::val_int()
{
639
  DBUG_ASSERT(fixed == 1);
640 641 642 643
  longlong value=args[0]->val_int();
  longlong val2=args[1]->val_int();
  if ((null_value= val2 == 0 || args[0]->null_value || args[1]->null_value))
    return 0;
644 645 646
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
647 648 649 650 651
}


void Item_func_int_div::fix_length_and_dec()
{
652
  find_num_type();
653 654 655 656 657
  max_length=args[0]->max_length - args[0]->decimals;
  maybe_null=1;
}


unknown's avatar
unknown committed
658 659
double Item_func_mod::val()
{
660
  DBUG_ASSERT(fixed == 1);
661 662 663
  double x= args[0]->val();
  double y= args[1]->val();
  if ((null_value= (y == 0.0) || args[0]->null_value || args[1]->null_value))
unknown's avatar
unknown committed
664
    return 0.0; /* purecov: inspected */
665
  return fmod(x, y);
unknown's avatar
unknown committed
666 667 668 669
}

longlong Item_func_mod::val_int()
{
670
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
671 672 673 674 675 676 677 678 679
  longlong value=  args[0]->val_int();
  longlong val2= args[1]->val_int();
  if ((null_value=val2 == 0 || args[0]->null_value || args[1]->null_value))
    return 0; /* purecov: inspected */
  return value % val2;
}

void Item_func_mod::fix_length_and_dec()
{
680
  Item_num_op::fix_length_and_dec();
unknown's avatar
unknown committed
681 682 683 684 685
}


double Item_func_neg::val()
{
686
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
687 688 689 690 691
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return -value;
}

unknown's avatar
unknown committed
692

unknown's avatar
unknown committed
693 694
longlong Item_func_neg::val_int()
{
695
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
696 697 698 699 700
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return -value;
}

unknown's avatar
unknown committed
701

unknown's avatar
unknown committed
702 703
void Item_func_neg::fix_length_and_dec()
{
704 705
  enum Item_result arg_result= args[0]->result_type();
  enum Item::Type  arg_type= args[0]->type();
unknown's avatar
unknown committed
706 707
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
unknown's avatar
unknown committed
708
  hybrid_type= REAL_RESULT;
709 710 711 712 713 714 715 716
  
  /*
    We need to account for added '-' in the following cases:
    A) argument is a real or integer positive constant - in this case 
    argument's max_length is set to actual number of bytes occupied, and not 
    maximum number of bytes real or integer may require. Note that all 
    constants are non negative so we don't need to account for removed '-'.
    B) argument returns a string.
717 718
    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.
719 720
  */
  if (arg_result == STRING_RESULT || 
721 722
      (arg_type == REAL_ITEM && args[0]->val() >= 0) ||
      (arg_type == INT_ITEM && args[0]->val_int() > 0))
723 724
    max_length++;

unknown's avatar
unknown committed
725 726 727 728 729 730 731 732 733 734 735 736 737
  if (args[0]->result_type() == INT_RESULT)
  {
    /*
      If this is in integer context keep the context as integer
      (This is how multiplication and other integer functions works)

      We must however do a special case in the case where the argument
      is a unsigned bigint constant as in this case the only safe
      number to convert in integer context is 9223372036854775808.
      (This is needed because the lex parser doesn't anymore handle
      signed integers)
    */
    if (args[0]->type() != INT_ITEM ||
738
	(((ulonglong) args[0]->val_int()) <= (ulonglong) LONGLONG_MIN))
unknown's avatar
unknown committed
739 740
      hybrid_type= INT_RESULT;
  }
unknown's avatar
unknown committed
741 742
}

unknown's avatar
unknown committed
743

unknown's avatar
unknown committed
744 745
double Item_func_abs::val()
{
746
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
747 748 749 750 751
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return fabs(value);
}

unknown's avatar
unknown committed
752

unknown's avatar
unknown committed
753 754
longlong Item_func_abs::val_int()
{
755
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
756 757 758 759 760
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return value >= 0 ? value : -value;
}

unknown's avatar
unknown committed
761

unknown's avatar
unknown committed
762 763 764 765
void Item_func_abs::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
unknown's avatar
unknown committed
766 767 768
  hybrid_type= REAL_RESULT;
  if (args[0]->result_type() == INT_RESULT)
    hybrid_type= INT_RESULT;
unknown's avatar
unknown committed
769 770
}

unknown's avatar
unknown committed
771

772 773 774
/* Gateway to natural LOG function */
double Item_func_ln::val()
{
775
  DBUG_ASSERT(fixed == 1);
776 777 778 779 780 781 782 783 784 785 786
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
  return log(value);
}

/* 
 Extended but so slower LOG function
 We have to check if all values are > zero and first one is not one
 as these are the cases then result is not a number.
*/ 
unknown's avatar
unknown committed
787 788
double Item_func_log::val()
{
789
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
790 791
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
792 793 794 795 796 797 798 799
    return 0.0;
  if (arg_count == 2)
  {
    double value2= args[1]->val();
    if ((null_value=(args[1]->null_value || value2 <= 0.0 || value == 1.0)))
      return 0.0;
    return log(value2) / log(value);
  }
unknown's avatar
unknown committed
800 801 802
  return log(value);
}

803 804
double Item_func_log2::val()
{
805
  DBUG_ASSERT(fixed == 1);
806 807 808 809 810 811
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
  return log(value) / log(2.0);
}

unknown's avatar
unknown committed
812 813
double Item_func_log10::val()
{
814
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
815 816 817 818 819 820 821 822
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0; /* purecov: inspected */
  return log10(value);
}

double Item_func_exp::val()
{
823
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
824 825 826 827 828 829 830 831
  double value=args[0]->val();
  if ((null_value=args[0]->null_value))
    return 0.0; /* purecov: inspected */
  return exp(value);
}

double Item_func_sqrt::val()
{
832
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
833 834 835 836 837 838 839 840
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value < 0)))
    return 0.0; /* purecov: inspected */
  return sqrt(value);
}

double Item_func_pow::val()
{
841
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
842 843 844 845 846 847 848 849 850 851 852
  double value=args[0]->val();
  double val2=args[1]->val();
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
    return 0.0; /* purecov: inspected */
  return pow(value,val2);
}

// Trigonometric functions

double Item_func_acos::val()
{
853
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
854
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
855
  volatile double value=args[0]->val();
unknown's avatar
unknown committed
856 857 858 859 860 861 862
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(acos(value));
}

double Item_func_asin::val()
{
863
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
864
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
865
  volatile double value=args[0]->val();
unknown's avatar
unknown committed
866 867 868 869 870 871 872
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(asin(value));
}

double Item_func_atan::val()
{
873
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
  double value=args[0]->val();
  if ((null_value=args[0]->null_value))
    return 0.0;
  if (arg_count == 2)
  {
    double val2= args[1]->val();
    if ((null_value=args[1]->null_value))
      return 0.0;
    return fix_result(atan2(value,val2));
  }
  return fix_result(atan(value));
}

double Item_func_cos::val()
{
889
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
890 891 892 893 894 895 896 897
  double value=args[0]->val();
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(cos(value));
}

double Item_func_sin::val()
{
898
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
899 900 901 902 903 904 905 906
  double value=args[0]->val();
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(sin(value));
}

double Item_func_tan::val()
{
907
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
908 909 910 911 912 913 914 915 916 917 918 919
  double value=args[0]->val();
  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()
{
920
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934
  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()
{
935
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  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()
{
951
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
  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;
}

longlong Item_func_ceiling::val_int()
{
971
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
972 973 974 975 976 977 978
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return (longlong) ceil(value);
}

longlong Item_func_floor::val_int()
{
979
  DBUG_ASSERT(fixed == 1);
980 981
  // the volatile's for BUG #3051 to calm optimizer down (because of gcc's bug)
  volatile double value=args[0]->val();
unknown's avatar
unknown committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995
  null_value=args[0]->null_value;
  return (longlong) floor(value);
}

void Item_func_round::fix_length_and_dec()
{
  max_length=args[0]->max_length;
  decimals=args[0]->decimals;
  if (args[1]->const_item())
  {
    int tmp=(int) args[1]->val_int();
    if (tmp < 0)
      decimals=0;
    else
996
      decimals=min(tmp,NOT_FIXED_DEC);
997 998
    if ((tmp= decimals - args[0]->decimals) > 0)
      max_length+= tmp;
unknown's avatar
unknown committed
999 1000 1001 1002 1003
  }
}

double Item_func_round::val()
{
1004
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1005 1006 1007
  double value=args[0]->val();
  int dec=(int) args[1]->val_int();
  uint abs_dec=abs(dec);
1008 1009 1010 1011 1012 1013
  double tmp;
  /*
    tmp2 is here to avoid return the value with 80 bit precision
    This will fix that the test round(0.1,1) = round(0.1,1) is true
  */
  volatile double tmp2;
unknown's avatar
unknown committed
1014 1015 1016

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

  if (truncate)
unknown's avatar
unknown committed
1021 1022
  {
    if (value >= 0)
1023
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
unknown's avatar
unknown committed
1024
    else
1025
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
unknown's avatar
unknown committed
1026
  }
1027 1028 1029
  else
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
  return tmp2;
unknown's avatar
unknown committed
1030 1031
}

unknown's avatar
unknown committed
1032

1033 1034
bool Item_func_rand::fix_fields(THD *thd, struct st_table_list *tables,
                                Item **ref)
unknown's avatar
unknown committed
1035
{
1036 1037
  if (Item_real_func::fix_fields(thd, tables, ref))
    return TRUE;
1038
  used_tables_cache|= RAND_TABLE_BIT;
unknown's avatar
unknown committed
1039 1040
  if (arg_count)
  {					// Only use argument once in query
1041 1042 1043 1044 1045
    if (!args[0]->const_during_execution())
    {
      my_error(ER_WRONG_ARGUMENTS, MYF(0), "RAND");
      return TRUE;
    }
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    /*
      Allocate rand structure once: we must use thd->current_arena
      to create rand in proper mem_root if it's a prepared statement or
      stored procedure.
    */
    if (!rand && !(rand= (struct rand_struct*)
                   thd->current_arena->alloc(sizeof(*rand))))
      return TRUE;
    /*
      PARAM_ITEM is returned if we're in statement prepare and consequently
      no placeholder value is set yet.
    */
    if (args[0]->type() != PARAM_ITEM)
    {
      /*
        TODO: do not do reinit 'rand' for every execute of PS/SP if
        args[0] is a constant.
      */
      uint32 tmp= (uint32) args[0]->val_int();
      randominit(rand, (uint32) (tmp*0x10001L+55555555L),
                 (uint32) (tmp*0x10000001L));
    }
unknown's avatar
unknown committed
1068
  }
1069
  else
unknown's avatar
unknown committed
1070
  {
1071 1072 1073
    /*
      No need to send a Rand log event if seed was given eg: RAND(seed),
      as it will be replicated in the query as such.
unknown's avatar
unknown committed
1074

1075 1076 1077 1078
      Save the seed only the first time RAND() is used in the query
      Once events are forwarded rather than recreated,
      the following can be skipped if inside the slave thread
    */
unknown's avatar
unknown committed
1079 1080 1081
    thd->rand_used=1;
    thd->rand_saved_seed1=thd->rand.seed1;
    thd->rand_saved_seed2=thd->rand.seed2;
1082
    rand= &thd->rand;
unknown's avatar
unknown committed
1083
  }
1084
  return FALSE;
1085 1086
}

unknown's avatar
unknown committed
1087 1088 1089 1090 1091 1092
void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

1093 1094 1095

double Item_func_rand::val()
{
1096
  DBUG_ASSERT(fixed == 1);
1097
  return my_rnd(rand);
unknown's avatar
unknown committed
1098 1099 1100 1101
}

longlong Item_func_sign::val_int()
{
1102
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1103 1104 1105 1106 1107 1108 1109 1110
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
}


double Item_func_units::val()
{
1111
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
  double value=args[0]->val();
  if ((null_value=args[0]->null_value))
    return 0;
  return value*mul+add;
}


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

unknown's avatar
unknown committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  for (uint i=0 ; i < arg_count ; i++)
  {
    if (max_length < args[i]->max_length)
      max_length=args[i]->max_length;
    if (decimals < args[i]->decimals)
      decimals=args[i]->decimals;
    if (!args[i]->maybe_null)
      maybe_null=0;
    cmp_type=item_cmp_type(cmp_type,args[i]->result_type());
  }
unknown's avatar
unknown committed
1136
  if (cmp_type == STRING_RESULT)
unknown's avatar
unknown committed
1137
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV);
unknown's avatar
unknown committed
1138 1139 1140 1141 1142
}


String *Item_func_min_max::val_str(String *str)
{
1143
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1144 1145 1146 1147 1148 1149
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
1150
    if (!unsigned_flag)
unknown's avatar
unknown committed
1151
      str->set(nr,&my_charset_bin);
1152
    else
unknown's avatar
unknown committed
1153
      str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
1154 1155 1156 1157 1158 1159 1160
    return str;
  }
  case REAL_RESULT:
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
unknown's avatar
unknown committed
1161
    str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    return str;
  }
  case STRING_RESULT:
  {
    String *res;
    LINT_INIT(res);
    null_value=1;
    for (uint i=0; i < arg_count ; i++)
    {
      if (null_value)
      {
	res=args[i]->val_str(str);
	null_value=args[i]->null_value;
      }
      else
      {
	String *res2;
	res2= args[i]->val_str(res == str ? &tmp_value : str);
	if (res2)
	{
1182
	  int cmp= sortcmp(res,res2,collation.collation);
unknown's avatar
unknown committed
1183 1184 1185 1186 1187
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
    }
unknown's avatar
unknown committed
1188 1189
    if (res)					// If !NULL
      res->set_charset(collation.collation);
unknown's avatar
unknown committed
1190 1191
    return res;
  }
1192
  case ROW_RESULT:
unknown's avatar
unknown committed
1193
  default:
unknown's avatar
unknown committed
1194 1195 1196
    // This case should never be choosen
    DBUG_ASSERT(0);
    return 0;
unknown's avatar
unknown committed
1197 1198 1199 1200 1201 1202 1203
  }
  return 0;					// Keep compiler happy
}


double Item_func_min_max::val()
{
1204
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
  double value=0.0;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
      value=args[i]->val();
      null_value=args[i]->null_value;
    }
    else
    {
      double tmp=args[i]->val();
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
  }
  return value;
}


longlong Item_func_min_max::val_int()
{
1227
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  longlong value=0;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
      value=args[i]->val_int();
      null_value=args[i]->null_value;
    }
    else
    {
      longlong tmp=args[i]->val_int();
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
  }
  return value;
}

longlong Item_func_length::val_int()
{
1249
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) res->length();
}

unknown's avatar
unknown committed
1260

unknown's avatar
unknown committed
1261 1262
longlong Item_func_char_length::val_int()
{
1263
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1264 1265 1266 1267 1268 1269 1270
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
1271
  return (longlong) res->numchars();
unknown's avatar
unknown committed
1272 1273
}

unknown's avatar
unknown committed
1274

unknown's avatar
unknown committed
1275 1276
longlong Item_func_coercibility::val_int()
{
1277
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1278
  null_value= 0;
1279
  return (longlong) args[0]->collation.derivation;
unknown's avatar
unknown committed
1280
}
unknown's avatar
unknown committed
1281

unknown's avatar
unknown committed
1282

1283 1284 1285
void Item_func_locate::fix_length_and_dec()
{
  maybe_null=0; max_length=11;
unknown's avatar
unknown committed
1286
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
1287 1288
}

unknown's avatar
unknown committed
1289

unknown's avatar
unknown committed
1290 1291
longlong Item_func_locate::val_int()
{
1292
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1293 1294 1295 1296 1297 1298 1299 1300
  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;
1301 1302
  uint start=0;
  uint start0=0;
1303
  my_match_t match;
1304

unknown's avatar
unknown committed
1305 1306
  if (arg_count == 3)
  {
1307 1308 1309
    start0= start =(uint) args[2]->val_int()-1;
    start=a->charpos(start);
    
unknown's avatar
unknown committed
1310 1311 1312
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
1313

unknown's avatar
unknown committed
1314 1315
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
1316
  
1317
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
1318
                                            a->ptr()+start, a->length()-start,
1319 1320 1321 1322
                                            b->ptr(), b->length(),
                                            &match, 1))
    return 0;
  return (longlong) match.mblen + start0 + 1;
unknown's avatar
unknown committed
1323 1324 1325
}


1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
void Item_func_locate::print(String *str)
{
  str->append("locate(", 7);
  args[1]->print(str);
  str->append(',');
  args[0]->print(str);
  if (arg_count == 3)
  {
    str->append(',');
    args[2]->print(str);
  }
  str->append(')');
}


unknown's avatar
unknown committed
1341 1342
longlong Item_func_field::val_int()
{
1343
  DBUG_ASSERT(fixed == 1);
1344

1345 1346 1347
  if (cmp_type == STRING_RESULT)
  {
    String *field;
1348
    if (!(field=args[0]->val_str(&value)))
1349
      return 0;					// -1 if null ?
1350
    for (uint i=1 ; i < arg_count ; i++)
1351 1352
    {
      String *tmp_value=args[i]->val_str(&tmp);
unknown's avatar
Fix:  
unknown committed
1353
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
1354
        return (longlong) (i);
1355 1356 1357 1358
    }
  }
  else if (cmp_type == INT_RESULT)
  {
1359
    longlong val= args[0]->val_int();
1360 1361
    if (args[0]->null_value)
      return 0;
1362
    for (uint i=1; i < arg_count ; i++)
1363
    {
1364
      if (val == args[i]->val_int() && !args[i]->null_value)
1365
        return (longlong) (i);
1366 1367 1368
    }
  }
  else
unknown's avatar
unknown committed
1369
  {
1370
    double val= args[0]->val();
1371 1372
    if (args[0]->null_value)
      return 0;
1373
    for (uint i=1; i < arg_count ; i++)
1374
    {
1375
      if (val == args[i]->val() && !args[i]->null_value)
1376
        return (longlong) (i);
1377
    }
unknown's avatar
unknown committed
1378 1379 1380 1381
  }
  return 0;
}

unknown's avatar
unknown committed
1382

1383 1384 1385
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
1386 1387
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
1388 1389
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
unknown's avatar
unknown committed
1390
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV);
1391
}
unknown's avatar
unknown committed
1392

1393

unknown's avatar
unknown committed
1394 1395
longlong Item_func_ascii::val_int()
{
1396
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
  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()
{
1409
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1410 1411 1412 1413 1414 1415 1416 1417 1418
  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
1419
  if (use_mb(res->charset()))
unknown's avatar
unknown committed
1420 1421
  {
    register const char *str=res->ptr();
1422
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
unknown's avatar
unknown committed
1423 1424
    if (!l)
      return (longlong)((uchar) *str);
unknown's avatar
unknown committed
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    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)
      {
1449 1450
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
unknown's avatar
unknown committed
1451 1452 1453 1454 1455 1456
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
unknown's avatar
unknown committed
1457
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
unknown's avatar
unknown committed
1458 1459 1460 1461 1462 1463
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
1464
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
  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)
  {
1488 1489 1490 1491 1492 1493 1494 1495 1496
    my_wc_t wc;
    CHARSET_INFO *cs= cmp_collation.collation;
    const char *str_begin= buffer->ptr();
    const char *str_end= buffer->ptr();
    const char *real_end= str_end+buffer->length();
    const uchar *find_str= (const uchar *) find->ptr();
    uint find_str_len= find->length();
    int position= 0;
    while (1)
unknown's avatar
unknown committed
1497
    {
1498 1499 1500
      int symbol_len;
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
                                       (uchar*) real_end)) > 0)
unknown's avatar
unknown committed
1501
      {
1502 1503
        const char *substr_end= str_end + symbol_len;
        bool is_last_item= (substr_end == real_end);
1504 1505
        bool is_separator= (wc == (my_wc_t) separator);
        if (is_separator || is_last_item)
1506 1507
        {
          position++;
1508
          if (is_last_item && !is_separator)
1509 1510 1511 1512 1513 1514 1515 1516 1517
            str_end= substr_end;
          if (!my_strnncoll(cs, (const uchar *) str_begin,
                            str_end - str_begin,
                            find_str, find_str_len))
            return (longlong) position;
          else
            str_begin= substr_end;
        }
        str_end= substr_end;
unknown's avatar
unknown committed
1518
      }
1519 1520 1521 1522 1523 1524 1525
      else if (str_end - str_begin == 0 && 
               find_str_len == 0 && 
               wc == (my_wc_t) separator)
        return (longlong) ++position;
      else
        return (longlong) 0;
    }
unknown's avatar
unknown committed
1526 1527 1528 1529 1530 1531
  }
  return 0;
}

longlong Item_func_bit_count::val_int()
{
1532
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1533 1534 1535 1536 1537 1538
  ulonglong value= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
unknown's avatar
unknown committed
1539
  return (longlong) my_count_bits(value);
unknown's avatar
unknown committed
1540 1541 1542 1543 1544 1545
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
1546
** Rewritten by monty.
unknown's avatar
unknown committed
1547 1548 1549 1550 1551
****************************************************************************/

#ifdef HAVE_DLOPEN

udf_handler::~udf_handler()
1552 1553 1554 1555 1556 1557 1558
{
  /* Everything should be properly cleaned up by this moment. */
  DBUG_ASSERT(not_original || !(initialized || buffers));
}


void udf_handler::cleanup()
unknown's avatar
unknown committed
1559
{
1560
  if (!not_original)
unknown's avatar
unknown committed
1561
  {
1562
    if (initialized)
unknown's avatar
unknown committed
1563
    {
1564 1565 1566 1567 1568 1569 1570
      if (u_d->func_deinit != NULL)
      {
        void (*deinit)(UDF_INIT *) = (void (*)(UDF_INIT*))
        u_d->func_deinit;
        (*deinit)(&initid);
      }
      free_udf(u_d);
1571
      initialized= FALSE;
unknown's avatar
unknown committed
1572
    }
1573 1574
    if (buffers)				// Because of bug in ecc
      delete [] buffers;
1575
    buffers= 0;
unknown's avatar
unknown committed
1576 1577 1578 1579 1580
  }
}


bool
unknown's avatar
unknown committed
1581
udf_handler::fix_fields(THD *thd, TABLE_LIST *tables, Item_result_field *func,
unknown's avatar
unknown committed
1582 1583
			uint arg_count, Item **arguments)
{
1584
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
1585
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
1586
#endif
unknown's avatar
unknown committed
1587 1588
  DBUG_ENTER("Item_udf_func::fix_fields");

unknown's avatar
unknown committed
1589 1590 1591
  if (check_stack_overrun(thd, buff))
    DBUG_RETURN(1);				// Fatal error flag is set!

1592
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
unknown's avatar
unknown committed
1593 1594 1595

  if (!tmp_udf)
  {
1596
    my_printf_error(ER_CANT_FIND_UDF,ER(ER_CANT_FIND_UDF),MYF(0),u_d->name.str,
unknown's avatar
unknown committed
1597 1598 1599 1600 1601 1602 1603
		    errno);
    DBUG_RETURN(1);
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
1604
  func->maybe_null=0;
unknown's avatar
unknown committed
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
  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);
      DBUG_RETURN(1);
    }
    uint i;
    Item **arg,**arg_end;
    for (i=0, arg=arguments, arg_end=arguments+arg_count;
	 arg != arg_end ;
	 arg++,i++)
    {
unknown's avatar
unknown committed
1623 1624
      if (!(*arg)->fixed && 
          (*arg)->fix_fields(thd, tables, arg))
unknown's avatar
unknown committed
1625
	DBUG_RETURN(1);
1626
      // we can't assign 'item' before, because fix_fields() can change arg
unknown's avatar
unknown committed
1627
      Item *item= *arg;
1628
      if (item->check_cols(1))
unknown's avatar
unknown committed
1629
	DBUG_RETURN(1);
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
      /*
	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
	the particular user definted function.
      */
1641 1642
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
unknown's avatar
unknown committed
1643
      if (item->maybe_null)
unknown's avatar
unknown committed
1644
	func->maybe_null=1;
unknown's avatar
unknown committed
1645 1646 1647 1648
      func->with_sum_func= func->with_sum_func || item->with_sum_func;
      used_tables_cache|=item->used_tables();
      const_item_cache&=item->const_item();
      f_args.arg_type[i]=item->result_type();
unknown's avatar
unknown committed
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 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    }
    if (!(buffers=new String[arg_count]) ||
	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
	!(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(ALIGN_SIZE(sizeof(double))*arg_count)))
    {
      free_udf(u_d);
      DBUG_RETURN(1);
    }
  }
  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;
      f_args.lengths[i]=arguments[i]->max_length;
      f_args.maybe_null[i]=(char) arguments[i]->maybe_null;

      switch(arguments[i]->type()) {
      case Item::STRING_ITEM:			// Constant string !
      {
	String *res=arguments[i]->val_str((String *) 0);
	if (arguments[i]->null_value)
	  continue;
	f_args.args[i]=    (char*) res->ptr();
	break;
      }
      case Item::INT_ITEM:
	*((longlong*) to) = arguments[i]->val_int();
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(longlong));
	}
	break;
      case Item::REAL_ITEM:
	*((double*) to) = arguments[i]->val();
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(double));
	}
	break;
      default:					// Skip these
	break;
      }
    }
1705
    thd->net.last_error[0]=0;
unknown's avatar
unknown committed
1706 1707 1708 1709 1710 1711
    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)))
    {
      my_printf_error(ER_CANT_INITIALIZE_UDF,ER(ER_CANT_INITIALIZE_UDF),MYF(0),
1712
		      u_d->name.str, thd->net.last_error);
unknown's avatar
unknown committed
1713 1714 1715 1716 1717 1718
      free_udf(u_d);
      DBUG_RETURN(1);
    }
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
    func->maybe_null=initid.maybe_null;
    const_item_cache=initid.const_item;
1719
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
unknown's avatar
unknown committed
1720 1721 1722 1723 1724
  }
  initialized=1;
  if (error)
  {
    my_printf_error(ER_CANT_INITIALIZE_UDF,ER(ER_CANT_INITIALIZE_UDF),MYF(0),
1725
		    u_d->name.str, ER(ER_UNKNOWN_ERROR));
unknown's avatar
unknown committed
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
    DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}


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:
      {
	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:
      *((double*) to) = args[i]->val();
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(double));
      }
      break;
1768
    case ROW_RESULT:
unknown's avatar
unknown committed
1769
    default:
unknown's avatar
unknown committed
1770 1771
      // This case should never be choosen
      DBUG_ASSERT(0);
1772
      break;
unknown's avatar
unknown committed
1773 1774 1775 1776 1777 1778 1779 1780 1781
    }
  }
  return 0;
}

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

String *udf_handler::val_str(String *str,String *save_str)
{
1782
  uchar is_null_tmp=0;
unknown's avatar
unknown committed
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
  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;
    }
  }
1799 1800 1801
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
		 &is_null_tmp, &error);
  if (is_null_tmp || !res || error)		// The !res is for safety
unknown's avatar
unknown committed
1802 1803 1804 1805 1806 1807 1808 1809
  {
    return 0;
  }
  if (res == str->ptr())
  {
    str->length(res_length);
    return str;
  }
1810
  save_str->set(res, res_length, str->charset());
unknown's avatar
unknown committed
1811 1812 1813 1814
  return save_str;
}


1815 1816 1817 1818 1819 1820
void Item_udf_func::cleanup()
{
  udf.cleanup();
  Item_func::cleanup();
}

unknown's avatar
unknown committed
1821 1822 1823

double Item_func_udf_float::val()
{
1824
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1825 1826 1827 1828 1829 1830 1831 1832 1833
  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)
{
1834
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1835 1836 1837
  double nr=val();
  if (null_value)
    return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
1838
  str->set(nr,decimals,&my_charset_bin);
unknown's avatar
unknown committed
1839 1840 1841 1842 1843 1844
  return str;
}


longlong Item_func_udf_int::val_int()
{
1845
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
  DBUG_ENTER("Item_func_udf_int::val_int");
  DBUG_PRINT("info",("result_type: %d  arg_count: %d",
		     args[0]->result_type(), arg_count));

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


String *Item_func_udf_int::val_str(String *str)
{
1856
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1857 1858 1859
  longlong nr=val_int();
  if (null_value)
    return 0;
1860
  if (!unsigned_flag)
unknown's avatar
unknown committed
1861
    str->set(nr,&my_charset_bin);
1862
  else
unknown's avatar
unknown committed
1863
    str->set((ulonglong) nr,&my_charset_bin);
unknown's avatar
unknown committed
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
  return str;
}

/* 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)
{
1880
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
  String *res=udf.val_str(str,&str_value);
  null_value = !res;
  return res;
}

#else
bool udf_handler::get_arguments() { return 0; }
#endif /* HAVE_DLOPEN */

/*
** User level locks
*/

pthread_mutex_t LOCK_user_locks;
static HASH hash_user_locks;

1897
class User_level_lock
unknown's avatar
unknown committed
1898 1899 1900 1901 1902 1903 1904 1905 1906
{
  char *key;
  uint key_length;

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

1909
  User_level_lock(const char *key_arg,uint length, ulong id) 
unknown's avatar
SCRUM  
unknown committed
1910
    :key_length(length),count(1),locked(1), thread_id(id)
unknown's avatar
unknown committed
1911 1912 1913 1914 1915
  {
    key=(char*) my_memdup((byte*) key_arg,length,MYF(0));
    pthread_cond_init(&cond,NULL);
    if (key)
    {
unknown's avatar
SCRUM  
unknown committed
1916
      if (my_hash_insert(&hash_user_locks,(byte*) this))
unknown's avatar
unknown committed
1917 1918 1919 1920 1921 1922
      {
	my_free((gptr) key,MYF(0));
	key=0;
      }
    }
  }
1923
  ~User_level_lock()
unknown's avatar
unknown committed
1924 1925 1926 1927 1928 1929 1930 1931 1932
  {
    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; }
1933 1934 1935
  friend void item_user_lock_release(User_level_lock *ull);
  friend char *ull_get_key(const User_level_lock *ull, uint *length,
                           my_bool not_used);
unknown's avatar
unknown committed
1936 1937
};

1938
char *ull_get_key(const User_level_lock *ull, uint *length,
unknown's avatar
unknown committed
1939 1940 1941 1942 1943 1944
		  my_bool not_used __attribute__((unused)))
{
  *length=(uint) ull->key_length;
  return (char*) ull->key;
}

1945 1946 1947

static bool item_user_lock_inited= 0;

unknown's avatar
unknown committed
1948 1949
void item_user_lock_init(void)
{
1950
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
unknown's avatar
unknown committed
1951 1952
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
1953
  item_user_lock_inited= 1;
unknown's avatar
unknown committed
1954 1955 1956 1957
}

void item_user_lock_free(void)
{
1958 1959 1960 1961 1962 1963
  if (item_user_lock_inited)
  {
    item_user_lock_inited= 0;
    hash_free(&hash_user_locks);
    pthread_mutex_destroy(&LOCK_user_locks);
  }
unknown's avatar
unknown committed
1964 1965
}

1966
void item_user_lock_release(User_level_lock *ull)
unknown's avatar
unknown committed
1967 1968
{
  ull->locked=0;
unknown's avatar
unknown committed
1969 1970 1971
  if (mysql_bin_log.is_open())
  {
    char buf[256];
unknown's avatar
unknown committed
1972 1973
    const char *command="DO RELEASE_LOCK(\"";
    String tmp(buf,sizeof(buf), system_charset_info);
unknown's avatar
unknown committed
1974
    tmp.copy(command, strlen(command), tmp.charset());
unknown's avatar
unknown committed
1975
    tmp.append(ull->key,ull->key_length);
1976
    tmp.append("\")", 2);
1977
    Query_log_event qev(current_thd, tmp.ptr(), tmp.length(),1, FALSE);
1978
    qev.error_code=0; // this query is always safe to run on slave
unknown's avatar
unknown committed
1979 1980
    mysql_bin_log.write(&qev);
  }
unknown's avatar
unknown committed
1981 1982 1983 1984 1985 1986
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

unknown's avatar
unknown committed
1987 1988 1989 1990 1991 1992 1993
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

longlong Item_master_pos_wait::val_int()
{
1994
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
1995 1996
  THD* thd = current_thd;
  String *log_name = args[0]->val_str(&value);
1997
  int event_count= 0;
unknown's avatar
unknown committed
1998

unknown's avatar
unknown committed
1999 2000 2001 2002 2003 2004
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
unknown's avatar
unknown committed
2005
  longlong pos = (ulong)args[1]->val_int();
2006
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
unknown's avatar
SCRUM  
unknown committed
2007
#ifdef HAVE_REPLICATION
2008
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
unknown's avatar
unknown committed
2009 2010 2011 2012
  {
    null_value = 1;
    event_count=0;
  }
2013
#endif
unknown's avatar
unknown committed
2014 2015 2016
  return event_count;
}

2017 2018 2019 2020
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
2021
  User_level_lock* ull;
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
  struct timespec abstime;
  int lock_name_len,error=0;
  lock_name_len=strlen(lock_name);
  pthread_mutex_lock(&LOCK_user_locks);

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

2033 2034 2035 2036 2037
  /*
    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
2038
  */
2039
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, lock_name,
2040 2041 2042 2043 2044 2045 2046
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

2047 2048 2049 2050
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
2051 2052 2053 2054
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

2055
  set_timespec(abstime,lock_timeout);
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
	 != ETIME && error != ETIMEDOUT && ull->locked) ;
  if (ull->locked)
  {
    if (!--ull->count)
      delete ull;				// Should never happen
  }
  else
  {
    ull->locked=1;
    ull->thread=thd->real_id;
    thd->ull=ull;
  }
  pthread_mutex_unlock(&LOCK_user_locks);
  pthread_mutex_lock(&thd->mysys_var->mutex);
  thd->proc_info=0;
  thd->mysys_var->current_mutex= 0;
  thd->mysys_var->current_cond=  0;
  pthread_mutex_unlock(&thd->mysys_var->mutex);
  pthread_mutex_lock(&LOCK_user_locks);
  if (thd->ull)
  {
    item_user_lock_release(thd->ull);
    thd->ull=0;
  }
  pthread_mutex_unlock(&LOCK_user_locks);
}

#endif

unknown's avatar
unknown committed
2087 2088 2089 2090 2091 2092 2093 2094 2095
/*
  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()
{
2096
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2097 2098 2099 2100
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
2101
  User_level_lock *ull;
unknown's avatar
unknown committed
2102
  int error=0;
unknown's avatar
unknown committed
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119

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

2120 2121 2122
  if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks,
                                              (byte*) res->ptr(),
                                              res->length()))))
unknown's avatar
unknown committed
2123
  {
2124
    ull=new User_level_lock(res->ptr(),res->length(), thd->thread_id);
unknown's avatar
unknown committed
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
    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++;

2139 2140 2141 2142
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks.
  */
unknown's avatar
unknown committed
2143 2144 2145 2146
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

2147
  set_timespec(abstime,timeout);
unknown's avatar
unknown committed
2148 2149
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
2150
	 != ETIME && error != ETIMEDOUT && error != EINVAL && ull->locked) ;
unknown's avatar
unknown committed
2151 2152
  if (thd->killed)
    error=EINTR;				// Return NULL
unknown's avatar
unknown committed
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
  if (ull->locked)
  {
    if (!--ull->count)
      delete ull;				// Should never happen
    if (error != ETIME && error != ETIMEDOUT)
    {
      error=1;
      null_value=1;				// Return NULL
    }
  }
  else
  {
    ull->locked=1;
    ull->thread=thd->real_id;
    thd->ull=ull;
    error=0;
  }
  pthread_mutex_unlock(&LOCK_user_locks);

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

  return !error ? 1 : 0;
}


/*
2183 2184 2185 2186 2187
  Release a user level lock.
  Return:
    1 if lock released
    0 if lock wasn't held
    (SQL) NULL if no such lock
unknown's avatar
unknown committed
2188 2189 2190 2191
*/

longlong Item_func_release_lock::val_int()
{
2192
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2193
  String *res=args[0]->val_str(&value);
2194
  User_level_lock *ull;
unknown's avatar
unknown committed
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
  longlong result;
  if (!res || !res->length())
  {
    null_value=1;
    return 0;
  }
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
2205 2206 2207
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
                                             (const byte*) res->ptr(),
                                             res->length()))))
unknown's avatar
unknown committed
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
  {
    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;
}


2225
longlong Item_func_last_insert_id::val_int()
unknown's avatar
unknown committed
2226
{
2227
  DBUG_ASSERT(fixed == 1);
2228 2229 2230 2231 2232 2233 2234
  if (arg_count)
  {
    longlong value=args[0]->val_int();
    current_thd->insert_id(value);
    null_value=args[0]->null_value;
  }
  else
unknown's avatar
unknown committed
2235 2236
    current_thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
  return current_thd->insert_id();
unknown's avatar
unknown committed
2237 2238 2239 2240 2241 2242
}

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

longlong Item_func_benchmark::val_int()
{
2243
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2244
  char buff[MAX_FIELD_WIDTH];
unknown's avatar
unknown committed
2245
  String tmp(buff,sizeof(buff), &my_charset_bin);
unknown's avatar
unknown committed
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
  THD *thd=current_thd;

  for (ulong loop=0 ; loop < loop_count && !thd->killed; loop++)
  {
    switch (args[0]->result_type()) {
    case REAL_RESULT:
      (void) args[0]->val();
      break;
    case INT_RESULT:
      (void) args[0]->val_int();
      break;
    case STRING_RESULT:
      (void) args[0]->val_str(&tmp);
      break;
2260
    case ROW_RESULT:
unknown's avatar
unknown committed
2261
    default:
unknown's avatar
unknown committed
2262 2263 2264
      // This case should never be choosen
      DBUG_ASSERT(0);
      return 0;
unknown's avatar
unknown committed
2265 2266 2267 2268 2269
    }
  }
  return 0;
}

2270

2271 2272 2273 2274
void Item_func_benchmark::print(String *str)
{
  str->append("benchmark(", 10);
  char buffer[20];
unknown's avatar
unknown committed
2275 2276 2277
  // my_charset_bin is good enough for numbers
  String st(buffer, sizeof(buffer), &my_charset_bin);
  st.set((ulonglong)loop_count, &my_charset_bin);
2278 2279 2280 2281 2282 2283
  str->append(st);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}

unknown's avatar
unknown committed
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
#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;
2305
    entry->update_query_id=0;
2306
    entry->collation.set(NULL, DERIVATION_IMPLICIT);
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    /*
      If we are here, we were called from a SET or a query which sets a
      variable. Imagine it is this:
      INSERT INTO t SELECT @a:=10, @a:=@a+1.
      Then when we have a Item_func_get_user_var (because of the @a+1) so we
      think we have to write the value of @a to the binlog. But before that,
      we have a Item_func_set_user_var to create @a (@a:=10), in this we mark
      the variable as "already logged" (line below) so that it won't be logged
      by Item_func_get_user_var (because that's not necessary).
    */
unknown's avatar
unknown committed
2317
    entry->used_query_id=current_thd->query_id;
unknown's avatar
unknown committed
2318 2319
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
unknown's avatar
SCRUM  
unknown committed
2320
    if (my_hash_insert(hash,(byte*) entry))
unknown's avatar
unknown committed
2321 2322 2323 2324 2325 2326 2327 2328
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

2329
/*
2330 2331
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
2332
*/
2333

unknown's avatar
unknown committed
2334 2335
bool Item_func_set_user_var::fix_fields(THD *thd, TABLE_LIST *tables,
					Item **ref)
unknown's avatar
unknown committed
2336
{
2337
  DBUG_ASSERT(fixed == 0);
2338
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
unknown's avatar
unknown committed
2339
  if (Item_func::fix_fields(thd, tables, ref) ||
unknown's avatar
unknown committed
2340 2341
      !(entry= get_variable(&thd->user_vars, name, 1)))
    return 1;
2342 2343 2344 2345 2346
  /* 
     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).
  */
2347
  entry->update_query_id= thd->query_id;
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
  /*
    As it is wrong and confusing to associate any 
    character set with NULL, @a should be latin2
    after this query sequence:

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

    I.e. the second query should not change the charset
    to the current default value, but should keep the 
    original value assigned during the first query.
    In order to do it, we don't copy charset
    from the argument if the argument is NULL
    and the variable has previously been initialized.
  */
  if (!entry->collation.collation || !args[0]->null_value)
2364 2365
    entry->collation.set(args[0]->collation.collation, DERIVATION_IMPLICIT);
  collation.set(entry->collation.collation, DERIVATION_IMPLICIT);
2366
  cached_result_type= args[0]->result_type();
unknown's avatar
unknown committed
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
  return 0;
}


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

2380

unknown's avatar
unknown committed
2381
bool Item_func_set_user_var::update_hash(void *ptr, uint length,
2382
					 Item_result type,
2383
					 CHARSET_INFO *cs,
2384
					 Derivation dv)
unknown's avatar
unknown committed
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
{
  if ((null_value=args[0]->null_value))
  {
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
    if (entry->value && entry->value != pos)
      my_free(entry->value,MYF(0));
    entry->value=0;
    entry->length=0;
  }
  else
  {
2396 2397
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
unknown's avatar
unknown committed
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
    if (length <= extra_size)
    {
      /* Save value in value struct */
      char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
      if (entry->value != pos)
      {
	if (entry->value)
	  my_free(entry->value,MYF(0));
	entry->value=pos;
      }
    }
    else
    {
      /* Allocate variable */
      if (entry->length != length)
      {
	char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
	if (entry->value == pos)
	  entry->value=0;
	if (!(entry->value=(char*) my_realloc(entry->value, length,
					      MYF(MY_ALLOW_ZERO_PTR))))
	  goto err;
      }
    }
2422 2423 2424 2425 2426
    if (type == STRING_RESULT)
    {
      length--;					// Fix length change above
      entry->value[length]= 0;			// Store end \0
    }
unknown's avatar
unknown committed
2427 2428 2429
    memcpy(entry->value,ptr,length);
    entry->length= length;
    entry->type=type;
2430
    entry->collation.set(cs, dv);
unknown's avatar
unknown committed
2431
  }
2432
  return 0;
unknown's avatar
unknown committed
2433 2434

 err:
2435
  current_thd->fatal_error();			// Probably end of memory
unknown's avatar
unknown committed
2436 2437
  null_value= 1;
  return 1;
unknown's avatar
unknown committed
2438 2439 2440
}


2441 2442 2443
/* Get the value of a variable as a double */

double user_var_entry::val(my_bool *null_value)
unknown's avatar
unknown committed
2444
{
2445 2446 2447 2448 2449 2450 2451 2452 2453
  if ((*null_value= (value == 0)))
    return 0.0;

  switch (type) {
  case REAL_RESULT:
    return *(double*) value;
  case INT_RESULT:
    return (double) *(longlong*) value;
  case STRING_RESULT:
unknown's avatar
unknown committed
2454
    return my_atof(value);                      // This is null terminated
2455 2456 2457
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
2458
  }
2459
  return 0.0;					// Impossible
unknown's avatar
unknown committed
2460 2461 2462
}


2463 2464 2465
/* Get the value of a variable as an integer */

longlong user_var_entry::val_int(my_bool *null_value)
unknown's avatar
unknown committed
2466
{
2467 2468 2469 2470 2471 2472 2473 2474
  if ((*null_value= (value == 0)))
    return LL(0);

  switch (type) {
  case REAL_RESULT:
    return (longlong) *(double*) value;
  case INT_RESULT:
    return *(longlong*) value;
unknown's avatar
unknown committed
2475
  case STRING_RESULT:
unknown's avatar
unknown committed
2476 2477 2478 2479
  {
    int error;
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
  }
2480 2481 2482
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
2483
  }
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
  return LL(0);					// Impossible
}


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

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

  switch (type) {
  case REAL_RESULT:
unknown's avatar
unknown committed
2498
    str->set(*(double*) value, decimals, &my_charset_bin);
2499 2500
    break;
  case INT_RESULT:
unknown's avatar
unknown committed
2501
    str->set(*(longlong*) value, &my_charset_bin);
2502 2503
    break;
  case STRING_RESULT:
unknown's avatar
unknown committed
2504
    if (str->copy(value, length, collation.collation))
2505
      str= 0;					// EOM error
2506 2507 2508
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
unknown's avatar
unknown committed
2509
  }
2510
  return(str);
unknown's avatar
unknown committed
2511 2512
}

2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
/*
  This functions is invoked on SET @variable or @variable:= expression.
  Evaluete (and check expression), store results.

  SYNOPSYS
    Item_func_set_user_var::check()

  NOTES
    For now it always return OK. All problem with value evalueting
    will be catched by thd->net.report_error check in sql_set_variables().

  RETURN
    0 - OK.
*/

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

  switch (cached_result_type) {
  case REAL_RESULT:
  {
    save_result.vreal= args[0]->val();
    break;
  }
  case INT_RESULT:
  {
    save_result.vint= args[0]->val_int();
    break;
  }
  case STRING_RESULT:
  {
    save_result.vstr= args[0]->val_str(&value);
    break;
  }
  case ROW_RESULT:
  default:
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
  }
  DBUG_RETURN(0);
}

2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574

/*
  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
    0	Ok
    1	EOM Error

*/

unknown's avatar
unknown committed
2575 2576 2577
bool
Item_func_set_user_var::update()
{
2578 2579 2580 2581
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

unknown's avatar
unknown committed
2582 2583
  switch (cached_result_type) {
  case REAL_RESULT:
unknown's avatar
unknown committed
2584
  {
2585
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
2586
		     REAL_RESULT, &my_charset_bin, DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
2587
    break;
unknown's avatar
unknown committed
2588
  }
unknown's avatar
unknown committed
2589
  case INT_RESULT:
2590
  {
2591
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
2592
		     INT_RESULT, &my_charset_bin, DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
2593
    break;
unknown's avatar
unknown committed
2594
  }
unknown's avatar
unknown committed
2595
  case STRING_RESULT:
unknown's avatar
unknown committed
2596
  {
2597
    if (!save_result.vstr)					// Null value
unknown's avatar
unknown committed
2598
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
2599
		       DERIVATION_IMPLICIT);
2600
    else
2601 2602 2603
      res= update_hash((void*) save_result.vstr->ptr(),
		       save_result.vstr->length(), STRING_RESULT,
		       save_result.vstr->charset(),
2604
		       DERIVATION_IMPLICIT);
unknown's avatar
unknown committed
2605 2606
    break;
  }
2607
  case ROW_RESULT:
unknown's avatar
unknown committed
2608
  default:
unknown's avatar
unknown committed
2609 2610 2611 2612
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
  }
2613
  DBUG_RETURN(res);
unknown's avatar
unknown committed
2614 2615 2616
}


2617
double Item_func_set_user_var::val()
unknown's avatar
unknown committed
2618
{
2619
  DBUG_ASSERT(fixed == 1);
2620
  check();
2621 2622
  update();					// Store expression
  return entry->val(&null_value);
unknown's avatar
unknown committed
2623 2624
}

2625
longlong Item_func_set_user_var::val_int()
unknown's avatar
unknown committed
2626
{
2627
  DBUG_ASSERT(fixed == 1);
2628
  check();
2629 2630
  update();					// Store expression
  return entry->val_int(&null_value);
unknown's avatar
unknown committed
2631 2632
}

2633
String *Item_func_set_user_var::val_str(String *str)
unknown's avatar
unknown committed
2634
{
2635
  DBUG_ASSERT(fixed == 1);
2636
  check();
2637 2638
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
unknown's avatar
unknown committed
2639 2640 2641
}


unknown's avatar
unknown committed
2642 2643
void Item_func_set_user_var::print(String *str)
{
2644 2645 2646
  str->append("(@", 2);
  str->append(name.str, name.length);
  str->append(":=", 2);
unknown's avatar
unknown committed
2647 2648 2649 2650 2651
  args[0]->print(str);
  str->append(')');
}


unknown's avatar
unknown committed
2652 2653 2654
String *
Item_func_get_user_var::val_str(String *str)
{
2655
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2656
  DBUG_ENTER("Item_func_get_user_var::val_str");
2657
  if (!var_entry)
2658
    DBUG_RETURN((String*) 0);			// No such variable
2659
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
unknown's avatar
unknown committed
2660 2661 2662 2663 2664
}


double Item_func_get_user_var::val()
{
2665
  DBUG_ASSERT(fixed == 1);
2666 2667 2668
  if (!var_entry)
    return 0.0;					// No such variable
  return (var_entry->val(&null_value));
unknown's avatar
unknown committed
2669 2670 2671 2672 2673
}


longlong Item_func_get_user_var::val_int()
{
2674
  DBUG_ASSERT(fixed == 1);
2675 2676 2677
  if (!var_entry)
    return LL(0);				// No such variable
  return (var_entry->val_int(&null_value));
unknown's avatar
unknown committed
2678 2679 2680
}


2681
/*
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691
  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.

2692 2693 2694 2695
  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).
2696 2697 2698 2699 2700
  
  RETURN
    0  OK 
    1  Failed to put appropiate record into binary log
    
2701 2702
*/

2703 2704
int get_var_with_binlog(THD *thd, LEX_STRING &name, 
                        user_var_entry **out_entry)
unknown's avatar
unknown committed
2705
{
2706
  BINLOG_USER_VAR_EVENT *user_var_event;
2707 2708
  user_var_entry *var_entry;
  var_entry= get_variable(&thd->user_vars, name, 0);
2709
  
2710
  if (!(opt_bin_log && is_update_query(thd->lex->sql_command)))
2711 2712 2713 2714
  {
    *out_entry= var_entry;
    return 0;
  }
2715 2716

  if (!var_entry)
unknown's avatar
unknown committed
2717
  {
2718
    /*
2719 2720 2721 2722
      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).
2723 2724 2725 2726 2727
      We create it like if it had been explicitely set with SET before.
      The 'new' mimicks what sql_yacc.yy does when 'SET @a=10;'.
      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();
2728 2729
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
2730 2731 2732 2733 2734
    */

    List<set_var_base> tmp_var_list;
    tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
                                                                       new Item_null())));
2735 2736
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
2737 2738 2739 2740 2741
      goto err;
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
  else if (var_entry->used_query_id == thd->query_id)
2742 2743 2744 2745 2746 2747 2748 2749 2750
  {
    /* 
       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;
  }
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773

  uint size;
  /*
    First we need to store value of var_entry, when the next situation
    appers:
    > set @a:=1;
    > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
    We have to write to binlog value @a= 1;
  */
  size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;      
  if (!(user_var_event= (BINLOG_USER_VAR_EVENT *) thd->alloc(size)))
    goto err;
  
  user_var_event->value= (char*) user_var_event +
    ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
  user_var_event->user_var_event= var_entry;
  user_var_event->type= var_entry->type;
  user_var_event->charset_number= var_entry->collation.collation->number;
  if (!var_entry->value)
  {
    /* NULL value*/
    user_var_event->length= 0;
    user_var_event->value= 0;
unknown's avatar
unknown committed
2774
  }
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
  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;
2785 2786 2787
  
  *out_entry= var_entry;
  return 0;
2788

unknown's avatar
unknown committed
2789
err:
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
  *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;
2802

2803
  error= get_var_with_binlog(thd, name, &var_entry);
2804 2805

  if (var_entry)
2806
  {
2807
    collation.set(var_entry->collation);
2808 2809 2810 2811 2812 2813 2814 2815 2816
    switch (var_entry->type) {
    case REAL_RESULT:
      max_length= DBL_DIG + 8;
    case INT_RESULT:
      max_length= MAX_BIGINT_WIDTH;
      break;
    case STRING_RESULT:
      max_length= MAX_BLOB_WIDTH;
      break;
unknown's avatar
unknown committed
2817 2818
    case ROW_RESULT:                            // Keep compiler happy
      break;
2819 2820
    }
  }
2821
  else
2822 2823
  {
    collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
2824
    null_value= 1;
2825
  }
2826

2827 2828
  if (error)
    thd->fatal_error();
2829

unknown's avatar
unknown committed
2830
  return;
unknown's avatar
unknown committed
2831 2832 2833
}


2834
bool Item_func_get_user_var::const_item() const
2835
{
2836
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
2837
}
unknown's avatar
unknown committed
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849


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

unknown's avatar
unknown committed
2850 2851 2852

void Item_func_get_user_var::print(String *str)
{
2853
  str->append("(@", 2);
unknown's avatar
unknown committed
2854 2855 2856 2857
  str->append(name.str,name.length);
  str->append(')');
}

2858

2859
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
unknown's avatar
unknown committed
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
{
  /* Assume we don't have rtti */
  if (this == item)
    return 1;					// Same item is same.
  /* Check if other type is also a get_user_var() object */
  if (item->type() != FUNC_ITEM ||
      ((Item_func*) item)->func_name() != func_name())
    return 0;
  Item_func_get_user_var *other=(Item_func_get_user_var*) item;
  return (name.length == other->name.length &&
	  !memcmp(name.str, other->name.str, name.length));
}


2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
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
Item_func_get_system_var::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
{
2888
  Item *item;
2889
  DBUG_ENTER("Item_func_get_system_var::fix_fields");
2890

2891 2892 2893 2894 2895
  /*
    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().
  */
2896
  if (!(item= var->item(thd, var_type, &component)))
2897 2898 2899 2900 2901 2902 2903 2904
    DBUG_RETURN(1);                             // Impossible
  item->set_name(name, 0, system_charset_info); // don't allocate a new name
  thd->change_item_tree(ref, item);

  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
2905 2906
longlong Item_func_inet_aton::val_int()
{
2907
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
2908 2909 2910 2911 2912
  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];
2913
  int dot_count= 0;
unknown's avatar
unknown committed
2914

unknown's avatar
unknown committed
2915
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
unknown's avatar
unknown committed
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931
  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 == '.')
    {
2932
      dot_count++;
unknown's avatar
unknown committed
2933 2934 2935 2936 2937 2938 2939
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
2940
  {
2941 2942 2943 2944 2945 2946
    /*
      Handle short-forms addresses according to standard. Examples:
      127		-> 0.0.0.127
      127.1		-> 127.0.0.1
      127.2.1		-> 127.2.0.1
    */
unknown's avatar
unknown committed
2947
    switch (dot_count) {
2948 2949
    case 1: result<<= 8; /* Fall through */
    case 2: result<<= 8; /* Fall through */
2950
    }
unknown's avatar
unknown committed
2951
    return (result << 8) + (ulonglong) byte_result;
2952
  }
unknown's avatar
unknown committed
2953 2954 2955 2956 2957 2958

err:
  null_value=1;
  return 0;
}

unknown's avatar
unknown committed
2959

unknown's avatar
unknown committed
2960
void Item_func_match::init_search(bool no_order)
2961
{
unknown's avatar
unknown committed
2962
  DBUG_ENTER("Item_func_match::init_search");
2963 2964

  /* Check if init_search() has been called before */
2965
  if (ft_handler)
unknown's avatar
unknown committed
2966
    DBUG_VOID_RETURN;
2967

2968
  if (key == NO_SUCH_KEY)
2969 2970
  {
    List<Item> fields;
2971
    fields.push_back(new Item_string(" ",1, cmp_collation.collation));
2972 2973
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
2974
    concat=new Item_func_concat_ws(fields);
unknown's avatar
unknown committed
2975 2976 2977
    /*
      Above function used only to get value and do not need fix_fields for it:
      Item_string - basic constant
unknown's avatar
unknown committed
2978 2979
      fields - fix_fields() was already called for this arguments
      Item_func_concat_ws - do not need fix_fields() to produce value
unknown's avatar
unknown committed
2980 2981
    */
    concat->quick_fix_field();
2982
  }
2983

2984 2985
  if (master)
  {
unknown's avatar
unknown committed
2986 2987
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
2988 2989
    ft_handler=master->ft_handler;
    join_key=master->join_key;
unknown's avatar
unknown committed
2990
    DBUG_VOID_RETURN;
2991 2992
  }

unknown's avatar
unknown committed
2993
  String *ft_tmp= 0;
2994

2995
  // MATCH ... AGAINST (NULL) is meaningless, but possible
2996
  if (!(ft_tmp=key_item()->val_str(&value)))
2997
  {
2998 2999
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
3000 3001
  }

3002 3003
  if (ft_tmp->charset() != cmp_collation.collation)
  {
unknown's avatar
unknown committed
3004
    uint dummy_errors;
3005
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
unknown's avatar
unknown committed
3006
                      cmp_collation.collation, &dummy_errors);
3007
    ft_tmp= &search_value;
3008 3009
  }

3010 3011
  if (join_key && !no_order)
    flags|=FT_SORTED;
3012
  ft_handler=table->file->ft_init_ext(flags, key, ft_tmp);
3013 3014 3015

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

  DBUG_VOID_RETURN;
3018 3019
}

unknown's avatar
unknown committed
3020

unknown's avatar
unknown committed
3021
bool Item_func_match::fix_fields(THD *thd, TABLE_LIST *tlist, Item **ref)
unknown's avatar
unknown committed
3022
{
3023
  DBUG_ASSERT(fixed == 0);
unknown's avatar
unknown committed
3024
  Item *item;
3025
  LINT_INIT(item);				// Safe as arg_count is > 1
unknown's avatar
unknown committed
3026

3027 3028 3029
  maybe_null=1;
  join_key=0;

3030 3031 3032 3033 3034
  /*
    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.
3035
   */
3036 3037
  if (Item_func::fix_fields(thd, tlist, ref) ||
      !args[0]->const_during_execution())
3038 3039
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
unknown's avatar
unknown committed
3040
    return 1;
3041
  }
unknown's avatar
unknown committed
3042

3043 3044
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
unknown's avatar
unknown committed
3045
  {
3046
    item=args[i];
unknown's avatar
unknown committed
3047
    if (item->type() == Item::REF_ITEM)
3048 3049
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
3050
      key=NO_SUCH_KEY;
unknown's avatar
unknown committed
3051
  }
3052 3053
  /*
    Check that all columns come from the same table.
3054
    We've already checked that columns in MATCH are fields so
3055 3056 3057
    PARAM_TABLE_BIT can only appear from AGAINST argument.
  */
  if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
3058
    key=NO_SUCH_KEY;
3059

3060
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
3061 3062
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
unknown's avatar
unknown committed
3063
    return 1;
3064
  }
3065
  table=((Item_field *)item)->field->table;
unknown's avatar
unknown committed
3066
  if (!(table->file->table_flags() & HA_CAN_FULLTEXT))
3067
  {
unknown's avatar
unknown committed
3068
    my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
unknown's avatar
unknown committed
3069
    return 1;
3070
  }
3071 3072
  table->fulltext_searched=1;
  return agg_arg_collations_for_comparison(cmp_collation, args+1, arg_count-1);
unknown's avatar
unknown committed
3073
}
3074

unknown's avatar
unknown committed
3075 3076 3077
bool Item_func_match::fix_index()
{
  Item_field *item;
3078
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
3079
  uint max_cnt=0, mkeys=0, i;
3080

3081
  if (key == NO_SUCH_KEY)
3082
    return 0;
3083 3084 3085
  
  if (!table) 
    goto err;
unknown's avatar
unknown committed
3086

3087
  for (keynr=0 ; keynr < table->keys ; keynr++)
unknown's avatar
unknown committed
3088
  {
3089
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
unknown's avatar
unknown committed
3090
        (table->keys_in_use_for_query.is_set(keynr)))
unknown's avatar
unknown committed
3091
    {
3092
      ft_to_key[fts]=keynr;
unknown's avatar
unknown committed
3093 3094 3095 3096 3097 3098
      ft_cnt[fts]=0;
      fts++;
    }
  }

  if (!fts)
3099
    goto err;
unknown's avatar
unknown committed
3100

3101
  for (i=1; i < arg_count; i++)
unknown's avatar
unknown committed
3102
  {
3103
    item=(Item_field*)args[i];
3104
    for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
3105
    {
3106
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
unknown's avatar
unknown committed
3107 3108 3109 3110 3111
      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))
3112
	  ft_cnt[keynr]++;
unknown's avatar
unknown committed
3113 3114 3115 3116
      }
    }
  }

3117
  for (keynr=0 ; keynr < fts ; keynr++)
unknown's avatar
unknown committed
3118
  {
3119
    if (ft_cnt[keynr] > max_cnt)
unknown's avatar
unknown committed
3120
    {
3121
      mkeys=0;
3122 3123
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
3124 3125
      continue;
    }
3126
    if (max_cnt && ft_cnt[keynr] == max_cnt)
3127 3128
    {
      mkeys++;
3129 3130
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
3131
      continue;
unknown's avatar
unknown committed
3132 3133 3134
    }
  }

3135
  for (keynr=0 ; keynr <= mkeys ; keynr++)
unknown's avatar
unknown committed
3136
  {
3137 3138
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
3139
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
3140
      continue;
unknown's avatar
unknown committed
3141

3142
    key=ft_to_key[keynr];
3143

3144 3145 3146
    return 0;
  }

3147
err:
3148
  if (flags & FT_BOOL)
3149
  {
3150
    key=NO_SUCH_KEY;
3151 3152
    return 0;
  }
3153
  my_error(ER_FT_MATCHING_KEY_NOT_FOUND,MYF(0));
3154
  return 1;
3155 3156
}

3157

3158
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
3159
{
3160 3161
  if (item->type() != FUNC_ITEM || ((Item_func*)item)->functype() != FT_FUNC ||
      flags != ((Item_func_match*)item)->flags)
3162 3163 3164 3165 3166
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
3167
      key_item()->eq(ifm->key_item(), binary_cmp))
3168
    return 1;
unknown's avatar
unknown committed
3169 3170 3171 3172

  return 0;
}

3173

unknown's avatar
unknown committed
3174 3175
double Item_func_match::val()
{
3176
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3177
  DBUG_ENTER("Item_func_match::val");
unknown's avatar
unknown committed
3178
  if (ft_handler == NULL)
unknown's avatar
unknown committed
3179
    DBUG_RETURN(-1.0);
unknown's avatar
unknown committed
3180

unknown's avatar
unknown committed
3181 3182 3183
  if (table->null_row) /* NULL row from an outer join */
    return 0.0;

unknown's avatar
unknown committed
3184 3185 3186
  if (join_key)
  {
    if (table->file->ft_handler)
unknown's avatar
unknown committed
3187
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
unknown's avatar
unknown committed
3188 3189 3190
    join_key=0;
  }

3191
  if (key == NO_SUCH_KEY)
unknown's avatar
unknown committed
3192
  {
3193 3194
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
unknown's avatar
unknown committed
3195 3196 3197
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
				      (byte *)a->ptr(), a->length()));
unknown's avatar
unknown committed
3198 3199
  }
  else
3200 3201
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                   table->record[0], 0));
unknown's avatar
unknown committed
3202 3203
}

3204 3205
void Item_func_match::print(String *str)
{
3206
  str->append("(match ", 7);
unknown's avatar
unknown committed
3207
  print_args(str, 1);
3208
  str->append(" against (", 10);
3209
  args[0]->print(str);
unknown's avatar
unknown committed
3210
  if (flags & FT_BOOL)
3211
    str->append(" in boolean mode", 16);
unknown's avatar
unknown committed
3212 3213
  else if (flags & FT_EXPAND)
    str->append(" with query expansion", 21);
3214
  str->append("))", 2);
3215
}
unknown's avatar
unknown committed
3216

unknown's avatar
unknown committed
3217 3218
longlong Item_func_bit_xor::val_int()
{
3219
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3220 3221
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
3222
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
unknown's avatar
unknown committed
3223 3224 3225 3226
    return 0;
  return (longlong) (arg1 ^ arg2);
}

3227

3228 3229 3230 3231
/***************************************************************************
  System variables
****************************************************************************/

3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
/*
  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
*/
3249

3250 3251 3252

Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
		     LEX_STRING component)
3253
{
3254 3255 3256 3257
  sys_var *var;
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *pos;
  LEX_STRING *base_name, *component_name;

3258 3259
  if (component.str == 0 &&
      !my_strcasecmp(system_charset_info, name.str, "VERSION"))
3260
    return new Item_string(NULL, server_version,
3261
			   (uint) strlen(server_version),
unknown's avatar
unknown committed
3262
			   system_charset_info, DERIVATION_SYSCONST);
unknown's avatar
unknown committed
3263

3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
  if (component.str)
  {
    base_name= &component;
    component_name= &name;
  }
  else
  {
    base_name= &name;
    component_name= &component;			// Empty string
  }
unknown's avatar
unknown committed
3274

3275
  if (!(var= find_sys_var(base_name->str, base_name->length)))
unknown's avatar
unknown committed
3276
    return 0;
3277 3278 3279 3280 3281 3282 3283 3284
  if (component.str)
  {
    if (!var->is_struct())
    {
      net_printf(thd, ER_VARIABLE_IS_NOT_STRUCT, base_name->str);
      return 0;
    }
  }
3285
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
3286

3287 3288
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);

3289
  return new Item_func_get_system_var(var, var_type, component_name,
3290
                                      NULL, 0);
3291 3292 3293
}


unknown's avatar
unknown committed
3294 3295
/*
  Check a user level lock.
3296 3297 3298 3299 3300 3301 3302 3303

  SYNOPSIS:
    val_int()

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

3306
longlong Item_func_is_free_lock::val_int()
unknown's avatar
unknown committed
3307
{
3308
  DBUG_ASSERT(fixed == 1);
unknown's avatar
unknown committed
3309
  String *res=args[0]->val_str(&value);
3310
  User_level_lock *ull;
unknown's avatar
unknown committed
3311 3312

  null_value=0;
3313
  if (!res || !res->length())
unknown's avatar
unknown committed
3314 3315 3316 3317 3318 3319
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
3320
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
unknown's avatar
unknown committed
3321 3322 3323 3324 3325 3326
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
unknown's avatar
unknown committed
3327

unknown's avatar
SCRUM  
unknown committed
3328 3329
longlong Item_func_is_used_lock::val_int()
{
3330
  DBUG_ASSERT(fixed == 1);
unknown's avatar
SCRUM  
unknown committed
3331
  String *res=args[0]->val_str(&value);
3332
  User_level_lock *ull;
unknown's avatar
SCRUM  
unknown committed
3333 3334 3335 3336 3337 3338

  null_value=1;
  if (!res || !res->length())
    return 0;
  
  pthread_mutex_lock(&LOCK_user_locks);
3339
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
unknown's avatar
SCRUM  
unknown committed
3340 3341 3342 3343 3344 3345 3346 3347
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 0;

  null_value=0;
  return ull->thread_id;
}
3348 3349 3350 3351 3352 3353 3354 3355 3356


longlong Item_func_found_rows::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->found_rows();
}