item_cmpfunc.cc 44.8 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   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.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   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.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21 22 23 24 25
   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 compare functions */

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

#include "mysql_priv.h"
#include <m_ctype.h>
unknown's avatar
unknown committed
26
#include "assert.h"
unknown's avatar
unknown committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Item_bool_func2* Item_bool_func2::eq_creator(Item *a, Item *b)
{
  return new Item_func_eq(a, b);
}
Item_bool_func2* Item_bool_func2::ne_creator(Item *a, Item *b)
{
  return new Item_func_ne(a, b);
}
Item_bool_func2* Item_bool_func2::gt_creator(Item *a, Item *b)
{
  return new Item_func_gt(a, b);
}
Item_bool_func2* Item_bool_func2::lt_creator(Item *a, Item *b)
{
  return new Item_func_lt(a, b);
}
Item_bool_func2* Item_bool_func2::ge_creator(Item *a, Item *b)
{
  return new Item_func_ge(a, b);
}
Item_bool_func2* Item_bool_func2::le_creator(Item *a, Item *b)
{
  return new Item_func_le(a, b);
}
unknown's avatar
unknown committed
51

unknown's avatar
unknown committed
52
/*
53
  Test functions
54 55
  Most of these  returns 0LL if false and 1LL if true and
  NULL if some arg is NULL.
unknown's avatar
unknown committed
56 57 58 59 60 61 62 63 64
*/

longlong Item_func_not::val_int()
{
  double value=args[0]->val();
  null_value=args[0]->null_value;
  return !null_value && value == 0 ? 1 : 0;
}

unknown's avatar
unknown committed
65 66 67 68 69
/*
  Convert a constant expression or string to an integer.
  This is done when comparing DATE's of different formats and
  also when comparing bigint to strings (in which case the string
  is converted once to a bigint).
unknown's avatar
unknown committed
70 71 72 73

  RESULT VALUES
  0	Can't convert item
  1	Item was replaced with an integer version of the item
unknown's avatar
unknown committed
74
*/
unknown's avatar
unknown committed
75 76 77

static bool convert_constant_item(Field *field, Item **item)
{
unknown's avatar
unknown committed
78
  if ((*item)->const_item() && (*item)->type() != Item::INT_ITEM)
unknown's avatar
unknown committed
79
  {
unknown's avatar
unknown committed
80
    if (!(*item)->save_in_field(field, 1) && !((*item)->null_value))
unknown's avatar
unknown committed
81
    {
82 83
      Item *tmp=new Item_int_with_ref(field->val_int(), *item);
      if (tmp)
unknown's avatar
unknown committed
84
	*item=tmp;
85
      return 1;					// Item was replaced
unknown's avatar
unknown committed
86 87 88 89 90 91 92
    }
  }
  return 0;
}

void Item_bool_func2::fix_length_and_dec()
{
93
  max_length=1;					// Function returns 0 or 1
unknown's avatar
unknown committed
94

95 96 97 98
  /*
    As some compare functions are generated after sql_yacc,
    we have to check for out of memory conditons here
  */
unknown's avatar
unknown committed
99 100 101 102 103 104
  if (!args[0] || !args[1])
    return;
  // Make a special case of compare with fields to get nicer DATE comparisons
  if (args[0]->type() == FIELD_ITEM)
  {
    Field *field=((Item_field*) args[0])->field;
105
    if (field->store_for_compare())
unknown's avatar
unknown committed
106 107 108
    {
      if (convert_constant_item(field,&args[1]))
      {
109 110
	cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
			 INT_RESULT); // Works for all types.
unknown's avatar
unknown committed
111 112 113 114 115 116 117
	return;
      }
    }
  }
  if (args[1]->type() == FIELD_ITEM)
  {
    Field *field=((Item_field*) args[1])->field;
118
    if (field->store_for_compare())
unknown's avatar
unknown committed
119 120 121
    {
      if (convert_constant_item(field,&args[0]))
      {
122 123
	cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
			 INT_RESULT); // Works for all types.
unknown's avatar
unknown committed
124 125 126 127
	return;
      }
    }
  }
128
  set_cmp_func();
unknown's avatar
unknown committed
129 130
}

131
int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
unknown's avatar
unknown committed
132
{
133
  owner= item;
unknown's avatar
unknown committed
134 135
  func= comparator_matrix[type][(owner->functype() == Item_func::EQUAL_FUNC)?
				1:0];
unknown's avatar
unknown committed
136
  if (type == ROW_RESULT)
unknown's avatar
unknown committed
137
  {
138 139
    uint n= (*a)->cols();
    if (n != (*b)->cols())
140 141 142 143 144 145 146
    {
      my_error(ER_CARDINALITY_COL, MYF(0), n);
      comparators= 0;
      return 1;
    }
    if ((comparators= (Arg_comparator *) sql_alloc(sizeof(Arg_comparator)*n)))
      for (uint i=0; i < n; i++)
147
	comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i));
148 149 150 151 152 153 154 155
    else
    {
      my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0));
      current_thd->fatal_error= 1;
      return 1;
    }
  }
  return 0;
unknown's avatar
unknown committed
156
}
unknown's avatar
unknown committed
157

158
int Arg_comparator::compare_string()
unknown's avatar
unknown committed
159 160
{
  String *res1,*res2;
161
  if ((res1= (*a)->val_str(&owner->tmp_value1)))
unknown's avatar
unknown committed
162
  {
163
    if ((res2= (*b)->val_str(&owner->tmp_value2)))
unknown's avatar
unknown committed
164
    {
unknown's avatar
unknown committed
165 166
      owner->null_value= 0;
      return owner->binary() ? stringcmp(res1,res2) : sortcmp(res1,res2);
unknown's avatar
unknown committed
167 168
    }
  }
unknown's avatar
unknown committed
169
  owner->null_value= 1;
unknown's avatar
unknown committed
170 171 172
  return -1;
}

unknown's avatar
unknown committed
173 174 175
int Arg_comparator::compare_e_string()
{
  String *res1,*res2;
176 177
  res1= (*a)->val_str(&owner->tmp_value1);
  res2= (*b)->val_str(&owner->tmp_value2);
unknown's avatar
unknown committed
178 179 180 181 182 183 184
  if (!res1 || !res2)
    return test(res1 == res2);
  return (owner->binary() ? test(stringcmp(res1, res2) == 0) :
	    test(sortcmp(res1, res2) == 0));
}


185
int Arg_comparator::compare_real()
unknown's avatar
unknown committed
186
{
187 188
  double val1= (*a)->val();
  if (!(*a)->null_value)
unknown's avatar
unknown committed
189
  {
190 191
    double val2= (*b)->val();
    if (!(*b)->null_value)
unknown's avatar
unknown committed
192
    {
unknown's avatar
unknown committed
193
      owner->null_value= 0;
unknown's avatar
unknown committed
194 195 196 197 198
      if (val1 < val2)	return -1;
      if (val1 == val2) return 0;
      return 1;
    }
  }
unknown's avatar
unknown committed
199
  owner->null_value= 1;
unknown's avatar
unknown committed
200 201 202
  return -1;
}

unknown's avatar
unknown committed
203 204
int Arg_comparator::compare_e_real()
{
205 206 207 208
  double val1= (*a)->val();
  double val2= (*b)->val();
  if ((*a)->null_value || (*b)->null_value)
    return test((*a)->null_value && (*b)->null_value);
unknown's avatar
unknown committed
209 210
  return test(val1 == val2);
}
unknown's avatar
unknown committed
211

