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

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

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

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


/* This file defines all numerical functions */

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

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

31 32 33

static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
			      const char *fname)
34
{
35
  my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
36
	   c1.collation->name,c1.derivation_name(),
37 38 39 40
	   c2.collation->name,c2.derivation_name(),
	   fname);
}

41
static void my_coll_agg_error(DTCollation &c1,
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
42 43 44 45 46 47 48 49 50 51 52
			       DTCollation &c2,
			       DTCollation &c3,
			       const char *fname)
{
  my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
  	   c1.collation->name,c1.derivation_name(),
	   c2.collation->name,c2.derivation_name(),
	   c3.collation->name,c3.derivation_name(),
	   fname);
}

53 54

static void my_coll_agg_error(Item** args, uint count, const char *fname)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
55
{
56
  if (count == 2)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
57
    my_coll_agg_error(args[0]->collation, args[1]->collation, fname);
58
  else if (count == 3)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
59 60 61 62 63 64 65 66
    my_coll_agg_error(args[0]->collation,
		      args[1]->collation,
		      args[2]->collation,
		      fname);
  else
    my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
}

67 68

bool Item_func::agg_arg_collations(DTCollation &c, Item **av, uint count)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
69 70
{
  uint i;
71
  c.set(av[0]->collation);
72
  for (i= 1; i < count; i++)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
73
  {
74
    if (c.aggregate(av[i]->collation))
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
75
    {
76
      my_coll_agg_error(av, count, func_name());
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
77 78 79 80 81 82
      return TRUE;
    }
  }
  return FALSE;
}

83

84
bool Item_func::agg_arg_collations_for_comparison(DTCollation &c,
85
						  Item **av, uint count)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
86
{
87
  if (agg_arg_collations(c, av, count))
88
    return TRUE;
89

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
90 91
  if (c.derivation == DERIVATION_NONE)
  {
92
    my_coll_agg_error(av, count, func_name());
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
93 94 95 96 97 98
    return TRUE;
  }
  return FALSE;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
99 100 101 102 103 104 105 106
/* return TRUE if item is a constant */

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

107

108
void Item_func::set_arguments(List<Item> &list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
109
{
110
  allowed_arg_cols= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
111 112 113 114
  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
115
    List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
116 117 118 119 120 121 122 123 124 125 126
    Item *item;

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

127 128 129 130 131 132
Item_func::Item_func(List<Item> &list)
  :allowed_arg_cols(1)
{
  set_arguments(list);
}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
Item_func::Item_func(THD *thd, Item_func &item)
  :Item_result_field(thd, item),
   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)
{
  if (arg_count)
  {
    if (arg_count <=2)
      args= tmp_arg;
    else
    {
      if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
	return;
    }
    memcpy((char*) args, (char*) item.args, sizeof(Item*)*arg_count);
  }
}

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

/*
  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
      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.
177
			If any argument is binary, this is set to binary
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
178 179 180 181 182 183 184 185 186 187 188

   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
189
bool
190
Item_func::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
191 192
{
  Item **arg,**arg_end;
193
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
194
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
195
#endif
196

197
  used_tables_cache= not_null_tables_cache= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
198 199
  const_item_cache=1;

200
  if (check_stack_overrun(thd, buff))
201
    return 1;					// Fatal error if flag is set!
bk@work.mysql.com's avatar
bk@work.mysql.com committed
202 203 204 205
  if (arg_count)
  {						// Print purify happy
    for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
206 207
      Item *item;
      /* We can't yet set item to *arg as fix_fields may change *arg */
208 209
      if ((*arg)->fix_fields(thd, tables, arg) ||
	  (*arg)->check_cols(allowed_arg_cols))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
210
	return 1;				/* purecov: inspected */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
211
      item= *arg;
212
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
213
	maybe_null=1;
214

215
      with_sum_func= with_sum_func || item->with_sum_func;
216 217 218
      used_tables_cache|=     item->used_tables();
      not_null_tables_cache|= item->not_null_tables();
      const_item_cache&=      item->const_item();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
219 220 221
    }
  }
  fix_length_and_dec();
222
  if (thd->net.last_errno) // An error inside fix_length_and_dec occured
223
    return 1;
224
  fixed= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
225 226 227
  return 0;
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
228 229 230 231 232 233 234 235 236 237 238 239 240
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);
}
241

