item_func.cc 87 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
#include "sp_head.h"
#include "sp_rcontext.h"
#include "sp.h"
34

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


45 46
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
			      const char *fname)
47
{
48 49 50 51
  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
           c1.collation->name, c1.derivation_name(),
           c2.collation->name, c2.derivation_name(),
           fname);
52 53
}

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

66 67

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
68
{
69
  if (count == 2)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
70
    my_coll_agg_error(args[0]->collation, args[1]->collation, fname);
71
  else if (count == 3)
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
72 73 74 75 76
    my_coll_agg_error(args[0]->collation,
		      args[1]->collation,
		      args[2]->collation,
		      fname);
  else
77
    my_error(ER_CANT_AGGREGATE_NCOLLATIONS, MYF(0), fname);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
78 79
}

80

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

105

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
114 115 116 117 118 119 120 121
/* return TRUE if item is a constant */

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

122

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

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

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

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

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

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

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

    if (!(conv= (*arg)->safe_charset_converter(coll.collation)))
    {
      if (nargs >=2 && nargs <= 3)
      {
        /* restore the original arguments for better error message */
        args[0]= safe_args[0];
        args[1]= safe_args[1];
      }
      my_coll_agg_error(args, nargs, func_name());
      res= TRUE;
      break; // we cannot return here, we need to restore "arena".
    }
monty@mysql.com's avatar
monty@mysql.com committed
195 196
    if ((*arg)->type() == FIELD_ITEM)
      ((Item_field *)(*arg))->no_const_subst= 1;
bar@mysql.com's avatar
bar@mysql.com committed
197 198 199
    conv->fix_fields(thd, 0, &conv);
    *arg= conv;
  }
200
  if (arena)
bar@mysql.com's avatar
bar@mysql.com committed
201 202 203 204 205 206
    thd->restore_backup_item_arena(arena, &backup);
  return res;
}



207
void Item_func::set_arguments(List<Item> &list)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
208
{
209
  allowed_arg_cols= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
210 211 212 213
  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
214
    List_iterator_fast<Item> li(list);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
215 216 217 218 219 220 221 222 223 224 225
    Item *item;

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

226 227 228 229 230 231
Item_func::Item_func(List<Item> &list)
  :allowed_arg_cols(1)
{
  set_arguments(list);
}

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

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

/*
  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
konstantin@mysql.com's avatar
konstantin@mysql.com committed
272
      used_tables_cache Set to union of the tables used by arguments
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
273 274 275

      str_value.charset If this is a string function, set this to the
			character set for the first argument.
276
			If any argument is binary, this is set to binary
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
277 278 279 280 281 282 283

   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
284 285
  FALSE	ok
  TRUE	Got error.  Stored with my_error().
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
286 287
*/

bk@work.mysql.com's avatar
bk@work.mysql.com committed
288
bool
289
Item_func::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
290
{
291
  DBUG_ASSERT(fixed == 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
292
  Item **arg,**arg_end;
293
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
294
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
295
#endif
296

297
  used_tables_cache= not_null_tables_cache= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
298 299
  const_item_cache=1;

300
  if (check_stack_overrun(thd, buff))
301
    return TRUE;				// Fatal error if flag is set!
bk@work.mysql.com's avatar
bk@work.mysql.com committed
302 303 304 305
  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
306
      Item *item;
bell@sanja.is.com.ua's avatar
merge  
bell@sanja.is.com.ua committed
307 308 309 310
      /*
	We can't yet set item to *arg as fix_fields may change *arg
	We shouldn't call fix_fields() twice, so check 'fixed' field first
      */
311
      if ((!(*arg)->fixed && (*arg)->fix_fields(thd, tables, arg)) ||
312
	  (*arg)->check_cols(allowed_arg_cols))
313
	return TRUE;				/* purecov: inspected */
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
314
      item= *arg;
315
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
316
	maybe_null=1;
317

318
      with_sum_func= with_sum_func || item->with_sum_func;
319 320 321
      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
322 323 324
    }
  }
  fix_length_and_dec();
325 326
  if (thd->net.report_error) // An error inside fix_length_and_dec occured
    return TRUE;
327
  fixed= 1;
328
  return FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
329 330
}

bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
331 332 333 334 335 336 337 338 339 340 341 342 343
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);
}
344

igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367

/*
  Transform an Item_func object with a transformer callback function
   
  SYNOPSIS
    transform()
    transformer   the transformer callback function to be applied to the nodes
                  of the tree of the object
    argument      parameter to be passed to the transformer
  
  DESCRIPTION
    The function recursively applies the transform method with the
    same transformer to each argument the function.
    If the call of the method for a member item returns a new item
    the old item is substituted for a new one.
    After this the transform method is applied to the root node
    of the Item_func object. 
     
  RETURN VALUES
    Item returned as the result of transformation of the root node 
*/

Item *Item_func::transform(Item_transformer transformer, byte *argument)
368 369 370 371 372 373
{
  if (arg_count)
  {
    Item **arg,**arg_end;
    for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
    {
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
374
      Item *new_item= (*arg)->transform(transformer, argument);
375 376
      if (!new_item)
	return 0;
monty@mysql.com's avatar
monty@mysql.com committed
377 378
      if (*arg != new_item)
        current_thd->change_item_tree(arg, new_item);
379 380
    }
  }
igor@rurik.mysql.com's avatar
igor@rurik.mysql.com committed
381
  return (this->*transformer)(argument);
382 383 384
}


385 386
void Item_func::split_sum_func(THD *thd, Item **ref_pointer_array,
                               List<Item> &fields)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
387
{
388 389
  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
390
  {
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
391
    Item *item=* arg;
392
    if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
393
      item->split_sum_func(thd, ref_pointer_array, fields);
394
    else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
395
    {
396
      uint el= fields.elements;
397
      ref_pointer_array[el]= item;
398
      Item *new_item= new Item_ref(ref_pointer_array + el, 0, item->name);
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
399 400
      fields.push_front(item);
      ref_pointer_array[el]= item;
401
      thd->change_item_tree(arg, new_item);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    }
  }
}


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

425 426 427 428 429 430 431

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


bk@work.mysql.com's avatar
bk@work.mysql.com committed
432 433 434 435
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
436
  print_args(str, 0);
437 438 439 440
  str->append(')');
}


bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
441
void Item_func::print_args(String *str, uint from)
442
{
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
443
  for (uint i=from ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
444
  {
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
445
    if (i != from)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      str->append(',');
    args[i]->print(str);
  }
}


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

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

467
bool Item_func::eq(const Item *item, bool binary_cmp) const
bk@work.mysql.com's avatar
bk@work.mysql.com committed
468 469 470 471 472 473 474 475 476 477 478
{
  /* 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++)
479
    if (!args[i]->eq(item_func->args[i], binary_cmp))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
480 481 482 483
      return 0;
  return 1;
}

484

485 486 487 488 489
Field *Item_func::tmp_table_field(TABLE *t_arg)
{
  Field *res;
  LINT_INIT(res);

490
  switch (result_type()) {
491 492 493 494 495 496 497 498 499 500 501 502
  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:
503
    res= make_string_field(t_arg);
504
    break;
505
  case ROW_RESULT:
506
  default:
507 508 509
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
510 511 512 513 514
  }
  return res;
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
515 516
String *Item_real_func::val_str(String *str)
{
517
  DBUG_ASSERT(fixed == 1);
518
  double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
519 520
  if (null_value)
    return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
521
  str->set(nr,decimals, &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
522 523 524 525 526 527
  return str;
}


String *Item_num_func::val_str(String *str)
{
528
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
529 530 531 532 533
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
534
    if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
535
      str->set(nr,&my_charset_bin);
536
    else
monty@mysql.com's avatar
monty@mysql.com committed
537
      str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
538 539 540
  }
  else
  {
541
    double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
542 543
    if (null_value)
      return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
544
    str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
545 546 547 548 549 550 551 552 553 554 555 556 557
  }
  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);
}

558 559 560 561 562 563 564 565 566 567
void Item_func::signal_divide_by_null()
{
  THD *thd= current_thd;
  if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
    push_warning(thd, MYSQL_ERROR::WARN_LEVEL_ERROR, ER_DIVISION_BY_ZERO,
                 ER(ER_DIVISION_BY_ZERO));
  null_value= 1;
}


568
Item *Item_func::get_tmp_table_item(THD *thd)
569 570 571
{
  if (!with_sum_func && !const_item())
    return new Item_field(result_field);
572
  return copy_or_same(thd);
573 574
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
575 576
String *Item_int_func::val_str(String *str)
{
577
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
578 579 580
  longlong nr=val_int();
  if (null_value)
    return 0;
581
  if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
582
    str->set(nr,&my_charset_bin);
583
  else
monty@mysql.com's avatar
monty@mysql.com committed
584
    str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
585 586 587
  return str;
}

588 589 590 591
/*
  Change from REAL_RESULT (default) to INT_RESULT if both arguments are
  integers
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
592 593 594 595 596

void Item_num_op::find_num_type(void)
{
  if (args[0]->result_type() == INT_RESULT &&
      args[1]->result_type() == INT_RESULT)
597
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
598
    hybrid_type=INT_RESULT;
599 600
    unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
601 602 603 604
}

String *Item_num_op::val_str(String *str)
{
605
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
606 607 608 609 610
  if (hybrid_type == INT_RESULT)
  {
    longlong nr=val_int();
    if (null_value)
      return 0; /* purecov: inspected */
611
    if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
612
      str->set(nr,&my_charset_bin);
613
    else
monty@mysql.com's avatar
monty@mysql.com committed
614
      str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
615 616 617
  }
  else
  {
618
    double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
619 620
    if (null_value)
      return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
621
    str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
622 623 624 625 626
  }
  return str;
}