212
int Arg_comparator::compare_int()
unknown's avatar
unknown committed
213
{
214 215
  longlong val1= (*a)->val_int();
  if (!(*a)->null_value)
unknown's avatar
unknown committed
216
  {
217 218
    longlong val2= (*b)->val_int();
    if (!(*b)->null_value)
unknown's avatar
unknown committed
219
    {
unknown's avatar
unknown committed
220
      owner->null_value= 0;
unknown's avatar
unknown committed
221 222 223 224 225
      if (val1 < val2)	return -1;
      if (val1 == val2)   return 0;
      return 1;
    }
  }
unknown's avatar
unknown committed
226
  owner->null_value= 1;
unknown's avatar
unknown committed
227 228 229
  return -1;
}

unknown's avatar
unknown committed
230 231
int Arg_comparator::compare_e_int()
{
232 233 234 235
  longlong val1= (*a)->val_int();
  longlong val2= (*b)->val_int();
  if ((*a)->null_value || (*b)->null_value)
    return test((*a)->null_value && (*b)->null_value);
unknown's avatar
unknown committed
236 237 238 239
  return test(val1 == val2);
}


240
int Arg_comparator::compare_row()
unknown's avatar
unknown committed
241 242
{
  int res= 0;
243
  uint n= (*a)->cols();
unknown's avatar
unknown committed
244
  for (uint i= 0; i<n; i++)
unknown's avatar
unknown committed
245
  {
246
    if ((res= comparators[i].compare()))
unknown's avatar
unknown committed
247 248 249 250 251 252
      return res;
    if (owner->null_value)
      return -1;
  }
  return res;
}
unknown's avatar
unknown committed
253

unknown's avatar
unknown committed
254 255 256
int Arg_comparator::compare_e_row()
{
  int res= 0;
257
  uint n= (*a)->cols();
unknown's avatar
unknown committed
258 259 260 261 262 263 264 265
  for (uint i= 0; i<n; i++)
  {
    if ((res= comparators[i].compare()))
      return 1;
  }
  return 1;
}

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
longlong Item_in_optimizer::val_int()
{
  int_cache_ok= 1;
  flt_cache_ok= 0;
  str_cache_ok= 0;
  int_cache= args[0]->val_int_result();
  if (args[0]->is_null_result())
  {
    null_value= 1;
    return 0;
  }
  longlong tmp= args[1]->val_int_result();
  null_value= args[1]->is_null_result();
  return tmp;
}

longlong Item_in_optimizer::get_cache_int()
{
  if (!int_cache_ok)
  {
    int_cache_ok= 1;
    flt_cache_ok= 0;
    str_cache_ok= 0;
    int_cache= args[0]->val_int_result();
    null_value= args[0]->is_null_result();
  }
  return int_cache;
}

double Item_in_optimizer::get_cache()
{
  if (!flt_cache_ok)
  {
    int_cache_ok= 0;
    flt_cache_ok= 1;
    str_cache_ok= 0;
    flt_cache= args[0]->val_result();
    null_value= args[0]->is_null_result();
  }
  return flt_cache;
}

String *Item_in_optimizer::get_cache_str(String *s)
{
  if (!str_cache_ok)
  {
    int_cache_ok= 0;
    flt_cache_ok= 0;
    str_cache_ok= 1;
    str_cache_buff.set(buffer, sizeof(buffer), s->charset());
    str_cache= args[0]->str_result(&str_cache_buff);
    null_value= args[0]->is_null_result();
  }
  return str_cache;
}
unknown's avatar
unknown committed
321

unknown's avatar
unknown committed
322 323
longlong Item_func_eq::val_int()
{
324
  int value= cmp.compare();
unknown's avatar
unknown committed
325 326 327 328 329
  return value == 0 ? 1 : 0;
}

/* Same as Item_func_eq, but NULL = NULL */

unknown's avatar
unknown committed
330 331 332 333
void Item_func_equal::fix_length_and_dec()
{
  Item_bool_func2::fix_length_and_dec();
  maybe_null=null_value=0;
unknown's avatar
unknown committed
334
  set_cmp_func();
unknown's avatar
unknown committed
335 336
}

unknown's avatar
unknown committed
337 338
longlong Item_func_equal::val_int()
{
339
  return cmp.compare();
unknown's avatar
unknown committed
340 341 342 343
}

longlong Item_func_ne::val_int()
{
344
  int value= cmp.compare();
345
  return value != 0 && !null_value ? 1 : 0;
unknown's avatar
unknown committed
346 347 348 349 350
}


longlong Item_func_ge::val_int()
{
351
  int value= cmp.compare();
unknown's avatar
unknown committed
352 353 354 355 356 357
  return value >= 0 ? 1 : 0;
}


longlong Item_func_gt::val_int()
{
358
  int value= cmp.compare();
unknown's avatar
unknown committed
359 360 361 362 363
  return value > 0 ? 1 : 0;
}

longlong Item_func_le::val_int()
{
364
  int value= cmp.compare();
unknown's avatar
unknown committed
365 366 367 368 369 370
  return value <= 0 && !null_value ? 1 : 0;
}


longlong Item_func_lt::val_int()
{
371
  int value= cmp.compare();
unknown's avatar
unknown committed
372 373 374 375 376 377 378 379 380 381 382 383 384
  return value < 0 && !null_value ? 1 : 0;
}


longlong Item_func_strcmp::val_int()
{
  String *a=args[0]->val_str(&tmp_value1);
  String *b=args[1]->val_str(&tmp_value2);
  if (!a || !b)
  {
    null_value=1;
    return 0;
  }
385
  int value= binary() ? stringcmp(a,b) : sortcmp(a,b);
unknown's avatar
unknown committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  null_value=0;
  return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
}


void Item_func_interval::fix_length_and_dec()
{
  bool nums=1;
  uint i;
  for (i=0 ; i < arg_count ; i++)
  {
    if (!args[i])
      return;					// End of memory
    if (args[i]->type() != Item::INT_ITEM &&
	args[i]->type() != Item::REAL_ITEM)
    {
      nums=0;
      break;
    }
  }
  if (nums && arg_count >= 8)
  {
    if ((intervals=(double*) sql_alloc(sizeof(double)*arg_count)))
    {
      for (i=0 ; i < arg_count ; i++)
	intervals[i]=args[i]->val();
    }
  }
  maybe_null=0; max_length=2;
  used_tables_cache|=item->used_tables();
}

/*
  return -1 if null value,
	  0 if lower than lowest
	  1 - arg_count if between args[n] and args[n+1]
	  arg_count+1 if higher than biggest argument
*/

longlong Item_func_interval::val_int()
{
  double value=item->val();
  if (item->null_value)
    return -1;				// -1 if null /* purecov: inspected */
  if (intervals)
  {					// Use binary search to find interval
    uint start,end;
    start=0; end=arg_count-1;
    while (start != end)
    {
      uint mid=(start+end+1)/2;
      if (intervals[mid] <= value)
	start=mid;
      else
	end=mid-1;
    }
    return (value < intervals[start]) ? 0 : start+1;
  }
  if (args[0]->val() > value)
    return 0;
  for (uint i=1 ; i < arg_count ; i++)
  {
    if (args[i]->val() > value)
      return i;
  }
  return (longlong) arg_count;
}


void Item_func_interval::update_used_tables()
{
  Item_func::update_used_tables();
  item->update_used_tables();
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}

unknown's avatar
unknown committed
463 464 465 466 467 468 469 470
bool Item_func_interval::check_loop(uint id)
{
  DBUG_ENTER("Item_func_interval::check_loop");
  if (Item_func::check_loop(id))
    DBUG_RETURN(1);
  DBUG_RETURN(item->check_loop(id));
}