242
void Item_func::split_sum_func(Item **ref_pointer_array, List<Item> &fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
243
{
244 245
  Item **arg, **arg_end;
  for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
246
  {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
247
    Item *item=* arg;
248
    if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
249
      item->split_sum_func(ref_pointer_array, fields);
250
    else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
251
    {
252
      uint el= fields.elements;
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
253 254 255
      fields.push_front(item);
      ref_pointer_array[el]= item;
      *arg= new Item_ref(ref_pointer_array + el, 0, item->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    }
  }
}


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

279 280 281 282 283 284 285

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
286 287 288 289
void Item_func::print(String *str)
{
  str->append(func_name());
  str->append('(');
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
290
  print_args(str, 0);
291 292 293 294
  str->append(')');
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
295
void Item_func::print_args(String *str, uint from)
296
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
297
  for (uint i=from ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
298
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
299
    if (i != from)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
      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(')');
}

320
bool Item_func::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
321 322 323 324 325 326 327 328 329 330 331
{
  /* 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++)
332
    if (!args[i]->eq(item_func->args[i], binary_cmp))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
333 334 335 336
      return 0;
  return 1;
}

337 338 339 340 341
Field *Item_func::tmp_table_field(TABLE *t_arg)
{
  Field *res;
  LINT_INIT(res);

342
  switch (result_type()) {
343 344 345 346 347 348 349 350 351 352 353 354 355
  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)
356
      res= new Field_blob(max_length, maybe_null, name, t_arg, collation.collation);
357
    else
358
      res= new Field_string(max_length, maybe_null, name, t_arg, collation.collation);
359
    break;
360
  case ROW_RESULT:
361
  default:
362 363 364
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
365 366 367 368 369
  }
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
370 371 372 373 374 375
String *Item_real_func::val_str(String *str)
{
  double nr=val();
  if (null_value)
    return 0; /* purecov: inspected */
  else
376
    str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
377 378 379 380 381 382 383 384 385 386 387
  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 */
388
    else if (!unsigned_flag)
389
      str->set(nr,default_charset());
390
    else
391
      str->set((ulonglong) nr,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
392 393 394 395 396 397 398
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
399
      str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
400 401 402 403 404 405 406 407 408 409 410 411 412
  }
  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);
}

413
Item *Item_func::get_tmp_table_item(THD *thd)
414 415 416
{
  if (!with_sum_func && !const_item())
    return new Item_field(result_field);
417
  return copy_or_same(thd);
418 419
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
420 421 422 423 424
String *Item_int_func::val_str(String *str)
{
  longlong nr=val_int();
  if (null_value)
    return 0;
425
  else if (!unsigned_flag)
426
    str->set(nr,default_charset());
427
  else
428
    str->set((ulonglong) nr,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
429 430 431
  return str;
}

432 433 434 435
/*
  Change from REAL_RESULT (default) to INT_RESULT if both arguments are
  integers
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
436 437 438 439 440

void Item_num_op::find_num_type(void)
{
  if (args[0]->result_type() == INT_RESULT &&
      args[1]->result_type() == INT_RESULT)
441
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
442
    hybrid_type=INT_RESULT;
443 444
    unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
445 446 447 448 449 450 451 452 453
}

String *Item_num_op::val_str(String *str)
{
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
454
    else if (!unsigned_flag)
455
      str->set(nr,default_charset());
456
    else
457
      str->set((ulonglong) nr,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
458 459 460 461 462 463 464
  }
  else
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
465
      str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
466 467 468 469 470
  }
  return str;
}


471 472
void Item_func_signed::print(String *str)
{
473
  str->append("cast(", 5);
474
  args[0]->print(str);
475
  str->append(" as signed)", 11);
476 477 478 479 480 481

}


void Item_func_unsigned::print(String *str)
{
482
  str->append("cast(", 5);
483
  args[0]->print(str);
484
  str->append(" as unsigned)", 13);
485 486 487 488

}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
489 490 491 492 493 494 495 496 497 498
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()
{
499 500 501 502 503 504 505 506
  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
507 508
}

509 510 511 512 513 514 515 516 517 518

/*
  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 &&
519
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
520 521 522 523
    unsigned_flag=0;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
524 525 526 527 528 529 530 531 532 533
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()
{
534 535 536 537 538 539 540 541
  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
542 543
}

544

bk@work.mysql.com's avatar
bk@work.mysql.com committed
545 546 547 548 549 550 551 552 553 554
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()
{
555 556 557 558 559 560 561 562
  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
563 564 565 566 567 568 569 570 571 572 573 574 575 576
}


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()
{
577 578 579 580 581 582 583 584 585
  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
586 587 588 589 590 591 592 593 594 595 596
}

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

597 598 599 600 601 602 603 604

/* Integer division */
longlong Item_func_int_div::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;
605 606 607
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
608 609 610 611 612
}


void Item_func_int_div::fix_length_and_dec()
{
613
  find_num_type();
614 615 616 617 618
  max_length=args[0]->max_length - args[0]->decimals;
  maybe_null=1;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
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;
}

653

bk@work.mysql.com's avatar
bk@work.mysql.com committed
654 655 656 657 658 659 660
longlong Item_func_neg::val_int()
{
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return -value;
}

661

bk@work.mysql.com's avatar
bk@work.mysql.com committed
662 663 664 665
void Item_func_neg::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
  hybrid_type= REAL_RESULT;
  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 ||
	((ulonglong) ((Item_uint*) args[0])->value <=
	 (ulonglong) LONGLONG_MIN))
      hybrid_type= INT_RESULT;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
684 685
}

686

bk@work.mysql.com's avatar
bk@work.mysql.com committed
687 688 689 690 691 692 693
double Item_func_abs::val()
{
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return fabs(value);
}

694

bk@work.mysql.com's avatar
bk@work.mysql.com committed
695 696 697 698 699 700 701
longlong Item_func_abs::val_int()
{
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return value >= 0 ? value : -value;
}

702

bk@work.mysql.com's avatar
bk@work.mysql.com committed
703 704 705 706
void Item_func_abs::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
707 708 709 710 711 712
  hybrid_type= REAL_RESULT;
  if (args[0]->result_type() == INT_RESULT)
  {
    hybrid_type= INT_RESULT;
    unsigned_flag= 1;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
713 714
}

715

716 717 718 719 720 721 722 723 724 725 726 727 728 729
/* 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
730 731 732 733
double Item_func_log::val()
{
  double value=args[0]->val();
  if ((null_value=(args[0]->null_value || value <= 0.0)))
734 735 736 737 738 739 740 741
    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
742 743 744
  return log(value);
}

745 746 747 748 749 750 751 752
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
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 806 807 808 809 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 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
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);
928 929 930 931 932 933
  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;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
934 935 936

  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
937 938
  tmp=(abs_dec < array_elements(log_10) ?
       log_10[abs_dec] : pow(10.0,(double) abs_dec));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
939 940

  if (truncate)
941 942
  {
    if (value >= 0)
943
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
944
    else
945
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
946
  }
947 948 949
  else
    tmp2=dec < 0 ? rint(value/tmp)*tmp : rint(value*tmp)/tmp;
  return tmp2;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
950 951 952
}


953
void Item_func_rand::fix_length_and_dec()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
954
{
955 956
  decimals=NOT_FIXED_DEC; 
  max_length=float_length(decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
957 958
  if (arg_count)
  {					// Only use argument once in query
959
    uint32 tmp= (uint32) (args[0]->val_int());
960 961 962
    if ((rand= (struct rand_struct*) sql_alloc(sizeof(*rand))))
      randominit(rand,(uint32) (tmp*0x10001L+55555555L),
		 (uint32) (tmp*0x10000001L));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
963
  }
964
  else
nick@mysql.com's avatar
nick@mysql.com committed
965
  {
966
    THD *thd= current_thd;
967 968 969
    /*
      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.
nick@mysql.com's avatar
nick@mysql.com committed
970

971 972 973 974
      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
    */
nick@mysql.com's avatar
nick@mysql.com committed
975 976 977
    thd->rand_used=1;
    thd->rand_saved_seed1=thd->rand.seed1;
    thd->rand_saved_seed2=thd->rand.seed2;
978
    rand= &thd->rand;
nick@mysql.com's avatar
nick@mysql.com committed
979
  }
