item_func.cc 57.9 KB
Newer Older
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

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

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


/* This file defines all numerical functions */

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

#include "mysql_priv.h"
25
#include "slave.h" // for wait_for_master_pos
bk@work.mysql.com's avatar
bk@work.mysql.com committed
26 27 28 29
#include <m_ctype.h>
#include <hash.h>
#include <time.h>
#include <ft_global.h>
30
#include <zlib.h>
31
#include <assert.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

/* return TRUE if item is a constant */

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


Item_func::Item_func(List<Item> &list)
{
  arg_count=list.elements;
  if ((args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
  {
    uint i=0;
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
48
    List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
49 50 51 52 53 54 55 56 57 58 59
    Item *item;

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

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94

/*
  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
      binary		Set if any of the arguments is binary
      with_sum_func	Set if any of the arguments contains a sum function
      used_table_cache  Set to union of the arguments used table

      str_value.charset If this is a string function, set this to the
			character set for the first argument.

   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().
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
95
bool
96
Item_func::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
97 98
{
  Item **arg,**arg_end;
99
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
bk@work.mysql.com's avatar
bk@work.mysql.com committed
100 101 102 103 104 105 106 107 108 109
  binary=0;
  used_tables_cache=0;
  const_item_cache=1;

  if (thd && check_stack_overrun(thd,buff))
    return 0;					// Fatal error if flag is set!
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
110
      if ((*arg)->fix_fields(thd, tables, arg))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
111 112 113 114 115 116 117 118 119
	return 1;				/* purecov: inspected */
      if ((*arg)->maybe_null)
	maybe_null=1;
      if ((*arg)->binary)
	binary=1;
      with_sum_func= with_sum_func || (*arg)->with_sum_func;
      used_tables_cache|=(*arg)->used_tables();
      const_item_cache&= (*arg)->const_item();
    }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
120 121 122 123 124 125
    /*
      Set return character set to first argument if we are returning a
      string.
    */
    if (result_type() == STRING_RESULT)
      str_value.set_charset((*args)->str_value.charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  }
  fix_length_and_dec();
  return 0;
}


void Item_func::split_sum_func(List<Item> &fields)
{
  Item **arg,**arg_end;
  for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
  {
    if ((*arg)->with_sum_func && (*arg)->type() != SUM_FUNC_ITEM)
      (*arg)->split_sum_func(fields);
    else if ((*arg)->used_tables() || (*arg)->type() == SUM_FUNC_ITEM)
    {
      fields.push_front(*arg);
      *arg=new Item_ref((Item**) fields.head_ref(),0,(*arg)->name);
    }
  }
}


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

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


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(')');
}

194
bool Item_func::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
195 196 197 198 199 200 201 202 203 204 205
{
  /* 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++)
206
    if (!args[i]->eq(item_func->args[i], binary_cmp))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
207 208 209 210 211
      return 0;
  return 1;
}


212 213 214 215 216 217 218
Field *Item_func::tmp_table_field(TABLE *t_arg)
{
  Field *res;
  LINT_INIT(res);

  if (!t_arg)
    return result_field;
219
  switch (result_type()) {
220 221 222 223 224 225 226 227 228 229 230 231 232
  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)
233 234
      res= new Field_blob(max_length, maybe_null, name, t_arg, binary,
			  str_value.charset());
235
    else
236 237
      res= new Field_string(max_length, maybe_null, name, t_arg, binary,
			    str_value.charset());
238 239 240 241 242 243
    break;
  }
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
String *Item_real_func::val_str(String *str)
{
  double nr=val();
  if (null_value)
    return 0; /* purecov: inspected */
  else
    str->set(nr,decimals);
  return str;
}


String *Item_num_func::val_str(String *str)
{
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
262
    else if (!unsigned_flag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
263
      str->set(nr);
264 265
    else
      str->set((ulonglong) nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
      str->set(nr,decimals);
  }
  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);
}

String *Item_int_func::val_str(String *str)
{
  longlong nr=val_int();
  if (null_value)
    return 0;
292
  else if (!unsigned_flag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
293
    str->set(nr);
294 295
  else
    str->set((ulonglong) nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
296 297 298
  return str;
}

299 300 301 302
/*
  Change from REAL_RESULT (default) to INT_RESULT if both arguments are
  integers
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
303 304 305 306 307

void Item_num_op::find_num_type(void)
{
  if (args[0]->result_type() == INT_RESULT &&
      args[1]->result_type() == INT_RESULT)
308
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
309
    hybrid_type=INT_RESULT;
310 311
    unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
312 313 314 315 316 317 318 319 320
}

String *Item_num_op::val_str(String *str)
{
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
321
    else if (!unsigned_flag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
322
      str->set(nr);
323 324
    else
      str->set((ulonglong) nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
      str->set(nr,decimals);
  }
  return str;
}


double Item_func_plus::val()
{
  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()
{
348 349 350 351 352 353 354 355
  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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
356 357
}

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

/*
  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 &&
      (current_thd->sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
    unsigned_flag=0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
373 374 375 376 377 378 379 380 381 382
double Item_func_minus::val()
{
  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()
{
383 384 385 386 387 388 389 390
  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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
391 392
}

393

bk@work.mysql.com's avatar
bk@work.mysql.com committed
394 395 396 397 398 399 400 401 402 403
double Item_func_mul::val()
{
  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()
{
404 405 406 407 408 409 410 411
  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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425
}


double Item_func_div::val()
{
  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()
{
426 427 428 429 430 431 432 433 434
  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();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
}

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

double Item_func_mod::val()
{
  double value= floor(args[0]->val()+0.5);
  double val2=floor(args[1]->val()+0.5);
  if ((null_value=val2 == 0.0 || args[0]->null_value || args[1]->null_value))
    return 0.0; /* purecov: inspected */
  return fmod(value,val2);
}

longlong Item_func_mod::val_int()
{
  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()
{
  max_length=args[1]->max_length;
  decimals=0;
  maybe_null=1;
  find_num_type();
}


double Item_func_neg::val()
{
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return -value;
}

longlong Item_func_neg::val_int()
{
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return -value;
}

void Item_func_neg::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
  hybrid_type= args[0]->result_type() == INT_RESULT ? INT_RESULT : REAL_RESULT;
}

double Item_func_abs::val()
{
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return fabs(value);
}

longlong Item_func_abs::val_int()
{
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return value >= 0 ? value : -value;
}

void Item_func_abs::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
  hybrid_type= args[0]->result_type() == INT_RESULT ? INT_RESULT : REAL_RESULT;
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528
/* Gateway to natural LOG function */
double Item_func_ln::val()
{
  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.
*/ 
bk@work.mysql.com's avatar
bk@work.mysql.com committed
529 530 531 532
double Item_func_log::val()
{
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
533 534 535 536 537 538 539 540
    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);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
541 542 543
  return log(value);
}

544 545 546 547 548 549 550 551
double Item_func_log2::val()
{
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
  return log(value) / log(2.0);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
double Item_func_log10::val()
{
  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()
{
  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()
{
  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()
{
  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()
{
  double value=args[0]->val();
  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()
{
  double value=args[0]->val();
  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()
{
  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()
{
  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()
{
  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()
{
  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()
{
  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()
{
  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()
{
  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()
{
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return (longlong) ceil(value);
}

longlong Item_func_floor::val_int()
{
  double value=args[0]->val();
  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
      decimals=tmp;
  }
}

double Item_func_round::val()
{
  double value=args[0]->val();
  int dec=(int) args[1]->val_int();
  uint abs_dec=abs(dec);

  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  double tmp=(abs_dec < array_elements(log_10) ?
	      log_10[abs_dec] : pow(10.0,(double) abs_dec));

  if (truncate)
734 735 736 737 738 739
  {
    if (value >= 0)
      return dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
    else
      return dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
740 741 742 743 744 745 746 747
  return dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
}


double Item_func_rand::val()
{
  if (arg_count)
  {					// Only use argument once in query
748 749 750
    uint32 tmp= (uint32) (args[0]->val_int());
    randominit(&current_thd->rand,(uint32) (tmp*0x10001L+55555555L),
	       (uint32) (tmp*0x10000001L));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
#ifdef DELETE_ITEMS
    delete args[0];
#endif
    arg_count=0;
  }
  return rnd(&current_thd->rand);
}

longlong Item_func_sign::val_int()
{
  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()
{
  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;
  binary=0;
  cmp_type=args[0]->result_type();
  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());
    if (args[i]->binary)
      binary=1;
  }
}


String *Item_func_min_max::val_str(String *str)
{
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
806
    else if (!unsigned_flag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
807
      str->set(nr);
808 809
    else
      str->set((ulonglong) nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    return str;
  }
  case REAL_RESULT:
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
      str->set(nr,decimals);
    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)
	{
	  int cmp=binary ? stringcmp(res,res2) : sortcmp(res,res2);
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
    }
    return res;
  }
  }
  return 0;					// Keep compiler happy
}


double Item_func_min_max::val()
{
  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()
{
  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;
}

895 896 897 898 899 900 901 902 903 904 905 906
longlong Item_func_crc32::val_int()
{
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) crc32(0L, (Bytef*)res->ptr(), res->length());
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943

longlong Item_func_length::val_int()
{
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) res->length();
}

longlong Item_func_char_length::val_int()
{
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) (!args[0]->binary) ? res->numchars() : res->length();
}


longlong Item_func_locate::val_int()
{
  String *a=args[0]->val_str(&value1);
  String *b=args[1]->val_str(&value2);
  bool binary_str = args[0]->binary || args[1]->binary;
  if (!a || !b)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
944 945 946 947
  uint start=0;
#ifdef USE_MB
  uint start0=0;
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
948 949 950 951
  if (arg_count == 3)
  {
    start=(uint) args[2]->val_int()-1;
#ifdef USE_MB
952
    if (use_mb(a->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
953 954 955 956 957 958 959 960 961 962 963 964
    {
      start0=start;
      if (!binary_str)
        start=a->charpos(start);
    }
#endif
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
#ifdef USE_MB
965
  if (use_mb(a->charset()) && !binary_str)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
  {
    const char *ptr=a->ptr()+start;
    const char *search=b->ptr();
    const char *strend = ptr+a->length();
    const char *end=strend-b->length()+1;
    const char *search_end=search+b->length();
    register  uint32 l;
    while (ptr < end)
    {
      if (*ptr == *search)
      {
        register char *i,*j;
        i=(char*) ptr+1; j=(char*) search+1;
        while (j != search_end)
          if (*i++ != *j++) goto skipp;
        return (longlong) start0+1;
      }
  skipp:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
984 985
      if ((l=my_ismbchar(a->charset(),ptr,strend)))
	ptr+=l;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
986 987 988 989 990 991
      else ++ptr;
      ++start0;
    }
    return 0;
  }
#endif /* USE_MB */
992 993
  return (longlong) (binary ? a->strstr(*b,start) :
		     (a->strstr_case(*b,start)))+1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
}


longlong Item_func_field::val_int()
{
  String *field;
  if (!(field=item->val_str(&value)))
    return 0;					// -1 if null ?
  for (uint i=0 ; i < arg_count ; i++)
  {
    String *tmp_value=args[i]->val_str(&tmp);
    if (tmp_value && field->length() == tmp_value->length() &&
	!memcmp(field->ptr(),tmp_value->ptr(),tmp_value->length()))
      return (longlong) (i+1);
  }
  return 0;
}


longlong Item_func_ascii::val_int()
{
  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()
{
  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
1036
  if (use_mb(res->charset()) && !args[0]->binary)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1037 1038
  {
    register const char *str=res->ptr();
1039
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1040 1041
    if (!l)
      return (longlong)((uchar) *str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    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)
      {
	enum_value=find_enum(((Field_enum*) field)->typelib,find->ptr(),
			     find->length());
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
  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;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1101
  CHARSET_INFO *charset= find->charset();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  if ((diff=buffer->length() - find->length()) >= 0)
  {
    const char *f_pos=find->ptr();
    const char *f_end=f_pos+find->length();
    const char *str=buffer->ptr();
    const char *end=str+diff+1;
    const char *real_end=str+buffer->length();
    uint position=1;
    do
    {
      const char *pos= f_pos;
      while (pos != f_end)
      {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1115
	if (my_toupper(charset,*str) != my_toupper(charset,*pos))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
	  goto not_found;
	str++;
	pos++;
      }
      if (str == real_end || str[0] == separator)
	return (longlong) position;
  not_found:
      while (str < end && str[0] != separator)
	str++;
      position++;
    } while (++str <= end);
  }
  return 0;
}

static char nbits[256] = {
  0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
};

uint count_bits(ulonglong v)
{
#if SIZEOF_LONG_LONG > 4
  /* The following code is a bit faster on 16 bit machines than if we would
     only shift v */
  ulong v2=(ulong) (v >> 32);
  return (uint) (uchar) (nbits[(uchar)  v] +
                         nbits[(uchar) (v >> 8)] +
                         nbits[(uchar) (v >> 16)] +
                         nbits[(uchar) (v >> 24)] +
                         nbits[(uchar) (v2)] +
                         nbits[(uchar) (v2 >> 8)] +
                         nbits[(uchar) (v2 >> 16)] +
                         nbits[(uchar) (v2 >> 24)]);
#else
  return (uint) (uchar) (nbits[(uchar)  v] +
                         nbits[(uchar) (v >> 8)] +
                         nbits[(uchar) (v >> 16)] +
                         nbits[(uchar) (v >> 24)]);
#endif
}

longlong Item_func_bit_count::val_int()
{
  ulonglong value= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  return (longlong) count_bits(value);
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
1187
** Rewritten by monty.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
****************************************************************************/

#ifdef HAVE_DLOPEN

udf_handler::~udf_handler()
{
  if (initialized)
  {
    if (u_d->func_deinit != NULL)
    {
      void (*deinit)(UDF_INIT *) = (void (*)(UDF_INIT*))
	u_d->func_deinit;
      (*deinit)(&initid);
    }
    free_udf(u_d);
  }
1204 1205
  if (buffers)					// Because of bug in ecc
    delete [] buffers;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1206 1207 1208 1209
}


bool
1210
udf_handler::fix_fields(THD *thd, TABLE_LIST *tables, Item_result_field *func,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1211 1212
			uint arg_count, Item **arguments)
{
1213
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1214 1215
  DBUG_ENTER("Item_udf_func::fix_fields");

1216 1217 1218 1219 1220 1221 1222
  if (thd)
  {
    if (check_stack_overrun(thd,buff))
      return 0;					// Fatal error flag is set!
  }
  else
    thd=current_thd;				// In WHERE / const clause
1223
  udf_func *tmp_udf=find_udf(u_d->name,(uint) strlen(u_d->name),1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

  if (!tmp_udf)
  {
    my_printf_error(ER_CANT_FIND_UDF,ER(ER_CANT_FIND_UDF),MYF(0),u_d->name,
		    errno);
    DBUG_RETURN(1);
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
  func->binary=func->maybe_null=0;
  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++)
    {
1254
      if ((*arg)->fix_fields(thd, tables, arg))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
	return 1;
      if ((*arg)->binary)
	func->binary=1;
      if ((*arg)->maybe_null)
	func->maybe_null=1;
      func->with_sum_func= func->with_sum_func || (*arg)->with_sum_func;
      used_tables_cache|=(*arg)->used_tables();
      const_item_cache&=(*arg)->const_item();
      f_args.arg_type[i]=(*arg)->result_type();
    }
    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;
      }
    }
1320
    thd->net.last_error[0]=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    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),
		      u_d->name,thd->net.last_error);
      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;
    func->decimals=min(initid.decimals,31);
  }
  initialized=1;
  if (error)
  {
    my_printf_error(ER_CANT_INITIALIZE_UDF,ER(ER_CANT_INITIALIZE_UDF),MYF(0),
		    u_d->name, ER(ER_UNKNOWN_ERROR));
    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;
    }
  }
  return 0;
}

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

String *udf_handler::val_str(String *str,String *save_str)
{
  uchar is_null=0;
  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;
    }
  }
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length, &is_null,
		&error);
  if (is_null || !res || error)			// The !res is for safety
  {
    return 0;
  }
  if (res == str->ptr())
  {
    str->length(res_length);
    return str;
  }
1420
  save_str->set(res, res_length, default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
  return save_str;
}



double Item_func_udf_float::val()
{
  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)
{
  double nr=val();
  if (null_value)
    return 0;					/* purecov: inspected */
  else
    str->set(nr,decimals);
  return str;
}


longlong Item_func_udf_int::val_int()
{
  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)
{
  longlong nr=val_int();
  if (null_value)
    return 0;
1461
  else if (!unsigned_flag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1462
    str->set(nr);
1463 1464
  else
    str->set((ulonglong) nr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
  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)
{
  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;

class ULL
{
  char *key;
  uint key_length;

public:
  int count;
  bool locked;
  pthread_cond_t cond;
  pthread_t thread;

  ULL(const char *key_arg,uint length) :key_length(length),count(1),locked(1)
  {
    key=(char*) my_memdup((byte*) key_arg,length,MYF(0));
    pthread_cond_init(&cond,NULL);
    if (key)
    {
      if (hash_insert(&hash_user_locks,(byte*) this))
      {
	my_free((gptr) key,MYF(0));
	key=0;
      }
    }
  }
  ~ULL()
  {
    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; }
  friend void item_user_lock_release(ULL *ull);
  friend char *ull_get_key(const ULL *ull,uint *length,my_bool not_used);
};

char *ull_get_key(const ULL *ull,uint *length,
		  my_bool not_used __attribute__((unused)))
{
  *length=(uint) ull->key_length;
  return (char*) ull->key;
}

void item_user_lock_init(void)
{
1544
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
1545 1546
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
}

void item_user_lock_free(void)
{
  hash_free(&hash_user_locks);
}

void item_user_lock_release(ULL *ull)
{
  ull->locked=0;
1557 1558 1559
  if (mysql_bin_log.is_open())
  {
    char buf[256];
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1560 1561 1562
    const char *command="DO RELEASE_LOCK(\"";
    String tmp(buf,sizeof(buf), system_charset_info);
    tmp.copy(command, strlen(command));
1563 1564
    tmp.append(ull->key,ull->key_length);
    tmp.append("\")");
1565
    Query_log_event qev(current_thd,tmp.ptr(), tmp.length());
1566
    qev.error_code=0; // this query is always safe to run on slave
1567 1568
    mysql_bin_log.write(&qev);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1569 1570 1571 1572 1573 1574
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

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

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1586 1587 1588 1589 1590 1591
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
1592
  ulong pos = (ulong)args[1]->val_int();
1593 1594
  LOCK_ACTIVE_MI;
  if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos)) == -1)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1595 1596 1597 1598
  {
    null_value = 1;
    event_count=0;
  }
1599
  UNLOCK_ACTIVE_MI;
1600 1601 1602
  return event_count;
}

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
  ULL* ull;
  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;
  }

1619 1620 1621 1622 1623
  /*
    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
1624 1625 1626 1627 1628 1629 1630 1631 1632
  */
  if (!(ull= ((ULL*) hash_search(&hash_user_locks,lock_name,
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

1633 1634 1635 1636
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
1637 1638 1639 1640
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

1641
  set_timespec(abstime,lock_timeout);
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
  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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
/*
  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()
{
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
  ULL *ull;
1687
  int error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

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

  if (!(ull= ((ULL*) hash_search(&hash_user_locks,(byte*) res->ptr(),
				 res->length()))))
  {
    ull=new ULL(res->ptr(),res->length());
    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++;

1723 1724 1725 1726
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks.
  */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1727 1728 1729 1730
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

1731
  set_timespec(abstime,timeout);
1732 1733
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
1734
	 != ETIME && error != ETIMEDOUT && error != EINVAL && ull->locked) ;
1735 1736
  if (thd->killed)
    error=EINTR;				// Return NULL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
  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;
}


/*
1767 1768 1769 1770 1771
  Release a user level lock.
  Return:
    1 if lock released
    0 if lock wasn't held
    (SQL) NULL if no such lock
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
*/

longlong Item_func_release_lock::val_int()
{
  String *res=args[0]->val_str(&value);
  ULL *ull;
  longlong result;
  if (!res || !res->length())
  {
    null_value=1;
    return 0;
  }
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
  if (!(ull= ((ULL*) hash_search(&hash_user_locks,(const byte*) res->ptr(),
				 res->length()))))
  {
    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;
}


longlong Item_func_set_last_insert_id::val_int()
{
  longlong value=args[0]->val_int();
  current_thd->insert_id(value);
  null_value=args[0]->null_value;
  return value;
}

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

longlong Item_func_benchmark::val_int()
{
  char buff[MAX_FIELD_WIDTH];
1820
  String tmp(buff,sizeof(buff), default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
  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;
    }
  }
  return 0;
}

1840

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
#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;
1862
    entry->update_query_id=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
    if (hash_insert(hash,(byte*) entry))
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}


1875 1876
bool Item_func_set_user_var::fix_fields(THD *thd, TABLE_LIST *tables,
					Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1877
{
1878
  if (!thd)
1879
    thd=current_thd;				// Should never happen
1880
  if (Item_func::fix_fields(thd, tables, ref) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1881 1882
      !(entry= get_variable(&thd->user_vars, name, 1)))
    return 1;
1883
  entry->update_query_id=thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
  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;
  cached_result_type=args[0]->result_type();
}

void Item_func_set_user_var::update_hash(void *ptr, uint length,
1898 1899
					 Item_result type,
					 CHARSET_INFO *cs)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1900 1901 1902 1903 1904 1905 1906 1907
{
  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;
1908
    entry->var_charset=cs;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
  }
  else
  {
    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;
      }
    }
    memcpy(entry->value,ptr,length);
    entry->length= length;
    entry->type=type;
1939
    entry->var_charset=cs;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
  }
  return;

 err:
  current_thd->fatal_error=1;			// Probably end of memory
  null_value=1;
  return;
}


bool
Item_func_set_user_var::update()
{
  switch (cached_result_type) {
  case REAL_RESULT:
    (void) val();
    break;
  case INT_RESULT:
    (void) val_int();
    break;
  case STRING_RESULT:
    char buffer[MAX_FIELD_WIDTH];
1962
    String tmp(buffer,sizeof(buffer),default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
    (void) val_str(&tmp);
    break;
  }
  return current_thd->fatal_error;
}


double
Item_func_set_user_var::val()
{
  double value=args[0]->val();
1974
  update_hash((void*) &value,sizeof(value), REAL_RESULT, default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1975 1976 1977 1978 1979 1980 1981
  return value;
}

longlong
Item_func_set_user_var::val_int()
{
  longlong value=args[0]->val_int();
1982
  update_hash((void*) &value,sizeof(longlong),INT_RESULT, default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1983 1984 1985 1986 1987 1988 1989 1990
  return value;
}

String *
Item_func_set_user_var::val_str(String *str)
{
  String *res=args[0]->val_str(str);
  if (!res)					// Null value
1991
    update_hash((void*) 0,0,STRING_RESULT, default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1992
  else
1993
    update_hash(res->c_ptr(),res->length()+1,STRING_RESULT,res->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1994 1995 1996 1997
  return res;
}


1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
void Item_func_set_user_var::print(String *str)
{
  str->append('(');
  str->append(name.str,name.length);
  str->append(":=",2);
  args[0]->print(str);
  str->append(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
user_var_entry *Item_func_get_user_var::get_entry()
{
  if (!entry  || ! entry->value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return entry;
}


String *
Item_func_get_user_var::val_str(String *str)
{
  user_var_entry *entry=get_entry();
  if (!entry)
    return NULL;
  switch (entry->type) {
  case REAL_RESULT:
2028
    str->set(*(double*) entry->value,decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    break;
  case INT_RESULT:
    str->set(*(longlong*) entry->value);
    break;
  case STRING_RESULT:
    if (str->copy(entry->value, entry->length-1))
    {
      null_value=1;
      return NULL;
    }
2039
    str->set_charset(entry->var_charset);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 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
    break;
  }
  return str;
}


double Item_func_get_user_var::val()
{
  user_var_entry *entry=get_entry();
  if (!entry)
    return 0.0;
  switch (entry->type) {
  case REAL_RESULT:
    return *(double*) entry->value;
  case INT_RESULT:
    return (double) *(longlong*) entry->value;
  case STRING_RESULT:
    return atof(entry->value);			// This is null terminated
  }
  return 0.0;					// Impossible
}


longlong Item_func_get_user_var::val_int()
{
  user_var_entry *entry=get_entry();
  if (!entry)
    return LL(0);
  switch (entry->type) {
  case REAL_RESULT:
    return (longlong) *(double*) entry->value;
  case INT_RESULT:
    return *(longlong*) entry->value;
  case STRING_RESULT:
    return strtoull(entry->value,NULL,10);	// String is null terminated
  }
  return LL(0);					// Impossible
}


void Item_func_get_user_var::fix_length_and_dec()
{
2082
  THD *thd=current_thd;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2083 2084 2085
  maybe_null=1;
  decimals=NOT_FIXED_DEC;
  max_length=MAX_BLOB_WIDTH;
2086 2087
  if ((entry= get_variable(&thd->user_vars, name, 0)))
    const_var_flag= thd->query_id != entry->update_query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
}


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

2101 2102 2103 2104 2105 2106 2107 2108

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

2109

2110
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
{
  /* 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 */
#ifdef FIX_THIS
  if (item->eq == &Item_func_get_user_var::eq)
    return 0;
#else
  if (item->type() != FUNC_ITEM ||
      ((Item_func*) item)->func_name() != func_name())
    return 0;
#endif
  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));
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2130 2131 2132 2133 2134 2135 2136 2137
longlong Item_func_inet_aton::val_int()
{
  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];

2138
  String *s,tmp(buff,sizeof(buff),default_charset_info);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
  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 == '.')
    {
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
    return (result << 8) + (ulonglong) byte_result;

err:
  null_value=1;
  return 0;
}

2169

2170
void Item_func_match::init_search(bool no_order)
2171
{
2172
  if (ft_handler)
2173 2174
    return;

2175
  if (key == NO_SUCH_KEY)
2176 2177 2178
    concat=new Item_func_concat_ws(new Item_string(" ",1,
						   default_charset_info),
				   fields);
2179

2180 2181
  if (master)
  {
2182 2183
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
2184 2185 2186 2187 2188
    ft_handler=master->ft_handler;
    join_key=master->join_key;
    return;
  }

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2189
  String *ft_tmp= 0;
2190
  char tmp1[FT_QUERY_MAXLEN];
2191
  String tmp2(tmp1,sizeof(tmp1),default_charset_info);
2192

2193
  // MATCH ... AGAINST (NULL) is meaningless, but possible
2194 2195
  if (!(ft_tmp=key_item()->val_str(&tmp2)))
  {
2196
    ft_tmp= &tmp2;
2197
    tmp2.set("",0,default_charset_info);
2198 2199
  }

2200
  ft_handler=table->file->ft_init_ext(mode, key,
2201 2202 2203
				      (byte*) ft_tmp->ptr(),
				      ft_tmp->length(),
				      join_key && !no_order);
2204 2205 2206 2207 2208 2209

  if (join_key)
  {
    table->file->ft_handler=ft_handler;
    return;
  }
2210 2211
}

2212

2213
bool Item_func_match::fix_fields(THD *thd, TABLE_LIST *tlist, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2214 2215 2216 2217
{
  List_iterator<Item> li(fields);
  Item *item;

2218 2219 2220
  maybe_null=1;
  join_key=0;

2221 2222 2223 2224 2225
  /*
    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.
2226
   */
2227
  if (Item_func::fix_fields(thd, tlist, ref) || !const_item())
2228 2229
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2230
    return 1;
2231
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2232 2233 2234

  while ((item=li++))
  {
2235
    if (item->fix_fields(thd, tlist, li.ref()))
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
2236 2237 2238 2239
      return 1;
    if (item->type() == Item::REF_ITEM)
      li.replace(item= *((Item_ref *)item)->ref);
    if (item->type() != Item::FIELD_ITEM || !item->used_tables())
2240
      key=NO_SUCH_KEY;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2241 2242
    used_tables_cache|=item->used_tables();
  }
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
2243
  /* check that all columns come from the same table */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2244
  if (count_bits(used_tables_cache) != 1)
2245
    key=NO_SUCH_KEY;
2246 2247
  const_item_cache=0;
  table=((Item_field *)fields.head())->field->table;
2248
  table->fulltext_searched=1;
2249 2250
  record=table->record[0];
  if (key == NO_SUCH_KEY && mode != FT_BOOL)
2251 2252
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2253
    return 1;
2254
  }
monty@hundin.mysql.fi's avatar
Merge  
monty@hundin.mysql.fi committed
2255

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2256 2257 2258
  return 0;
}

2259

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2260 2261
bool Item_func_match::fix_index()
{
monty@tik.mysql.fi's avatar
monty@tik.mysql.fi committed
2262
  List_iterator_fast<Item> li(fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2263 2264
  Item_field *item;
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, key;
2265 2266 2267 2268
  uint max_cnt=0, mkeys=0;

  if (this->key == NO_SUCH_KEY)
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281

  for (key=0 ; key<table->keys ; key++)
  {
    if ((table->key_info[key].flags & HA_FULLTEXT) &&
        (table->keys_in_use_for_query & (((key_map)1) << key)))
    {
      ft_to_key[fts]=key;
      ft_cnt[fts]=0;
      fts++;
    }
  }

  if (!fts)
2282
    goto err;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302

  while ((item=(Item_field*)(li++)))
  {
    for (key=0 ; key<fts ; key++)
    {
      KEY *ft_key=&table->key_info[ft_to_key[key]];
      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))
	  ft_cnt[key]++;
      }
    }
  }

  for (key=0 ; key<fts ; key++)
  {
    if (ft_cnt[key] > max_cnt)
    {
2303 2304 2305 2306 2307
      mkeys=0;
      max_cnt=ft_cnt[mkeys]=ft_cnt[key];
      ft_to_key[mkeys]=ft_to_key[key];
      continue;
    }
2308
    if (max_cnt && ft_cnt[key] == max_cnt)
2309 2310 2311 2312 2313
    {
      mkeys++;
      ft_cnt[mkeys]=ft_cnt[key];
      ft_to_key[mkeys]=ft_to_key[key];
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2314 2315 2316
    }
  }

2317
  for (key=0 ; key<=mkeys ; key++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2318
  {
2319 2320 2321 2322
    // for now, partial keys won't work. SerG
    if (max_cnt < fields.elements ||
        max_cnt < table->key_info[ft_to_key[key]].key_parts)
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2323

2324
    this->key=ft_to_key[key];
2325

2326 2327 2328
    return 0;
  }

2329 2330 2331 2332 2333 2334
err:
  if (mode == FT_BOOL)
  {
    this->key=NO_SUCH_KEY;
    return 0;
  }
2335
  my_printf_error(ER_FT_MATCHING_KEY_NOT_FOUND,
2336
		  ER(ER_FT_MATCHING_KEY_NOT_FOUND),MYF(0));
2337
  return 1;
2338 2339
}

2340

2341
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
2342
{
2343 2344
  if (item->type() != FUNC_ITEM ||
      func_name() != ((Item_func*)item)->func_name())
2345 2346 2347 2348 2349
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
2350
      key_item()->eq(ifm->key_item(), binary_cmp))
2351
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2352 2353 2354 2355

  return 0;
}

2356

2357 2358
double Item_func_match::val()
{
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2359
  if (ft_handler == NULL)
2360
    return -1.0;
2361 2362 2363 2364 2365 2366 2367 2368

  if (join_key)
  {
    if (table->file->ft_handler)
      return ft_handler->please->get_relevance(ft_handler);
    join_key=0;
  }

2369
  if (key == NO_SUCH_KEY)
2370
  {
2371 2372
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
2373 2374
      return 0;
    return ft_handler->please->find_relevance(ft_handler,
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2375
					      (byte *)a->ptr(), a->length());
2376 2377
  }
  else
2378
    return ft_handler->please->find_relevance(ft_handler, record, 0);
2379 2380
}

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2381

2382 2383 2384 2385
longlong Item_func_bit_xor::val_int()
{
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
2386
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
2387 2388 2389 2390
    return 0;
  return (longlong) (arg1 ^ arg2);
}

2391

2392 2393 2394 2395
/***************************************************************************
  System variables
****************************************************************************/

2396
Item *get_system_var(enum_var_type var_type, LEX_STRING name)
2397
{
2398 2399 2400 2401
  if (!my_strcasecmp(system_charset_info, name.str, "VERSION"))
    return new Item_string("@@VERSION", server_version,
			   (uint) strlen(server_version),
			   system_charset_info);
2402 2403 2404 2405

  THD *thd=current_thd;
  Item *item;
  sys_var *var;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2406
  char buff[MAX_SYS_VAR_LENGTH+3+8], *pos;
2407

2408
  if (!(var= find_sys_var(name.str, name.length)))
2409
  {
2410
    net_printf(thd, ER_UNKNOWN_SYSTEM_VARIABLE, name.str);
2411 2412 2413 2414 2415 2416 2417
    return 0;
  }
  if (!(item=var->item(thd, var_type)))
    return 0;					// Impossible
  thd->safe_to_cache_query=0;
  buff[0]='@';
  buff[1]='@';
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2418 2419 2420 2421 2422 2423 2424 2425
  pos=buff+2;
  if (var_type == OPT_SESSION)
    pos=strmov(pos,"session.");
  else if (var_type == OPT_GLOBAL)
    pos=strmov(pos,"global.");
  memcpy(pos, var->name, var->name_length+1);
  // set_name() will allocate the name
  item->set_name(buff,(uint) (pos-buff)+var->name_length);
2426
  return item;
2427
}
2428

2429

2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
Item *get_system_var(enum_var_type var_type, const char *var_name, uint length,
		     const char *item_name)
{
  THD *thd=current_thd;
  Item *item;
  sys_var *var;

  var= find_sys_var(var_name, length);
  DBUG_ASSERT(var != 0);
  if (!(item=var->item(thd, var_type)))
    return 0;					// Impossible
  thd->safe_to_cache_query=0;
  item->set_name(item_name);		// Will use original name
  return item;
}


2447 2448
/*
  Check a user level lock.
2449 2450 2451 2452 2453 2454 2455 2456

  SYNOPSIS:
    val_int()

  RETURN VALUES
    1		Available
    0		Already taken
    NULL	Error
2457 2458
*/

2459
longlong Item_func_is_free_lock::val_int()
2460 2461 2462 2463 2464 2465 2466
{
  String *res=args[0]->val_str(&value);
  THD *thd=current_thd;
  ULL *ull;
  int error=0;

  null_value=0;
2467
  if (!res || !res->length())
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
  ull= (ULL*) hash_search(&hash_user_locks,(byte*) res->ptr(),
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
2481 2482 2483


/**************************************************************************
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2484
  Spatial functions
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
***************************************************************************/

longlong Item_func_dimension::val_int()
{
  uint32 dim;
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb || 
               args[0]->null_value ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               geom.dimension(&dim));

  return (longlong) dim;
}

longlong Item_func_numinteriorring::val_int()
{
  uint32 num;
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb || 
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,num_interior_ring) || 
	       geom.num_interior_ring(&num));

  return (longlong) num;
}

longlong Item_func_numgeometries::val_int()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2517
  uint32 num=0;
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,num_geometries) || 
               geom.num_geometries(&num));

  return (longlong) num;
}

longlong Item_func_numpoints::val_int()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2531
  uint32 num=0;
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb ||
               args[0]->null_value ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) ||
               !GEOM_METHOD_PRESENT(geom,num_points) ||
               geom.num_points(&num));

  return (longlong) num;
}


double Item_func_x::val()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2547
  double res=0;
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,get_x) || 
               geom.get_x(&res));

  return res;
}


double Item_func_y::val()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2562
  double res=0;
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,get_y) || 
               geom.get_y(&res));

  return res;
}


double Item_func_area::val()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2577
  double res=0;
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb ||
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,area) || 
               geom.area(&res));

  return res;
}


double Item_func_glength::val()
{
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2592
  double res=0;
2593 2594 2595 2596 2597 2598 2599 2600 2601
  String *wkb=args[0]->val_str(&value);
  Geometry geom;

  null_value= (!wkb || 
               geom.create_from_wkb(wkb->ptr(),wkb->length()) || 
               !GEOM_METHOD_PRESENT(geom,length) || 
               geom.length(&res));
  return res;
}