unknown's avatar
unknown committed
471 472 473 474
void Item_func_between::fix_length_and_dec()
{
   max_length=1;

475 476 477 478
  /*
    As some compare functions are generated after sql_yacc,
    we have to check for out of memory conditons here
  */
unknown's avatar
unknown committed
479 480
  if (!args[0] || !args[1] || !args[2])
    return;
unknown's avatar
unknown committed
481 482 483
  cmp_type=item_cmp_type(args[0]->result_type(),
           item_cmp_type(args[1]->result_type(),
                         args[2]->result_type()));
unknown's avatar
unknown committed
484
  if (args[0]->binary() | args[1]->binary() | args[2]->binary())
unknown's avatar
unknown committed
485 486 487 488
    string_compare=stringcmp;
  else
    string_compare=sortcmp;

unknown's avatar
unknown committed
489 490 491 492 493
  /*
    Make a special case of compare with date/time and longlong fields.
    They are compared as integers, so for const item this time-consuming
    conversion can be done only once, not for every single comparison
  */
unknown's avatar
unknown committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  if (args[0]->type() == FIELD_ITEM)
  {
    Field *field=((Item_field*) args[0])->field;
    if (field->store_for_compare())
    {
      if (convert_constant_item(field,&args[1]))
	cmp_type=INT_RESULT;			// Works for all types.
      if (convert_constant_item(field,&args[2]))
	cmp_type=INT_RESULT;			// Works for all types.
    }
  }
}


longlong Item_func_between::val_int()
{						// ANSI BETWEEN
  if (cmp_type == STRING_RESULT)
  {
    String *value,*a,*b;
    value=args[0]->val_str(&value0);
    if ((null_value=args[0]->null_value))
      return 0;
    a=args[1]->val_str(&value1);
    b=args[2]->val_str(&value2);
    if (!args[1]->null_value && !args[2]->null_value)
      return (string_compare(value,a) >= 0 && string_compare(value,b) <= 0) ?
	1 : 0;
    if (args[1]->null_value && args[2]->null_value)
      null_value=1;
    else if (args[1]->null_value)
    {
      null_value= string_compare(value,b) <= 0; // not null if false range.
    }
    else
    {
      null_value= string_compare(value,a) >= 0; // not null if false range.
    }
  }
  else if (cmp_type == INT_RESULT)
  {
    longlong value=args[0]->val_int(),a,b;
    if ((null_value=args[0]->null_value))
536
      return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    a=args[1]->val_int();
    b=args[2]->val_int();
    if (!args[1]->null_value && !args[2]->null_value)
      return (value >= a && value <= b) ? 1 : 0;
    if (args[1]->null_value && args[2]->null_value)
      null_value=1;
    else if (args[1]->null_value)
    {
      null_value= value <= b;			// not null if false range.
    }
    else
    {
      null_value= value >= a;
    }
  }
  else
  {
    double value=args[0]->val(),a,b;
    if ((null_value=args[0]->null_value))
556
      return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    a=args[1]->val();
    b=args[2]->val();
    if (!args[1]->null_value && !args[2]->null_value)
      return (value >= a && value <= b) ? 1 : 0;
    if (args[1]->null_value && args[2]->null_value)
      null_value=1;
    else if (args[1]->null_value)
    {
      null_value= value <= b;			// not null if false range.
    }
    else
    {
      null_value= value >= a;
    }
  }
  return 0;
}

575 576 577 578 579 580 581 582 583 584
static Item_result item_store_type(Item_result a,Item_result b)
{
  if (a == STRING_RESULT || b == STRING_RESULT)
    return STRING_RESULT;
  else if (a == REAL_RESULT || b == REAL_RESULT)
    return REAL_RESULT;
  else
    return INT_RESULT;
}

unknown's avatar
unknown committed
585 586 587 588 589 590
void
Item_func_ifnull::fix_length_and_dec()
{
  maybe_null=args[1]->maybe_null;
  max_length=max(args[0]->max_length,args[1]->max_length);
  decimals=max(args[0]->decimals,args[1]->decimals);
591 592 593 594
  if ((cached_result_type=item_store_type(args[0]->result_type(),
					  args[1]->result_type())) !=
      REAL_RESULT)
    decimals= 0;
unknown's avatar
unknown committed
595 596
}

597

unknown's avatar
unknown committed
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
double
Item_func_ifnull::val()
{
  double value=args[0]->val();
  if (!args[0]->null_value)
  {
    null_value=0;
    return value;
  }
  value=args[1]->val();
  if ((null_value=args[1]->null_value))
    return 0.0;
  return value;
}

longlong
Item_func_ifnull::val_int()
{
  longlong value=args[0]->val_int();
  if (!args[0]->null_value)
  {
    null_value=0;
    return value;
  }
  value=args[1]->val_int();
  if ((null_value=args[1]->null_value))
    return 0;
  return value;
}

String *
Item_func_ifnull::val_str(String *str)
{
  String *res  =args[0]->val_str(str);
  if (!args[0]->null_value)
  {
    null_value=0;
    return res;
  }
  res=args[1]->val_str(str);
  if ((null_value=args[1]->null_value))
    return 0;
  return res;
}

643

unknown's avatar
unknown committed
644 645 646 647 648
void
Item_func_if::fix_length_and_dec()
{
  maybe_null=args[1]->maybe_null || args[2]->maybe_null;
  max_length=max(args[1]->max_length,args[2]->max_length);
649
  decimals=max(args[1]->decimals,args[2]->decimals);
unknown's avatar
unknown committed
650 651
  enum Item_result arg1_type=args[1]->result_type();
  enum Item_result arg2_type=args[2]->result_type();
652 653 654 655 656 657
  bool null1=args[1]->null_value;
  bool null2=args[2]->null_value;

  if (null1)
  {
    cached_result_type= arg2_type;
658
    set_charset(args[2]->charset());
659 660 661
  }
  else if (null2)
  {
unknown's avatar
unknown committed
662
    cached_result_type= arg1_type;
663
    set_charset(args[1]->charset());
664 665
  }
  else if (arg1_type == STRING_RESULT || arg2_type == STRING_RESULT)
666
  {
unknown's avatar
unknown committed
667
    cached_result_type = STRING_RESULT;
668 669
    set_charset( (args[1]->binary() || args[2]->binary()) ? 
		my_charset_bin : args[1]->charset());
670
  }
unknown's avatar
unknown committed
671
  else
672
  {
673
    set_charset(my_charset_bin);	// Number
674 675 676 677 678
    if (arg1_type == REAL_RESULT || arg2_type == REAL_RESULT)
      cached_result_type = REAL_RESULT;
    else
      cached_result_type=arg1_type;		// Should be INT_RESULT
  }
unknown's avatar
unknown committed
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
}


double
Item_func_if::val()
{
  Item *arg= args[0]->val_int() ? args[1] : args[2];
  double value=arg->val();
  null_value=arg->null_value;
  return value;
}

longlong
Item_func_if::val_int()
{
  Item *arg= args[0]->val_int() ? args[1] : args[2];
  longlong value=arg->val_int();
  null_value=arg->null_value;
  return value;
}

String *
Item_func_if::val_str(String *str)
{
  Item *arg= args[0]->val_int() ? args[1] : args[2];
  String *res=arg->val_str(str);
  null_value=arg->null_value;
  return res;
}


void
Item_func_nullif::fix_length_and_dec()
{
  Item_bool_func2::fix_length_and_dec();
  maybe_null=1;
  if (args[0])					// Only false if EOM
  {
    max_length=args[0]->max_length;
    decimals=args[0]->decimals;
    cached_result_type=args[0]->result_type();
  }
}

/*
724
  nullif () returns NULL if arguments are different, else it returns the
unknown's avatar
unknown committed
725 726 727 728 729 730 731 732 733
  first argument.
  Note that we have to evaluate the first argument twice as the compare
  may have been done with a different type than return value
*/

double
Item_func_nullif::val()
{
  double value;
734
  if (!cmp.compare() || null_value)
unknown's avatar
unknown committed
735 736 737 738 739 740 741 742 743 744 745 746 747
  {
    null_value=1;
    return 0.0;
  }
  value=args[0]->val();
  null_value=args[0]->null_value;
  return value;
}