980 981 982 983 984
}


double Item_func_rand::val()
{
985
  return my_rnd(rand);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
}

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;
  cmp_type=args[0]->result_type();
1011

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  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());
  }
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1022 1023
  if (cmp_type == STRING_RESULT)
    agg_arg_collations_for_comparison(collation, args, arg_count);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
}


String *Item_func_min_max::val_str(String *str)
{
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
1035
    else if (!unsigned_flag)
1036
      str->set(nr,default_charset());
1037
    else
1038
      str->set((ulonglong) nr,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1039 1040 1041 1042 1043 1044 1045 1046
    return str;
  }
  case REAL_RESULT:
  {
    double nr=val();
    if (null_value)
      return 0; /* purecov: inspected */
    else
1047
      str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    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)
	{
1068
	  int cmp= sortcmp(res,res2,collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1069 1070 1071 1072 1073
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
    }
1074
    res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1075 1076
    return res;
  }
1077
  case ROW_RESULT:
1078
  default:
1079 1080 1081 1082
    // This case should never be choosen
    DBUG_ASSERT(0);
    return 0;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 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
  }
  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;
}

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

1143

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1144 1145 1146 1147 1148 1149 1150 1151 1152
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;
1153
  return (longlong) res->numchars();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1154 1155
}

1156

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1157 1158 1159 1160 1161 1162 1163 1164
longlong Item_func_coercibility::val_int()
{
  if (args[0]->null_value)
  {
    null_value= 1;
    return 0;
  }
  null_value= 0;
1165
  return (longlong) args[0]->collation.derivation;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1166
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1167

1168

1169 1170 1171
void Item_func_locate::fix_length_and_dec()
{
  maybe_null=0; max_length=11;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1172
  agg_arg_collations_for_comparison(cmp_collation, args, 2);
1173 1174
}

1175

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
longlong Item_func_locate::val_int()
{
  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;
1186 1187
  uint start=0;
  uint start0=0;
1188
  my_match_t match;
1189

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1190 1191
  if (arg_count == 3)
  {
1192 1193 1194
    start0= start =(uint) args[2]->val_int()-1;
    start=a->charpos(start);
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1195 1196 1197
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
1198

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1199 1200
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
1201
  
1202
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
1203
                                            a->ptr()+start, a->length()-start,
1204 1205 1206 1207
                                            b->ptr(), b->length(),
                                            &match, 1))
    return 0;
  return (longlong) match.mblen + start0 + 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1208 1209 1210
}