627 628
void Item_func_signed::print(String *str)
{
629
  str->append("cast(", 5);
630
  args[0]->print(str);
631
  str->append(" as signed)", 11);
632 633 634 635 636 637

}


void Item_func_unsigned::print(String *str)
{
638
  str->append("cast(", 5);
639
  args[0]->print(str);
640
  str->append(" as unsigned)", 13);
641 642 643 644

}


645
double Item_func_plus::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
646
{
647
  DBUG_ASSERT(fixed == 1);
648
  double value= args[0]->val_real() + args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
649 650 651 652 653 654 655
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

longlong Item_func_plus::val_int()
{
656
  DBUG_ASSERT(fixed == 1);
657 658 659 660 661 662 663
  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;
  }
664
  return (longlong) Item_func_plus::val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
665 666
}

667 668 669 670 671 672 673 674 675 676

/*
  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 &&
677
      (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
678 679 680 681
    unsigned_flag=0;
}


682
double Item_func_minus::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
683
{
684
  DBUG_ASSERT(fixed == 1);
685
  double value= args[0]->val_real() - args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
686 687 688 689 690 691 692
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
  return value;
}

longlong Item_func_minus::val_int()
{
693
  DBUG_ASSERT(fixed == 1);
694 695 696 697 698 699 700
  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;
  }
701
  return (longlong) Item_func_minus::val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
702 703
}

704

705
double Item_func_mul::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
706
{
707
  DBUG_ASSERT(fixed == 1);
708
  double value= args[0]->val_real() * args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
709 710 711 712 713 714 715
  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0; /* purecov: inspected */
  return value;
}

longlong Item_func_mul::val_int()
{
716
  DBUG_ASSERT(fixed == 1);
717 718 719 720 721 722 723
  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;
  }
724
  return (longlong) Item_func_mul::val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
725 726 727
}