longlong
Item_func_nullif::val_int()
{
  longlong value;
748
  if (!cmp.compare() || null_value)
unknown's avatar
unknown committed
749 750 751 752 753 754 755 756 757 758 759 760 761
  {
    null_value=1;
    return 0;
  }
  value=args[0]->val_int();
  null_value=args[0]->null_value;
  return value;
}

String *
Item_func_nullif::val_str(String *str)
{
  String *res;
762
  if (!cmp.compare() || null_value)
unknown's avatar
unknown committed
763 764 765 766 767 768 769 770 771 772
  {
    null_value=1;
    return 0;
  }
  res=args[0]->val_str(str);
  null_value=args[0]->null_value;
  return res;
}

/*
773 774
  CASE expression 
  Return the matching ITEM or NULL if all compares (including else) failed
unknown's avatar
unknown committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
*/

Item *Item_func_case::find_item(String *str)
{
  String *first_expr_str,*tmp;
  longlong first_expr_int;
  double   first_expr_real;
  bool int_used, real_used,str_used;
  int_used=real_used=str_used=0;

  /* These will be initialized later */
  LINT_INIT(first_expr_str);
  LINT_INIT(first_expr_int);
  LINT_INIT(first_expr_real);

  // Compare every WHEN argument with it and return the first match
  for (uint i=0 ; i < arg_count ; i+=2)
  {
    if (!first_expr)
    {
      // No expression between CASE and first WHEN
      if (args[i]->val_int())
	return args[i+1];
      continue;
    }
    switch (args[i]->result_type()) {
    case STRING_RESULT:
      if (!str_used)
      {
	str_used=1;
	// We can't use 'str' here as this may be overwritten
	if (!(first_expr_str= first_expr->val_str(&str_value)))
	  return else_expr;			// Impossible
      }
      if ((tmp=args[i]->val_str(str)))		// If not null
      {
811
	if (first_expr->binary() || args[i]->binary())
unknown's avatar
unknown committed
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
	{
	  if (stringcmp(tmp,first_expr_str)==0)
	    return args[i+1];
	}
	else if (sortcmp(tmp,first_expr_str)==0)
	  return args[i+1];
      }
      break;
    case INT_RESULT:
      if (!int_used)
      {
	int_used=1;
	first_expr_int= first_expr->val_int();
	if (first_expr->null_value)
	  return else_expr;
      }
      if (args[i]->val_int()==first_expr_int && !args[i]->null_value) 
        return args[i+1];
      break;
    case REAL_RESULT: 
      if (!real_used)
      {
	real_used=1;
	first_expr_real= first_expr->val();
	if (first_expr->null_value)
	  return else_expr;
      }
      if (args[i]->val()==first_expr_real && !args[i]->null_value) 
        return args[i+1];
unknown's avatar
unknown committed
841 842 843 844 845
      break;
    case ROW_RESULT:
      // This case should never be choosen
      DBUG_ASSERT(0);
      break;
unknown's avatar
unknown committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    }
  }
  // No, WHEN clauses all missed, return ELSE expression
  return else_expr;
}



String *Item_func_case::val_str(String *str)
{
  String *res;
  Item *item=find_item(str);

  if (!item)
  {
    null_value=1;
    return 0;
  }
  if (!(res=item->val_str(str)))
    null_value=1;
  return res;
}


longlong Item_func_case::val_int()
{
  char buff[MAX_FIELD_WIDTH];
873
  String dummy_str(buff,sizeof(buff),default_charset_info);
unknown's avatar
unknown committed
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  Item *item=find_item(&dummy_str);
  longlong res;

  if (!item)
  {
    null_value=1;
    return 0;
  }
  res=item->val_int();
  null_value=item->null_value;
  return res;
}

double Item_func_case::val()
{
  char buff[MAX_FIELD_WIDTH];
890
  String dummy_str(buff,sizeof(buff),default_charset_info);
unknown's avatar
unknown committed
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
  Item *item=find_item(&dummy_str);
  double res;

  if (!item)
  {
    null_value=1;
    return 0;
  }
  res=item->val();
  null_value=item->null_value;
  return res;
}


bool
unknown's avatar
unknown committed
906
Item_func_case::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
907
{
unknown's avatar
unknown committed
908 909 910 911
  if (first_expr && (first_expr->check_cols(1) ||
		     first_expr->fix_fields(thd, tables, &first_expr)) ||
      else_expr && (else_expr->check_cols(1) ||
		    else_expr->fix_fields(thd, tables, &else_expr)))
unknown's avatar
unknown committed
912
    return 1;
unknown's avatar
unknown committed
913
  if (Item_func::fix_fields(thd, tables, ref))
unknown's avatar
unknown committed
914
    return 1;
915 916 917 918 919 920 921 922 923 924
  if (first_expr)
  {
    used_tables_cache|=(first_expr)->used_tables();
    const_item_cache&= (first_expr)->const_item();
  }
  if (else_expr)
  {
    used_tables_cache|=(else_expr)->used_tables();
    const_item_cache&= (else_expr)->const_item();
  }
unknown's avatar
unknown committed
925 926 927 928 929
  if (!else_expr || else_expr->maybe_null)
    maybe_null=1;				// The result may be NULL
  return 0;
}

unknown's avatar
unknown committed
930 931 932 933 934 935 936 937 938 939
bool Item_func_case::check_loop(uint id)
{
  DBUG_ENTER("Item_func_case::check_loop");
  if (Item_func::check_loop(id))
    DBUG_RETURN(1);

  DBUG_RETURN((first_expr && first_expr->check_loop(id)) ||
	      (else_expr && else_expr->check_loop(id)));
}

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
void Item_func_case::update_used_tables()
{
  Item_func::update_used_tables();
  if (first_expr)
  {
    used_tables_cache|=(first_expr)->used_tables();
    const_item_cache&= (first_expr)->const_item();
  }
  if (else_expr)
  {
    used_tables_cache|=(else_expr)->used_tables();
    const_item_cache&= (else_expr)->const_item();
  }
}

unknown's avatar
unknown committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972

void Item_func_case::fix_length_and_dec()
{
  max_length=0;
  decimals=0;
  cached_result_type = args[1]->result_type();
  for (uint i=0 ; i < arg_count ; i+=2)
  {
    set_if_bigger(max_length,args[i+1]->max_length);
    set_if_bigger(decimals,args[i+1]->decimals);
  }
  if (else_expr != NULL) 
  {
    set_if_bigger(max_length,else_expr->max_length);
    set_if_bigger(decimals,else_expr->decimals);
  }
}

973
/* TODO:  Fix this so that it prints the whole CASE expression */
unknown's avatar
unknown committed
974 975 976 977 978 979 980

void Item_func_case::print(String *str)
{
  str->append("case ");				// Not yet complete
}

/*
981
  Coalesce - return first not NULL argument.
unknown's avatar
unknown committed
982 983 984 985 986 987 988
*/

String *Item_func_coalesce::val_str(String *str)
{
  null_value=0;
  for (uint i=0 ; i < arg_count ; i++)
  {
unknown's avatar
unknown committed
989 990 991
    String *res;
    if ((res=args[i]->val_str(str)))
      return res;
unknown's avatar
unknown committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  }
  null_value=1;
  return 0;
}

longlong Item_func_coalesce::val_int()
{
  null_value=0;
  for (uint i=0 ; i < arg_count ; i++)
  {
    longlong res=args[i]->val_int();
    if (!args[i]->null_value)
      return res;
  }
  null_value=1;
  return 0;
}

double Item_func_coalesce::val()
{
  null_value=0;
  for (uint i=0 ; i < arg_count ; i++)
  {
    double res=args[i]->val();
    if (!args[i]->null_value)
      return res;
  }
  null_value=1;
  return 0;
}