1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
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(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
1226 1227
longlong Item_func_field::val_int()
{
1228 1229 1230
  if (cmp_type == STRING_RESULT)
  {
    String *field;
1231
    if (!(field=args[0]->val_str(&value)))
1232
      return 0;					// -1 if null ?
1233
    for (uint i=1 ; i < arg_count ; i++)
1234 1235
    {
      String *tmp_value=args[i]->val_str(&tmp);
bar@bar.mysql.r18.ru's avatar
Fix:  
bar@bar.mysql.r18.ru committed
1236
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
1237
        return (longlong) (i);
1238 1239 1240 1241
    }
  }
  else if (cmp_type == INT_RESULT)
  {
1242 1243
    longlong val= args[0]->val_int();
    for (uint i=1; i < arg_count ; i++)
1244 1245
    {
      if (val == args[i]->val_int())
1246
 	return (longlong) (i);
1247 1248 1249
    }
  }
  else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1250
  {
1251 1252
    double val= args[0]->val();
    for (uint i=1; i < arg_count ; i++)
1253 1254
    {
      if (val == args[i]->val())
1255
 	return (longlong) (i);
1256
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1257 1258 1259 1260
  }
  return 0;
}

1261

1262 1263 1264
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
1265 1266
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
1267 1268
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
1269
    agg_arg_collations_for_comparison(cmp_collation, args, arg_count);
1270
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1271

1272

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
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
1296
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1297 1298
  {
    register const char *str=res->ptr();
1299
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1300 1301
    if (!l)
      return (longlong)((uchar) *str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    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)
      {
1326 1327
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1328 1329 1330 1331 1332 1333
	enum_bit=0;
	if (enum_value)
	  enum_bit=LL(1) << (enum_value-1);
      }
    }
  }
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1334
  agg_arg_collations_for_comparison(cmp_collation, args, 2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
}

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;
  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)
      {
1375 1376
	if (my_toupper(cmp_collation.collation,*str) != 
	    my_toupper(cmp_collation.collation,*pos))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
	  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;
}

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 */
  }
1400
  return (longlong) my_count_bits(value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1401 1402 1403 1404 1405 1406
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
1407
** Rewritten by monty.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
****************************************************************************/

#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);
  }
1424 1425
  if (buffers)					// Because of bug in ecc
    delete [] buffers;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1426 1427 1428 1429
}


bool
1430
udf_handler::fix_fields(THD *thd, TABLE_LIST *tables, Item_result_field *func,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1431 1432
			uint arg_count, Item **arguments)
{
1433
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
1434
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
1435
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1436 1437
  DBUG_ENTER("Item_udf_func::fix_fields");

1438 1439 1440
  if (check_stack_overrun(thd, buff))
    DBUG_RETURN(1);				// Fatal error flag is set!

1441
  udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1442 1443 1444

  if (!tmp_udf)
  {
1445
    my_printf_error(ER_CANT_FIND_UDF,ER(ER_CANT_FIND_UDF),MYF(0),u_d->name.str,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1446 1447 1448 1449 1450 1451 1452
		    errno);
    DBUG_RETURN(1);
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
1453
  func->maybe_null=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
  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++)
    {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1472 1473
      Item *item= *arg;
      if (item->fix_fields(thd, tables, arg) || item->check_cols(1))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1474
	return 1;
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
      /*
	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.
      */
1486 1487
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
1488
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1489
	func->maybe_null=1;
1490 1491 1492 1493
      func->with_sum_func= func->with_sum_func || item->with_sum_func;
      used_tables_cache|=item->used_tables();
      const_item_cache&=item->const_item();
      f_args.arg_type[i]=item->result_type();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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 1544 1545 1546 1547 1548 1549
    }
    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;
      }
    }
1550
    thd->net.last_error[0]=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
    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;
1613
    case ROW_RESULT:
1614
    default:
1615 1616
      // This case should never be choosen
      DBUG_ASSERT(0);
1617
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    }
  }
  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;
  }