728
double Item_func_div::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
729
{
730
  DBUG_ASSERT(fixed == 1);
731 732
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
733 734 735 736 737
  if ((null_value= args[0]->null_value || args[1]->null_value))
    return 0.0;
  if (val2 == 0.0)
  {
    signal_divide_by_null();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
738
    return 0.0;
739
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
740 741 742
  return value/val2;
}

743

bk@work.mysql.com's avatar
bk@work.mysql.com committed
744 745
longlong Item_func_div::val_int()
{
746
  DBUG_ASSERT(fixed == 1);
747 748 749 750
  if (hybrid_type == INT_RESULT)
  {
    longlong value=args[0]->val_int();
    longlong val2=args[1]->val_int();
751
    if ((null_value= args[0]->null_value || args[1]->null_value))
752
      return 0;
753 754 755 756 757
    if (val2 == 0)
    {
      signal_divide_by_null();
      return 0;
    }
758 759
    return value/val2;
  }
760
  return (longlong) Item_func_div::val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
761 762
}

763

bk@work.mysql.com's avatar
bk@work.mysql.com committed
764 765 766
void Item_func_div::fix_length_and_dec()
{
  decimals=max(args[0]->decimals,args[1]->decimals)+2;
767
  set_if_smaller(decimals, NOT_FIXED_DEC);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
768 769 770 771 772 773
  max_length=args[0]->max_length - args[0]->decimals + decimals;
  uint tmp=float_length(decimals);
  set_if_smaller(max_length,tmp);
  maybe_null=1;
}

774 775 776 777

/* Integer division */
longlong Item_func_int_div::val_int()
{
778
  DBUG_ASSERT(fixed == 1);
779 780
  longlong value=args[0]->val_int();
  longlong val2=args[1]->val_int();
781 782 783 784 785
  if (args[0]->null_value || args[1]->null_value)
    return 0;
  if (val2 == 0)
  {
    signal_divide_by_null();
786
    return 0;
787
  }
788 789 790
  return (unsigned_flag ?
	  (ulonglong) value / (ulonglong) val2 :
	  value / val2);
791 792 793 794 795
}


void Item_func_int_div::fix_length_and_dec()
{
796
  find_num_type();
797 798 799 800 801
  max_length=args[0]->max_length - args[0]->decimals;
  maybe_null=1;
}


802
double Item_func_mod::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
803
{
804
  DBUG_ASSERT(fixed == 1);
805 806
  double value= args[0]->val_real();
  double val2=  args[1]->val_real();
807
  if ((null_value= args[0]->null_value || args[1]->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
808
    return 0.0; /* purecov: inspected */
809 810 811 812 813
  if (val2 == 0.0)
  {
    signal_divide_by_null();
    return 0.0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
814 815 816 817 818
  return fmod(value,val2);
}

longlong Item_func_mod::val_int()
{
819
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
820 821
  longlong value=  args[0]->val_int();
  longlong val2= args[1]->val_int();
822
  if ((null_value= args[0]->null_value || args[1]->null_value))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
823
    return 0; /* purecov: inspected */
824 825 826 827 828
  if (val2 == 0)
  {
    signal_divide_by_null();
    return 0;
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
829 830 831 832 833
  return value % val2;
}

void Item_func_mod::fix_length_and_dec()
{
834
  Item_num_op::fix_length_and_dec();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
835 836 837
}


838
double Item_func_neg::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
839
{
840
  DBUG_ASSERT(fixed == 1);
841
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
842 843 844 845
  null_value=args[0]->null_value;
  return -value;
}

846

bk@work.mysql.com's avatar
bk@work.mysql.com committed
847 848
longlong Item_func_neg::val_int()
{
849
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
850 851 852 853 854
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return -value;
}

855

bk@work.mysql.com's avatar
bk@work.mysql.com committed
856 857
void Item_func_neg::fix_length_and_dec()
{
858 859
  enum Item_result arg_result= args[0]->result_type();
  enum Item::Type  arg_type= args[0]->type();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
860 861
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
862
  hybrid_type= REAL_RESULT;
863 864 865 866 867 868 869 870 871 872 873 874 875 876
  
  /*
    We need to account for added '-' in the following cases:
    A) argument is a real or integer positive constant - in this case 
    argument's max_length is set to actual number of bytes occupied, and not 
    maximum number of bytes real or integer may require. Note that all 
    constants are non negative so we don't need to account for removed '-'.
    B) argument returns a string.
  */
  if (arg_result == STRING_RESULT || 
      (arg_type == REAL_ITEM && ((Item_real*)args[0])->value >= 0) ||
      (arg_type == INT_ITEM && ((Item_int*)args[0])->value > 0))
    max_length++;

877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
  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
894 895
}

896

897
double Item_func_abs::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
898
{
899
  DBUG_ASSERT(fixed == 1);
900
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
901 902 903 904
  null_value=args[0]->null_value;
  return fabs(value);
}

905

bk@work.mysql.com's avatar
bk@work.mysql.com committed
906 907
longlong Item_func_abs::val_int()
{
908
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
909 910 911 912 913
  longlong value=args[0]->val_int();
  null_value=args[0]->null_value;
  return value >= 0 ? value : -value;
}

914

bk@work.mysql.com's avatar
bk@work.mysql.com committed
915 916 917 918
void Item_func_abs::fix_length_and_dec()
{
  decimals=args[0]->decimals;
  max_length=args[0]->max_length;
919 920 921 922 923 924
  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
925 926
}

927

928
/* Gateway to natural LOG function */
929
double Item_func_ln::val_real()
930
{
931
  DBUG_ASSERT(fixed == 1);
932
  double value= args[0]->val_real();
933 934 935 936 937 938 939 940 941 942
  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.
*/ 
943
double Item_func_log::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
944
{
945
  DBUG_ASSERT(fixed == 1);
946
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
947
  if ((null_value=(args[0]->null_value || value <= 0.0)))
948 949 950
    return 0.0;
  if (arg_count == 2)
  {
951
    double value2= args[1]->val_real();
952 953 954 955
    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
956 957 958
  return log(value);
}

959
double Item_func_log2::val_real()
960
{
961
  DBUG_ASSERT(fixed == 1);
962
  double value= args[0]->val_real();
963 964
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0;
965
  return log(value) / M_LN2;
966 967
}

968
double Item_func_log10::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
969
{
970
  DBUG_ASSERT(fixed == 1);
971
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
972 973 974 975 976
  if ((null_value=(args[0]->null_value || value <= 0.0)))
    return 0.0; /* purecov: inspected */
  return log10(value);
}

977
double Item_func_exp::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
978
{
979
  DBUG_ASSERT(fixed == 1);
980
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
981 982 983 984 985
  if ((null_value=args[0]->null_value))
    return 0.0; /* purecov: inspected */
  return exp(value);
}

986
double Item_func_sqrt::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
987
{
988
  DBUG_ASSERT(fixed == 1);
989
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
990 991 992 993 994
  if ((null_value=(args[0]->null_value || value < 0)))
    return 0.0; /* purecov: inspected */
  return sqrt(value);
}

995
double Item_func_pow::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
996
{
997
  DBUG_ASSERT(fixed == 1);
998 999
  double value= args[0]->val_real();
  double val2= args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1000 1001 1002 1003 1004 1005 1006
  if ((null_value=(args[0]->null_value || args[1]->null_value)))
    return 0.0; /* purecov: inspected */
  return pow(value,val2);
}

// Trigonometric functions

1007
double Item_func_acos::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1008
{
1009
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1010
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1011
  volatile double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1012 1013 1014 1015 1016
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(acos(value));
}

1017
double Item_func_asin::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1018
{
1019
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
1020
  // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
1021
  volatile double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1022 1023 1024 1025 1026
  if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
    return 0.0;
  return fix_result(asin(value));
}

1027
double Item_func_atan::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1028
{
1029
  DBUG_ASSERT(fixed == 1);
1030
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1031 1032 1033 1034
  if ((null_value=args[0]->null_value))
    return 0.0;
  if (arg_count == 2)
  {
1035
    double val2= args[1]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1036 1037 1038 1039 1040 1041 1042
    if ((null_value=args[1]->null_value))
      return 0.0;
    return fix_result(atan2(value,val2));
  }
  return fix_result(atan(value));
}

1043
double Item_func_cos::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1044
{
1045
  DBUG_ASSERT(fixed == 1);
1046
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1047 1048 1049 1050 1051
  if ((null_value=args[0]->null_value))
    return 0.0;
  return fix_result(cos(value));
}

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

1061
double Item_func_tan::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1062
{
1063
  DBUG_ASSERT(fixed == 1);
1064
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  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()
{
1076
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  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()
{
1091
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  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()
{
1107
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  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()
{
1127
  DBUG_ASSERT(fixed == 1);
1128
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1129 1130 1131 1132 1133 1134
  null_value=args[0]->null_value;
  return (longlong) ceil(value);
}

longlong Item_func_floor::val_int()
{
1135
  DBUG_ASSERT(fixed == 1);
1136
  // the volatile's for BUG #3051 to calm optimizer down (because of gcc's bug)
1137
  volatile double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  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
1152
      decimals=min(tmp,NOT_FIXED_DEC);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1153 1154 1155
  }
}

1156
double Item_func_round::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1157
{
1158
  DBUG_ASSERT(fixed == 1);
1159
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1160 1161
  int dec=(int) args[1]->val_int();
  uint abs_dec=abs(dec);
1162 1163 1164 1165 1166 1167
  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
1168 1169 1170

  if ((null_value=args[0]->null_value || args[1]->null_value))
    return 0.0;
1171 1172
  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
1173 1174

  if (truncate)
1175 1176
  {
    if (value >= 0)
1177
      tmp2= dec < 0 ? floor(value/tmp)*tmp : floor(value*tmp)/tmp;
1178
    else
1179
      tmp2= dec < 0 ? ceil(value/tmp)*tmp : ceil(value*tmp)/tmp;
1180
  }
1181 1182 1183
  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
1184 1185 1186
}


1187 1188
bool Item_func_rand::fix_fields(THD *thd, struct st_table_list *tables,
                                Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1189
{
1190 1191
  if (Item_real_func::fix_fields(thd, tables, ref))
    return TRUE;
1192
  used_tables_cache|= RAND_TABLE_BIT;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1193 1194
  if (arg_count)
  {					// Only use argument once in query
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    /*
      Allocate rand structure once: we must use thd->current_arena
      to create rand in proper mem_root if it's a prepared statement or
      stored procedure.
    */
    if (!rand && !(rand= (struct rand_struct*)
                   thd->current_arena->alloc(sizeof(*rand))))
      return TRUE;
    /*
      PARAM_ITEM is returned if we're in statement prepare and consequently
      no placeholder value is set yet.
    */
    if (args[0]->type() != PARAM_ITEM)
    {
      /*
        TODO: do not do reinit 'rand' for every execute of PS/SP if
        args[0] is a constant.
      */
      uint32 tmp= (uint32) args[0]->val_int();
      randominit(rand, (uint32) (tmp*0x10001L+55555555L),
                 (uint32) (tmp*0x10000001L));
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1217
  }
1218
  else
nick@mysql.com's avatar
nick@mysql.com committed
1219
  {
1220 1221 1222
    /*
      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
1223

1224 1225 1226 1227
      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
1228 1229 1230
    thd->rand_used=1;
    thd->rand_saved_seed1=thd->rand.seed1;
    thd->rand_saved_seed2=thd->rand.seed2;
1231
    rand= &thd->rand;
nick@mysql.com's avatar
nick@mysql.com committed
1232
  }
1233
  return FALSE;
1234 1235
}

1236 1237 1238 1239 1240 1241
void Item_func_rand::update_used_tables()
{
  Item_real_func::update_used_tables();
  used_tables_cache|= RAND_TABLE_BIT;
}

1242

1243
double Item_func_rand::val_real()
1244
{
1245
  DBUG_ASSERT(fixed == 1);
1246
  return my_rnd(rand);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1247 1248 1249 1250
}

longlong Item_func_sign::val_int()
{
1251
  DBUG_ASSERT(fixed == 1);
1252
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253 1254 1255 1256 1257
  null_value=args[0]->null_value;
  return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
}


1258
double Item_func_units::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1259
{
1260
  DBUG_ASSERT(fixed == 1);
1261
  double value= args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
  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();
1274

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
  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
1285
  if (cmp_type == STRING_RESULT)
bar@mysql.com's avatar
bar@mysql.com committed
1286
    agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1287 1288 1289 1290 1291
}


String *Item_func_min_max::val_str(String *str)
{
1292
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1293 1294 1295 1296 1297 1298
  switch (cmp_type) {
  case INT_RESULT:
  {
    longlong nr=val_int();
    if (null_value)
      return 0;
1299
    if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
1300
      str->set(nr,&my_charset_bin);
1301
    else
monty@mysql.com's avatar
monty@mysql.com committed
1302
      str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1303 1304 1305 1306
    return str;
  }
  case REAL_RESULT:
  {
1307
    double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1308 1309
    if (null_value)
      return 0; /* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
1310
    str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
    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)
	{
1331
	  int cmp= sortcmp(res,res2,collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1332 1333 1334 1335 1336
	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
	    res=res2;
	}
      }
    }
1337 1338
    if (res)					// If !NULL
      res->set_charset(collation.collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1339 1340
    return res;
  }
1341
  case ROW_RESULT:
1342
  default:
1343 1344 1345
    // This case should never be choosen
    DBUG_ASSERT(0);
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1346 1347 1348 1349 1350
  }
  return 0;					// Keep compiler happy
}


1351
double Item_func_min_max::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1352
{
1353
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1354 1355 1356 1357 1358 1359
  double value=0.0;
  null_value=1;
  for (uint i=0; i < arg_count ; i++)
  {
    if (null_value)
    {
1360
      value= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1361 1362 1363 1364
      null_value=args[i]->null_value;
    }
    else
    {
1365
      double tmp= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
      if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
	value=tmp;
    }
  }
  return value;
}


longlong Item_func_min_max::val_int()
{
1376
  DBUG_ASSERT(fixed == 1);
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
  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()
{
1398
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) res->length();
}

1409

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1410 1411
longlong Item_func_char_length::val_int()
{
1412
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1413 1414 1415 1416 1417 1418 1419
  String *res=args[0]->val_str(&value);
  if (!res)
  {
    null_value=1;
    return 0; /* purecov: inspected */
  }
  null_value=0;
1420
  return (longlong) res->numchars();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1421 1422
}

1423

bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1424 1425
longlong Item_func_coercibility::val_int()
{
1426
  DBUG_ASSERT(fixed == 1);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1427 1428 1429 1430 1431 1432
  if (args[0]->null_value)
  {
    null_value= 1;
    return 0;
  }
  null_value= 0;
1433
  return (longlong) args[0]->collation.derivation;
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
1434
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1435

1436

1437 1438 1439
void Item_func_locate::fix_length_and_dec()
{
  maybe_null=0; max_length=11;
bar@mysql.com's avatar
bar@mysql.com committed
1440
  agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV);
1441 1442
}

1443

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1444 1445
longlong Item_func_locate::val_int()
{
1446
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1447 1448 1449 1450 1451 1452 1453 1454
  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;
1455 1456
  uint start=0;
  uint start0=0;
1457
  my_match_t match;
1458

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1459 1460
  if (arg_count == 3)
  {
1461 1462 1463
    start0= start =(uint) args[2]->val_int()-1;
    start=a->charpos(start);
    
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1464 1465 1466
    if (start > a->length() || start+b->length() > a->length())
      return 0;
  }
1467

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1468 1469
  if (!b->length())				// Found empty string at start
    return (longlong) (start+1);
1470
  
1471
  if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
1472
                                            a->ptr()+start, a->length()-start,
1473 1474 1475 1476
                                            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
1477 1478 1479
}


1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
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
1495 1496
longlong Item_func_field::val_int()
{
1497
  DBUG_ASSERT(fixed == 1);
1498 1499 1500
  if (cmp_type == STRING_RESULT)
  {
    String *field;
1501
    if (!(field=args[0]->val_str(&value)))
1502
      return 0;					// -1 if null ?
1503
    for (uint i=1 ; i < arg_count ; i++)
1504 1505
    {
      String *tmp_value=args[i]->val_str(&tmp);
bar@bar.mysql.r18.ru's avatar
Fix:  
bar@bar.mysql.r18.ru committed
1506
      if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
1507
        return (longlong) (i);
1508 1509 1510 1511
    }
  }
  else if (cmp_type == INT_RESULT)
  {
1512 1513
    longlong val= args[0]->val_int();
    for (uint i=1; i < arg_count ; i++)
1514 1515
    {
      if (val == args[i]->val_int())
1516
 	return (longlong) (i);
1517 1518 1519
    }
  }
  else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1520
  {
1521
    double val= args[0]->val_real();
1522
    for (uint i=1; i < arg_count ; i++)
1523
    {
1524
      if (val == args[i]->val_real())
1525
 	return (longlong) (i);
1526
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1527 1528 1529 1530
  }
  return 0;
}

1531

1532 1533 1534
void Item_func_field::fix_length_and_dec()
{
  maybe_null=0; max_length=3;
1535 1536
  cmp_type= args[0]->result_type();
  for (uint i=1; i < arg_count ; i++)
1537 1538
    cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
  if (cmp_type == STRING_RESULT)
bar@mysql.com's avatar
bar@mysql.com committed
1539
    agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV);
1540
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1541

1542

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1543 1544
longlong Item_func_ascii::val_int()
{
1545
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
  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()
{
1558
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1559 1560 1561 1562 1563 1564 1565 1566 1567
  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
1568
  if (use_mb(res->charset()))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1569 1570
  {
    register const char *str=res->ptr();
1571
    register uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1572 1573
    if (!l)
      return (longlong)((uchar) *str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    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)
      {
1598 1599
	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
			      find->length(), 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1600 1601 1602 1603 1604 1605
	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
1606
  agg_arg_collations_for_comparison(cmp_collation, args, 2);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1607 1608 1609 1610 1611 1612
}

static const char separator=',';

longlong Item_func_find_in_set::val_int()
{
1613
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  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)
  {
1637 1638 1639 1640 1641 1642 1643 1644 1645
    my_wc_t wc;
    CHARSET_INFO *cs= cmp_collation.collation;
    const char *str_begin= buffer->ptr();
    const char *str_end= buffer->ptr();
    const char *real_end= str_end+buffer->length();
    const uchar *find_str= (const uchar *) find->ptr();
    uint find_str_len= find->length();
    int position= 0;
    while (1)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1646
    {
1647 1648 1649
      int symbol_len;
      if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end, 
                                       (uchar*) real_end)) > 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1650
      {
1651 1652
        const char *substr_end= str_end + symbol_len;
        bool is_last_item= (substr_end == real_end);
1653 1654
        bool is_separator= (wc == (my_wc_t) separator);
        if (is_separator || is_last_item)
1655 1656
        {
          position++;
1657
          if (is_last_item && !is_separator)
1658 1659 1660 1661 1662 1663 1664 1665 1666
            str_end= substr_end;
          if (!my_strnncoll(cs, (const uchar *) str_begin,
                            str_end - str_begin,
                            find_str, find_str_len))
            return (longlong) position;
          else
            str_begin= substr_end;
        }
        str_end= substr_end;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1667
      }
1668 1669 1670 1671 1672 1673 1674
      else if (str_end - str_begin == 0 && 
               find_str_len == 0 && 
               wc == (my_wc_t) separator)
        return (longlong) ++position;
      else
        return (longlong) 0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1675 1676 1677 1678 1679 1680
  }
  return 0;
}

longlong Item_func_bit_count::val_int()
{
1681
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1682 1683 1684 1685 1686 1687
  ulonglong value= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
1688
  return (longlong) my_count_bits(value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1689 1690 1691 1692 1693 1694
}


/****************************************************************************
** Functions to handle dynamic loadable functions
** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
1695
** Rewritten by monty.
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1696 1697 1698 1699 1700 1701
****************************************************************************/

#ifdef HAVE_DLOPEN

udf_handler::~udf_handler()
{
1702
  if (!not_original)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1703
  {
1704
    if (initialized)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1705
    {
1706 1707 1708 1709 1710 1711 1712
      if (u_d->func_deinit != NULL)
      {
        void (*deinit)(UDF_INIT *) = (void (*)(UDF_INIT*))
        u_d->func_deinit;
        (*deinit)(&initid);
      }
      free_udf(u_d);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1713
    }
1714 1715
    if (buffers)				// Because of bug in ecc
      delete [] buffers;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1716 1717 1718 1719 1720
  }
}


bool
1721
udf_handler::fix_fields(THD *thd, TABLE_LIST *tables, Item_result_field *func,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1722 1723
			uint arg_count, Item **arguments)
{
1724
#ifndef EMBEDDED_LIBRARY			// Avoid compiler warning
1725
  char buff[STACK_BUFF_ALLOC];			// Max argument in function
1726
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1727 1728
  DBUG_ENTER("Item_udf_func::fix_fields");

1729
  if (check_stack_overrun(thd, buff))
1730
    DBUG_RETURN(TRUE);				// Fatal error flag is set!
1731

1732
  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
1733 1734 1735

  if (!tmp_udf)
  {
1736
    my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
1737
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1738 1739 1740 1741 1742
  }
  u_d=tmp_udf;
  args=arguments;

  /* Fix all arguments */
1743
  func->maybe_null=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  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);
1754
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1755 1756 1757 1758 1759 1760 1761
    }
    uint i;
    Item **arg,**arg_end;
    for (i=0, arg=arguments, arg_end=arguments+arg_count;
	 arg != arg_end ;
	 arg++,i++)
    {
1762 1763
      if (!(*arg)->fixed && 
          (*arg)->fix_fields(thd, tables, arg))
1764
	DBUG_RETURN(1);
1765
      // we can't assign 'item' before, because fix_fields() can change arg
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
1766
      Item *item= *arg;
1767
      if (item->check_cols(1))
1768
	DBUG_RETURN(TRUE);
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
      /*
	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.
      */
1780 1781
      if (item->collation.collation->state & MY_CS_BINSORT)
	func->collation.set(&my_charset_bin);
1782
      if (item->maybe_null)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1783
	func->maybe_null=1;
1784 1785 1786 1787
      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
1788
    }
1789
    //TODO: why all folowing memory is not allocated with 1 call of sql_alloc?
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1790 1791
    if (!(buffers=new String[arg_count]) ||
	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
1792 1793 1794 1795 1796 1797 1798
	!(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) ||
	!(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) ||
	!(num_buffer= (char*) sql_alloc(arg_count *
					ALIGN_SIZE(sizeof(double)))) ||
	!(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) ||
	!(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count *
						       sizeof(long))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1799 1800
    {
      free_udf(u_d);
1801
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    }
  }
  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;
1817 1818 1819 1820
      f_args.lengths[i]= arguments[i]->max_length;
      f_args.maybe_null[i]= (char) arguments[i]->maybe_null;
      f_args.attributes[i]= arguments[i]->name;
      f_args.attribute_lengths[i]= arguments[i]->name_length;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839

      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:
1840
	*((double*) to)= arguments[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
	if (!arguments[i]->null_value)
	{
	  f_args.args[i]=to;
	  to+= ALIGN_SIZE(sizeof(double));
	}
	break;
      default:					// Skip these
	break;
      }
    }
1851
    thd->net.last_error[0]=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1852 1853 1854 1855 1856
    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)))
    {
1857 1858
      my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
               u_d->name.str, thd->net.last_error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1859
      free_udf(u_d);
1860
      DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1861 1862 1863 1864
    }
    func->max_length=min(initid.max_length,MAX_BLOB_WIDTH);
    func->maybe_null=initid.maybe_null;
    const_item_cache=initid.const_item;
1865
    func->decimals=min(initid.decimals,NOT_FIXED_DEC);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1866 1867 1868 1869
  }
  initialized=1;
  if (error)
  {
1870 1871
    my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
             u_d->name.str, ER(ER_UNKNOWN_ERROR));
1872
    DBUG_RETURN(TRUE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1873
  }
1874
  DBUG_RETURN(FALSE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
}


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:
1907
      *((double*) to)= args[i]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1908 1909 1910 1911 1912 1913
      if (!args[i]->null_value)
      {
	f_args.args[i]=to;
	to+= ALIGN_SIZE(sizeof(double));
      }
      break;
1914
    case ROW_RESULT:
1915
    default:
1916 1917
      // This case should never be choosen
      DBUG_ASSERT(0);
1918
      break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1919 1920 1921 1922 1923 1924 1925 1926 1927
    }
  }
  return 0;
}

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

String *udf_handler::val_str(String *str,String *save_str)
{
1928
  uchar is_null_tmp=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
  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;
    }
  }
1945 1946 1947
  char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
		 &is_null_tmp, &error);
  if (is_null_tmp || !res || error)		// The !res is for safety
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1948 1949 1950 1951 1952 1953 1954 1955
  {
    return 0;
  }
  if (res == str->ptr())
  {
    str->length(res_length);
    return str;
  }
1956
  save_str->set(res, res_length, str->charset());
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1957 1958 1959 1960 1961
  return save_str;
}



1962
double Item_func_udf_float::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1963
{
1964
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1965 1966 1967 1968 1969 1970 1971 1972 1973
  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)
{
1974
  DBUG_ASSERT(fixed == 1);
1975
  double nr= val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1976 1977
  if (null_value)
    return 0;					/* purecov: inspected */
monty@mysql.com's avatar
monty@mysql.com committed
1978
  str->set(nr,decimals,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1979 1980 1981 1982 1983 1984
  return str;
}


longlong Item_func_udf_int::val_int()
{
1985
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
  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)
{
1996
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1997 1998 1999
  longlong nr=val_int();
  if (null_value)
    return 0;
2000
  if (!unsigned_flag)
monty@mysql.com's avatar
monty@mysql.com committed
2001
    str->set(nr,&my_charset_bin);
2002
  else
monty@mysql.com's avatar
monty@mysql.com committed
2003
    str->set((ulonglong) nr,&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
  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)
{
2020
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
  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;

2037
class User_level_lock
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2038 2039 2040 2041 2042 2043 2044 2045 2046
{
  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
2047
  ulong thread_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2048

2049
  User_level_lock(const char *key_arg,uint length, ulong id) 
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
2050
    :key_length(length),count(1),locked(1), thread_id(id)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2051 2052 2053 2054 2055
  {
    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
2056
      if (my_hash_insert(&hash_user_locks,(byte*) this))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2057 2058 2059 2060 2061 2062
      {
	my_free((gptr) key,MYF(0));
	key=0;
      }
    }
  }
2063
  ~User_level_lock()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2064 2065 2066 2067 2068 2069 2070 2071 2072
  {
    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; }
2073 2074 2075
  friend void item_user_lock_release(User_level_lock *ull);
  friend char *ull_get_key(const User_level_lock *ull, uint *length,
                           my_bool not_used);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2076 2077
};

2078
char *ull_get_key(const User_level_lock *ull, uint *length,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2079 2080 2081 2082 2083 2084
		  my_bool not_used __attribute__((unused)))
{
  *length=(uint) ull->key_length;
  return (char*) ull->key;
}

2085 2086 2087

static bool item_user_lock_inited= 0;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2088 2089
void item_user_lock_init(void)
{
2090
  pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
2091 2092
  hash_init(&hash_user_locks,system_charset_info,
	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
2093
  item_user_lock_inited= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2094 2095 2096 2097
}

void item_user_lock_free(void)
{
2098 2099 2100 2101 2102 2103
  if (item_user_lock_inited)
  {
    item_user_lock_inited= 0;
    hash_free(&hash_user_locks);
    pthread_mutex_destroy(&LOCK_user_locks);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2104 2105
}

2106
void item_user_lock_release(User_level_lock *ull)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2107 2108
{
  ull->locked=0;
2109 2110 2111
  if (mysql_bin_log.is_open())
  {
    char buf[256];
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2112 2113
    const char *command="DO RELEASE_LOCK(\"";
    String tmp(buf,sizeof(buf), system_charset_info);
2114
    tmp.copy(command, strlen(command), tmp.charset());
2115
    tmp.append(ull->key,ull->key_length);
2116
    tmp.append("\")", 2);
2117
    Query_log_event qev(current_thd, tmp.ptr(), tmp.length(),1, FALSE);
2118
    qev.error_code=0; // this query is always safe to run on slave
2119 2120
    mysql_bin_log.write(&qev);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2121 2122 2123 2124 2125 2126
  if (--ull->count)
    pthread_cond_signal(&ull->cond);
  else
    delete ull;
}

2127 2128 2129 2130 2131 2132 2133
/*
   Wait until we are at or past the given position in the master binlog
   on the slave
 */

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

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2139 2140 2141 2142 2143 2144
  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
2145
  longlong pos = (ulong)args[1]->val_int();
2146
  longlong timeout = (arg_count==3) ? args[2]->val_int() : 0 ;
hf@deer.mysql.r18.ru's avatar
SCRUM  
hf@deer.mysql.r18.ru committed
2147
#ifdef HAVE_REPLICATION
2148
  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
2149 2150 2151 2152
  {
    null_value = 1;
    event_count=0;
  }
2153
#endif
2154 2155 2156
  return event_count;
}

2157 2158 2159 2160
#ifdef EXTRA_DEBUG
void debug_sync_point(const char* lock_name, uint lock_timeout)
{
  THD* thd=current_thd;
2161
  User_level_lock* ull;
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
  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;
  }

2173 2174 2175 2176 2177
  /*
    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
2178
  */
2179
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks, lock_name,
2180 2181 2182 2183 2184 2185 2186
				 lock_name_len))))
  {
    pthread_mutex_unlock(&LOCK_user_locks);
    return;
  }
  ull->count++;

2187 2188 2189 2190
  /*
    Structure is now initialized.  Try to get the lock.
    Set up control struct to allow others to abort locks
  */
2191 2192 2193 2194
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

2195
  set_timespec(abstime,lock_timeout);
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
  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
2227 2228 2229 2230 2231 2232 2233 2234 2235
/*
  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()
{
2236
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2237 2238 2239 2240
  String *res=args[0]->val_str(&value);
  longlong timeout=args[1]->val_int();
  struct timespec abstime;
  THD *thd=current_thd;
2241
  User_level_lock *ull;
2242
  int error=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259

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

2260 2261 2262
  if (!(ull= ((User_level_lock *) hash_search(&hash_user_locks,
                                              (byte*) res->ptr(),
                                              res->length()))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2263
  {
2264
    ull=new User_level_lock(res->ptr(),res->length(), thd->thread_id);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
    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++;

2279 2280 2281 2282
  /*
    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
2283 2284 2285 2286
  thd->proc_info="User lock";
  thd->mysys_var->current_mutex= &LOCK_user_locks;
  thd->mysys_var->current_cond=  &ull->cond;

2287
  set_timespec(abstime,timeout);
2288 2289
  while (!thd->killed &&
	 (error=pthread_cond_timedwait(&ull->cond,&LOCK_user_locks,&abstime))
2290
	 != ETIME && error != ETIMEDOUT && error != EINVAL && ull->locked) ;
2291 2292
  if (thd->killed)
    error=EINTR;				// Return NULL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
  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;
}


/*
2323 2324 2325 2326 2327
  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
2328 2329 2330 2331
*/

longlong Item_func_release_lock::val_int()
{
2332
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2333
  String *res=args[0]->val_str(&value);
2334
  User_level_lock *ull;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
  longlong result;
  if (!res || !res->length())
  {
    null_value=1;
    return 0;
  }
  null_value=0;

  result=0;
  pthread_mutex_lock(&LOCK_user_locks);
2345 2346 2347
  if (!(ull= ((User_level_lock*) hash_search(&hash_user_locks,
                                             (const byte*) res->ptr(),
                                             res->length()))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
  {
    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;
}


2365
longlong Item_func_last_insert_id::val_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2366
{
2367
  DBUG_ASSERT(fixed == 1);
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
  if (arg_count)
  {
    longlong value=args[0]->val_int();
    current_thd->insert_id(value);
    null_value=args[0]->null_value;
    return value;
  }
  else
  {
    Item *it= get_system_var(current_thd, OPT_SESSION, "last_insert_id", 14,
			     "last_insert_id()");
    return it->val_int();
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2381 2382 2383 2384 2385 2386
}

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

longlong Item_func_benchmark::val_int()
{
2387
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2388
  char buff[MAX_FIELD_WIDTH];
2389
  String tmp(buff,sizeof(buff), &my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2390 2391 2392 2393 2394 2395
  THD *thd=current_thd;

  for (ulong loop=0 ; loop < loop_count && !thd->killed; loop++)
  {
    switch (args[0]->result_type()) {
    case REAL_RESULT:
2396
      (void) args[0]->val_real();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2397 2398 2399 2400 2401 2402 2403
      break;
    case INT_RESULT:
      (void) args[0]->val_int();
      break;
    case STRING_RESULT:
      (void) args[0]->val_str(&tmp);
      break;
2404
    case ROW_RESULT:
2405
    default:
2406 2407 2408
      // This case should never be choosen
      DBUG_ASSERT(0);
      return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2409 2410 2411 2412 2413
    }
  }
  return 0;
}

2414

2415 2416 2417 2418
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
2419 2420 2421
  // my_charset_bin is good enough for numbers
  String st(buffer, sizeof(buffer), &my_charset_bin);
  st.set((ulonglong)loop_count, &my_charset_bin);
2422 2423 2424 2425 2426 2427
  str->append(st);
  str->append(',');
  args[0]->print(str);
  str->append(')');
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
#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;
2449
    entry->update_query_id=0;
2450
    entry->collation.set(NULL, DERIVATION_NONE);
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
    /*
      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).
    */
2461
    entry->used_query_id=current_thd->query_id;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2462 2463
    entry->type=STRING_RESULT;
    memcpy(entry->name.str, name.str, name.length+1);
hf@deer.(none)'s avatar
SCRUM  
hf@deer.(none) committed
2464
    if (my_hash_insert(hash,(byte*) entry))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2465 2466 2467 2468 2469 2470 2471 2472
    {
      my_free((char*) entry,MYF(0));
      return 0;
    }
  }
  return entry;
}

2473
/*
2474 2475
  When a user variable is updated (in a SET command or a query like
  SELECT @a:= ).
2476
*/
2477

2478 2479
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
2480
{
2481
  DBUG_ASSERT(fixed == 0);
2482
  /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
2483
  if (Item_func::fix_fields(thd, tables, ref) ||
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2484
      !(entry= get_variable(&thd->user_vars, name, 1)))
2485
    return TRUE;
2486 2487 2488 2489 2490
  /* 
     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).
  */
2491
  entry->update_query_id= thd->query_id;
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509
  /*
    As it is wrong and confusing to associate any 
    character set with NULL, @a should be latin2
    after this query sequence:

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

    I.e. the second query should not change the charset
    to the current default value, but should keep the 
    original value assigned during the first query.
    In order to do it, we don't copy charset
    from the argument if the argument is NULL
    and the variable has previously been initialized.
  */
  if (!entry->collation.collation || !args[0]->null_value)
    entry->collation.set(args[0]->collation);
  collation.set(entry->collation);
2510
  cached_result_type= args[0]->result_type();
2511
  return FALSE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2512 2513 2514 2515 2516 2517 2518 2519 2520
}


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;
2521
  collation.set(args[0]->collation);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2522 2523
}

2524

monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2525
bool Item_func_set_user_var::update_hash(void *ptr, uint length,
2526
					 Item_result type,
2527
					 CHARSET_INFO *cs,
2528
					 Derivation dv)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
{
  if ((null_value=args[0]->null_value))
  {
    char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
    if (entry->value && entry->value != pos)
      my_free(entry->value,MYF(0));
    entry->value=0;
    entry->length=0;
  }
  else
  {
2540 2541
    if (type == STRING_RESULT)
      length++;					// Store strings with end \0
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
    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;
      }
    }
2566 2567 2568 2569 2570
    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
2571 2572 2573
    memcpy(entry->value,ptr,length);
    entry->length= length;
    entry->type=type;
2574
    entry->collation.set(cs, dv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2575
  }
2576
  return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2577 2578

 err:
2579
  current_thd->fatal_error();			// Probably end of memory
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2580 2581
  null_value= 1;
  return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2582 2583 2584
}


2585 2586 2587
/* 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
2588
{
2589 2590 2591 2592 2593 2594 2595 2596 2597
  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:
serg@serg.mylan's avatar
serg@serg.mylan committed
2598
    return my_atof(value);                      // This is null terminated
2599 2600 2601
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2602
  }
2603
  return 0.0;					// Impossible
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2604 2605 2606
}


2607 2608 2609
/* 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
2610
{
2611 2612 2613 2614 2615 2616 2617 2618
  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
2619
  case STRING_RESULT:
monty@mysql.com's avatar
monty@mysql.com committed
2620 2621 2622 2623
  {
    int error;
    return my_strtoll10(value, (char**) 0, &error);// String is null terminated
  }
2624 2625 2626
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2627
  }
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
  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
2642
    str->set(*(double*) value, decimals, &my_charset_bin);
2643 2644
    break;
  case INT_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2645
    str->set(*(longlong*) value, &my_charset_bin);
2646 2647
    break;
  case STRING_RESULT:
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2648
    if (str->copy(value, length, collation.collation))
2649
      str= 0;					// EOM error
2650 2651 2652
  case ROW_RESULT:
    DBUG_ASSERT(1);				// Impossible
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2653
  }
2654
  return(str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2655 2656
}

2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
/*
  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
2669
    FALSE OK.
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
*/

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

  switch (cached_result_type) {
  case REAL_RESULT:
  {
2680
    save_result.vreal= args[0]->val_real();
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
    break;
  }
  case INT_RESULT:
  {
    save_result.vint= args[0]->val_int();
    break;
  }
  case STRING_RESULT:
  {
    save_result.vstr= args[0]->val_str(&value);
    break;
  }
  case ROW_RESULT:
  default:
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
  }
2699
  DBUG_RETURN(FALSE);
2700 2701
}

2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718

/*
  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
2719 2720 2721
bool
Item_func_set_user_var::update()
{
2722 2723 2724 2725
  bool res;
  DBUG_ENTER("Item_func_set_user_var::update");
  LINT_INIT(res);

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2726 2727
  switch (cached_result_type) {
  case REAL_RESULT:
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2728
  {
2729 2730
    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
2731
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2732
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2733
  case INT_RESULT:
2734
  {
2735 2736
    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
2737
    break;
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2738
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2739
  case STRING_RESULT:
2740
  {
2741
    if (!save_result.vstr)					// Null value
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
2742 2743
      res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin,
		       DERIVATION_NONE);
2744
    else
2745 2746 2747 2748
      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
2749 2750
    break;
  }
2751
  case ROW_RESULT:
2752
  default:
2753 2754 2755 2756
    // This case should never be choosen
    DBUG_ASSERT(0);
    break;
  }
2757
  DBUG_RETURN(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2758 2759 2760
}


2761
double Item_func_set_user_var::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2762
{
2763
  DBUG_ASSERT(fixed == 1);
2764
  check();
2765 2766
  update();					// Store expression
  return entry->val(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2767 2768
}

2769
longlong Item_func_set_user_var::val_int()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2770
{
2771
  DBUG_ASSERT(fixed == 1);
2772
  check();
2773 2774
  update();					// Store expression
  return entry->val_int(&null_value);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2775 2776
}

2777
String *Item_func_set_user_var::val_str(String *str)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2778
{
2779
  DBUG_ASSERT(fixed == 1);
2780
  check();
2781 2782
  update();					// Store expression
  return entry->val_str(&null_value, str, decimals);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2783 2784 2785
}


2786 2787
void Item_func_set_user_var::print(String *str)
{
2788 2789 2790
  str->append("(@", 2);
  str->append(name.str, name.length);
  str->append(":=", 2);
2791 2792 2793 2794 2795
  args[0]->print(str);
  str->append(')');
}


2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
void Item_func_set_user_var::print_as_stmt(String *str)
{
  str->append("set @", 5);
  str->append(name.str, name.length);
  str->append(":=", 2);
  args[0]->print(str);
  str->append(')');
}


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2806 2807 2808
String *
Item_func_get_user_var::val_str(String *str)
{
2809
  DBUG_ASSERT(fixed == 1);
vva@eagle.mysql.r18.ru's avatar
vva@eagle.mysql.r18.ru committed
2810
  DBUG_ENTER("Item_func_get_user_var::val_str");
2811
  if (!var_entry)
2812
    DBUG_RETURN((String*) 0);			// No such variable
2813
  DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2814 2815 2816
}


2817
double Item_func_get_user_var::val_real()
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2818
{
2819
  DBUG_ASSERT(fixed == 1);
2820 2821 2822
  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
2823 2824 2825 2826 2827
}


longlong Item_func_get_user_var::val_int()
{
2828
  DBUG_ASSERT(fixed == 1);
2829 2830 2831
  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
2832 2833 2834
}


2835
/*
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
  Get variable by name and, if necessary, put the record of variable 
  use into the binary log.
  
  SYNOPSIS
    get_var_with_binlog()
      thd        Current thread
      name       Variable name 
      out_entry  [out] variable structure or NULL. The pointer is set 
                 regardless of whether function succeeded or not.

2846 2847 2848 2849
  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).
2850 2851 2852 2853 2854
  
  RETURN
    0  OK 
    1  Failed to put appropiate record into binary log
    
2855 2856
*/

2857 2858
int get_var_with_binlog(THD *thd, LEX_STRING &name, 
                        user_var_entry **out_entry)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2859
{
2860
  BINLOG_USER_VAR_EVENT *user_var_event;
2861 2862
  user_var_entry *var_entry;
  var_entry= get_variable(&thd->user_vars, name, 0);
2863
  
pem@mysql.com's avatar
pem@mysql.com committed
2864
  if (!(opt_bin_log && is_update_query(thd->lex->sql_command)))
2865 2866 2867 2868
  {
    *out_entry= var_entry;
    return 0;
  }
2869 2870

  if (!var_entry)
2871
  {
2872
    /*
2873 2874 2875 2876
      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).
2877 2878 2879 2880 2881
      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();
2882 2883
      this would save memory and time; but calling sql_set_variables() makes
      one unique place to maintain (sql_set_variables()). 
2884 2885 2886 2887 2888
    */

    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())));
2889 2890
    /* Create the variable */
    if (sql_set_variables(thd, &tmp_var_list))
2891 2892 2893 2894 2895
      goto err;
    if (!(var_entry= get_variable(&thd->user_vars, name, 0)))
      goto err;
  }
  else if (var_entry->used_query_id == thd->query_id)
2896 2897 2898 2899 2900 2901 2902 2903 2904
  {
    /* 
       If this variable was already stored in user_var_events by this query
       (because it's used in more than one place in the query), don't store
       it.
    */
    *out_entry= var_entry;
    return 0;
  }
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927

  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;
2928
  }
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
  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;