void Item_func_coalesce::fix_length_and_dec()
{
  max_length=0;
  decimals=0;
  cached_result_type = args[0]->result_type();
  for (uint i=0 ; i < arg_count ; i++)
  {
    set_if_bigger(max_length,args[i]->max_length);
    set_if_bigger(decimals,args[i]->decimals);
  }
}

/****************************************************************************
1037
 Classes and function for the IN operator
unknown's avatar
unknown committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
****************************************************************************/

static int cmp_longlong(longlong *a,longlong *b)
{
  return *a < *b ? -1 : *a == *b ? 0 : 1;
}

static int cmp_double(double *a,double *b)
{
  return *a < *b ? -1 : *a == *b ? 0 : 1;
}

int in_vector::find(Item *item)
{
  byte *result=get_value(item);
  if (!result || !used_count)
    return 0;				// Null value

  uint start,end;
  start=0; end=used_count-1;
  while (start != end)
  {
    uint mid=(start+end+1)/2;
    int res;
    if ((res=(*compare)(base+mid*size,result)) == 0)
      return 1;
    if (res < 0)
      start=mid;
    else
      end=mid-1;
  }
  return (int) ((*compare)(base+start*size,result) == 0);
}


in_string::in_string(uint elements,qsort_cmp cmp_func)
1074
  :in_vector(elements,sizeof(String),cmp_func),tmp(buff,sizeof(buff),default_charset_info)
unknown's avatar
unknown committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
{}

in_string::~in_string()
{
  for (uint i=0 ; i < count ; i++)
    ((String*) base)[i].free();
}

void in_string::set(uint pos,Item *item)
{
  String *str=((String*) base)+pos;
  String *res=item->val_str(str);
  if (res && res != str)
    *str= *res;
1089 1090 1091
  // BAR TODO: I'm not sure this is absolutely correct
  if (!str->charset())
      str->set_charset(default_charset_info);
unknown's avatar
unknown committed
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
}

byte *in_string::get_value(Item *item)
{
  return (byte*) item->val_str(&tmp);
}


in_longlong::in_longlong(uint elements)
  :in_vector(elements,sizeof(longlong),(qsort_cmp) cmp_longlong)
{}

void in_longlong::set(uint pos,Item *item)
{
  ((longlong*) base)[pos]=item->val_int();
}

byte *in_longlong::get_value(Item *item)
{
  tmp=item->val_int();
  if (item->null_value)
1113
    return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  return (byte*) &tmp;
}


in_double::in_double(uint elements)
  :in_vector(elements,sizeof(double),(qsort_cmp) cmp_double)
{}

void in_double::set(uint pos,Item *item)
{
  ((double*) base)[pos]=item->val();
}

byte *in_double::get_value(Item *item)
{
  tmp=item->val();
  if (item->null_value)
1131
    return 0;					/* purecov: inspected */
unknown's avatar
unknown committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
  return (byte*) &tmp;
}


void Item_func_in::fix_length_and_dec()
{
  if (const_item())
  {
    switch (item->result_type()) {
    case STRING_RESULT:
1142
      if (item->binary())
unknown's avatar
unknown committed
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
	array=new in_string(arg_count,(qsort_cmp) stringcmp); /* purecov: inspected */
      else
	array=new in_string(arg_count,(qsort_cmp) sortcmp);
      break;
    case INT_RESULT:
      array= new in_longlong(arg_count);
      break;
    case REAL_RESULT:
      array= new in_double(arg_count);
      break;
unknown's avatar
unknown committed
1153 1154 1155 1156
    case ROW_RESULT:
      // This case should never be choosen
      DBUG_ASSERT(0);
      break;
unknown's avatar
unknown committed
1157 1158 1159 1160 1161
    }
    uint j=0;
    for (uint i=0 ; i < arg_count ; i++)
    {
      array->set(j,args[i]);
unknown's avatar
unknown committed
1162
      if (!args[i]->null_value)			// Skip NULL values
unknown's avatar
unknown committed
1163
	j++;
1164 1165
      else
	have_null= 1;
unknown's avatar
unknown committed
1166 1167 1168 1169 1170 1171 1172 1173
    }
    if ((array->used_count=j))
      array->sort();
  }
  else
  {
    switch (item->result_type()) {
    case STRING_RESULT:
1174
      if (item->binary())
unknown's avatar
unknown committed
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
	in_item= new cmp_item_binary_string;
      else
	in_item= new cmp_item_sort_string;
      break;
    case INT_RESULT:
      in_item=	  new cmp_item_int;
      break;
    case REAL_RESULT:
      in_item=	  new cmp_item_real;
      break;
unknown's avatar
unknown committed
1185 1186 1187 1188
    case ROW_RESULT:
      // This case should never be choosen
      DBUG_ASSERT(0);
      break;
unknown's avatar
unknown committed
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    }
  }
  maybe_null= item->maybe_null;
  max_length=2;
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}


void Item_func_in::print(String *str)
{
  str->append('(');
  item->print(str);
  Item_func::print(str);
  str->append(')');
}


longlong Item_func_in::val_int()
{
  if (array)
  {
    int tmp=array->find(item);
1212
    null_value=item->null_value || (!tmp && have_null);
unknown's avatar
unknown committed
1213 1214 1215 1216 1217
    return tmp;
  }
  in_item->store_value(item);
  if ((null_value=item->null_value))
    return 0;
1218
  have_null= 0;
unknown's avatar
unknown committed
1219 1220 1221 1222
  for (uint i=0 ; i < arg_count ; i++)
  {
    if (!in_item->cmp(args[i]) && !args[i]->null_value)
      return 1;					// Would maybe be nice with i ?
1223
    have_null|= args[i]->null_value;
unknown's avatar
unknown committed
1224
  }
1225
  null_value= have_null;
unknown's avatar
unknown committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
  return 0;
}


void Item_func_in::update_used_tables()
{
  Item_func::update_used_tables();
  item->update_used_tables();
  used_tables_cache|=item->used_tables();
  const_item_cache&=item->const_item();
}

1238 1239
void Item_func_in::split_sum_func(List<Item> &fields)
{
unknown's avatar
unknown committed
1240 1241 1242
  if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
    item->split_sum_func(fields);
  else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
1243 1244 1245 1246
  {
    fields.push_front(item);
    item=new Item_ref((Item**) fields.head_ref(),0,item->name);
  }  
unknown's avatar
unknown committed
1247
  Item_func::split_sum_func(fields);
1248
}
unknown's avatar
unknown committed
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289