1655
  save_str->set(res, res_length, str->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
  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
1676
    str->set(nr,decimals,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
  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;
1696
  else if (!unsigned_flag)
1697
    str->set(nr,default_charset());
1698
  else
1699
    str->set((ulonglong) nr,default_charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
  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;
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1742
  ulong thread_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1743

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1744 1745
  ULL(const char *key_arg,uint length, ulong id) 
    :key_length(length),count(1),locked(1), thread_id(id)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1746 1747 1748 1749 1750
  {
    key=(char*) my_memdup((byte*) key_arg,length,MYF(0));
    pthread_cond_init(&cond,NULL);
    if (key)
    {
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
1751
      if (my_hash_insert(&hash_user_locks,(byte*) this))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
      {
	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)
{
1781
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
1782 1783
  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
1784 1785 1786 1787 1788
}

void item_user_lock_free(void)
{
  hash_free(&hash_user_locks);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1789
  pthread_mutex_destroy(&LOCK_user_locks);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1790 1791 1792 1793 1794
}

void item_user_lock_release(ULL *ull)
{
  ull->locked=0;
1795 1796 1797
  if (mysql_bin_log.is_open())
  {
    char buf[256];
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1798 1799
    const char *command="DO RELEASE_LOCK(\"";
    String tmp(buf,sizeof(buf), system_charset_info);
1800
    tmp.copy(command, strlen(command), tmp.charset());
1801
    tmp.append(ull->key,ull->key_length);
1802
    tmp.append("\")", 2);
1803
    Query_log_event qev(current_thd, tmp.ptr(), tmp.length(),1);
1804
    qev.error_code=0; // this query is always safe to run on slave
1805 1806
    mysql_bin_log.write(&qev);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1807 1808 1809 1810 1811 1812
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

1813 1814 1815 1816 1817 1818 1819 1820 1821
/*
   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);
1822
  int event_count= 0;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1823

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1824 1825 1826 1827 1828 1829
  null_value=0;
  if (thd->slave_thread || !log_name || !log_name->length())
  {
    null_value = 1;
    return 0;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1830
  longlong pos = (ulong)args[1]->val_int();
1831
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
1832
#ifdef HAVE_REPLICATION
1833
  LOCK_ACTIVE_MI;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1834 1835
   if ((event_count = active_mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
   {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1836 1837 1838
    null_value = 1;
    event_count=0;
  }
1839
  UNLOCK_ACTIVE_MI;
1840
#endif
1841 1842 1843
  return event_count;
}

1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
#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;
  }

1860 1861 1862 1863 1864
  /*
    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
1865 1866 1867 1868 1869 1870 1871 1872 1873
  */
  if (!(ull= ((ULL*) hash_search(&hash_user_locks,lock_name,
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

1874 1875 1876 1877
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
1878 1879 1880 1881
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

1882
  set_timespec(abstime,lock_timeout);
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
  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
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
/*
  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;
1928
  int error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948

  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()))))
  {
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
1949
    ull=new ULL(res->ptr(),res->length(), thd->thread_id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    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++;

1964 1965 1966 1967
  /*
    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
1968 1969 1970 1971
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

1972
  set_timespec(abstime,timeout);
1973 1974
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
1975
	 != ETIME && error != ETIMEDOUT && error != EINVAL && ull->locked) ;
1976 1977
  if (thd->killed)
    error=EINTR;				// Return NULL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
  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;
}


/*
2008 2009 2010 2011 2012
  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
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
*/

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];
2061
  String tmp(buff,sizeof(buff), &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
  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;
2076
    case ROW_RESULT:
2077
    default:
2078 2079 2080
      // This case should never be choosen
      DBUG_ASSERT(0);
      return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2081 2082 2083 2084 2085
    }
  }
  return 0;
}

2086

2087 2088 2089 2090
void Item_func_benchmark::print(String *str)
{
  str->append("benchmark(", 10);
  char buffer[20];
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2091 2092 2093
  // my_charset_bin is good enough for numbers
  String st(buffer, sizeof(buffer), &my_charset_bin);
  st.set((ulonglong)loop_count, &my_charset_bin);
2094 2095 2096 2097 2098 2099
  str->append(st);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
#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;
2121
    entry->update_query_id=0;
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
    /*
      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).
    */
2132
    entry->used_query_id=current_thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2133 2134
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2135
    if (my_hash_insert(hash,(byte*) entry))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2136 2137 2138 2139 2140 2141 2142 2143
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

2144
/*
2145 2146
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
2147
*/
2148

2149 2150
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
2151
{
2152
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
2153
  if (Item_func::fix_fields(thd, tables, ref) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2154 2155
      !(entry= get_variable(&thd->user_vars, name, 1)))
    return 1;
2156 2157 2158 2159 2160
  /* 
     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).
  */
2161 2162
  entry->update_query_id= thd->query_id;
  cached_result_type= args[0]->result_type();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
  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;
}

2175

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2176
bool Item_func_set_user_var::update_hash(void *ptr, uint length,
2177
					 Item_result type,
2178
					 CHARSET_INFO *cs,
2179
					 Derivation dv)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2180 2181 2182 2183 2184 2185 2186 2187
{
  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;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2188
    entry->collation.set(cs, dv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2189 2190 2191
  }
  else
  {
2192 2193
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    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;
      }
    }
2218 2219 2220 2221 2222
    if (type == STRING_RESULT)
    {
      length--;					// Fix length change above
      entry->value[length]= 0;			// Store end \0
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2223 2224 2225
    memcpy(entry->value,ptr,length);
    entry->length= length;
    entry->type=type;
2226
    entry->collation.set(cs, dv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2227
  }
2228
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2229 2230

 err:
2231
  current_thd->fatal_error();			// Probably end of memory
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2232 2233
  null_value= 1;
  return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2234 2235 2236
}


2237 2238 2239
/* Get the value of a variable as a double */

double user_var_entry::val(my_bool *null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2240
{
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
  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:
    return atof(value);				// This is null terminated
2251 2252 2253
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2254
  }
2255
  return 0.0;					// Impossible
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2256 2257 2258
}


2259 2260 2261
/* Get the value of a variable as an integer */

longlong user_var_entry::val_int(my_bool *null_value)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2262
{
2263 2264 2265 2266 2267 2268 2269 2270
  if ((*null_value= (value == 0)))
    return LL(0);

  switch (type) {
  case REAL_RESULT:
    return (longlong) *(double*) value;
  case INT_RESULT:
    return *(longlong*) value;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2271
  case STRING_RESULT:
2272
    return strtoull(value,NULL,10);		// String is null terminated
2273 2274 2275
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2276
  }
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
  return LL(0);					// Impossible
}


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

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

  switch (type) {
  case REAL_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2291
    str->set(*(double*) value, decimals, &my_charset_bin);
2292 2293
    break;
  case INT_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2294
    str->set(*(longlong*) value, &my_charset_bin);
2295 2296
    break;
  case STRING_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2297
    if (str->copy(value, length, collation.collation))
2298
      str= 0;					// EOM error
2299 2300 2301
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2302
  }
2303
  return(str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2304 2305
}

2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
/*
  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;
  }
  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);
}

2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368

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

*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2369 2370 2371
bool
Item_func_set_user_var::update()
{
2372 2373 2374 2375
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2376 2377
  switch (cached_result_type) {
  case REAL_RESULT:
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2378
  {
2379 2380
    res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
		     REAL_RESULT, &my_charset_bin, DERIVATION_NONE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2381
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2382
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2383
  case INT_RESULT:
2384
  {
2385 2386
    res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
		     INT_RESULT, &my_charset_bin, DERIVATION_NONE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2387
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2388
  }
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2389
  break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2390
  case STRING_RESULT:
2391
  {
2392
    if (!save_result.vstr)					// Null value
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2393 2394
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
		       DERIVATION_NONE);
2395
    else
2396 2397 2398 2399
      res= update_hash((void*) save_result.vstr->ptr(),
		       save_result.vstr->length(), STRING_RESULT,
		       save_result.vstr->charset(),
		       args[0]->collation.derivation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2400 2401
    break;
  }
2402
  case ROW_RESULT:
2403
  default:
2404 2405 2406 2407
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
  }
2408
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2409 2410 2411
}


2412
double Item_func_set_user_var::val()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2413
{
2414
  check();
2415 2416
  update();					// Store expression
  return entry->val(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2417 2418
}

2419
longlong Item_func_set_user_var::val_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2420
{
2421
  check();
2422 2423
  update();					// Store expression
  return entry->val_int(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2424 2425
}

2426
String *Item_func_set_user_var::val_str(String *str)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2427
{
2428
  check();
2429 2430
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2431 2432 2433
}


2434 2435
void Item_func_set_user_var::print(String *str)
{
2436 2437 2438
  str->append("(@", 2);
  str->append(name.str, name.length);
  str->append(":=", 2);
2439 2440 2441 2442 2443
  args[0]->print(str);
  str->append(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2444 2445 2446
String *
Item_func_get_user_var::val_str(String *str)
{
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2447
  DBUG_ENTER("Item_func_get_user_var::val_str");
2448 2449 2450
  if (!var_entry)
    return (String*) 0;				// No such variable
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2451 2452 2453 2454 2455
}


double Item_func_get_user_var::val()
{
2456 2457 2458
  if (!var_entry)
    return 0.0;					// No such variable
  return (var_entry->val(&null_value));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2459 2460 2461 2462 2463
}


longlong Item_func_get_user_var::val_int()
{
2464 2465 2466
  if (!var_entry)
    return LL(0);				// No such variable
  return (var_entry->val_int(&null_value));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2467 2468 2469
}


2470 2471 2472 2473 2474 2475 2476
/*
  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).
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2477 2478
void Item_func_get_user_var::fix_length_and_dec()
{
2479
  THD *thd=current_thd;
2480
  BINLOG_USER_VAR_EVENT *user_var_event;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2481 2482 2483
  maybe_null=1;
  decimals=NOT_FIXED_DEC;
  max_length=MAX_BLOB_WIDTH;
2484

2485 2486
  if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
    null_value= 1;
2487 2488 2489 2490 2491

  if (!(opt_bin_log && is_update_query(thd->lex.sql_command)))
    return;

  if (!var_entry)
2492
  {
2493
    /*
2494 2495 2496 2497
      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).
2498 2499 2500 2501 2502
      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();
2503 2504
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
2505 2506 2507 2508 2509
    */

    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())));
2510 2511
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
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
      goto err;
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
  /* 
     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.
  */
  else if (var_entry->used_query_id == thd->query_id)
    return;

  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;
2546
  }
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
  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;

2558
  return;
2559

2560
err:
2561
  thd->fatal_error();
2562
  return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2563 2564 2565
}


2566
bool Item_func_get_user_var::const_item() const
2567
{
2568
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
2569
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581


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

2582 2583 2584

void Item_func_get_user_var::print(String *str)
{
2585
  str->append("(@", 2);
2586 2587 2588 2589
  str->append(name.str,name.length);
  str->append(')');
}

2590

2591
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
{
  /* 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));
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2606 2607 2608 2609 2610 2611 2612 2613
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];

2614
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
  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;
}

2645

2646
void Item_func_match::init_search(bool no_order)
2647
{
2648
  DBUG_ENTER("Item_func_match::init_search");
2649 2650

  /* Check if init_search() has been called before */
2651
  if (ft_handler)
2652
    DBUG_VOID_RETURN;
2653

2654
  if (key == NO_SUCH_KEY)
2655 2656 2657 2658
  {
    List<Item> fields;
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
2659
    concat=new Item_func_concat_ws(new Item_string(" ",1,
2660 2661
                                   cmp_collation.collation), fields);
  }
2662

2663 2664
  if (master)
  {
2665 2666
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
2667 2668
    ft_handler=master->ft_handler;
    join_key=master->join_key;
2669
    DBUG_VOID_RETURN;
2670 2671
  }

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

2674
  // MATCH ... AGAINST (NULL) is meaningless, but possible
2675
  if (!(ft_tmp=key_item()->val_str(&value)))
2676
  {
2677 2678
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
2679 2680
  }

2681 2682 2683 2684 2685
  if (ft_tmp->charset() != cmp_collation.collation)
  {
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
                      cmp_collation.collation);
    ft_tmp= &search_value;
2686 2687
  }

2688 2689
  if (join_key && !no_order)
    flags|=FT_SORTED;
2690
  ft_handler=table->file->ft_init_ext(flags, key,
2691
				      (byte*) ft_tmp->ptr(),
2692
				      ft_tmp->length());
2693 2694 2695

  if (join_key)
    table->file->ft_handler=ft_handler;
2696 2697

  DBUG_VOID_RETURN;
2698 2699
}

2700

2701
bool Item_func_match::fix_fields(THD *thd, TABLE_LIST *tlist, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2702 2703 2704
{
  Item *item;

2705 2706 2707
  maybe_null=1;
  join_key=0;

2708 2709 2710 2711 2712
  /*
    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.
2713
   */
2714 2715
  if (Item_func::fix_fields(thd, tlist, ref) ||
      !args[0]->const_during_execution())
2716 2717
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2718
    return 1;
2719
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2720

2721 2722
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2723
  {
2724
    item=args[i];
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
2725
    if (item->type() == Item::REF_ITEM)
2726 2727
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
2728
      key=NO_SUCH_KEY;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2729
  }
2730 2731 2732 2733 2734 2735
  /*
    Check that all columns come from the same table.
    We've already checked that columns in MATCH are fields so 
    PARAM_TABLE_BIT can only appear from AGAINST argument.
  */
  if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
2736
    key=NO_SUCH_KEY;
2737
  
2738
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
2739 2740
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2741
    return 1;
2742
  }
2743 2744 2745
  table=((Item_field *)item)->field->table;
  table->fulltext_searched=1;
  return agg_arg_collations_for_comparison(cmp_collation, args+1, arg_count-1);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2746
}
2747

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2748 2749 2750
bool Item_func_match::fix_index()
{
  Item_field *item;
2751
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
2752
  uint max_cnt=0, mkeys=0, i;
2753

2754
  if (key == NO_SUCH_KEY)
2755
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2756

2757
  for (keynr=0 ; keynr < table->keys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2758
  {
2759
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
2760
        (table->keys_in_use_for_query.is_set(keynr)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2761
    {
2762
      ft_to_key[fts]=keynr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2763 2764 2765 2766 2767 2768
      ft_cnt[fts]=0;
      fts++;
    }
  }

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

2771
  for (i=1; i < arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2772
  {
2773
    item=(Item_field*)args[i];
2774
    for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2775
    {
2776
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2777 2778 2779 2780 2781
      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))
2782
	  ft_cnt[keynr]++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2783 2784 2785 2786
      }
    }
  }

2787
  for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2788
  {
2789
    if (ft_cnt[keynr] > max_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2790
    {
2791
      mkeys=0;
2792 2793
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
2794 2795
      continue;
    }
2796
    if (max_cnt && ft_cnt[keynr] == max_cnt)
2797 2798
    {
      mkeys++;
2799 2800
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
2801
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2802 2803 2804
    }
  }

2805
  for (keynr=0 ; keynr <= mkeys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2806
  {
2807 2808
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
2809
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
2810
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2811

2812
    key=ft_to_key[keynr];
2813

2814 2815 2816
    return 0;
  }

2817
err:
2818
  if (flags & FT_BOOL)
2819
  {
2820
    key=NO_SUCH_KEY;
2821 2822
    return 0;
  }
2823
  my_error(ER_FT_MATCHING_KEY_NOT_FOUND,MYF(0));
2824
  return 1;
2825 2826
}

2827

2828
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
2829
{
2830 2831
  if (item->type() != FUNC_ITEM || ((Item_func*)item)->functype() != FT_FUNC ||
      flags != ((Item_func_match*)item)->flags)
2832 2833 2834 2835 2836
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
2837
      key_item()->eq(ifm->key_item(), binary_cmp))
2838
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2839 2840 2841 2842

  return 0;
}

2843

2844 2845
double Item_func_match::val()
{
2846
  DBUG_ENTER("Item_func_match::val");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2847
  if (ft_handler == NULL)
2848
    DBUG_RETURN(-1.0);
2849

2850 2851 2852
  if (table->null_row) /* NULL row from an outer join */
    return 0.0;

2853 2854 2855
  if (join_key)
  {
    if (table->file->ft_handler)
2856
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
2857 2858 2859
    join_key=0;
  }

2860
  if (key == NO_SUCH_KEY)
2861
  {
2862 2863
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
2864 2865 2866
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
				      (byte *)a->ptr(), a->length()));
2867 2868
  }
  else
2869 2870
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                   table->record[0], 0));
2871 2872
}

2873 2874
void Item_func_match::print(String *str)
{
2875
  str->append("(match ", 7);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2876
  print_args(str, 1);
2877
  str->append(" against (", 10);
2878
  args[0]->print(str);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2879
  if (flags & FT_BOOL)
2880
    str->append(" in boolean mode", 16);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
2881 2882
  else if (flags & FT_EXPAND)
    str->append(" with query expansion", 21);
2883
  str->append("))", 2);
2884
}
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2885

2886 2887 2888 2889
longlong Item_func_bit_xor::val_int()
{
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
2890
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
2891 2892 2893 2894
    return 0;
  return (longlong) (arg1 ^ arg2);
}

2895

2896 2897 2898 2899
/***************************************************************************
  System variables
****************************************************************************/

2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
/*
  Return value of an system variable base[.name] as a constant item

  SYNOPSIS
    get_system_var()
    thd			Thread handler
    var_type		global / session
    name		Name of base or system variable
    component		Component.

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

  RETURN
    0	error
    #	constant item
*/
  

Item *get_system_var(THD *thd, enum_var_type var_type, LEX_STRING name,
		     LEX_STRING component)
2921
{
2922 2923
  if (component.str == 0 &&
      !my_strcasecmp(system_charset_info, name.str, "VERSION"))
2924 2925 2926
    return new Item_string("@@VERSION", server_version,
			   (uint) strlen(server_version),
			   system_charset_info);
2927 2928 2929

  Item *item;
  sys_var *var;
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
  char buff[MAX_SYS_VAR_LENGTH*2+4+8], *pos;
  LEX_STRING *base_name, *component_name;

  if (component.str)
  {
    base_name= &component;
    component_name= &name;
  }
  else
  {
    base_name= &name;
    component_name= &component;			// Empty string
  }
2943

2944
  if (!(var= find_sys_var(base_name->str, base_name->length)))
2945
    return 0;
2946 2947 2948 2949 2950 2951 2952 2953 2954
  if (component.str)
  {
    if (!var->is_struct())
    {
      net_printf(thd, ER_VARIABLE_IS_NOT_STRUCT, base_name->str);
      return 0;
    }
  }
  if (!(item=var->item(thd, var_type, component_name)))
2955
    return 0;					// Impossible
2956
  thd->lex.uncacheable(UNCACHEABLE_SIDEEFFECT);
2957 2958
  buff[0]='@';
  buff[1]='@';
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2959 2960 2961 2962 2963
  pos=buff+2;
  if (var_type == OPT_SESSION)
    pos=strmov(pos,"session.");
  else if (var_type == OPT_GLOBAL)
    pos=strmov(pos,"global.");
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
  
  set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
  set_if_smaller(base_name->length, MAX_SYS_VAR_LENGTH);

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

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2977
  // set_name() will allocate the name
2978
  item->set_name(buff,(uint) (pos-buff), system_charset_info);
2979
  return item;
2980
}
2981

2982

2983 2984
Item *get_system_var(THD *thd, enum_var_type var_type, const char *var_name,
		     uint length, const char *item_name)
2985 2986 2987
{
  Item *item;
  sys_var *var;
2988 2989 2990
  LEX_STRING null_lex_string;

  null_lex_string.str= 0;
2991 2992 2993

  var= find_sys_var(var_name, length);
  DBUG_ASSERT(var != 0);
2994
  if (!(item=var->item(thd, var_type, &null_lex_string)))
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2995
    return 0;						// Impossible
2996
  thd->lex.uncacheable(UNCACHEABLE_SIDEEFFECT);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
2997
  item->set_name(item_name, 0, system_charset_info);	// Will use original name
2998 2999 3000 3001
  return item;
}


3002 3003
/*
  Check a user level lock.
3004 3005 3006 3007 3008 3009 3010 3011

  SYNOPSIS:
    val_int()

  RETURN VALUES
    1		Available
    0		Already taken
    NULL	Error
3012 3013
*/

3014
longlong Item_func_is_free_lock::val_int()
3015 3016 3017 3018 3019 3020
{
  String *res=args[0]->val_str(&value);
  THD *thd=current_thd;
  ULL *ull;

  null_value=0;
3021
  if (!res || !res->length())
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034
  {
    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;
}
3035

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
longlong Item_func_is_used_lock::val_int()
{
  String *res=args[0]->val_str(&value);
  THD *thd=current_thd;
  ULL *ull;

  null_value=1;
  if (!res || !res->length())
    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 0;

  null_value=0;
  return ull->thread_id;
}