2939 2940 2941
  
  *out_entry= var_entry;
  return 0;
2942

2943
err:
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
  *out_entry= var_entry;
  return 1;
}


void Item_func_get_user_var::fix_length_and_dec()
{
  THD *thd=current_thd;
  int error;
  maybe_null=1;
  decimals=NOT_FIXED_DEC;
  max_length=MAX_BLOB_WIDTH;
2956

2957
  error= get_var_with_binlog(thd, name, &var_entry);
2958 2959

  if (var_entry)
2960
  {
2961
    collation.set(var_entry->collation);
2962 2963 2964 2965 2966 2967 2968 2969 2970
    switch (var_entry->type) {
    case REAL_RESULT:
      max_length= DBL_DIG + 8;
    case INT_RESULT:
      max_length= MAX_BIGINT_WIDTH;
      break;
    case STRING_RESULT:
      max_length= MAX_BLOB_WIDTH;
      break;
monty@mysql.com's avatar
monty@mysql.com committed
2971 2972
    case ROW_RESULT:                            // Keep compiler happy
      break;
2973 2974
    }
  }
2975 2976 2977
  else
    null_value= 1;

2978 2979
  if (error)
    thd->fatal_error();
2980

2981
  return;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2982 2983 2984
}


2985
bool Item_func_get_user_var::const_item() const
2986
{
2987
  return (!var_entry || current_thd->query_id != var_entry->update_query_id);
2988
}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000


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