longlong Item_func_bit_or::val_int()
{
  ulonglong arg1= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  ulonglong arg2= (ulonglong) args[1]->val_int();
  if (args[1]->null_value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
  return (longlong) (arg1 | arg2);
}


longlong Item_func_bit_and::val_int()
{
  ulonglong arg1= (ulonglong) args[0]->val_int();
  if (args[0]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  ulonglong arg2= (ulonglong) args[1]->val_int();
  if (args[1]->null_value)
  {
    null_value=1; /* purecov: inspected */
    return 0; /* purecov: inspected */
  }
  null_value=0;
  return (longlong) (arg1 & arg2);
}


bool
unknown's avatar
unknown committed
1290
Item_cond::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
{
  List_iterator<Item> li(list);
  Item *item;
  char buff[sizeof(char*)];			// Max local vars in function
  used_tables_cache=0;
  const_item_cache=0;

  if (thd && check_stack_overrun(thd,buff))
    return 0;					// Fatal error flag is set!
  while ((item=li++))
  {
    while (item->type() == Item::COND_ITEM &&
	   ((Item_cond*) item)->functype() == functype())
    {						// Identical function
      li.replace(((Item_cond*) item)->list);
      ((Item_cond*) item)->list.empty();
#ifdef DELETE_ITEMS
      delete (Item_cond*) item;
#endif
      item= *li.ref();				// new current item
    }
1312 1313
    if (abort_on_null)
      item->top_level_item();
unknown's avatar
unknown committed
1314
    if (item->check_cols(1) || item->fix_fields(thd, tables, li.ref()))
unknown's avatar
unknown committed
1315 1316 1317 1318
      return 1; /* purecov: inspected */
    used_tables_cache|=item->used_tables();
    with_sum_func= with_sum_func || item->with_sum_func;
    const_item_cache&=item->const_item();
unknown's avatar
unknown committed
1319 1320
    if (item->maybe_null)
      maybe_null=1;
unknown's avatar
unknown committed
1321 1322 1323 1324
  }
  if (thd)
    thd->cond_count+=list.elements;
  fix_length_and_dec();
1325
  fixed= 1;
unknown's avatar
unknown committed
1326 1327 1328
  return 0;
}

unknown's avatar
unknown committed
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
bool Item_cond::check_loop(uint id)
{
  DBUG_ENTER("Item_cond::check_loop");
  if (Item_func::check_loop(id))
    DBUG_RETURN(1);
  List_iterator<Item> li(list);
  Item *item;
  while ((item= li++))
  {
    if (item->check_loop(id))
      DBUG_RETURN(1);
  }
  DBUG_RETURN(0);
}
unknown's avatar
unknown committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

void Item_cond::split_sum_func(List<Item> &fields)
{
  List_iterator<Item> li(list);
  Item *item;
  used_tables_cache=0;
  const_item_cache=0;
  while ((item=li++))
  {
    if (item->with_sum_func && item->type() != SUM_FUNC_ITEM)
      item->split_sum_func(fields);
    else if (item->used_tables() || item->type() == SUM_FUNC_ITEM)
    {
      fields.push_front(item);
      li.replace(new Item_ref((Item**) fields.head_ref(),0,item->name));
    }
    item->update_used_tables();
    used_tables_cache|=item->used_tables();
    const_item_cache&=item->const_item();
  }
}


table_map
Item_cond::used_tables() const
{						// This caches used_tables
  return used_tables_cache;
}

void Item_cond::update_used_tables()
{
  used_tables_cache=0;
  const_item_cache=1;
unknown's avatar
unknown committed
1376
  List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  Item *item;
  while ((item=li++))
  {
    item->update_used_tables();
    used_tables_cache|=item->used_tables();
    const_item_cache&= item->const_item();
  }
}


void Item_cond::print(String *str)
{
  str->append('(');
unknown's avatar
unknown committed
1390
  List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
  Item *item;
  if ((item=li++))
    item->print(str);
  while ((item=li++))
  {
    str->append(' ');
    str->append(func_name());
    str->append(' ');
    item->print(str);
  }
  str->append(')');
}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
/*
  Evalution of AND(expr, expr, expr ...)

  NOTES:
    abort_if_null is set for AND expressions for which we don't care if the
    result is NULL or 0. This is set for:
    - WHERE clause
    - HAVING clause
    - IF(expression)

  RETURN VALUES
    1  If all expressions are true
    0  If all expressions are false or if we find a NULL expression and
       'abort_on_null' is set.
    NULL if all expression are either 1 or NULL
*/

unknown's avatar
unknown committed
1421 1422 1423

longlong Item_cond_and::val_int()
{
unknown's avatar
unknown committed
1424
  List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
1425
  Item *item;
1426
  null_value= 0;
unknown's avatar
unknown committed
1427 1428 1429 1430
  while ((item=li++))
  {
    if (item->val_int() == 0)
    {
1431 1432
      if (abort_on_null || !(null_value= item->null_value))
	return 0;				// return FALSE
unknown's avatar
unknown committed
1433 1434
    }
  }
1435
  return null_value ? 0 : 1;
unknown's avatar
unknown committed
1436 1437
}

1438

unknown's avatar
unknown committed
1439 1440
longlong Item_cond_or::val_int()
{
unknown's avatar
unknown committed
1441
  List_iterator_fast<Item> li(list);
unknown's avatar
unknown committed
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
  Item *item;
  null_value=0;
  while ((item=li++))
  {
    if (item->val_int() != 0)
    {
      null_value=0;
      return 1;
    }
    if (item->null_value)
      null_value=1;
  }
  return 0;
}

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
/*
  Create an AND expression from two expressions

  SYNOPSIS
   and_expressions()
   a		expression or NULL
   b    	expression.
   org_item	Don't modify a if a == *org_item
		If a == NULL, org_item is set to point at b,
		to ensure that future calls will not modify b.

  NOTES
    This will not modify item pointed to by org_item or b
    The idea is that one can call this in a loop and create and
    'and' over all items without modifying any of the original items.

  RETURN
    NULL	Error
    Item
*/

Item *and_expressions(Item *a, Item *b, Item **org_item)
{
  if (!a)
1481
    return (*org_item= (Item*) b);
1482 1483 1484
  if (a == *org_item)
  {
    Item_cond *res;
1485
    if ((res= new Item_cond_and(a, (Item*) b)))
1486 1487 1488
      res->used_tables_cache= a->used_tables() | b->used_tables();
    return res;
  }
1489
  if (((Item_cond_and*) a)->add((Item*) b))
1490 1491 1492 1493 1494 1495
    return 0;
  ((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
  return a;
}


unknown's avatar
unknown committed
1496 1497
longlong Item_func_isnull::val_int()
{
1498 1499 1500 1501 1502
  /*
    Handle optimization if the argument can't be null
    This has to be here because of the test in update_used_tables().
  */
  if (!used_tables_cache)
unknown's avatar
unknown committed
1503
    return cached_value;
unknown's avatar
unknown committed
1504
  return args[0]->is_null() ? 1: 0;
unknown's avatar
unknown committed
1505 1506 1507 1508
}

longlong Item_func_isnotnull::val_int()
{
unknown's avatar
unknown committed
1509
  return args[0]->is_null() ? 0 : 1;
unknown's avatar
unknown committed
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
}


void Item_func_like::fix_length_and_dec()
{
  decimals=0; max_length=1;
  //  cmp_type=STRING_RESULT;			// For quick select
}

longlong Item_func_like::val_int()
{
1521
  String* res = args[0]->val_str(&tmp_value1);
unknown's avatar
unknown committed
1522 1523 1524 1525 1526
  if (args[0]->null_value)
  {
    null_value=1;
    return 0;
  }
1527
  String* res2 = args[1]->val_str(&tmp_value2);
unknown's avatar
unknown committed
1528 1529 1530 1531 1532 1533
  if (args[1]->null_value)
  {
    null_value=1;
    return 0;
  }
  null_value=0;
1534 1535 1536
  if ((res->charset()->state & MY_CS_BINSORT) ||
      (res2->charset()->state & MY_CS_BINSORT))
    set_charset(my_charset_bin);
1537 1538
  if (canDoTurboBM)
    return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
1539 1540 1541 1542
  return my_wildcmp(charset(),
		    res->ptr(),res->ptr()+res->length(),
		    res2->ptr(),res2->ptr()+res2->length(),
		    escape,wild_one,wild_many) ? 0 : 1;
unknown's avatar
unknown committed
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
}


/* We can optimize a where if first character isn't a wildcard */

Item_func::optimize_type Item_func_like::select_optimize() const
{
  if (args[1]->type() == STRING_ITEM)
  {
    if (((Item_string *) args[1])->str_value[0] != wild_many)
    {
      if ((args[0]->result_type() != STRING_RESULT) ||
	  ((Item_string *) args[1])->str_value[0] != wild_one)
	return OPTIMIZE_OP;
    }
  }
  return OPTIMIZE_NONE;
}

unknown's avatar
unknown committed
1562
bool Item_func_like::fix_fields(THD *thd, TABLE_LIST *tlist, Item ** ref)
1563
{
unknown's avatar
unknown committed
1564
  if (Item_bool_func2::fix_fields(thd, tlist, ref))
1565 1566 1567 1568 1569 1570 1571 1572 1573
    return 1;

  /*
    TODO--we could do it for non-const, but we'd have to
    recompute the tables for each row--probably not worth it.
  */
  if (args[1]->const_item() && !(specialflag & SPECIAL_NO_NEW_FUNC))
  {
    String* res2 = args[1]->val_str(&tmp_value2);
unknown's avatar
unknown committed
1574 1575 1576
    if (!res2)
      return 0;					// Null argument

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
    const size_t len   = res2->length();
    const char*  first = res2->ptr();
    const char*  last  = first + len - 1;
    /*
      len must be > 2 ('%pattern%')
      heuristic: only do TurboBM for pattern_len > 2
    */

    if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
	*first == wild_many &&
	*last  == wild_many)
    {
      const char* tmp = first + 1;
1590
      for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
1591 1592 1593 1594 1595 1596 1597
      canDoTurboBM = tmp == last;
    }

    if (canDoTurboBM)
    {
      pattern     = first + 1;
      pattern_len = len - 2;
1598 1599 1600 1601 1602
      DBUG_PRINT("info", ("Initializing pattern: '%s'", first));
      int *suff = (int*) thd->alloc(sizeof(int)*((pattern_len + 1)*2+
						 alphabet_size));
      bmGs      = suff + pattern_len + 1;
      bmBc      = bmGs + pattern_len + 1;
1603 1604
      turboBM_compute_good_suffix_shifts(suff);
      turboBM_compute_bad_character_shifts();
1605
      DBUG_PRINT("info",("done"));
1606 1607 1608 1609 1610
    }
  }
  return 0;
}

unknown's avatar
unknown committed
1611 1612 1613
#ifdef USE_REGEX

bool
unknown's avatar
unknown committed
1614
Item_func_regex::fix_fields(THD *thd, TABLE_LIST *tables, Item **ref)
unknown's avatar
unknown committed
1615
{
unknown's avatar
unknown committed
1616 1617 1618
  if (args[0]->check_cols(1) ||
      args[1]->check_cols(1) ||
      args[0]->fix_fields(thd, tables, args) ||
unknown's avatar
unknown committed
1619
      args[1]->fix_fields(thd,tables, args + 1))
unknown's avatar
unknown committed
1620 1621 1622
    return 1;					/* purecov: inspected */
  with_sum_func=args[0]->with_sum_func || args[1]->with_sum_func;
  max_length=1; decimals=0;
1623 1624 1625
  if (args[0]->binary() || args[1]->binary())
    set_charset(my_charset_bin);

unknown's avatar
unknown committed
1626 1627 1628 1629 1630
  used_tables_cache=args[0]->used_tables() | args[1]->used_tables();
  const_item_cache=args[0]->const_item() && args[1]->const_item();
  if (!regex_compiled && args[1]->const_item())
  {
    char buff[MAX_FIELD_WIDTH];
1631
    String tmp(buff,sizeof(buff),default_charset_info);
unknown's avatar
unknown committed
1632 1633 1634 1635 1636 1637 1638 1639
    String *res=args[1]->val_str(&tmp);
    if (args[1]->null_value)
    {						// Will always return NULL
      maybe_null=1;
      return 0;
    }
    int error;
    if ((error=regcomp(&preg,res->c_ptr(),
1640
		       binary() ? REG_EXTENDED | REG_NOSUB :
1641
		       REG_EXTENDED | REG_NOSUB | REG_ICASE,
1642
		       res->charset())))
unknown's avatar
unknown committed
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
    {
      (void) regerror(error,&preg,buff,sizeof(buff));
      my_printf_error(ER_REGEXP_ERROR,ER(ER_REGEXP_ERROR),MYF(0),buff);
      return 1;
    }
    regex_compiled=regex_is_const=1;
    maybe_null=args[0]->maybe_null;
  }
  else
    maybe_null=1;
1653
  fixed= 1;
unknown's avatar
unknown committed
1654 1655 1656 1657 1658 1659
  return 0;
}

longlong Item_func_regex::val_int()
{
  char buff[MAX_FIELD_WIDTH];
1660
  String *res, tmp(buff,sizeof(buff),default_charset_info);
unknown's avatar
unknown committed
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670

  res=args[0]->val_str(&tmp);
  if (args[0]->null_value)
  {
    null_value=1;
    return 0;
  }
  if (!regex_is_const)
  {
    char buff2[MAX_FIELD_WIDTH];
1671
    String *res2, tmp2(buff2,sizeof(buff2),default_charset_info);
unknown's avatar
unknown committed
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687

    res2= args[1]->val_str(&tmp2);
    if (args[1]->null_value)
    {
      null_value=1;
      return 0;
    }
    if (!regex_compiled || stringcmp(res2,&prev_regexp))
    {
      prev_regexp.copy(*res2);
      if (regex_compiled)
      {
	regfree(&preg);
	regex_compiled=0;
      }
      if (regcomp(&preg,res2->c_ptr(),
1688
		  binary() ? REG_EXTENDED | REG_NOSUB :
1689
		  REG_EXTENDED | REG_NOSUB | REG_ICASE,
1690
		  res->charset()))
unknown's avatar
unknown committed
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

      {
	null_value=1;
	return 0;
      }
      regex_compiled=1;
    }
  }
  null_value=0;
  return regexec(&preg,res->c_ptr(),0,(regmatch_t*) 0,0) ? 0 : 1;
}


Item_func_regex::~Item_func_regex()
{
  if (regex_compiled)
  {
    regfree(&preg);
    regex_compiled=0;
  }
}

#endif /* USE_REGEX */
1714 1715 1716


#ifdef LIKE_CMP_TOUPPER
unknown's avatar
unknown committed
1717
#define likeconv(cs,A) (uchar) (cs)->toupper(A)
1718
#else
unknown's avatar
unknown committed
1719
#define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
#endif


/**********************************************************************
  turboBM_compute_suffixes()
  Precomputation dependent only on pattern_len.
**********************************************************************/

void Item_func_like::turboBM_compute_suffixes(int* suff)
{
  const int   plm1 = pattern_len - 1;
  int            f = 0;
  int            g = plm1;
unknown's avatar
unknown committed
1733 1734
  int *const splm1 = suff + plm1;
  CHARSET_INFO	*cs=system_charset_info;	// QQ Needs to be fixed
1735 1736 1737

  *splm1 = pattern_len;

1738
  if (binary())
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
  {
    int i;
    for (i = pattern_len - 2; i >= 0; i--)
    {
      int tmp = *(splm1 + i - f);
      if (g < i && tmp < i - g)
	suff[i] = tmp;
      else
      {
	if (i < g)
	  g = i; // g = min(i, g)
	f = i;
	while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
	  g--;
	suff[i] = f - g;
      }
    }
  }
  else
  {
    int i;
    for (i = pattern_len - 2; 0 <= i; --i)
    {
      int tmp = *(splm1 + i - f);
      if (g < i && tmp < i - g)
	suff[i] = tmp;
      else
      {
	if (i < g)
	  g = i; // g = min(i, g)
	f = i;
unknown's avatar
unknown committed
1770 1771
	while (g >= 0 && likeconv(cs, pattern[g]) ==
	       likeconv(cs, pattern[g + plm1 - f]))
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
	  g--;
	suff[i] = f - g;
      }
    }
  }
}


/**********************************************************************
   turboBM_compute_good_suffix_shifts()
   Precomputation dependent only on pattern_len.
**********************************************************************/

void Item_func_like::turboBM_compute_good_suffix_shifts(int* suff)
{
  turboBM_compute_suffixes(suff);

  int* end = bmGs + pattern_len;
  int* k;
  for (k = bmGs; k < end; k++)
    *k = pattern_len;

  int tmp;
  int i;
  int j          = 0;
  const int plm1 = pattern_len - 1;
  for (i = plm1; i > -1; i--)
  {
    if (suff[i] == i + 1)
    {
      for (tmp = plm1 - i; j < tmp; j++)
      {
	int* tmp2 = bmGs + j;
	if (*tmp2 == pattern_len)
	  *tmp2 = tmp;
      }
    }
  }

  int* tmp2;
  for (tmp = plm1 - i; j < tmp; j++)
  {
    tmp2 = bmGs + j;
    if (*tmp2 == pattern_len)
      *tmp2 = tmp;
  }

  tmp2 = bmGs + plm1;
  for (i = 0; i <= pattern_len - 2; i++)
    *(tmp2 - suff[i]) = plm1 - i;
}


/**********************************************************************
   turboBM_compute_bad_character_shifts()
   Precomputation dependent on pattern_len.
**********************************************************************/

void Item_func_like::turboBM_compute_bad_character_shifts()
{
unknown's avatar
unknown committed
1832 1833 1834 1835 1836 1837
  int *i;
  int *end = bmBc + alphabet_size;
  int j;
  const int plm1 = pattern_len - 1;
  CHARSET_INFO	*cs=system_charset_info;	// QQ Needs to be fixed

1838 1839 1840
  for (i = bmBc; i < end; i++)
    *i = pattern_len;

1841
  if (binary())
unknown's avatar
unknown committed
1842
  {
1843 1844
    for (j = 0; j < plm1; j++)
      bmBc[pattern[j]] = plm1 - j;
unknown's avatar
unknown committed
1845
  }
1846
  else
unknown's avatar
unknown committed
1847
  {
1848
    for (j = 0; j < plm1; j++)
unknown's avatar
unknown committed
1849 1850
      bmBc[likeconv(cs,pattern[j])] = plm1 - j;
  }
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
}


/**********************************************************************
  turboBM_matches()
  Search for pattern in text, returns true/false for match/no match
**********************************************************************/

bool Item_func_like::turboBM_matches(const char* text, int text_len) const
{
  register int bcShift;
  register int turboShift;
  int shift = pattern_len;
  int j     = 0;
  int u     = 0;
unknown's avatar
unknown committed
1866
  CHARSET_INFO	*cs=system_charset_info;	// QQ Needs to be fixed
1867 1868 1869 1870 1871

  const int plm1  = pattern_len - 1;
  const int tlmpl =    text_len - pattern_len;

  /* Searching */
1872
  if (binary())
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
  {
    while (j <= tlmpl)
    {
      register int i = plm1;
      while (i >= 0 && pattern[i] == text[i + j])
      {
	i--;
	if (i == plm1 - shift)
	  i -= u;
      }
      if (i < 0)
unknown's avatar
unknown committed
1884
	return 1;
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900

      register const int v = plm1 - i;
      turboShift = u - v;
      bcShift    = bmBc[text[i + j]] - plm1 + i;
      shift      = max(turboShift, bcShift);
      shift      = max(shift, bmGs[i]);
      if (shift == bmGs[i])
	u = min(pattern_len - shift, v);
      else
      {
	if (turboShift < bcShift)
	  shift = max(shift, u + 1);
	u = 0;
      }
      j += shift;
    }
unknown's avatar
unknown committed
1901
    return 0;
1902 1903 1904 1905 1906 1907
  }
  else
  {
    while (j <= tlmpl)
    {
      register int i = plm1;
unknown's avatar
unknown committed
1908
      while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
1909 1910 1911 1912 1913 1914
      {
	i--;
	if (i == plm1 - shift)
	  i -= u;
      }
      if (i < 0)
unknown's avatar
unknown committed
1915
	return 1;
1916 1917 1918

      register const int v = plm1 - i;
      turboShift = u - v;
unknown's avatar
unknown committed
1919
      bcShift    = bmBc[likeconv(cs, text[i + j])] - plm1 + i;
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
      shift      = max(turboShift, bcShift);
      shift      = max(shift, bmGs[i]);
      if (shift == bmGs[i])
	u = min(pattern_len - shift, v);
      else
      {
	if (turboShift < bcShift)
	  shift = max(shift, u + 1);
	u = 0;
      }
      j += shift;
    }
unknown's avatar
unknown committed
1932
    return 0;
1933 1934
  }
}
unknown's avatar
unknown committed
1935

1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956

/*
  Make a logical XOR of the arguments.

  SYNOPSIS
    val_int()

  DESCRIPTION
  If either operator is NULL, return NULL.

  NOTE
    As we don't do any index optimization on XOR this is not going to be
    very fast to use.

  TODO (low priority)
    Change this to be optimized as:
      A XOR B   ->  (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1)
    To be able to do this, we would however first have to extend the MySQL
    range optimizer to handle OR better.
*/

unknown's avatar
unknown committed
1957 1958 1959 1960 1961
longlong Item_cond_xor::val_int()
{
  List_iterator<Item> li(list);
  Item *item;
  int result=0;	
1962
  null_value=0;
unknown's avatar
unknown committed
1963 1964
  while ((item=li++))
  {
1965 1966 1967 1968 1969 1970
    result^= (item->val_int() != 0);
    if (item->null_value)
    {
      null_value=1;
      return 0;
    }
unknown's avatar
unknown committed
1971
  }
1972
  return (longlong) result;
unknown's avatar
unknown committed
1973
}
unknown's avatar
unknown committed
1974

unknown's avatar
unknown committed
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
/****************************************************************
 Classes and functions for spatial relations
*****************************************************************/

longlong Item_func_spatial_rel::val_int()
{
  String *res1=args[0]->val_str(&tmp_value1);
  String *res2=args[1]->val_str(&tmp_value2);
  Geometry g1, g2;
  MBR mbr1,mbr2;

  if ((null_value=(args[0]->null_value ||
                   args[1]->null_value ||
                   g1.create_from_wkb(res1->ptr(),res1->length()) || 
                   g2.create_from_wkb(res2->ptr(),res2->length()) ||
                   g1.get_mbr(&mbr1) || 
                   g2.get_mbr(&mbr2))))
   return 0;

  switch (spatial_rel)
  {
    case SP_CONTAINS_FUNC:
      return mbr1.contains(&mbr2);
    case SP_WITHIN_FUNC:
      return mbr1.within(&mbr2);
    case SP_EQUALS_FUNC:
      return mbr1.equals(&mbr2);
    case SP_DISJOINT_FUNC:
      return mbr1.disjoint(&mbr2);
    case SP_INTERSECTS_FUNC:
      return mbr1.intersects(&mbr2);
    case SP_TOUCHES_FUNC:
      return mbr1.touches(&mbr2);
    case SP_OVERLAPS_FUNC:
      return mbr1.overlaps(&mbr2);
    case SP_CROSSES_FUNC:
      return 0;
    default:
      break;
  }

  null_value=1;
  return 0;
}

longlong Item_func_isempty::val_int()
{
  String tmp; 
  null_value=0;
  return args[0]->null_value ? 1 : 0;
}

longlong Item_func_issimple::val_int()
{
  String tmp;
  String *wkb=args[0]->val_str(&tmp);

  if ((null_value= (!wkb || args[0]->null_value )))
    return 0;
  /* TODO: Ramil or Holyfoot, add real IsSimple calculation */
  return 0;
}

longlong Item_func_isclosed::val_int()
{
  String tmp;
  String *wkb=args[0]->val_str(&tmp);
  Geometry geom;
  int isclosed;

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

  return (longlong) isclosed;
}