3001 3002 3003

void Item_func_get_user_var::print(String *str)
{
3004
  str->append("(@", 2);
3005 3006 3007 3008
  str->append(name.str,name.length);
  str->append(')');
}

3009

3010
bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
{
  /* 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
3025 3026
longlong Item_func_inet_aton::val_int()
{
3027
  DBUG_ASSERT(fixed == 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3028 3029 3030 3031 3032
  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];
3033
  int dot_count= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3034

3035
  String *s,tmp(buff,sizeof(buff),&my_charset_bin);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
  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 == '.')
    {
3052
      dot_count++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3053 3054 3055 3056 3057 3058 3059
      result= (result << 8) + (ulonglong) byte_result;
      byte_result = 0;
    }
    else
      goto err;					// Invalid character
  }
  if (c != '.')					// IP number can't end on '.'
3060
  {
3061 3062 3063 3064 3065 3066
    /*
      Handle short-forms addresses according to standard. Examples:
      127		-> 0.0.0.127
      127.1		-> 127.0.0.1
      127.2.1		-> 127.2.0.1
    */
3067
    switch (dot_count) {
3068 3069
    case 1: result<<= 8; /* Fall through */
    case 2: result<<= 8; /* Fall through */
3070
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3071
    return (result << 8) + (ulonglong) byte_result;
3072
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3073 3074 3075 3076 3077 3078

err:
  null_value=1;
  return 0;
}

3079

3080
void Item_func_match::init_search(bool no_order)
3081
{
3082
  DBUG_ENTER("Item_func_match::init_search");
3083 3084

  /* Check if init_search() has been called before */
3085
  if (ft_handler)
3086
    DBUG_VOID_RETURN;
3087

3088
  if (key == NO_SUCH_KEY)
3089 3090
  {
    List<Item> fields;
3091
    fields.push_back(new Item_string(" ",1, cmp_collation.collation));
3092 3093
    for (uint i=1; i < arg_count; i++)
      fields.push_back(args[i]);
3094
    concat=new Item_func_concat_ws(fields);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3095 3096 3097
    /*
      Above function used only to get value and do not need fix_fields for it:
      Item_string - basic constant
monty@mysql.com's avatar
monty@mysql.com committed
3098 3099
      fields - fix_fields() was already called for this arguments
      Item_func_concat_ws - do not need fix_fields() to produce value
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3100 3101
    */
    concat->quick_fix_field();
3102
  }
3103

3104 3105
  if (master)
  {
3106 3107
    join_key=master->join_key=join_key|master->join_key;
    master->init_search(no_order);
3108 3109
    ft_handler=master->ft_handler;
    join_key=master->join_key;
3110
    DBUG_VOID_RETURN;
3111 3112
  }

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

3115
  // MATCH ... AGAINST (NULL) is meaningless, but possible
3116
  if (!(ft_tmp=key_item()->val_str(&value)))
3117
  {
3118 3119
    ft_tmp= &value;
    value.set("",0,cmp_collation.collation);
3120 3121
  }

3122 3123
  if (ft_tmp->charset() != cmp_collation.collation)
  {
3124
    uint dummy_errors;
3125
    search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
3126
                      cmp_collation.collation, &dummy_errors);
3127
    ft_tmp= &search_value;
3128 3129
  }

3130 3131
  if (join_key && !no_order)
    flags|=FT_SORTED;
3132
  ft_handler=table->file->ft_init_ext(flags, key,
3133
				      (byte*) ft_tmp->ptr(),
3134
				      ft_tmp->length());
3135 3136 3137

  if (join_key)
    table->file->ft_handler=ft_handler;
3138 3139

  DBUG_VOID_RETURN;
3140 3141
}

3142

3143
bool Item_func_match::fix_fields(THD *thd, TABLE_LIST *tlist, Item **ref)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3144
{
3145
  DBUG_ASSERT(fixed == 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3146
  Item *item;
3147
  LINT_INIT(item);				// Safe as arg_count is > 1
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3148

3149 3150 3151
  maybe_null=1;
  join_key=0;

3152 3153 3154 3155 3156
  /*
    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.
3157
   */
3158 3159
  if (Item_func::fix_fields(thd, tlist, ref) ||
      !args[0]->const_during_execution())
3160 3161
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
3162
    return TRUE;
3163
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3164

3165 3166
  const_item_cache=0;
  for (uint i=1 ; i < arg_count ; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3167
  {
3168
    item=args[i];
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
3169
    if (item->type() == Item::REF_ITEM)
3170 3171
      args[i]= item= *((Item_ref *)item)->ref;
    if (item->type() != Item::FIELD_ITEM)
3172
      key=NO_SUCH_KEY;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3173
  }
3174 3175 3176 3177 3178 3179
  /*
    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())
3180
    key=NO_SUCH_KEY;
3181
  
3182
  if (key == NO_SUCH_KEY && !(flags & FT_BOOL))
3183 3184
  {
    my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
3185
    return TRUE;
3186
  }
3187 3188 3189
  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
3190
}
3191

bk@work.mysql.com's avatar
bk@work.mysql.com committed
3192 3193 3194
bool Item_func_match::fix_index()
{
  Item_field *item;
3195
  uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
3196
  uint max_cnt=0, mkeys=0, i;
3197

3198
  if (key == NO_SUCH_KEY)
3199
    return 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3200

3201
  for (keynr=0 ; keynr < table->keys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3202
  {
3203
    if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
3204
        (table->keys_in_use_for_query.is_set(keynr)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3205
    {
3206
      ft_to_key[fts]=keynr;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3207 3208 3209 3210 3211 3212
      ft_cnt[fts]=0;
      fts++;
    }
  }

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

3215
  for (i=1; i < arg_count; i++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3216
  {
3217
    item=(Item_field*)args[i];
3218
    for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3219
    {
3220
      KEY *ft_key=&table->key_info[ft_to_key[keynr]];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3221 3222 3223 3224 3225
      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))
3226
	  ft_cnt[keynr]++;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3227 3228 3229 3230
      }
    }
  }

3231
  for (keynr=0 ; keynr < fts ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3232
  {
3233
    if (ft_cnt[keynr] > max_cnt)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3234
    {
3235
      mkeys=0;
3236 3237
      max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
3238 3239
      continue;
    }
3240
    if (max_cnt && ft_cnt[keynr] == max_cnt)
3241 3242
    {
      mkeys++;
3243 3244
      ft_cnt[mkeys]=ft_cnt[keynr];
      ft_to_key[mkeys]=ft_to_key[keynr];
3245
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3246 3247 3248
    }
  }

3249
  for (keynr=0 ; keynr <= mkeys ; keynr++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3250
  {
3251 3252
    // partial keys doesn't work
    if (max_cnt < arg_count-1 ||
3253
        max_cnt < table->key_info[ft_to_key[keynr]].key_parts)
3254
      continue;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3255

3256
    key=ft_to_key[keynr];
3257

3258 3259 3260
    return 0;
  }

3261
err:
3262
  if (flags & FT_BOOL)
3263
  {
3264
    key=NO_SUCH_KEY;
3265 3266
    return 0;
  }
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3267 3268
  my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
             ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
3269
  return 1;
3270 3271
}

3272

3273
bool Item_func_match::eq(const Item *item, bool binary_cmp) const
3274
{
3275 3276
  if (item->type() != FUNC_ITEM || ((Item_func*)item)->functype() != FT_FUNC ||
      flags != ((Item_func_match*)item)->flags)
3277 3278 3279 3280 3281
    return 0;

  Item_func_match *ifm=(Item_func_match*) item;

  if (key == ifm->key && table == ifm->table &&
3282
      key_item()->eq(ifm->key_item(), binary_cmp))
3283
    return 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
3284 3285 3286 3287

  return 0;
}

3288

3289
double Item_func_match::val_real()
3290
{
3291
  DBUG_ASSERT(fixed == 1);
3292
  DBUG_ENTER("Item_func_match::val");
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
3293
  if (ft_handler == NULL)
3294
    DBUG_RETURN(-1.0);
3295

3296 3297 3298
  if (table->null_row) /* NULL row from an outer join */
    return 0.0;

3299 3300 3301
  if (join_key)
  {
    if (table->file->ft_handler)
3302
      DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
3303 3304 3305
    join_key=0;
  }

3306
  if (key == NO_SUCH_KEY)
3307
  {
3308 3309
    String *a= concat->val_str(&value);
    if ((null_value= (a == 0)))
3310 3311 3312
      DBUG_RETURN(0);
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
				      (byte *)a->ptr(), a->length()));
3313 3314
  }
  else
3315 3316
    DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
                                                   table->record[0], 0));
3317 3318
}

3319 3320
void Item_func_match::print(String *str)
{
3321
  str->append("(match ", 7);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3322
  print_args(str, 1);
3323
  str->append(" against (", 10);
3324
  args[0]->print(str);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3325
  if (flags & FT_BOOL)
3326
    str->append(" in boolean mode", 16);
bell@sanja.is.com.ua's avatar
bell@sanja.is.com.ua committed
3327 3328
  else if (flags & FT_EXPAND)
    str->append(" with query expansion", 21);
3329
  str->append("))", 2);
3330
}
monty@narttu.mysql.fi's avatar
monty@narttu.mysql.fi committed
3331

3332 3333
longlong Item_func_bit_xor::val_int()
{
3334
  DBUG_ASSERT(fixed == 1);
3335 3336
  ulonglong arg1= (ulonglong) args[0]->val_int();
  ulonglong arg2= (ulonglong) args[1]->val_int();
3337
  if ((null_value= (args[0]->null_value || args[1]->null_value)))
3338 3339 3340 3341
    return 0;
  return (longlong) (arg1 ^ arg2);
}

3342

3343 3344 3345 3346
/***************************************************************************
  System variables
****************************************************************************/

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
/*
  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)
3368
{
3369 3370
  if (component.str == 0 &&
      !my_strcasecmp(system_charset_info, name.str, "VERSION"))
3371 3372 3373
    return new Item_string("@@VERSION", server_version,
			   (uint) strlen(server_version),
			   system_charset_info);
3374 3375 3376

  Item *item;
  sys_var *var;
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389
  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
  }
3390

3391
  if (!(var= find_sys_var(base_name->str, base_name->length)))
3392
    return 0;
3393 3394 3395 3396
  if (component.str)
  {
    if (!var->is_struct())
    {
3397
      my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
3398 3399 3400 3401
      return 0;
    }
  }
  if (!(item=var->item(thd, var_type, component_name)))
3402
    return 0;					// Impossible
pem@mysql.com's avatar
pem@mysql.com committed
3403
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
3404 3405
  buff[0]='@';
  buff[1]='@';
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
3406 3407 3408 3409 3410
  pos=buff+2;
  if (var_type == OPT_SESSION)
    pos=strmov(pos,"session.");
  else if (var_type == OPT_GLOBAL)
    pos=strmov(pos,"global.");
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
  
  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
3424
  // set_name() will allocate the name
3425
  item->set_name(buff,(uint) (pos-buff), system_charset_info);
3426
  return item;
3427
}
3428

3429

3430 3431
Item *get_system_var(THD *thd, enum_var_type var_type, const char *var_name,
		     uint length, const char *item_name)
3432 3433 3434
{
  Item *item;
  sys_var *var;
3435 3436 3437
  LEX_STRING null_lex_string;

  null_lex_string.str= 0;
3438 3439 3440

  var= find_sys_var(var_name, length);
  DBUG_ASSERT(var != 0);
3441
  if (!(item=var->item(thd, var_type, &null_lex_string)))
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
3442
    return 0;						// Impossible
pem@mysql.com's avatar
pem@mysql.com committed
3443
  thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
bar@bar.mysql.r18.ru's avatar
bar@bar.mysql.r18.ru committed
3444
  item->set_name(item_name, 0, system_charset_info);	// Will use original name
3445 3446 3447 3448
  return item;
}


3449 3450
/*
  Check a user level lock.
3451 3452 3453 3454 3455 3456 3457 3458

  SYNOPSIS:
    val_int()

  RETURN VALUES
    1		Available
    0		Already taken
    NULL	Error
3459 3460
*/

3461
longlong Item_func_is_free_lock::val_int()
3462
{
3463
  DBUG_ASSERT(fixed == 1);
3464
  String *res=args[0]->val_str(&value);
3465
  User_level_lock *ull;
3466 3467

  null_value=0;
3468
  if (!res || !res->length())
3469 3470 3471 3472 3473 3474
  {
    null_value=1;
    return 0;
  }
  
  pthread_mutex_lock(&LOCK_user_locks);
3475
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
3476 3477 3478 3479 3480 3481
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 1;
  return 0;
}
3482

hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
3483 3484
longlong Item_func_is_used_lock::val_int()
{
3485
  DBUG_ASSERT(fixed == 1);
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
3486
  String *res=args[0]->val_str(&value);
3487
  User_level_lock *ull;
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
3488 3489 3490 3491 3492 3493

  null_value=1;
  if (!res || !res->length())
    return 0;
  
  pthread_mutex_lock(&LOCK_user_locks);
3494
  ull= (User_level_lock *) hash_search(&hash_user_locks, (byte*) res->ptr(),
hf@genie.(none)'s avatar
SCRUM  
hf@genie.(none) committed
3495 3496 3497 3498 3499 3500 3501 3502 3503
			  res->length());
  pthread_mutex_unlock(&LOCK_user_locks);
  if (!ull || !ull->locked)
    return 0;

  null_value=0;
  return ull->thread_id;
}

3504

3505 3506 3507 3508 3509 3510 3511 3512 3513
longlong Item_func_row_count::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->row_count_func;
}


3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
Item_func_sp::Item_func_sp(sp_name *name)
  :Item_func(), m_name(name), m_sp(NULL)
{
  m_name->init_qname(current_thd);
}

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

const char *
Item_func_sp::func_name() const
{
3529
  THD *thd= current_thd;
3530
  /* Calculate length to avoud reallocation of string for sure */
3531 3532 3533 3534
  uint len= ((m_name->m_db.length +
              m_name->m_name.length)*2 + //characters*quoting
             2 +                         // ` and `
             1 +                         // .
3535 3536
             1 +                         // end of string
             ALIGN_SIZE(1));             // to avoid String reallocation
monty@mysql.com's avatar
monty@mysql.com committed
3537
  String qname((char *)alloc_root(thd->mem_root, len), len,
3538
               system_charset_info);
3539

3540 3541 3542 3543 3544
  qname.length(0);
  append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
  qname.append('.');
  append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
  return qname.ptr();
3545 3546
}

3547

3548 3549 3550 3551 3552
int
Item_func_sp::execute(Item **itp)
{
  DBUG_ENTER("Item_func_sp::execute");
  THD *thd= current_thd;
3553
  int res;
3554 3555 3556
#ifndef NO_EMBEDDED_ACCESS_CHECKS
  st_sp_security_context save_ctx;
#endif
3557

3558
  if (! m_sp)
3559
    m_sp= sp_find_function(thd, m_name);
3560
  if (! m_sp)
3561
  {
3562
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
3563
    DBUG_RETURN(-1);
3564
  }
3565

3566
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3567 3568 3569
  if (check_procedure_access(thd, EXECUTE_ACL, 
			     m_sp->m_db.str, m_sp->m_name.str, 0))
      DBUG_RETURN(-1);
3570
  sp_change_security_context(thd, m_sp, &save_ctx);
3571 3572 3573 3574 3575 3576 3577
  if (save_ctx.changed && 
      check_procedure_access(thd, EXECUTE_ACL, 
			     m_sp->m_db.str, m_sp->m_name.str, 0))
  {
    sp_restore_security_context(thd, m_sp, &save_ctx);
    DBUG_RETURN(-1);
  }
3578
#endif
3579

3580 3581 3582 3583 3584
  /*
    We don't need to surpress senfing of ok packet here (by setting
    thd->net.no_send_ok to true), because we are not allowing statements
    in functions now.
  */
3585 3586
  res= m_sp->execute_function(thd, args, arg_count, itp);

3587
#ifndef NO_EMBEDDED_ACCESS_CHECKS
3588
  sp_restore_security_context(thd, m_sp, &save_ctx);
3589
#endif
3590 3591

  DBUG_RETURN(res);
3592 3593
}

3594

3595 3596
enum enum_field_types
Item_func_sp::field_type() const
3597
{
3598
  DBUG_ENTER("Item_func_sp::field_type");
3599

3600
  if (! m_sp)
3601
    m_sp= sp_find_function(current_thd, m_name);
3602 3603
  if (m_sp)
  {
3604 3605
    DBUG_PRINT("info", ("m_returns = %d", m_sp->m_returns));
    DBUG_RETURN(m_sp->m_returns);
3606
  }
3607
  my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
3608
  DBUG_RETURN(MYSQL_TYPE_VARCHAR);
3609 3610
}

3611

3612 3613
Item_result
Item_func_sp::result_type() const
3614
{
3615 3616
  DBUG_ENTER("Item_func_sp::result_type");
  DBUG_PRINT("info", ("m_sp = %p", m_sp));
3617

3618
  if (! m_sp)
3619
    m_sp= sp_find_function(current_thd, m_name);
3620
  if (m_sp)
3621
  {
3622
    DBUG_RETURN(m_sp->result());
3623
  }
3624
  my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
3625
  DBUG_RETURN(STRING_RESULT);
3626 3627 3628 3629 3630 3631 3632
}

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

3633
  if (! m_sp)
3634
    m_sp= sp_find_function(current_thd, m_name);
3635 3636
  if (! m_sp)
  {
3637
    my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", m_name->m_qname.str);
3638 3639
  }
  else
3640 3641 3642 3643
  {
    switch (m_sp->result()) {
    case STRING_RESULT:
      maybe_null= 1;
3644
      max_length= MAX_BLOB_WIDTH;
3645 3646 3647 3648 3649 3650 3651 3652 3653
      break;
    case REAL_RESULT:
      decimals= NOT_FIXED_DEC;
      max_length= float_length(decimals);
      break;
    case INT_RESULT:
      decimals= 0;
      max_length= 21;
      break;
3654 3655 3656 3657 3658
    case ROW_RESULT:
    default:
      // This case should never be choosen
      DBUG_ASSERT(0);
      break;
3659 3660 3661 3662
    }
  }
  DBUG_VOID_RETURN;
}
monty@mysql.com's avatar
monty@mysql.com committed
3663 3664


3665 3666 3667 3668 3669 3670 3671
longlong Item_func_found_rows::val_int()
{
  DBUG_ASSERT(fixed == 1);
  THD *thd= current_thd;

  return thd->found_rows();
}